Completed
Branch Gutenberg/form-system (1dc3a2)
by
unknown
75:13 queued 66:52
created
entities/route_match/specifications/admin/WordPressPostTypeEditor.php 1 patch
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -15,15 +15,15 @@
 block discarded – undo
15 15
  */
16 16
 class WordPressPostTypeEditor extends RouteMatchSpecification
17 17
 {
18
-    /**
19
-     * returns true if current request matches specification
20
-     *
21
-     * @since $VID:$
22
-     * @return boolean
23
-     */
24
-    public function isMatchingRoute()
25
-    {
26
-        return strpos($this->request->requestUri(), 'wp-admin/post.php') !== false
27
-            || strpos($this->request->requestUri(), 'wp-admin/post-new.php') !== false;
28
-    }
18
+	/**
19
+	 * returns true if current request matches specification
20
+	 *
21
+	 * @since $VID:$
22
+	 * @return boolean
23
+	 */
24
+	public function isMatchingRoute()
25
+	{
26
+		return strpos($this->request->requestUri(), 'wp-admin/post.php') !== false
27
+			|| strpos($this->request->requestUri(), 'wp-admin/post-new.php') !== false;
28
+	}
29 29
 }
Please login to merge, or discard this patch.
core/libraries/messages/messenger/EE_Pdf_messenger.class.php 1 patch
Indentation   +344 added lines, -344 removed lines patch added patch discarded remove patch
@@ -15,349 +15,349 @@
 block discarded – undo
15 15
 {
16 16
 
17 17
 
18
-    /**
19
-     * The following are the properties that this messenger requires for generating pdf
20
-     */
21
-
22
-    /**
23
-     * This is the pdf body generated by the template via the message type.
24
-     *
25
-     * @var string
26
-     */
27
-    protected $_content;
28
-
29
-
30
-    /**
31
-     * This is for the page title that gets displayed.  This will end up being the filename for the generated pdf.
32
-     *
33
-     * @var string
34
-     */
35
-    protected $_subject;
36
-
37
-
38
-    /**
39
-     * @return EE_Pdf_messenger
40
-     */
41
-    public function __construct()
42
-    {
43
-        // set properties
44
-        $this->name = 'pdf';
45
-        $this->description = __('This messenger is used for generating a pdf version of the message.', 'event_espresso');
46
-        $this->label = array(
47
-            'singular' => __('PDF', 'event_espresso'),
48
-            'plural' => __('PDFs', 'event_espresso')
49
-        );
50
-        $this->activate_on_install = true;
51
-
52
-        parent::__construct();
53
-    }
54
-
55
-
56
-    /**
57
-     * PDF Messenger desires execution immediately.
58
-     * @see  parent::send_now() for documentation.
59
-     * @since  4.9.0
60
-     * @return bool
61
-     */
62
-    public function send_now()
63
-    {
64
-        return true;
65
-    }
66
-
67
-
68
-    /**
69
-     * HTML Messenger allows an empty to field.
70
-     * @see parent::allow_empty_to_field() for documentation
71
-     * @since  4.9.0
72
-     * @return bool
73
-     */
74
-    public function allow_empty_to_field()
75
-    {
76
-        return true;
77
-    }
78
-
79
-
80
-    /**
81
-     * @see abstract declaration in EE_messenger for details.
82
-     */
83
-    protected function _set_admin_pages()
84
-    {
85
-        $this->admin_registered_pages = array('events_edit' => false);
86
-    }
87
-
88
-
89
-    /**
90
-     * @see abstract declaration in EE_messenger for details.
91
-     */
92
-    protected function _set_valid_shortcodes()
93
-    {
94
-        $this->_valid_shortcodes = array();
95
-    }
96
-
97
-
98
-    /**
99
-     * @see abstract declaration in EE_messenger for details.
100
-     */
101
-    protected function _set_validator_config()
102
-    {
103
-        $this->_validator_config = array(
104
-            'subject' => array(
105
-                'shortcodes' => array('recipient_details', 'organization', 'event', 'ticket', 'venue', 'primary_registration_details', 'event_author', 'email', 'event_meta', 'recipient_list', 'transaction', 'datetime_list', 'datetime')
106
-            ),
107
-            'content' => array(
108
-                'shortcodes' => array('recipient_details', 'organization', 'event', 'ticket', 'venue', 'primary_registration_details', 'event_author', 'email', 'event_meta', 'recipient_list', 'transaction', 'datetime_list', 'datetime')
109
-            ),
110
-            'attendee_list' => array(
111
-                'shortcodes' => array('attendee', 'event_list', 'ticket_list'),
112
-                'required' => array('[ATTENDEE_LIST]')
113
-            ),
114
-            'event_list' => array(
115
-                'shortcodes' => array('event', 'attendee_list', 'ticket_list', 'venue', 'datetime_list', 'attendee', 'primary_registration_details', 'primary_registration_list', 'event_author', 'recipient_details', 'recipient_list'),
116
-                'required' => array('[EVENT_LIST]')
117
-            ),
118
-            'ticket_list' => array(
119
-                'shortcodes' => array('event_list', 'attendee_list', 'ticket', 'datetime_list', 'primary_registration_details', 'recipient_details'),
120
-                'required' => array('[TICKET_LIST]')
121
-            ),
122
-            'datetime_list' => array(
123
-                'shortcodes' => array('datetime'),
124
-                'required' => array('[DATETIME_LIST]')
125
-            ),
126
-        );
127
-    }
128
-
129
-
130
-    /**
131
-     * Takes care of enqueuing any necessary scripts or styles for the page.  A do_action() so message types using this messenger can add their own js.
132
-     *
133
-     * @return void.
134
-     */
135
-    public function enqueue_scripts_styles()
136
-    {
137
-        parent::enqueue_scripts_styles();
138
-        do_action('AHEE__EE_Pdf_messenger__enqueue_scripts_styles');
139
-    }
140
-
141
-
142
-    /**
143
-     * _set_template_fields
144
-     * This sets up the fields that a messenger requires for the message to go out.
145
-     *
146
-     * @access  protected
147
-     * @return void
148
-     */
149
-    protected function _set_template_fields()
150
-    {
151
-        // any extra template fields that are NOT used by the messenger but will get used by a messenger field for shortcode replacement get added to the 'extra' key in an associated array indexed by the messenger field they relate to.  This is important for the Messages_admin to know what fields to display to the user.  Also, notice that the "values" are equal to the field type that messages admin will use to know what kind of field to display. The values ALSO have one index labeled "shortcode".  the values in that array indicate which ACTUAL SHORTCODE (i.e. [SHORTCODE]) is required in order for this extra field to be displayed.  If the required shortcode isn't part of the shortcodes array then the field is not needed and will not be displayed/parsed.
152
-        $this->_template_fields = array(
153
-            'subject' => array(
154
-                'input' => 'text',
155
-                'label' => __('Page Title', 'event_espresso'),
156
-                'type' => 'string',
157
-                'required' => true,
158
-                'validation' => true,
159
-                'css_class' => 'large-text',
160
-                'format' => '%s'
161
-            ),
162
-            'content' => '', // left empty b/c it is in the "extra array" but messenger still needs needs to know this is a field.
163
-            'extra' => array(
164
-                'content' => array(
165
-                    'main' => array(
166
-                        'input' => 'wp_editor',
167
-                        'label' => __('Main Content', 'event_espresso'),
168
-                        'type' => 'string',
169
-                        'required' => true,
170
-                        'validation' => true,
171
-                        'format' => '%s',
172
-                        'rows' => '15'
173
-                    ),
174
-                    'event_list' => array(
175
-                        'input' => 'wp_editor',
176
-                        'label' => '[EVENT_LIST]',
177
-                        'type' => 'string',
178
-                        'required' => true,
179
-                        'validation' => true,
180
-                        'format' => '%s',
181
-                        'rows' => '15',
182
-                        'shortcodes_required' => array('[EVENT_LIST]')
183
-                    ),
184
-                    'attendee_list' => array(
185
-                        'input' => 'textarea',
186
-                        'label' => '[ATTENDEE_LIST]',
187
-                        'type' => 'string',
188
-                        'required' => true,
189
-                        'validation' => true,
190
-                        'format' => '%s',
191
-                        'css_class' => 'large-text',
192
-                        'rows' => '5',
193
-                        'shortcodes_required' => array('[ATTENDEE_LIST]')
194
-                    ),
195
-                    'ticket_list' => array(
196
-                        'input' => 'textarea',
197
-                        'label' => '[TICKET_LIST]',
198
-                        'type' => 'string',
199
-                        'required' => true,
200
-                        'validation' => true,
201
-                        'format' => '%s',
202
-                        'css_class' => 'large-text',
203
-                        'rows' => '10',
204
-                        'shortcodes_required' => array('[TICKET_LIST]')
205
-                    ),
206
-                    'datetime_list' => array(
207
-                        'input' => 'textarea',
208
-                        'label' => '[DATETIME_LIST]',
209
-                        'type' => 'string',
210
-                        'required' => true,
211
-                        'validation' => true,
212
-                        'format' => '%s',
213
-                        'css_class' => 'large-text',
214
-                        'rows' => '10',
215
-                        'shortcodes_required' => array('[DATETIME_LIST]')
216
-                    )
217
-                )
218
-            )
219
-        );
220
-    }
221
-
222
-
223
-    /**
224
-     * @see definition of this method in parent
225
-     *
226
-     * @since 4.5.0
227
-     *
228
-     */
229
-    protected function _set_default_message_types()
230
-    {
231
-        // note currently PDF is only a secondary messenger so it never has any associated message types.
232
-        $this->_default_message_types = array();
233
-    }
234
-
235
-
236
-    /**
237
-     * @see definition of this method in parent
238
-     *
239
-     * @since 4.5.0
240
-     */
241
-    protected function _set_valid_message_types()
242
-    {
243
-        $this->_valid_message_types = array();
244
-    }
245
-
246
-
247
-    /**
248
-     * Generates html version of the message content and then sends it to the pdf generator.
249
-     *
250
-     *
251
-     * @since 4.5.0
252
-     *
253
-     * @return string.
254
-     */
255
-    protected function _send_message()
256
-    {
257
-        $this->_template_args = array(
258
-            'page_title' => $this->_subject,
259
-            'base_css' => $this->get_variation($this->_tmp_pack, $this->_incoming_message_type->name, true, 'base', $this->_variation),
260
-            'print_css' => $this->get_variation($this->_tmp_pack, $this->_incoming_message_type->name, true, 'print', $this->_variation),
261
-            'main_css' => $this->get_variation($this->_tmp_pack, $this->_incoming_message_type->name, true, 'main', $this->_variation),
262
-            'extra_css' => EE_LIBRARIES_URL . 'messages/defaults/default/variations/pdf_base_default.css',
263
-            'main_body' => apply_filters('FHEE__EE_Pdf_messenger___send_message__main_body', wpautop($this->_content), $this->_content)
264
-        );
265
-        $this->_deregister_wp_hooks();
266
-        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts_styles'));
267
-        $content = $this->_get_main_template();
18
+	/**
19
+	 * The following are the properties that this messenger requires for generating pdf
20
+	 */
21
+
22
+	/**
23
+	 * This is the pdf body generated by the template via the message type.
24
+	 *
25
+	 * @var string
26
+	 */
27
+	protected $_content;
28
+
29
+
30
+	/**
31
+	 * This is for the page title that gets displayed.  This will end up being the filename for the generated pdf.
32
+	 *
33
+	 * @var string
34
+	 */
35
+	protected $_subject;
36
+
37
+
38
+	/**
39
+	 * @return EE_Pdf_messenger
40
+	 */
41
+	public function __construct()
42
+	{
43
+		// set properties
44
+		$this->name = 'pdf';
45
+		$this->description = __('This messenger is used for generating a pdf version of the message.', 'event_espresso');
46
+		$this->label = array(
47
+			'singular' => __('PDF', 'event_espresso'),
48
+			'plural' => __('PDFs', 'event_espresso')
49
+		);
50
+		$this->activate_on_install = true;
51
+
52
+		parent::__construct();
53
+	}
54
+
55
+
56
+	/**
57
+	 * PDF Messenger desires execution immediately.
58
+	 * @see  parent::send_now() for documentation.
59
+	 * @since  4.9.0
60
+	 * @return bool
61
+	 */
62
+	public function send_now()
63
+	{
64
+		return true;
65
+	}
66
+
67
+
68
+	/**
69
+	 * HTML Messenger allows an empty to field.
70
+	 * @see parent::allow_empty_to_field() for documentation
71
+	 * @since  4.9.0
72
+	 * @return bool
73
+	 */
74
+	public function allow_empty_to_field()
75
+	{
76
+		return true;
77
+	}
78
+
79
+
80
+	/**
81
+	 * @see abstract declaration in EE_messenger for details.
82
+	 */
83
+	protected function _set_admin_pages()
84
+	{
85
+		$this->admin_registered_pages = array('events_edit' => false);
86
+	}
87
+
88
+
89
+	/**
90
+	 * @see abstract declaration in EE_messenger for details.
91
+	 */
92
+	protected function _set_valid_shortcodes()
93
+	{
94
+		$this->_valid_shortcodes = array();
95
+	}
96
+
97
+
98
+	/**
99
+	 * @see abstract declaration in EE_messenger for details.
100
+	 */
101
+	protected function _set_validator_config()
102
+	{
103
+		$this->_validator_config = array(
104
+			'subject' => array(
105
+				'shortcodes' => array('recipient_details', 'organization', 'event', 'ticket', 'venue', 'primary_registration_details', 'event_author', 'email', 'event_meta', 'recipient_list', 'transaction', 'datetime_list', 'datetime')
106
+			),
107
+			'content' => array(
108
+				'shortcodes' => array('recipient_details', 'organization', 'event', 'ticket', 'venue', 'primary_registration_details', 'event_author', 'email', 'event_meta', 'recipient_list', 'transaction', 'datetime_list', 'datetime')
109
+			),
110
+			'attendee_list' => array(
111
+				'shortcodes' => array('attendee', 'event_list', 'ticket_list'),
112
+				'required' => array('[ATTENDEE_LIST]')
113
+			),
114
+			'event_list' => array(
115
+				'shortcodes' => array('event', 'attendee_list', 'ticket_list', 'venue', 'datetime_list', 'attendee', 'primary_registration_details', 'primary_registration_list', 'event_author', 'recipient_details', 'recipient_list'),
116
+				'required' => array('[EVENT_LIST]')
117
+			),
118
+			'ticket_list' => array(
119
+				'shortcodes' => array('event_list', 'attendee_list', 'ticket', 'datetime_list', 'primary_registration_details', 'recipient_details'),
120
+				'required' => array('[TICKET_LIST]')
121
+			),
122
+			'datetime_list' => array(
123
+				'shortcodes' => array('datetime'),
124
+				'required' => array('[DATETIME_LIST]')
125
+			),
126
+		);
127
+	}
128
+
129
+
130
+	/**
131
+	 * Takes care of enqueuing any necessary scripts or styles for the page.  A do_action() so message types using this messenger can add their own js.
132
+	 *
133
+	 * @return void.
134
+	 */
135
+	public function enqueue_scripts_styles()
136
+	{
137
+		parent::enqueue_scripts_styles();
138
+		do_action('AHEE__EE_Pdf_messenger__enqueue_scripts_styles');
139
+	}
140
+
141
+
142
+	/**
143
+	 * _set_template_fields
144
+	 * This sets up the fields that a messenger requires for the message to go out.
145
+	 *
146
+	 * @access  protected
147
+	 * @return void
148
+	 */
149
+	protected function _set_template_fields()
150
+	{
151
+		// any extra template fields that are NOT used by the messenger but will get used by a messenger field for shortcode replacement get added to the 'extra' key in an associated array indexed by the messenger field they relate to.  This is important for the Messages_admin to know what fields to display to the user.  Also, notice that the "values" are equal to the field type that messages admin will use to know what kind of field to display. The values ALSO have one index labeled "shortcode".  the values in that array indicate which ACTUAL SHORTCODE (i.e. [SHORTCODE]) is required in order for this extra field to be displayed.  If the required shortcode isn't part of the shortcodes array then the field is not needed and will not be displayed/parsed.
152
+		$this->_template_fields = array(
153
+			'subject' => array(
154
+				'input' => 'text',
155
+				'label' => __('Page Title', 'event_espresso'),
156
+				'type' => 'string',
157
+				'required' => true,
158
+				'validation' => true,
159
+				'css_class' => 'large-text',
160
+				'format' => '%s'
161
+			),
162
+			'content' => '', // left empty b/c it is in the "extra array" but messenger still needs needs to know this is a field.
163
+			'extra' => array(
164
+				'content' => array(
165
+					'main' => array(
166
+						'input' => 'wp_editor',
167
+						'label' => __('Main Content', 'event_espresso'),
168
+						'type' => 'string',
169
+						'required' => true,
170
+						'validation' => true,
171
+						'format' => '%s',
172
+						'rows' => '15'
173
+					),
174
+					'event_list' => array(
175
+						'input' => 'wp_editor',
176
+						'label' => '[EVENT_LIST]',
177
+						'type' => 'string',
178
+						'required' => true,
179
+						'validation' => true,
180
+						'format' => '%s',
181
+						'rows' => '15',
182
+						'shortcodes_required' => array('[EVENT_LIST]')
183
+					),
184
+					'attendee_list' => array(
185
+						'input' => 'textarea',
186
+						'label' => '[ATTENDEE_LIST]',
187
+						'type' => 'string',
188
+						'required' => true,
189
+						'validation' => true,
190
+						'format' => '%s',
191
+						'css_class' => 'large-text',
192
+						'rows' => '5',
193
+						'shortcodes_required' => array('[ATTENDEE_LIST]')
194
+					),
195
+					'ticket_list' => array(
196
+						'input' => 'textarea',
197
+						'label' => '[TICKET_LIST]',
198
+						'type' => 'string',
199
+						'required' => true,
200
+						'validation' => true,
201
+						'format' => '%s',
202
+						'css_class' => 'large-text',
203
+						'rows' => '10',
204
+						'shortcodes_required' => array('[TICKET_LIST]')
205
+					),
206
+					'datetime_list' => array(
207
+						'input' => 'textarea',
208
+						'label' => '[DATETIME_LIST]',
209
+						'type' => 'string',
210
+						'required' => true,
211
+						'validation' => true,
212
+						'format' => '%s',
213
+						'css_class' => 'large-text',
214
+						'rows' => '10',
215
+						'shortcodes_required' => array('[DATETIME_LIST]')
216
+					)
217
+				)
218
+			)
219
+		);
220
+	}
221
+
222
+
223
+	/**
224
+	 * @see definition of this method in parent
225
+	 *
226
+	 * @since 4.5.0
227
+	 *
228
+	 */
229
+	protected function _set_default_message_types()
230
+	{
231
+		// note currently PDF is only a secondary messenger so it never has any associated message types.
232
+		$this->_default_message_types = array();
233
+	}
234
+
235
+
236
+	/**
237
+	 * @see definition of this method in parent
238
+	 *
239
+	 * @since 4.5.0
240
+	 */
241
+	protected function _set_valid_message_types()
242
+	{
243
+		$this->_valid_message_types = array();
244
+	}
245
+
246
+
247
+	/**
248
+	 * Generates html version of the message content and then sends it to the pdf generator.
249
+	 *
250
+	 *
251
+	 * @since 4.5.0
252
+	 *
253
+	 * @return string.
254
+	 */
255
+	protected function _send_message()
256
+	{
257
+		$this->_template_args = array(
258
+			'page_title' => $this->_subject,
259
+			'base_css' => $this->get_variation($this->_tmp_pack, $this->_incoming_message_type->name, true, 'base', $this->_variation),
260
+			'print_css' => $this->get_variation($this->_tmp_pack, $this->_incoming_message_type->name, true, 'print', $this->_variation),
261
+			'main_css' => $this->get_variation($this->_tmp_pack, $this->_incoming_message_type->name, true, 'main', $this->_variation),
262
+			'extra_css' => EE_LIBRARIES_URL . 'messages/defaults/default/variations/pdf_base_default.css',
263
+			'main_body' => apply_filters('FHEE__EE_Pdf_messenger___send_message__main_body', wpautop($this->_content), $this->_content)
264
+		);
265
+		$this->_deregister_wp_hooks();
266
+		add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts_styles'));
267
+		$content = $this->_get_main_template();
268 268
 //      die( $content );
269
-        $this->_do_pdf($content);
270
-        exit(0);
271
-    }
272
-
273
-
274
-    /**
275
-     * The purpose of this function is to de register all actions hooked into wp_head and wp_footer so that it doesn't interfere with our templates.  If users want to add any custom styles or scripts they must use the AHEE__EE_Pdf_messenger__enqueue_scripts_styles hook.
276
-     *
277
-     * @since 4.5.0
278
-     *
279
-     * @return void
280
-     */
281
-    protected function _deregister_wp_hooks()
282
-    {
283
-        remove_all_actions('wp_head');
284
-        remove_all_actions('wp_footer');
285
-        remove_all_actions('wp_print_footer_scripts');
286
-        remove_all_actions('wp_enqueue_scripts');
287
-        global $wp_scripts, $wp_styles;
288
-        $wp_scripts = $wp_styles = array();
289
-
290
-        // just add back in wp_enqueue_scripts and wp_print_footer_scripts cause that's all we want to load.
291
-        add_action('wp_head', 'wp_enqueue_scripts');
292
-        add_action('wp_footer', 'wp_print_footer_scripts');
293
-        add_action('wp_print_footer_scripts', '_wp_footer_scripts');
294
-    }
295
-
296
-
297
-    /**
298
-     * Overwrite parent _get_main_template for pdf purposes.
299
-     *
300
-     * @since  4.5.0
301
-     *
302
-     * @param bool $preview
303
-     * @return string
304
-     */
305
-    protected function _get_main_template($preview = false)
306
-    {
307
-        $wrapper_template = $this->_tmp_pack->get_wrapper('html', 'main');
308
-        // add message type to template_args
309
-        $this->_template_args['message_type'] = $this->_incoming_message_type;
310
-        return EEH_Template::display_template($wrapper_template, $this->_template_args, true);
311
-    }
312
-
313
-
314
-    /**
315
-     * This takes care of loading the dompdf library and generating the actual pdf
316
-     *
317
-     * @param string $content This is the generated html content being converted into a pdf.
318
-     *
319
-     * @return void
320
-     */
321
-    protected function _do_pdf($content = '')
322
-    {
323
-        $invoice_name = $this->_subject;
324
-
325
-        // only load dompdf if nobody else has yet...
326
-        if (! class_exists('Dompdf\Dompdf')) {
327
-            require_once(EE_THIRD_PARTY . 'dompdf/src/Autoloader.php');
328
-            Dompdf\Autoloader::register();
329
-        }
330
-        $options = new Dompdf\Options();
331
-        $options->set('isRemoteEnabled', true);
332
-        $options->set('isJavascriptEnabled', false);
333
-        if (defined('DOMPDF_FONT_DIR')) {
334
-            $options->setFontDir(DOMPDF_FONT_DIR);
335
-            $options->setFontCache(DOMPDF_FONT_DIR);
336
-        }
337
-        // Allow changing the paper size.
338
-        if (defined('DOMPDF_DEFAULT_PAPER_SIZE')) {
339
-            $options->set('defaultPaperSize', DOMPDF_DEFAULT_PAPER_SIZE);
340
-        }
341
-        $dompdf = new Dompdf\Dompdf($options);
342
-        // Remove all spaces between HTML tags
343
-        $content = preg_replace('/>\s+</', '><', $content);
344
-        $dompdf->loadHtml($content);
345
-        $dompdf->render();
346
-        // forcing the browser to open a download dialog.
347
-        $dompdf->stream($invoice_name . ".pdf", array('Attachment' => true));
348
-    }
349
-
350
-
351
-    /**
352
-     * @return string
353
-     */
354
-    protected function _preview()
355
-    {
356
-        return $this->_send_message();
357
-    }
358
-
359
-
360
-    protected function _set_admin_settings_fields()
361
-    {
362
-    }
269
+		$this->_do_pdf($content);
270
+		exit(0);
271
+	}
272
+
273
+
274
+	/**
275
+	 * The purpose of this function is to de register all actions hooked into wp_head and wp_footer so that it doesn't interfere with our templates.  If users want to add any custom styles or scripts they must use the AHEE__EE_Pdf_messenger__enqueue_scripts_styles hook.
276
+	 *
277
+	 * @since 4.5.0
278
+	 *
279
+	 * @return void
280
+	 */
281
+	protected function _deregister_wp_hooks()
282
+	{
283
+		remove_all_actions('wp_head');
284
+		remove_all_actions('wp_footer');
285
+		remove_all_actions('wp_print_footer_scripts');
286
+		remove_all_actions('wp_enqueue_scripts');
287
+		global $wp_scripts, $wp_styles;
288
+		$wp_scripts = $wp_styles = array();
289
+
290
+		// just add back in wp_enqueue_scripts and wp_print_footer_scripts cause that's all we want to load.
291
+		add_action('wp_head', 'wp_enqueue_scripts');
292
+		add_action('wp_footer', 'wp_print_footer_scripts');
293
+		add_action('wp_print_footer_scripts', '_wp_footer_scripts');
294
+	}
295
+
296
+
297
+	/**
298
+	 * Overwrite parent _get_main_template for pdf purposes.
299
+	 *
300
+	 * @since  4.5.0
301
+	 *
302
+	 * @param bool $preview
303
+	 * @return string
304
+	 */
305
+	protected function _get_main_template($preview = false)
306
+	{
307
+		$wrapper_template = $this->_tmp_pack->get_wrapper('html', 'main');
308
+		// add message type to template_args
309
+		$this->_template_args['message_type'] = $this->_incoming_message_type;
310
+		return EEH_Template::display_template($wrapper_template, $this->_template_args, true);
311
+	}
312
+
313
+
314
+	/**
315
+	 * This takes care of loading the dompdf library and generating the actual pdf
316
+	 *
317
+	 * @param string $content This is the generated html content being converted into a pdf.
318
+	 *
319
+	 * @return void
320
+	 */
321
+	protected function _do_pdf($content = '')
322
+	{
323
+		$invoice_name = $this->_subject;
324
+
325
+		// only load dompdf if nobody else has yet...
326
+		if (! class_exists('Dompdf\Dompdf')) {
327
+			require_once(EE_THIRD_PARTY . 'dompdf/src/Autoloader.php');
328
+			Dompdf\Autoloader::register();
329
+		}
330
+		$options = new Dompdf\Options();
331
+		$options->set('isRemoteEnabled', true);
332
+		$options->set('isJavascriptEnabled', false);
333
+		if (defined('DOMPDF_FONT_DIR')) {
334
+			$options->setFontDir(DOMPDF_FONT_DIR);
335
+			$options->setFontCache(DOMPDF_FONT_DIR);
336
+		}
337
+		// Allow changing the paper size.
338
+		if (defined('DOMPDF_DEFAULT_PAPER_SIZE')) {
339
+			$options->set('defaultPaperSize', DOMPDF_DEFAULT_PAPER_SIZE);
340
+		}
341
+		$dompdf = new Dompdf\Dompdf($options);
342
+		// Remove all spaces between HTML tags
343
+		$content = preg_replace('/>\s+</', '><', $content);
344
+		$dompdf->loadHtml($content);
345
+		$dompdf->render();
346
+		// forcing the browser to open a download dialog.
347
+		$dompdf->stream($invoice_name . ".pdf", array('Attachment' => true));
348
+	}
349
+
350
+
351
+	/**
352
+	 * @return string
353
+	 */
354
+	protected function _preview()
355
+	{
356
+		return $this->_send_message();
357
+	}
358
+
359
+
360
+	protected function _set_admin_settings_fields()
361
+	{
362
+	}
363 363
 }
Please login to merge, or discard this patch.
core/services/blocks/BlockRenderer.php 2 patches
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -14,44 +14,44 @@
 block discarded – undo
14 14
 abstract class BlockRenderer implements BlockRendererInterface
15 15
 {
16 16
 
17
-    /**
18
-     * @var DomainInterface
19
-     */
20
-    protected $domain;
21
-
22
-    /**
23
-     * @var string
24
-     */
25
-    private $template_root_path;
26
-
27
-
28
-    /**
29
-     * BlockRenderer constructor.
30
-     *
31
-     * @param DomainInterface $domain
32
-     */
33
-    public function __construct(DomainInterface $domain)
34
-    {
35
-        $this->domain = $domain;
36
-        $this->setTemplateRootPath();
37
-    }
38
-
39
-
40
-    /**
41
-     * Sets the root path to the main block template.
42
-     */
43
-    private function setTemplateRootPath()
44
-    {
45
-        $this->template_root_path = $this->domain->pluginPath() . 'ui/blocks/';
46
-    }
47
-
48
-
49
-    /**
50
-     * Exposes the root path for the main block template.
51
-     * @return string
52
-     */
53
-    public function templateRootPath()
54
-    {
55
-        return $this->template_root_path;
56
-    }
17
+	/**
18
+	 * @var DomainInterface
19
+	 */
20
+	protected $domain;
21
+
22
+	/**
23
+	 * @var string
24
+	 */
25
+	private $template_root_path;
26
+
27
+
28
+	/**
29
+	 * BlockRenderer constructor.
30
+	 *
31
+	 * @param DomainInterface $domain
32
+	 */
33
+	public function __construct(DomainInterface $domain)
34
+	{
35
+		$this->domain = $domain;
36
+		$this->setTemplateRootPath();
37
+	}
38
+
39
+
40
+	/**
41
+	 * Sets the root path to the main block template.
42
+	 */
43
+	private function setTemplateRootPath()
44
+	{
45
+		$this->template_root_path = $this->domain->pluginPath() . 'ui/blocks/';
46
+	}
47
+
48
+
49
+	/**
50
+	 * Exposes the root path for the main block template.
51
+	 * @return string
52
+	 */
53
+	public function templateRootPath()
54
+	{
55
+		return $this->template_root_path;
56
+	}
57 57
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -42,7 +42,7 @@
 block discarded – undo
42 42
      */
43 43
     private function setTemplateRootPath()
44 44
     {
45
-        $this->template_root_path = $this->domain->pluginPath() . 'ui/blocks/';
45
+        $this->template_root_path = $this->domain->pluginPath().'ui/blocks/';
46 46
     }
47 47
 
48 48
 
Please login to merge, or discard this patch.
ui/blocks/event-attendees.php 2 patches
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -11,30 +11,30 @@
 block discarded – undo
11 11
 <div id="ee-block-event-attendees" class="ee-core-blocks event-espresso-blocks event-attendees">
12 12
     <ul>
13 13
         <?php
14
-        foreach ($attendees as $attendee) {
15
-            $gravatar = $attributes['showGravatar']
16
-                ? get_avatar_url(
17
-                    $attendee->email(),
18
-                    array(
19
-                        'default' => 'mm',
20
-                        'width'   => $attributes['avatarSize'],
21
-                        'height'  => $attributes['avatarSize']
22
-                    )
23
-                )
24
-                : '';
25
-            $gravatar_class = $attributes['avatarClass']
26
-                ? $attributes['avatarClass'] . ' contact-avatar-img avatar'
27
-                : 'contact-avatar-img avatar';
28
-            $gravatar = $gravatar !== ''
29
-                ? '<div class="contact-image-wrap-div">'
30
-                    . '<img class="' . $gravatar_class . '"'
31
-                    . ' width="' . $attributes['avatarSize'] . '"'
32
-                    . ' height="' . $attributes['avatarSize'] . '"'
33
-                    . ' src="' . $gravatar . '" alt="contact avatar">'
34
-                    . '</div>'
35
-                : '';
36
-            echo "<li>{$gravatar}<span>{$attendee->full_name()}</span>";
37
-        }
38
-        ?>
14
+		foreach ($attendees as $attendee) {
15
+			$gravatar = $attributes['showGravatar']
16
+				? get_avatar_url(
17
+					$attendee->email(),
18
+					array(
19
+						'default' => 'mm',
20
+						'width'   => $attributes['avatarSize'],
21
+						'height'  => $attributes['avatarSize']
22
+					)
23
+				)
24
+				: '';
25
+			$gravatar_class = $attributes['avatarClass']
26
+				? $attributes['avatarClass'] . ' contact-avatar-img avatar'
27
+				: 'contact-avatar-img avatar';
28
+			$gravatar = $gravatar !== ''
29
+				? '<div class="contact-image-wrap-div">'
30
+					. '<img class="' . $gravatar_class . '"'
31
+					. ' width="' . $attributes['avatarSize'] . '"'
32
+					. ' height="' . $attributes['avatarSize'] . '"'
33
+					. ' src="' . $gravatar . '" alt="contact avatar">'
34
+					. '</div>'
35
+				: '';
36
+			echo "<li>{$gravatar}<span>{$attendee->full_name()}</span>";
37
+		}
38
+		?>
39 39
     </ul>
40 40
 </div>
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -23,14 +23,14 @@
 block discarded – undo
23 23
                 )
24 24
                 : '';
25 25
             $gravatar_class = $attributes['avatarClass']
26
-                ? $attributes['avatarClass'] . ' contact-avatar-img avatar'
26
+                ? $attributes['avatarClass'].' contact-avatar-img avatar'
27 27
                 : 'contact-avatar-img avatar';
28 28
             $gravatar = $gravatar !== ''
29 29
                 ? '<div class="contact-image-wrap-div">'
30
-                    . '<img class="' . $gravatar_class . '"'
31
-                    . ' width="' . $attributes['avatarSize'] . '"'
32
-                    . ' height="' . $attributes['avatarSize'] . '"'
33
-                    . ' src="' . $gravatar . '" alt="contact avatar">'
30
+                    . '<img class="'.$gravatar_class.'"'
31
+                    . ' width="'.$attributes['avatarSize'].'"'
32
+                    . ' height="'.$attributes['avatarSize'].'"'
33
+                    . ' src="'.$gravatar.'" alt="contact avatar">'
34 34
                     . '</div>'
35 35
                 : '';
36 36
             echo "<li>{$gravatar}<span>{$attendee->full_name()}</span>";
Please login to merge, or discard this patch.
admin_pages/transactions/Transactions_Admin_Page.core.php 1 patch
Indentation   +2499 added lines, -2499 removed lines patch added patch discarded remove patch
@@ -14,2503 +14,2503 @@
 block discarded – undo
14 14
 class Transactions_Admin_Page extends EE_Admin_Page
15 15
 {
16 16
 
17
-    /**
18
-     * @var EE_Transaction
19
-     */
20
-    private $_transaction;
21
-
22
-    /**
23
-     * @var EE_Session
24
-     */
25
-    private $_session;
26
-
27
-    /**
28
-     * @var array $_txn_status
29
-     */
30
-    private static $_txn_status;
31
-
32
-    /**
33
-     * @var array $_pay_status
34
-     */
35
-    private static $_pay_status;
36
-
37
-    /**
38
-     * @var array $_existing_reg_payment_REG_IDs
39
-     */
40
-    protected $_existing_reg_payment_REG_IDs = null;
41
-
42
-
43
-    /**
44
-     * @Constructor
45
-     * @access public
46
-     * @param bool $routing
47
-     * @throws EE_Error
48
-     * @throws InvalidArgumentException
49
-     * @throws ReflectionException
50
-     * @throws InvalidDataTypeException
51
-     * @throws InvalidInterfaceException
52
-     */
53
-    public function __construct($routing = true)
54
-    {
55
-        parent::__construct($routing);
56
-    }
57
-
58
-
59
-    /**
60
-     *    _init_page_props
61
-     *
62
-     * @return void
63
-     */
64
-    protected function _init_page_props()
65
-    {
66
-        $this->page_slug = TXN_PG_SLUG;
67
-        $this->page_label = esc_html__('Transactions', 'event_espresso');
68
-        $this->_admin_base_url = TXN_ADMIN_URL;
69
-        $this->_admin_base_path = TXN_ADMIN;
70
-    }
71
-
72
-
73
-    /**
74
-     *    _ajax_hooks
75
-     *
76
-     * @return void
77
-     */
78
-    protected function _ajax_hooks()
79
-    {
80
-        add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
81
-        add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
82
-        add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
83
-    }
84
-
85
-
86
-    /**
87
-     *    _define_page_props
88
-     *
89
-     * @return void
90
-     */
91
-    protected function _define_page_props()
92
-    {
93
-        $this->_admin_page_title = $this->page_label;
94
-        $this->_labels = array(
95
-            'buttons' => array(
96
-                'add'    => esc_html__('Add New Transaction', 'event_espresso'),
97
-                'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
98
-                'delete' => esc_html__('Delete Transaction', 'event_espresso'),
99
-            ),
100
-        );
101
-    }
102
-
103
-
104
-    /**
105
-     *        grab url requests and route them
106
-     *
107
-     * @access private
108
-     * @return void
109
-     * @throws EE_Error
110
-     * @throws InvalidArgumentException
111
-     * @throws InvalidDataTypeException
112
-     * @throws InvalidInterfaceException
113
-     */
114
-    public function _set_page_routes()
115
-    {
116
-
117
-        $this->_set_transaction_status_array();
118
-
119
-        $txn_id = ! empty($this->_req_data['TXN_ID'])
120
-                  && ! is_array($this->_req_data['TXN_ID'])
121
-            ? $this->_req_data['TXN_ID']
122
-            : 0;
123
-
124
-        $this->_page_routes = array(
125
-
126
-            'default' => array(
127
-                'func'       => '_transactions_overview_list_table',
128
-                'capability' => 'ee_read_transactions',
129
-            ),
130
-
131
-            'view_transaction' => array(
132
-                'func'       => '_transaction_details',
133
-                'capability' => 'ee_read_transaction',
134
-                'obj_id'     => $txn_id,
135
-            ),
136
-
137
-            'send_payment_reminder' => array(
138
-                'func'       => '_send_payment_reminder',
139
-                'noheader'   => true,
140
-                'capability' => 'ee_send_message',
141
-            ),
142
-
143
-            'espresso_apply_payment' => array(
144
-                'func'       => 'apply_payments_or_refunds',
145
-                'noheader'   => true,
146
-                'capability' => 'ee_edit_payments',
147
-            ),
148
-
149
-            'espresso_apply_refund' => array(
150
-                'func'       => 'apply_payments_or_refunds',
151
-                'noheader'   => true,
152
-                'capability' => 'ee_edit_payments',
153
-            ),
154
-
155
-            'espresso_delete_payment' => array(
156
-                'func'       => 'delete_payment',
157
-                'noheader'   => true,
158
-                'capability' => 'ee_delete_payments',
159
-            ),
160
-
161
-        );
162
-    }
163
-
164
-
165
-    protected function _set_page_config()
166
-    {
167
-        $this->_page_config = array(
168
-            'default'          => array(
169
-                'nav'           => array(
170
-                    'label' => esc_html__('Overview', 'event_espresso'),
171
-                    'order' => 10,
172
-                ),
173
-                'list_table'    => 'EE_Admin_Transactions_List_Table',
174
-                'help_tabs'     => array(
175
-                    'transactions_overview_help_tab'                       => array(
176
-                        'title'    => esc_html__('Transactions Overview', 'event_espresso'),
177
-                        'filename' => 'transactions_overview',
178
-                    ),
179
-                    'transactions_overview_table_column_headings_help_tab' => array(
180
-                        'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
181
-                        'filename' => 'transactions_overview_table_column_headings',
182
-                    ),
183
-                    'transactions_overview_views_filters_help_tab'         => array(
184
-                        'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
185
-                        'filename' => 'transactions_overview_views_filters_search',
186
-                    ),
187
-                ),
188
-                'help_tour'     => array('Transactions_Overview_Help_Tour'),
189
-                /**
190
-                 * commented out because currently we are not displaying tips for transaction list table status but this
191
-                 * may change in a later iteration so want to keep the code for then.
192
-                 */
193
-                // 'qtips' => array( 'Transactions_List_Table_Tips' ),
194
-                'require_nonce' => false,
195
-            ),
196
-            'view_transaction' => array(
197
-                'nav'       => array(
198
-                    'label'      => esc_html__('View Transaction', 'event_espresso'),
199
-                    'order'      => 5,
200
-                    'url'        => isset($this->_req_data['TXN_ID'])
201
-                        ? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url)
202
-                        : $this->_admin_base_url,
203
-                    'persistent' => false,
204
-                ),
205
-                'help_tabs' => array(
206
-                    'transactions_view_transaction_help_tab'                                              => array(
207
-                        'title'    => esc_html__('View Transaction', 'event_espresso'),
208
-                        'filename' => 'transactions_view_transaction',
209
-                    ),
210
-                    'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
211
-                        'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
212
-                        'filename' => 'transactions_view_transaction_transaction_details_table',
213
-                    ),
214
-                    'transactions_view_transaction_attendees_registered_help_tab'                         => array(
215
-                        'title'    => esc_html__('Attendees Registered', 'event_espresso'),
216
-                        'filename' => 'transactions_view_transaction_attendees_registered',
217
-                    ),
218
-                    'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
219
-                        'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
220
-                        'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
221
-                    ),
222
-                ),
223
-                'qtips'     => array('Transaction_Details_Tips'),
224
-                'help_tour' => array('Transaction_Details_Help_Tour'),
225
-                'metaboxes' => array('_transaction_details_metaboxes'),
226
-
227
-                'require_nonce' => false,
228
-            ),
229
-        );
230
-    }
231
-
232
-
233
-    /**
234
-     * The below methods aren't used by this class currently
235
-     */
236
-    protected function _add_screen_options()
237
-    {
238
-        // noop
239
-    }
240
-
241
-    protected function _add_feature_pointers()
242
-    {
243
-        // noop
244
-    }
245
-
246
-    public function admin_init()
247
-    {
248
-        // IF a registration was JUST added via the admin...
249
-        if (isset(
250
-            $this->_req_data['redirect_from'],
251
-            $this->_req_data['EVT_ID'],
252
-            $this->_req_data['event_name']
253
-        )) {
254
-            // then set a cookie so that we can block any attempts to use
255
-            // the back button as a way to enter another registration.
256
-            setcookie(
257
-                'ee_registration_added',
258
-                $this->_req_data['EVT_ID'],
259
-                time() + WEEK_IN_SECONDS,
260
-                '/'
261
-            );
262
-            // and update the global
263
-            $_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
264
-        }
265
-        EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
266
-            'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
267
-            'event_espresso'
268
-        );
269
-        EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__(
270
-            'An error occurred! Please refresh the page and try again.',
271
-            'event_espresso'
272
-        );
273
-        EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status;
274
-        EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status;
275
-        EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso');
276
-        EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__(
277
-            'This transaction has been overpaid ! Payments Total',
278
-            'event_espresso'
279
-        );
280
-    }
281
-
282
-    public function admin_notices()
283
-    {
284
-        // noop
285
-    }
286
-
287
-    public function admin_footer_scripts()
288
-    {
289
-        // noop
290
-    }
291
-
292
-
293
-    /**
294
-     * _set_transaction_status_array
295
-     * sets list of transaction statuses
296
-     *
297
-     * @access private
298
-     * @return void
299
-     * @throws EE_Error
300
-     * @throws InvalidArgumentException
301
-     * @throws InvalidDataTypeException
302
-     * @throws InvalidInterfaceException
303
-     */
304
-    private function _set_transaction_status_array()
305
-    {
306
-        self::$_txn_status = EEM_Transaction::instance()->status_array(true);
307
-    }
308
-
309
-
310
-    /**
311
-     * get_transaction_status_array
312
-     * return the transaction status array for wp_list_table
313
-     *
314
-     * @access public
315
-     * @return array
316
-     */
317
-    public function get_transaction_status_array()
318
-    {
319
-        return self::$_txn_status;
320
-    }
321
-
322
-
323
-    /**
324
-     *    get list of payment statuses
325
-     *
326
-     * @access private
327
-     * @return void
328
-     * @throws EE_Error
329
-     * @throws InvalidArgumentException
330
-     * @throws InvalidDataTypeException
331
-     * @throws InvalidInterfaceException
332
-     */
333
-    private function _get_payment_status_array()
334
-    {
335
-        self::$_pay_status = EEM_Payment::instance()->status_array(true);
336
-        $this->_template_args['payment_status'] = self::$_pay_status;
337
-    }
338
-
339
-
340
-    /**
341
-     *    _add_screen_options_default
342
-     *
343
-     * @access protected
344
-     * @return void
345
-     * @throws InvalidArgumentException
346
-     * @throws InvalidDataTypeException
347
-     * @throws InvalidInterfaceException
348
-     */
349
-    protected function _add_screen_options_default()
350
-    {
351
-        $this->_per_page_screen_option();
352
-    }
353
-
354
-
355
-    /**
356
-     * load_scripts_styles
357
-     *
358
-     * @access public
359
-     * @return void
360
-     */
361
-    public function load_scripts_styles()
362
-    {
363
-        // enqueue style
364
-        wp_register_style(
365
-            'espresso_txn',
366
-            TXN_ASSETS_URL . 'espresso_transactions_admin.css',
367
-            array(),
368
-            EVENT_ESPRESSO_VERSION
369
-        );
370
-        wp_enqueue_style('espresso_txn');
371
-        // scripts
372
-        wp_register_script(
373
-            'espresso_txn',
374
-            TXN_ASSETS_URL . 'espresso_transactions_admin.js',
375
-            array(
376
-                'ee_admin_js',
377
-                'ee-datepicker',
378
-                'jquery-ui-datepicker',
379
-                'jquery-ui-draggable',
380
-                'ee-dialog',
381
-                'ee-accounting',
382
-                'ee-serialize-full-array',
383
-            ),
384
-            EVENT_ESPRESSO_VERSION,
385
-            true
386
-        );
387
-        wp_enqueue_script('espresso_txn');
388
-    }
389
-
390
-
391
-    /**
392
-     *    load_scripts_styles_view_transaction
393
-     *
394
-     * @access public
395
-     * @return void
396
-     */
397
-    public function load_scripts_styles_view_transaction()
398
-    {
399
-        // styles
400
-        wp_enqueue_style('espresso-ui-theme');
401
-    }
402
-
403
-
404
-    /**
405
-     *    load_scripts_styles_default
406
-     *
407
-     * @access public
408
-     * @return void
409
-     */
410
-    public function load_scripts_styles_default()
411
-    {
412
-        // styles
413
-        wp_enqueue_style('espresso-ui-theme');
414
-    }
415
-
416
-
417
-    /**
418
-     *    _set_list_table_views_default
419
-     *
420
-     * @access protected
421
-     * @return void
422
-     */
423
-    protected function _set_list_table_views_default()
424
-    {
425
-        $this->_views = array(
426
-            'all'       => array(
427
-                'slug'  => 'all',
428
-                'label' => esc_html__('View All Transactions', 'event_espresso'),
429
-                'count' => 0,
430
-            ),
431
-            'abandoned' => array(
432
-                'slug'  => 'abandoned',
433
-                'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
434
-                'count' => 0,
435
-            ),
436
-            'incomplete' => array(
437
-                'slug'  => 'incomplete',
438
-                'label' => esc_html__('Incomplete Transactions', 'event_espresso'),
439
-                'count' => 0,
440
-            )
441
-        );
442
-        if (/**
443
-             * Filters whether a link to the "Failed Transactions" list table
444
-             * appears on the Transactions Admin Page list table.
445
-             * List display can be turned back on via the following:
446
-             * add_filter(
447
-             *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
448
-             *     '__return_true'
449
-             * );
450
-             *
451
-             * @since 4.9.70.p
452
-             * @param boolean                 $display_failed_txns_list
453
-             * @param Transactions_Admin_Page $this
454
-             */
455
-            apply_filters(
456
-                'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
457
-                false,
458
-                $this
459
-            )
460
-        ) {
461
-            $this->_views['failed'] = array(
462
-                'slug'  => 'failed',
463
-                'label' => esc_html__('Failed Transactions', 'event_espresso'),
464
-                'count' => 0,
465
-            );
466
-        }
467
-    }
468
-
469
-
470
-    /**
471
-     * _set_transaction_object
472
-     * This sets the _transaction property for the transaction details screen
473
-     *
474
-     * @access private
475
-     * @return void
476
-     * @throws EE_Error
477
-     * @throws InvalidArgumentException
478
-     * @throws RuntimeException
479
-     * @throws InvalidDataTypeException
480
-     * @throws InvalidInterfaceException
481
-     * @throws ReflectionException
482
-     */
483
-    private function _set_transaction_object()
484
-    {
485
-        if ($this->_transaction instanceof EE_Transaction) {
486
-            return;
487
-        } //get out we've already set the object
488
-
489
-        $TXN_ID = ! empty($this->_req_data['TXN_ID'])
490
-            ? absint($this->_req_data['TXN_ID'])
491
-            : false;
492
-
493
-        // get transaction object
494
-        $this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
495
-        $this->_session = $this->_transaction instanceof EE_Transaction
496
-            ? $this->_transaction->get('TXN_session_data')
497
-            : null;
498
-        if ($this->_transaction instanceof EE_Transaction) {
499
-            $this->_transaction->verify_abandoned_transaction_status();
500
-        }
501
-
502
-        if (! $this->_transaction instanceof EE_Transaction) {
503
-            $error_msg = sprintf(
504
-                esc_html__(
505
-                    'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
506
-                    'event_espresso'
507
-                ),
508
-                $TXN_ID
509
-            );
510
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
511
-        }
512
-    }
513
-
514
-
515
-    /**
516
-     *    _transaction_legend_items
517
-     *
518
-     * @access protected
519
-     * @return array
520
-     * @throws EE_Error
521
-     * @throws InvalidArgumentException
522
-     * @throws ReflectionException
523
-     * @throws InvalidDataTypeException
524
-     * @throws InvalidInterfaceException
525
-     */
526
-    protected function _transaction_legend_items()
527
-    {
528
-        EE_Registry::instance()->load_helper('MSG_Template');
529
-        $items = array();
530
-
531
-        if (EE_Registry::instance()->CAP->current_user_can(
532
-            'ee_read_global_messages',
533
-            'view_filtered_messages'
534
-        )) {
535
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
536
-            if (is_array($related_for_icon)
537
-                && isset($related_for_icon['css_class'], $related_for_icon['label'])
538
-            ) {
539
-                $items['view_related_messages'] = array(
540
-                    'class' => $related_for_icon['css_class'],
541
-                    'desc'  => $related_for_icon['label'],
542
-                );
543
-            }
544
-        }
545
-
546
-        $items = apply_filters(
547
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
548
-            array_merge(
549
-                $items,
550
-                array(
551
-                    'view_details'          => array(
552
-                        'class' => 'dashicons dashicons-cart',
553
-                        'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
554
-                    ),
555
-                    'view_invoice'          => array(
556
-                        'class' => 'dashicons dashicons-media-spreadsheet',
557
-                        'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
558
-                    ),
559
-                    'view_receipt'          => array(
560
-                        'class' => 'dashicons dashicons-media-default',
561
-                        'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
562
-                    ),
563
-                    'view_registration'     => array(
564
-                        'class' => 'dashicons dashicons-clipboard',
565
-                        'desc'  => esc_html__('View Registration Details', 'event_espresso'),
566
-                    ),
567
-                    'payment_overview_link' => array(
568
-                        'class' => 'dashicons dashicons-money',
569
-                        'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
570
-                    ),
571
-                )
572
-            )
573
-        );
574
-
575
-        if (EE_Registry::instance()->CAP->current_user_can(
576
-            'ee_send_message',
577
-            'espresso_transactions_send_payment_reminder'
578
-        )) {
579
-            if (EEH_MSG_Template::is_mt_active('payment_reminder')) {
580
-                $items['send_payment_reminder'] = array(
581
-                    'class' => 'dashicons dashicons-email-alt',
582
-                    'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
583
-                );
584
-            } else {
585
-                $items['blank*'] = array(
586
-                    'class' => '',
587
-                    'desc'  => '',
588
-                );
589
-            }
590
-        } else {
591
-            $items['blank*'] = array(
592
-                'class' => '',
593
-                'desc'  => '',
594
-            );
595
-        }
596
-        $more_items = apply_filters(
597
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
598
-            array(
599
-                'overpaid'   => array(
600
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
601
-                    'desc'  => EEH_Template::pretty_status(
602
-                        EEM_Transaction::overpaid_status_code,
603
-                        false,
604
-                        'sentence'
605
-                    ),
606
-                ),
607
-                'complete'   => array(
608
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
609
-                    'desc'  => EEH_Template::pretty_status(
610
-                        EEM_Transaction::complete_status_code,
611
-                        false,
612
-                        'sentence'
613
-                    ),
614
-                ),
615
-                'incomplete' => array(
616
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
617
-                    'desc'  => EEH_Template::pretty_status(
618
-                        EEM_Transaction::incomplete_status_code,
619
-                        false,
620
-                        'sentence'
621
-                    ),
622
-                ),
623
-                'abandoned'  => array(
624
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
625
-                    'desc'  => EEH_Template::pretty_status(
626
-                        EEM_Transaction::abandoned_status_code,
627
-                        false,
628
-                        'sentence'
629
-                    ),
630
-                ),
631
-                'failed'     => array(
632
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
633
-                    'desc'  => EEH_Template::pretty_status(
634
-                        EEM_Transaction::failed_status_code,
635
-                        false,
636
-                        'sentence'
637
-                    ),
638
-                ),
639
-            )
640
-        );
641
-
642
-        return array_merge($items, $more_items);
643
-    }
644
-
645
-
646
-    /**
647
-     *    _transactions_overview_list_table
648
-     *
649
-     * @access protected
650
-     * @return void
651
-     * @throws DomainException
652
-     * @throws EE_Error
653
-     * @throws InvalidArgumentException
654
-     * @throws InvalidDataTypeException
655
-     * @throws InvalidInterfaceException
656
-     * @throws ReflectionException
657
-     */
658
-    protected function _transactions_overview_list_table()
659
-    {
660
-        $this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
661
-        $event = isset($this->_req_data['EVT_ID'])
662
-            ? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID'])
663
-            : null;
664
-        $this->_template_args['admin_page_header'] = $event instanceof EE_Event
665
-            ? sprintf(
666
-                esc_html__(
667
-                    '%sViewing Transactions for the Event: %s%s',
668
-                    'event_espresso'
669
-                ),
670
-                '<h3>',
671
-                '<a href="'
672
-                . EE_Admin_Page::add_query_args_and_nonce(
673
-                    array('action' => 'edit', 'post' => $event->ID()),
674
-                    EVENTS_ADMIN_URL
675
-                )
676
-                . '" title="'
677
-                . esc_attr__(
678
-                    'Click to Edit event',
679
-                    'event_espresso'
680
-                )
681
-                . '">' . $event->get('EVT_name') . '</a>',
682
-                '</h3>'
683
-            )
684
-            : '';
685
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items());
686
-        $this->display_admin_list_table_page_with_no_sidebar();
687
-    }
688
-
689
-
690
-    /**
691
-     *    _transaction_details
692
-     * generates HTML for the View Transaction Details Admin page
693
-     *
694
-     * @access protected
695
-     * @return void
696
-     * @throws DomainException
697
-     * @throws EE_Error
698
-     * @throws InvalidArgumentException
699
-     * @throws InvalidDataTypeException
700
-     * @throws InvalidInterfaceException
701
-     * @throws RuntimeException
702
-     * @throws ReflectionException
703
-     */
704
-    protected function _transaction_details()
705
-    {
706
-        do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
707
-
708
-        $this->_set_transaction_status_array();
709
-
710
-        $this->_template_args = array();
711
-        $this->_template_args['transactions_page'] = $this->_wp_page_slug;
712
-
713
-        $this->_set_transaction_object();
714
-
715
-        if (! $this->_transaction instanceof EE_Transaction) {
716
-            return;
717
-        }
718
-        $primary_registration = $this->_transaction->primary_registration();
719
-        $attendee = $primary_registration instanceof EE_Registration
720
-            ? $primary_registration->attendee()
721
-            : null;
722
-
723
-        $this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
724
-        $this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
725
-
726
-        $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
727
-        $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
728
-
729
-        $this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->get('STS_ID') ];
730
-        $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
731
-        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID');
732
-
733
-        $this->_template_args['grand_total'] = $this->_transaction->get('TXN_total');
734
-        $this->_template_args['total_paid'] = $this->_transaction->get('TXN_paid');
735
-
736
-        $amount_due = $this->_transaction->get('TXN_total') - $this->_transaction->get('TXN_paid');
737
-        $this->_template_args['amount_due'] = EEH_Template::format_currency(
738
-            $amount_due,
739
-            true
740
-        );
741
-        if (EE_Registry::instance()->CFG->currency->sign_b4) {
742
-            $this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
743
-                                                  . $this->_template_args['amount_due'];
744
-        } else {
745
-            $this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
746
-        }
747
-        $this->_template_args['amount_due_class'] = '';
748
-
749
-        if ($this->_transaction->get('TXN_paid') == $this->_transaction->get('TXN_total')) {
750
-            // paid in full
751
-            $this->_template_args['amount_due'] = false;
752
-        } elseif ($this->_transaction->get('TXN_paid') > $this->_transaction->get('TXN_total')) {
753
-            // overpaid
754
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
755
-        } elseif ($this->_transaction->get('TXN_total') > 0
756
-                  && $this->_transaction->get('TXN_paid') > 0
757
-        ) {
758
-            // monies owing
759
-            $this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
760
-        } elseif ($this->_transaction->get('TXN_total') > 0
761
-                  && $this->_transaction->get('TXN_paid') == 0
762
-        ) {
763
-            // no payments made yet
764
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
765
-        } elseif ($this->_transaction->get('TXN_total') == 0) {
766
-            // free event
767
-            $this->_template_args['amount_due'] = false;
768
-        }
769
-
770
-        $payment_method = $this->_transaction->payment_method();
771
-
772
-        $this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
773
-            ? $payment_method->admin_name()
774
-            : esc_html__('Unknown', 'event_espresso');
775
-
776
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
777
-        // link back to overview
778
-        $this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER'])
779
-            ? $_SERVER['HTTP_REFERER']
780
-            : TXN_ADMIN_URL;
781
-
782
-
783
-        // next link
784
-        $next_txn = $this->_transaction->next(
785
-            null,
786
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
787
-            'TXN_ID'
788
-        );
789
-        $this->_template_args['next_transaction'] = $next_txn
790
-            ? $this->_next_link(
791
-                EE_Admin_Page::add_query_args_and_nonce(
792
-                    array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
793
-                    TXN_ADMIN_URL
794
-                ),
795
-                'dashicons dashicons-arrow-right ee-icon-size-22'
796
-            )
797
-            : '';
798
-        // previous link
799
-        $previous_txn = $this->_transaction->previous(
800
-            null,
801
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
802
-            'TXN_ID'
803
-        );
804
-        $this->_template_args['previous_transaction'] = $previous_txn
805
-            ? $this->_previous_link(
806
-                EE_Admin_Page::add_query_args_and_nonce(
807
-                    array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
808
-                    TXN_ADMIN_URL
809
-                ),
810
-                'dashicons dashicons-arrow-left ee-icon-size-22'
811
-            )
812
-            : '';
813
-
814
-        // were we just redirected here after adding a new registration ???
815
-        if (isset(
816
-            $this->_req_data['redirect_from'],
817
-            $this->_req_data['EVT_ID'],
818
-            $this->_req_data['event_name']
819
-        )) {
820
-            if (EE_Registry::instance()->CAP->current_user_can(
821
-                'ee_edit_registrations',
822
-                'espresso_registrations_new_registration',
823
-                $this->_req_data['EVT_ID']
824
-            )) {
825
-                $this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
826
-                $this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
827
-                    array(
828
-                        'page'     => 'espresso_registrations',
829
-                        'action'   => 'new_registration',
830
-                        'return'   => 'default',
831
-                        'TXN_ID'   => $this->_transaction->ID(),
832
-                        'event_id' => $this->_req_data['EVT_ID'],
833
-                    ),
834
-                    REG_ADMIN_URL
835
-                );
836
-                $this->_admin_page_title .= '">';
837
-
838
-                $this->_admin_page_title .= sprintf(
839
-                    esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
840
-                    htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
841
-                );
842
-                $this->_admin_page_title .= '</a>';
843
-            }
844
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
845
-        }
846
-        // grab messages at the last second
847
-        $this->_template_args['notices'] = EE_Error::get_notices();
848
-        // path to template
849
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
850
-        $this->_template_args['admin_page_header'] = EEH_Template::display_template(
851
-            $template_path,
852
-            $this->_template_args,
853
-            true
854
-        );
855
-
856
-        // the details template wrapper
857
-        $this->display_admin_page_with_sidebar();
858
-    }
859
-
860
-
861
-    /**
862
-     *        _transaction_details_metaboxes
863
-     *
864
-     * @access protected
865
-     * @return void
866
-     * @throws EE_Error
867
-     * @throws InvalidArgumentException
868
-     * @throws InvalidDataTypeException
869
-     * @throws InvalidInterfaceException
870
-     * @throws RuntimeException
871
-     * @throws ReflectionException
872
-     */
873
-    protected function _transaction_details_metaboxes()
874
-    {
875
-
876
-        $this->_set_transaction_object();
877
-
878
-        if (! $this->_transaction instanceof EE_Transaction) {
879
-            return;
880
-        }
881
-        add_meta_box(
882
-            'edit-txn-details-mbox',
883
-            esc_html__('Transaction Details', 'event_espresso'),
884
-            array($this, 'txn_details_meta_box'),
885
-            $this->_wp_page_slug,
886
-            'normal',
887
-            'high'
888
-        );
889
-        add_meta_box(
890
-            'edit-txn-attendees-mbox',
891
-            esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
892
-            array($this, 'txn_attendees_meta_box'),
893
-            $this->_wp_page_slug,
894
-            'normal',
895
-            'high',
896
-            array('TXN_ID' => $this->_transaction->ID())
897
-        );
898
-        add_meta_box(
899
-            'edit-txn-registrant-mbox',
900
-            esc_html__('Primary Contact', 'event_espresso'),
901
-            array($this, 'txn_registrant_side_meta_box'),
902
-            $this->_wp_page_slug,
903
-            'side',
904
-            'high'
905
-        );
906
-        add_meta_box(
907
-            'edit-txn-billing-info-mbox',
908
-            esc_html__('Billing Information', 'event_espresso'),
909
-            array($this, 'txn_billing_info_side_meta_box'),
910
-            $this->_wp_page_slug,
911
-            'side',
912
-            'high'
913
-        );
914
-    }
915
-
916
-
917
-    /**
918
-     * Callback for transaction actions metabox.
919
-     *
920
-     * @param EE_Transaction|null $transaction
921
-     * @throws DomainException
922
-     * @throws EE_Error
923
-     * @throws InvalidArgumentException
924
-     * @throws InvalidDataTypeException
925
-     * @throws InvalidInterfaceException
926
-     * @throws ReflectionException
927
-     * @throws RuntimeException
928
-     */
929
-    public function getActionButtons(EE_Transaction $transaction = null)
930
-    {
931
-        $content = '';
932
-        $actions = array();
933
-        if (! $transaction instanceof EE_Transaction) {
934
-            return $content;
935
-        }
936
-        /** @var EE_Registration $primary_registration */
937
-        $primary_registration = $transaction->primary_registration();
938
-        $attendee = $primary_registration instanceof EE_Registration
939
-            ? $primary_registration->attendee()
940
-            : null;
941
-
942
-        if ($attendee instanceof EE_Attendee
943
-            && EE_Registry::instance()->CAP->current_user_can(
944
-                'ee_send_message',
945
-                'espresso_transactions_send_payment_reminder'
946
-            )
947
-        ) {
948
-            $actions['payment_reminder'] =
949
-                EEH_MSG_Template::is_mt_active('payment_reminder')
950
-                && $this->_transaction->get('STS_ID') !== EEM_Transaction::complete_status_code
951
-                && $this->_transaction->get('STS_ID') !== EEM_Transaction::overpaid_status_code
952
-                    ? EEH_Template::get_button_or_link(
953
-                        EE_Admin_Page::add_query_args_and_nonce(
954
-                            array(
955
-                                'action'      => 'send_payment_reminder',
956
-                                'TXN_ID'      => $this->_transaction->ID(),
957
-                                'redirect_to' => 'view_transaction',
958
-                            ),
959
-                            TXN_ADMIN_URL
960
-                        ),
961
-                        esc_html__(' Send Payment Reminder', 'event_espresso'),
962
-                        'button secondary-button',
963
-                        'dashicons dashicons-email-alt'
964
-                    )
965
-                    : '';
966
-        }
967
-
968
-        if ($primary_registration instanceof EE_Registration
969
-            && EEH_MSG_Template::is_mt_active('receipt')
970
-        ) {
971
-            $actions['receipt'] = EEH_Template::get_button_or_link(
972
-                $primary_registration->receipt_url(),
973
-                esc_html__('View Receipt', 'event_espresso'),
974
-                'button secondary-button',
975
-                'dashicons dashicons-media-default'
976
-            );
977
-        }
978
-
979
-        if ($primary_registration instanceof EE_Registration
980
-            && EEH_MSG_Template::is_mt_active('invoice')
981
-        ) {
982
-            $actions['invoice'] = EEH_Template::get_button_or_link(
983
-                $primary_registration->invoice_url(),
984
-                esc_html__('View Invoice', 'event_espresso'),
985
-                'button secondary-button',
986
-                'dashicons dashicons-media-spreadsheet'
987
-            );
988
-        }
989
-        $actions = array_filter(
990
-            apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
991
-        );
992
-        if ($actions) {
993
-            $content = '<ul>';
994
-            $content .= '<li>' . implode('</li><li>', $actions) . '</li>';
995
-            $content .= '</uL>';
996
-        }
997
-        return $content;
998
-    }
999
-
1000
-
1001
-    /**
1002
-     * txn_details_meta_box
1003
-     * generates HTML for the Transaction main meta box
1004
-     *
1005
-     * @return void
1006
-     * @throws DomainException
1007
-     * @throws EE_Error
1008
-     * @throws InvalidArgumentException
1009
-     * @throws InvalidDataTypeException
1010
-     * @throws InvalidInterfaceException
1011
-     * @throws RuntimeException
1012
-     * @throws ReflectionException
1013
-     */
1014
-    public function txn_details_meta_box()
1015
-    {
1016
-        $this->_set_transaction_object();
1017
-        $this->_template_args['TXN_ID'] = $this->_transaction->ID();
1018
-        $this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration
1019
-            ? $this->_transaction->primary_registration()->attendee()
1020
-            : null;
1021
-        $this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
1022
-            'ee_edit_payments',
1023
-            'apply_payment_or_refund_from_registration_details'
1024
-        );
1025
-        $this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1026
-            'ee_delete_payments',
1027
-            'delete_payment_from_registration_details'
1028
-        );
1029
-
1030
-        // get line table
1031
-        EEH_Autoloader::register_line_item_display_autoloaders();
1032
-        $Line_Item_Display = new EE_Line_Item_Display(
1033
-            'admin_table',
1034
-            'EE_Admin_Table_Line_Item_Display_Strategy'
1035
-        );
1036
-        $this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1037
-            $this->_transaction->total_line_item()
1038
-        );
1039
-        $this->_template_args['REG_code'] = $this->_transaction->get_first_related('Registration')
1040
-                                                               ->get('REG_code');
1041
-
1042
-        // process taxes
1043
-        $taxes = $this->_transaction->get_many_related(
1044
-            'Line_Item',
1045
-            array(array('LIN_type' => EEM_Line_Item::type_tax))
1046
-        );
1047
-        $this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1048
-
1049
-        $this->_template_args['grand_total'] = EEH_Template::format_currency(
1050
-            $this->_transaction->get('TXN_total'),
1051
-            false,
1052
-            false
1053
-        );
1054
-        $this->_template_args['grand_raw_total'] = $this->_transaction->get('TXN_total');
1055
-        $this->_template_args['TXN_status'] = $this->_transaction->get('STS_ID');
1056
-
1057
-        // process payment details
1058
-        $payments = $this->_transaction->get_many_related('Payment');
1059
-        if (! empty($payments)) {
1060
-            $this->_template_args['payments'] = $payments;
1061
-            $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1062
-        } else {
1063
-            $this->_template_args['payments'] = false;
1064
-            $this->_template_args['existing_reg_payments'] = array();
1065
-        }
1066
-
1067
-        $this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
1068
-        $this->_template_args['delete_payment_url'] = add_query_arg(
1069
-            array('action' => 'espresso_delete_payment'),
1070
-            TXN_ADMIN_URL
1071
-        );
1072
-
1073
-        if (isset($txn_details['invoice_number'])) {
1074
-            $this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1075
-            $this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1076
-                'Invoice Number',
1077
-                'event_espresso'
1078
-            );
1079
-        }
1080
-
1081
-        $this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction
1082
-            ->get_first_related('Registration')
1083
-            ->get('REG_session');
1084
-        $this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1085
-            'Registration Session',
1086
-            'event_espresso'
1087
-        );
1088
-
1089
-        $this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1090
-            ? $this->_session['ip_address']
1091
-            : '';
1092
-        $this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1093
-            'Transaction placed from IP',
1094
-            'event_espresso'
1095
-        );
1096
-
1097
-        $this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1098
-            ? $this->_session['user_agent']
1099
-            : '';
1100
-        $this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1101
-            'Registrant User Agent',
1102
-            'event_espresso'
1103
-        );
1104
-
1105
-        $reg_steps = '<ul>';
1106
-        foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1107
-            if ($reg_step_status === true) {
1108
-                $reg_steps .= '<li style="color:#70cc50">'
1109
-                              . sprintf(
1110
-                                  esc_html__('%1$s : Completed', 'event_espresso'),
1111
-                                  ucwords(str_replace('_', ' ', $reg_step))
1112
-                              )
1113
-                              . '</li>';
1114
-            } elseif (is_numeric($reg_step_status) && $reg_step_status !== false) {
1115
-                $reg_steps .= '<li style="color:#2EA2CC">'
1116
-                              . sprintf(
1117
-                                  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1118
-                                  ucwords(str_replace('_', ' ', $reg_step)),
1119
-                                  date(
1120
-                                      get_option('date_format') . ' ' . get_option('time_format'),
1121
-                                      ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS))
1122
-                                  )
1123
-                              )
1124
-                              . '</li>';
1125
-            } else {
1126
-                $reg_steps .= '<li style="color:#E76700">'
1127
-                              . sprintf(
1128
-                                  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1129
-                                  ucwords(str_replace('_', ' ', $reg_step))
1130
-                              )
1131
-                              . '</li>';
1132
-            }
1133
-        }
1134
-        $reg_steps .= '</ul>';
1135
-        $this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1136
-        $this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1137
-            'Registration Step Progress',
1138
-            'event_espresso'
1139
-        );
1140
-
1141
-
1142
-        $this->_get_registrations_to_apply_payment_to();
1143
-        $this->_get_payment_methods($payments);
1144
-        $this->_get_payment_status_array();
1145
-        $this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1146
-
1147
-        $this->_template_args['transaction_form_url'] = add_query_arg(
1148
-            array(
1149
-                'action'  => 'edit_transaction',
1150
-                'process' => 'transaction',
1151
-            ),
1152
-            TXN_ADMIN_URL
1153
-        );
1154
-        $this->_template_args['apply_payment_form_url'] = add_query_arg(
1155
-            array(
1156
-                'page'   => 'espresso_transactions',
1157
-                'action' => 'espresso_apply_payment',
1158
-            ),
1159
-            WP_AJAX_URL
1160
-        );
1161
-        $this->_template_args['delete_payment_form_url'] = add_query_arg(
1162
-            array(
1163
-                'page'   => 'espresso_transactions',
1164
-                'action' => 'espresso_delete_payment',
1165
-            ),
1166
-            WP_AJAX_URL
1167
-        );
1168
-
1169
-        $this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1170
-
1171
-        // 'espresso_delete_payment_nonce'
1172
-
1173
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1174
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1175
-    }
1176
-
1177
-
1178
-    /**
1179
-     * _get_registration_payment_IDs
1180
-     *    generates an array of Payment IDs and their corresponding Registration IDs
1181
-     *
1182
-     * @access protected
1183
-     * @param EE_Payment[] $payments
1184
-     * @return array
1185
-     * @throws EE_Error
1186
-     * @throws InvalidArgumentException
1187
-     * @throws InvalidDataTypeException
1188
-     * @throws InvalidInterfaceException
1189
-     * @throws ReflectionException
1190
-     */
1191
-    protected function _get_registration_payment_IDs($payments = array())
1192
-    {
1193
-        $existing_reg_payments = array();
1194
-        // get all reg payments for these payments
1195
-        $reg_payments = EEM_Registration_Payment::instance()->get_all(
1196
-            array(
1197
-                array(
1198
-                    'PAY_ID' => array(
1199
-                        'IN',
1200
-                        array_keys($payments),
1201
-                    ),
1202
-                ),
1203
-            )
1204
-        );
1205
-        if (! empty($reg_payments)) {
1206
-            foreach ($payments as $payment) {
1207
-                if (! $payment instanceof EE_Payment) {
1208
-                    continue;
1209
-                } elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1210
-                    $existing_reg_payments[ $payment->ID() ] = array();
1211
-                }
1212
-                foreach ($reg_payments as $reg_payment) {
1213
-                    if ($reg_payment instanceof EE_Registration_Payment
1214
-                        && $reg_payment->payment_ID() === $payment->ID()
1215
-                    ) {
1216
-                        $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1217
-                    }
1218
-                }
1219
-            }
1220
-        }
1221
-
1222
-        return $existing_reg_payments;
1223
-    }
1224
-
1225
-
1226
-    /**
1227
-     * _get_registrations_to_apply_payment_to
1228
-     *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1229
-     * which allows the admin to only apply the payment to the specific registrations
1230
-     *
1231
-     * @access protected
1232
-     * @return void
1233
-     * @throws \EE_Error
1234
-     */
1235
-    protected function _get_registrations_to_apply_payment_to()
1236
-    {
1237
-        // we want any registration with an active status (ie: not deleted or cancelled)
1238
-        $query_params = array(
1239
-            array(
1240
-                'STS_ID' => array(
1241
-                    'IN',
1242
-                    array(
1243
-                        EEM_Registration::status_id_approved,
1244
-                        EEM_Registration::status_id_pending_payment,
1245
-                        EEM_Registration::status_id_not_approved,
1246
-                    ),
1247
-                ),
1248
-            ),
1249
-        );
1250
-        $registrations_to_apply_payment_to = EEH_HTML::br()
1251
-                                             . EEH_HTML::div(
1252
-                                                 '',
1253
-                                                 'txn-admin-apply-payment-to-registrations-dv',
1254
-                                                 '',
1255
-                                                 'clear: both; margin: 1.5em 0 0; display: none;'
1256
-                                             );
1257
-        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1258
-        $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1259
-        $registrations_to_apply_payment_to .= EEH_HTML::thead(
1260
-            EEH_HTML::tr(
1261
-                EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1262
-                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1263
-                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1264
-                EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1265
-                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1266
-                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1267
-                EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1268
-            )
1269
-        );
1270
-        $registrations_to_apply_payment_to .= EEH_HTML::tbody();
1271
-        // get registrations for TXN
1272
-        $registrations = $this->_transaction->registrations($query_params);
1273
-        $existing_reg_payments = $this->_template_args['existing_reg_payments'];
1274
-        foreach ($registrations as $registration) {
1275
-            if ($registration instanceof EE_Registration) {
1276
-                $attendee_name = $registration->attendee() instanceof EE_Attendee
1277
-                    ? $registration->attendee()->full_name()
1278
-                    : esc_html__('Unknown Attendee', 'event_espresso');
1279
-                $owing = $registration->final_price() - $registration->paid();
1280
-                $taxable = $registration->ticket()->taxable()
1281
-                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1282
-                    : '';
1283
-                $checked = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments)
1284
-                    ? ' checked="checked"'
1285
-                    : '';
1286
-                $disabled = $registration->final_price() > 0 ? '' : ' disabled';
1287
-                $registrations_to_apply_payment_to .= EEH_HTML::tr(
1288
-                    EEH_HTML::td($registration->ID()) .
1289
-                    EEH_HTML::td($attendee_name) .
1290
-                    EEH_HTML::td(
1291
-                        $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1292
-                    ) .
1293
-                    EEH_HTML::td($registration->event_name()) .
1294
-                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1295
-                    EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') .
1296
-                    EEH_HTML::td(
1297
-                        '<input type="checkbox" value="' . $registration->ID()
1298
-                        . '" name="txn_admin_payment[registrations]"'
1299
-                        . $checked . $disabled . '>',
1300
-                        '',
1301
-                        'jst-cntr'
1302
-                    ),
1303
-                    'apply-payment-registration-row-' . $registration->ID()
1304
-                );
1305
-            }
1306
-        }
1307
-        $registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1308
-        $registrations_to_apply_payment_to .= EEH_HTML::tablex();
1309
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1310
-        $registrations_to_apply_payment_to .= EEH_HTML::p(
1311
-            esc_html__(
1312
-                'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1313
-                'event_espresso'
1314
-            ),
1315
-            '',
1316
-            'clear description'
1317
-        );
1318
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1319
-        $this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * _get_reg_status_selection
1325
-     *
1326
-     * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1327
-     *         instead of events.
1328
-     * @access protected
1329
-     * @return void
1330
-     * @throws EE_Error
1331
-     */
1332
-    protected function _get_reg_status_selection()
1333
-    {
1334
-        // first get all possible statuses
1335
-        $statuses = EEM_Registration::reg_status_array(array(), true);
1336
-        // let's add a "don't change" option.
1337
-        $status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso');
1338
-        $status_array = array_merge($status_array, $statuses);
1339
-        $this->_template_args['status_change_select'] = EEH_Form_Fields::select_input(
1340
-            'txn_reg_status_change[reg_status]',
1341
-            $status_array,
1342
-            'NAN',
1343
-            'id="txn-admin-payment-reg-status-inp"',
1344
-            'txn-reg-status-change-reg-status'
1345
-        );
1346
-        $this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1347
-            'delete_txn_reg_status_change[reg_status]',
1348
-            $status_array,
1349
-            'NAN',
1350
-            'delete-txn-admin-payment-reg-status-inp',
1351
-            'delete-txn-reg-status-change-reg-status'
1352
-        );
1353
-    }
1354
-
1355
-
1356
-    /**
1357
-     *    _get_payment_methods
1358
-     * Gets all the payment methods available generally, or the ones that are already
1359
-     * selected on these payments (in case their payment methods are no longer active).
1360
-     * Has the side-effect of updating the template args' payment_methods item
1361
-     *
1362
-     * @access private
1363
-     * @param EE_Payment[] to show on this page
1364
-     * @return void
1365
-     * @throws EE_Error
1366
-     * @throws InvalidArgumentException
1367
-     * @throws InvalidDataTypeException
1368
-     * @throws InvalidInterfaceException
1369
-     * @throws ReflectionException
1370
-     */
1371
-    private function _get_payment_methods($payments = array())
1372
-    {
1373
-        $payment_methods_of_payments = array();
1374
-        foreach ($payments as $payment) {
1375
-            if ($payment instanceof EE_Payment) {
1376
-                $payment_methods_of_payments[] = $payment->get('PMD_ID');
1377
-            }
1378
-        }
1379
-        if ($payment_methods_of_payments) {
1380
-            $query_args = array(
1381
-                array(
1382
-                    'OR*payment_method_for_payment' => array(
1383
-                        'PMD_ID'    => array('IN', $payment_methods_of_payments),
1384
-                        'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1385
-                    ),
1386
-                ),
1387
-            );
1388
-        } else {
1389
-            $query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1390
-        }
1391
-        $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1392
-    }
1393
-
1394
-
1395
-    /**
1396
-     * txn_attendees_meta_box
1397
-     *    generates HTML for the Attendees Transaction main meta box
1398
-     *
1399
-     * @access public
1400
-     * @param WP_Post $post
1401
-     * @param array   $metabox
1402
-     * @return void
1403
-     * @throws DomainException
1404
-     * @throws EE_Error
1405
-     */
1406
-    public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1407
-    {
1408
-
1409
-        /** @noinspection NonSecureExtractUsageInspection */
1410
-        extract($metabox['args']);
1411
-        $this->_template_args['post'] = $post;
1412
-        $this->_template_args['event_attendees'] = array();
1413
-        // process items in cart
1414
-        $line_items = $this->_transaction->get_many_related(
1415
-            'Line_Item',
1416
-            array(array('LIN_type' => 'line-item'))
1417
-        );
1418
-        if (! empty($line_items)) {
1419
-            foreach ($line_items as $item) {
1420
-                if ($item instanceof EE_Line_Item) {
1421
-                    switch ($item->OBJ_type()) {
1422
-                        case 'Event':
1423
-                            break;
1424
-                        case 'Ticket':
1425
-                            $ticket = $item->ticket();
1426
-                            // right now we're only handling tickets here.
1427
-                            // Cause its expected that only tickets will have attendees right?
1428
-                            if (! $ticket instanceof EE_Ticket) {
1429
-                                continue;
1430
-                            }
1431
-                            try {
1432
-                                $event_name = $ticket->get_event_name();
1433
-                            } catch (Exception $e) {
1434
-                                EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1435
-                                $event_name = esc_html__('Unknown Event', 'event_espresso');
1436
-                            }
1437
-                            $event_name .= ' - ' . $item->get('LIN_name');
1438
-                            $ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price'));
1439
-                            // now get all of the registrations for this transaction that use this ticket
1440
-                            $registrations = $ticket->get_many_related(
1441
-                                'Registration',
1442
-                                array(array('TXN_ID' => $this->_transaction->ID()))
1443
-                            );
1444
-                            foreach ($registrations as $registration) {
1445
-                                if (! $registration instanceof EE_Registration) {
1446
-                                    continue;
1447
-                                }
1448
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1449
-                                    = $registration->status_ID();
1450
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1451
-                                    = $registration->count();
1452
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1453
-                                    = $event_name;
1454
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1455
-                                    = $ticket_price;
1456
-                                // attendee info
1457
-                                $attendee = $registration->get_first_related('Attendee');
1458
-                                if ($attendee instanceof EE_Attendee) {
1459
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1460
-                                        = $attendee->ID();
1461
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1462
-                                        = $attendee->full_name();
1463
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']
1464
-                                        = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1465
-                                          . esc_html__(
1466
-                                              ' Event',
1467
-                                              'event_espresso'
1468
-                                          )
1469
-                                          . '">' . $attendee->email() . '</a>';
1470
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']
1471
-                                        = EEH_Address::format($attendee, 'inline', false, false);
1472
-                                } else {
1473
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1474
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1475
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1476
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1477
-                                }
1478
-                            }
1479
-                            break;
1480
-                    }
1481
-                }
1482
-            }
1483
-
1484
-            $this->_template_args['transaction_form_url'] = add_query_arg(
1485
-                array(
1486
-                    'action'  => 'edit_transaction',
1487
-                    'process' => 'attendees',
1488
-                ),
1489
-                TXN_ADMIN_URL
1490
-            );
1491
-            echo EEH_Template::display_template(
1492
-                TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1493
-                $this->_template_args,
1494
-                true
1495
-            );
1496
-        } else {
1497
-            echo sprintf(
1498
-                esc_html__(
1499
-                    '%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1500
-                    'event_espresso'
1501
-                ),
1502
-                '<p class="important-notice">',
1503
-                '</p>'
1504
-            );
1505
-        }
1506
-    }
1507
-
1508
-
1509
-    /**
1510
-     * txn_registrant_side_meta_box
1511
-     * generates HTML for the Edit Transaction side meta box
1512
-     *
1513
-     * @access public
1514
-     * @return void
1515
-     * @throws DomainException
1516
-     * @throws EE_Error
1517
-     * @throws InvalidArgumentException
1518
-     * @throws InvalidDataTypeException
1519
-     * @throws InvalidInterfaceException
1520
-     * @throws ReflectionException
1521
-     */
1522
-    public function txn_registrant_side_meta_box()
1523
-    {
1524
-        $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1525
-            ? $this->_transaction->primary_registration()->get_first_related('Attendee')
1526
-            : null;
1527
-        if (! $primary_att instanceof EE_Attendee) {
1528
-            $this->_template_args['no_attendee_message'] = esc_html__(
1529
-                'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1530
-                'event_espresso'
1531
-            );
1532
-            $primary_att = EEM_Attendee::instance()->create_default_object();
1533
-        }
1534
-        $this->_template_args['ATT_ID'] = $primary_att->ID();
1535
-        $this->_template_args['prime_reg_fname'] = $primary_att->fname();
1536
-        $this->_template_args['prime_reg_lname'] = $primary_att->lname();
1537
-        $this->_template_args['prime_reg_email'] = $primary_att->email();
1538
-        $this->_template_args['prime_reg_phone'] = $primary_att->phone();
1539
-        $this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1540
-            array(
1541
-                'action' => 'edit_attendee',
1542
-                'post'   => $primary_att->ID(),
1543
-            ),
1544
-            REG_ADMIN_URL
1545
-        );
1546
-        // get formatted address for registrant
1547
-        $this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1548
-        echo EEH_Template::display_template(
1549
-            TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1550
-            $this->_template_args,
1551
-            true
1552
-        );
1553
-    }
1554
-
1555
-
1556
-    /**
1557
-     * txn_billing_info_side_meta_box
1558
-     *    generates HTML for the Edit Transaction side meta box
1559
-     *
1560
-     * @access public
1561
-     * @return void
1562
-     * @throws DomainException
1563
-     * @throws EE_Error
1564
-     */
1565
-    public function txn_billing_info_side_meta_box()
1566
-    {
1567
-
1568
-        $this->_template_args['billing_form'] = $this->_transaction->billing_info();
1569
-        $this->_template_args['billing_form_url'] = add_query_arg(
1570
-            array('action' => 'edit_transaction', 'process' => 'billing'),
1571
-            TXN_ADMIN_URL
1572
-        );
1573
-
1574
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1575
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/
1576
-    }
1577
-
1578
-
1579
-    /**
1580
-     * apply_payments_or_refunds
1581
-     *    registers a payment or refund made towards a transaction
1582
-     *
1583
-     * @access public
1584
-     * @return void
1585
-     * @throws EE_Error
1586
-     * @throws InvalidArgumentException
1587
-     * @throws ReflectionException
1588
-     * @throws RuntimeException
1589
-     * @throws InvalidDataTypeException
1590
-     * @throws InvalidInterfaceException
1591
-     */
1592
-    public function apply_payments_or_refunds()
1593
-    {
1594
-        $json_response_data = array('return_data' => false);
1595
-        $valid_data = $this->_validate_payment_request_data();
1596
-        $has_access = EE_Registry::instance()->CAP->current_user_can(
1597
-            'ee_edit_payments',
1598
-            'apply_payment_or_refund_from_registration_details'
1599
-        );
1600
-        if (! empty($valid_data) && $has_access) {
1601
-            $PAY_ID = $valid_data['PAY_ID'];
1602
-            // save  the new payment
1603
-            $payment = $this->_create_payment_from_request_data($valid_data);
1604
-            // get the TXN for this payment
1605
-            $transaction = $payment->transaction();
1606
-            // verify transaction
1607
-            if ($transaction instanceof EE_Transaction) {
1608
-                // calculate_total_payments_and_update_status
1609
-                $this->_process_transaction_payments($transaction);
1610
-                $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1611
-                $this->_remove_existing_registration_payments($payment, $PAY_ID);
1612
-                // apply payment to registrations (if applicable)
1613
-                if (! empty($REG_IDs)) {
1614
-                    $this->_update_registration_payments($transaction, $payment, $REG_IDs);
1615
-                    $this->_maybe_send_notifications();
1616
-                    // now process status changes for the same registrations
1617
-                    $this->_process_registration_status_change($transaction, $REG_IDs);
1618
-                }
1619
-                $this->_maybe_send_notifications($payment);
1620
-                // prepare to render page
1621
-                $json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1622
-                do_action(
1623
-                    'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1624
-                    $transaction,
1625
-                    $payment
1626
-                );
1627
-            } else {
1628
-                EE_Error::add_error(
1629
-                    esc_html__(
1630
-                        'A valid Transaction for this payment could not be retrieved.',
1631
-                        'event_espresso'
1632
-                    ),
1633
-                    __FILE__,
1634
-                    __FUNCTION__,
1635
-                    __LINE__
1636
-                );
1637
-            }
1638
-        } else {
1639
-            if ($has_access) {
1640
-                EE_Error::add_error(
1641
-                    esc_html__(
1642
-                        'The payment form data could not be processed. Please try again.',
1643
-                        'event_espresso'
1644
-                    ),
1645
-                    __FILE__,
1646
-                    __FUNCTION__,
1647
-                    __LINE__
1648
-                );
1649
-            } else {
1650
-                EE_Error::add_error(
1651
-                    esc_html__(
1652
-                        'You do not have access to apply payments or refunds to a registration.',
1653
-                        'event_espresso'
1654
-                    ),
1655
-                    __FILE__,
1656
-                    __FUNCTION__,
1657
-                    __LINE__
1658
-                );
1659
-            }
1660
-        }
1661
-        $notices = EE_Error::get_notices(
1662
-            false,
1663
-            false,
1664
-            false
1665
-        );
1666
-        $this->_template_args = array(
1667
-            'data'    => $json_response_data,
1668
-            'error'   => $notices['errors'],
1669
-            'success' => $notices['success'],
1670
-        );
1671
-        $this->_return_json();
1672
-    }
1673
-
1674
-
1675
-    /**
1676
-     * _validate_payment_request_data
1677
-     *
1678
-     * @return array
1679
-     * @throws EE_Error
1680
-     */
1681
-    protected function _validate_payment_request_data()
1682
-    {
1683
-        if (! isset($this->_req_data['txn_admin_payment'])) {
1684
-            return false;
1685
-        }
1686
-        $payment_form = $this->_generate_payment_form_section();
1687
-        try {
1688
-            if ($payment_form->was_submitted()) {
1689
-                $payment_form->receive_form_submission();
1690
-                if (! $payment_form->is_valid()) {
1691
-                    $submission_error_messages = array();
1692
-                    foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1693
-                        if ($validation_error instanceof EE_Validation_Error) {
1694
-                            $submission_error_messages[] = sprintf(
1695
-                                _x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1696
-                                $validation_error->get_form_section()->html_label_text(),
1697
-                                $validation_error->getMessage()
1698
-                            );
1699
-                        }
1700
-                    }
1701
-                    EE_Error::add_error(
1702
-                        implode('<br />', $submission_error_messages),
1703
-                        __FILE__,
1704
-                        __FUNCTION__,
1705
-                        __LINE__
1706
-                    );
1707
-
1708
-                    return array();
1709
-                }
1710
-            }
1711
-        } catch (EE_Error $e) {
1712
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1713
-
1714
-            return array();
1715
-        }
1716
-
1717
-        return $payment_form->valid_data();
1718
-    }
1719
-
1720
-
1721
-    /**
1722
-     * _generate_payment_form_section
1723
-     *
1724
-     * @return EE_Form_Section_Proper
1725
-     * @throws EE_Error
1726
-     */
1727
-    protected function _generate_payment_form_section()
1728
-    {
1729
-        return new EE_Form_Section_Proper(
1730
-            array(
1731
-                'name'        => 'txn_admin_payment',
1732
-                'subsections' => array(
1733
-                    'PAY_ID'          => new EE_Text_Input(
1734
-                        array(
1735
-                            'default'               => 0,
1736
-                            'required'              => false,
1737
-                            'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1738
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1739
-                        )
1740
-                    ),
1741
-                    'TXN_ID'          => new EE_Text_Input(
1742
-                        array(
1743
-                            'default'               => 0,
1744
-                            'required'              => true,
1745
-                            'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1746
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1747
-                        )
1748
-                    ),
1749
-                    'type'            => new EE_Text_Input(
1750
-                        array(
1751
-                            'default'               => 1,
1752
-                            'required'              => true,
1753
-                            'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1754
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1755
-                        )
1756
-                    ),
1757
-                    'amount'          => new EE_Text_Input(
1758
-                        array(
1759
-                            'default'               => 0,
1760
-                            'required'              => true,
1761
-                            'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1762
-                            'validation_strategies' => array(new EE_Float_Normalization()),
1763
-                        )
1764
-                    ),
1765
-                    'status'          => new EE_Text_Input(
1766
-                        array(
1767
-                            'default'         => EEM_Payment::status_id_approved,
1768
-                            'required'        => true,
1769
-                            'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1770
-                        )
1771
-                    ),
1772
-                    'PMD_ID'          => new EE_Text_Input(
1773
-                        array(
1774
-                            'default'               => 2,
1775
-                            'required'              => true,
1776
-                            'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1777
-                            'validation_strategies' => array(new EE_Int_Normalization()),
1778
-                        )
1779
-                    ),
1780
-                    'date'            => new EE_Text_Input(
1781
-                        array(
1782
-                            'default'         => time(),
1783
-                            'required'        => true,
1784
-                            'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1785
-                        )
1786
-                    ),
1787
-                    'txn_id_chq_nmbr' => new EE_Text_Input(
1788
-                        array(
1789
-                            'default'               => '',
1790
-                            'required'              => false,
1791
-                            'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1792
-                            'validation_strategies' => array(
1793
-                                new EE_Max_Length_Validation_Strategy(
1794
-                                    esc_html__('Input too long', 'event_espresso'),
1795
-                                    100
1796
-                                ),
1797
-                            ),
1798
-                        )
1799
-                    ),
1800
-                    'po_number'       => new EE_Text_Input(
1801
-                        array(
1802
-                            'default'               => '',
1803
-                            'required'              => false,
1804
-                            'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1805
-                            'validation_strategies' => array(
1806
-                                new EE_Max_Length_Validation_Strategy(
1807
-                                    esc_html__('Input too long', 'event_espresso'),
1808
-                                    100
1809
-                                ),
1810
-                            ),
1811
-                        )
1812
-                    ),
1813
-                    'accounting'      => new EE_Text_Input(
1814
-                        array(
1815
-                            'default'               => '',
1816
-                            'required'              => false,
1817
-                            'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1818
-                            'validation_strategies' => array(
1819
-                                new EE_Max_Length_Validation_Strategy(
1820
-                                    esc_html__('Input too long', 'event_espresso'),
1821
-                                    100
1822
-                                ),
1823
-                            ),
1824
-                        )
1825
-                    ),
1826
-                ),
1827
-            )
1828
-        );
1829
-    }
1830
-
1831
-
1832
-    /**
1833
-     * _create_payment_from_request_data
1834
-     *
1835
-     * @param array $valid_data
1836
-     * @return EE_Payment
1837
-     * @throws EE_Error
1838
-     */
1839
-    protected function _create_payment_from_request_data($valid_data)
1840
-    {
1841
-        $PAY_ID = $valid_data['PAY_ID'];
1842
-        // get payment amount
1843
-        $amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1844
-        // payments have a type value of 1 and refunds have a type value of -1
1845
-        // so multiplying amount by type will give a positive value for payments, and negative values for refunds
1846
-        $amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1847
-        // for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1848
-        $date = $valid_data['date']
1849
-            ? preg_replace('/\s+/', ' ', $valid_data['date'])
1850
-            : date('Y-m-d g:i a', current_time('timestamp'));
1851
-        $payment = EE_Payment::new_instance(
1852
-            array(
1853
-                'TXN_ID'              => $valid_data['TXN_ID'],
1854
-                'STS_ID'              => $valid_data['status'],
1855
-                'PAY_timestamp'       => $date,
1856
-                'PAY_source'          => EEM_Payment_Method::scope_admin,
1857
-                'PMD_ID'              => $valid_data['PMD_ID'],
1858
-                'PAY_amount'          => $amount,
1859
-                'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1860
-                'PAY_po_number'       => $valid_data['po_number'],
1861
-                'PAY_extra_accntng'   => $valid_data['accounting'],
1862
-                'PAY_details'         => $valid_data,
1863
-                'PAY_ID'              => $PAY_ID,
1864
-            ),
1865
-            '',
1866
-            array('Y-m-d', 'g:i a')
1867
-        );
1868
-
1869
-        if (! $payment->save()) {
1870
-            EE_Error::add_error(
1871
-                sprintf(
1872
-                    esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1873
-                    $payment->ID()
1874
-                ),
1875
-                __FILE__,
1876
-                __FUNCTION__,
1877
-                __LINE__
1878
-            );
1879
-        }
1880
-
1881
-        return $payment;
1882
-    }
1883
-
1884
-
1885
-    /**
1886
-     * _process_transaction_payments
1887
-     *
1888
-     * @param \EE_Transaction $transaction
1889
-     * @return void
1890
-     * @throws EE_Error
1891
-     * @throws InvalidArgumentException
1892
-     * @throws ReflectionException
1893
-     * @throws InvalidDataTypeException
1894
-     * @throws InvalidInterfaceException
1895
-     */
1896
-    protected function _process_transaction_payments(EE_Transaction $transaction)
1897
-    {
1898
-        /** @type EE_Transaction_Payments $transaction_payments */
1899
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1900
-        // update the transaction with this payment
1901
-        if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1902
-            EE_Error::add_success(
1903
-                esc_html__(
1904
-                    'The payment has been processed successfully.',
1905
-                    'event_espresso'
1906
-                ),
1907
-                __FILE__,
1908
-                __FUNCTION__,
1909
-                __LINE__
1910
-            );
1911
-        } else {
1912
-            EE_Error::add_error(
1913
-                esc_html__(
1914
-                    'The payment was processed successfully but the amount paid for the transaction was not updated.',
1915
-                    'event_espresso'
1916
-                ),
1917
-                __FILE__,
1918
-                __FUNCTION__,
1919
-                __LINE__
1920
-            );
1921
-        }
1922
-    }
1923
-
1924
-
1925
-    /**
1926
-     * _get_REG_IDs_to_apply_payment_to
1927
-     * returns a list of registration IDs that the payment will apply to
1928
-     *
1929
-     * @param \EE_Payment $payment
1930
-     * @return array
1931
-     * @throws EE_Error
1932
-     */
1933
-    protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1934
-    {
1935
-        $REG_IDs = array();
1936
-        // grab array of IDs for specific registrations to apply changes to
1937
-        if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1938
-            $REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations'];
1939
-        }
1940
-        // nothing specified ? then get all reg IDs
1941
-        if (empty($REG_IDs)) {
1942
-            $registrations = $payment->transaction()->registrations();
1943
-            $REG_IDs = ! empty($registrations)
1944
-                ? array_keys($registrations)
1945
-                : $this->_get_existing_reg_payment_REG_IDs($payment);
1946
-        }
1947
-
1948
-        // ensure that REG_IDs are integers and NOT strings
1949
-        return array_map('intval', $REG_IDs);
1950
-    }
1951
-
1952
-
1953
-    /**
1954
-     * @return array
1955
-     */
1956
-    public function existing_reg_payment_REG_IDs()
1957
-    {
1958
-        return $this->_existing_reg_payment_REG_IDs;
1959
-    }
1960
-
1961
-
1962
-    /**
1963
-     * @param array $existing_reg_payment_REG_IDs
1964
-     */
1965
-    public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1966
-    {
1967
-        $this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1968
-    }
1969
-
1970
-
1971
-    /**
1972
-     * _get_existing_reg_payment_REG_IDs
1973
-     * returns a list of registration IDs that the payment is currently related to
1974
-     * as recorded in the database
1975
-     *
1976
-     * @param \EE_Payment $payment
1977
-     * @return array
1978
-     * @throws EE_Error
1979
-     */
1980
-    protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1981
-    {
1982
-        if ($this->existing_reg_payment_REG_IDs() === null) {
1983
-            // let's get any existing reg payment records for this payment
1984
-            $existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
1985
-            // but we only want the REG IDs, so grab the array keys
1986
-            $existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
1987
-                ? array_keys($existing_reg_payment_REG_IDs)
1988
-                : array();
1989
-            $this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
1990
-        }
1991
-
1992
-        return $this->existing_reg_payment_REG_IDs();
1993
-    }
1994
-
1995
-
1996
-    /**
1997
-     * _remove_existing_registration_payments
1998
-     * this calculates the difference between existing relations
1999
-     * to the supplied payment and the new list registration IDs,
2000
-     * removes any related registrations that no longer apply,
2001
-     * and then updates the registration paid fields
2002
-     *
2003
-     * @param \EE_Payment $payment
2004
-     * @param int         $PAY_ID
2005
-     * @return bool;
2006
-     * @throws EE_Error
2007
-     * @throws InvalidArgumentException
2008
-     * @throws ReflectionException
2009
-     * @throws InvalidDataTypeException
2010
-     * @throws InvalidInterfaceException
2011
-     */
2012
-    protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2013
-    {
2014
-        // newly created payments will have nothing recorded for $PAY_ID
2015
-        if ($PAY_ID == 0) {
2016
-            return false;
2017
-        }
2018
-        $existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2019
-        if (empty($existing_reg_payment_REG_IDs)) {
2020
-            return false;
2021
-        }
2022
-        /** @type EE_Transaction_Payments $transaction_payments */
2023
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2024
-
2025
-        return $transaction_payments->delete_registration_payments_and_update_registrations(
2026
-            $payment,
2027
-            array(
2028
-                array(
2029
-                    'PAY_ID' => $payment->ID(),
2030
-                    'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
2031
-                ),
2032
-            )
2033
-        );
2034
-    }
2035
-
2036
-
2037
-    /**
2038
-     * _update_registration_payments
2039
-     * this applies the payments to the selected registrations
2040
-     * but only if they have not already been paid for
2041
-     *
2042
-     * @param  EE_Transaction $transaction
2043
-     * @param \EE_Payment     $payment
2044
-     * @param array           $REG_IDs
2045
-     * @return void
2046
-     * @throws EE_Error
2047
-     * @throws InvalidArgumentException
2048
-     * @throws ReflectionException
2049
-     * @throws RuntimeException
2050
-     * @throws InvalidDataTypeException
2051
-     * @throws InvalidInterfaceException
2052
-     */
2053
-    protected function _update_registration_payments(
2054
-        EE_Transaction $transaction,
2055
-        EE_Payment $payment,
2056
-        $REG_IDs = array()
2057
-    ) {
2058
-        // we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2059
-        // so let's do that using our set of REG_IDs from the form
2060
-        $registration_query_where_params = array(
2061
-            'REG_ID' => array('IN', $REG_IDs),
2062
-        );
2063
-        // but add in some conditions regarding payment,
2064
-        // so that we don't apply payments to registrations that are free or have already been paid for
2065
-        // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2066
-        if (! $payment->is_a_refund()) {
2067
-            $registration_query_where_params['REG_final_price'] = array('!=', 0);
2068
-            $registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2069
-        }
2070
-        $registrations = $transaction->registrations(array($registration_query_where_params));
2071
-        if (! empty($registrations)) {
2072
-            /** @type EE_Payment_Processor $payment_processor */
2073
-            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2074
-            $payment_processor->process_registration_payments($transaction, $payment, $registrations);
2075
-        }
2076
-    }
2077
-
2078
-
2079
-    /**
2080
-     * _process_registration_status_change
2081
-     * This processes requested registration status changes for all the registrations
2082
-     * on a given transaction and (optionally) sends out notifications for the changes.
2083
-     *
2084
-     * @param  EE_Transaction $transaction
2085
-     * @param array           $REG_IDs
2086
-     * @return bool
2087
-     * @throws EE_Error
2088
-     * @throws InvalidArgumentException
2089
-     * @throws ReflectionException
2090
-     * @throws InvalidDataTypeException
2091
-     * @throws InvalidInterfaceException
2092
-     */
2093
-    protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2094
-    {
2095
-        // first if there is no change in status then we get out.
2096
-        if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2097
-            || $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2098
-        ) {
2099
-            // no error message, no change requested, just nothing to do man.
2100
-            return false;
2101
-        }
2102
-        /** @type EE_Transaction_Processor $transaction_processor */
2103
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2104
-
2105
-        // made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2106
-        return $transaction_processor->manually_update_registration_statuses(
2107
-            $transaction,
2108
-            sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
2109
-            array(array('REG_ID' => array('IN', $REG_IDs)))
2110
-        );
2111
-    }
2112
-
2113
-
2114
-    /**
2115
-     * _build_payment_json_response
2116
-     *
2117
-     * @access public
2118
-     * @param \EE_Payment $payment
2119
-     * @param array       $REG_IDs
2120
-     * @param bool | null $delete_txn_reg_status_change
2121
-     * @return array
2122
-     * @throws EE_Error
2123
-     * @throws InvalidArgumentException
2124
-     * @throws InvalidDataTypeException
2125
-     * @throws InvalidInterfaceException
2126
-     * @throws ReflectionException
2127
-     */
2128
-    protected function _build_payment_json_response(
2129
-        EE_Payment $payment,
2130
-        $REG_IDs = array(),
2131
-        $delete_txn_reg_status_change = null
2132
-    ) {
2133
-        // was the payment deleted ?
2134
-        if (is_bool($delete_txn_reg_status_change)) {
2135
-            return array(
2136
-                'PAY_ID'                       => $payment->ID(),
2137
-                'amount'                       => $payment->amount(),
2138
-                'total_paid'                   => $payment->transaction()->paid(),
2139
-                'txn_status'                   => $payment->transaction()->status_ID(),
2140
-                'pay_status'                   => $payment->STS_ID(),
2141
-                'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2142
-                'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2143
-            );
2144
-        } else {
2145
-            $this->_get_payment_status_array();
2146
-
2147
-            return array(
2148
-                'amount'           => $payment->amount(),
2149
-                'total_paid'       => $payment->transaction()->paid(),
2150
-                'txn_status'       => $payment->transaction()->status_ID(),
2151
-                'pay_status'       => $payment->STS_ID(),
2152
-                'PAY_ID'           => $payment->ID(),
2153
-                'STS_ID'           => $payment->STS_ID(),
2154
-                'status'           => self::$_pay_status[ $payment->STS_ID() ],
2155
-                'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2156
-                'method'           => strtoupper($payment->source()),
2157
-                'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2158
-                'gateway'          => $payment->payment_method()
2159
-                    ? $payment->payment_method()->admin_name()
2160
-                    : esc_html__("Unknown", 'event_espresso'),
2161
-                'gateway_response' => $payment->gateway_response(),
2162
-                'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2163
-                'po_number'        => $payment->po_number(),
2164
-                'extra_accntng'    => $payment->extra_accntng(),
2165
-                'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2166
-            );
2167
-        }
2168
-    }
2169
-
2170
-
2171
-    /**
2172
-     * delete_payment
2173
-     *    delete a payment or refund made towards a transaction
2174
-     *
2175
-     * @access public
2176
-     * @return void
2177
-     * @throws EE_Error
2178
-     * @throws InvalidArgumentException
2179
-     * @throws ReflectionException
2180
-     * @throws InvalidDataTypeException
2181
-     * @throws InvalidInterfaceException
2182
-     */
2183
-    public function delete_payment()
2184
-    {
2185
-        $json_response_data = array('return_data' => false);
2186
-        $PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2187
-            ? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2188
-            : 0;
2189
-        $can_delete = EE_Registry::instance()->CAP->current_user_can(
2190
-            'ee_delete_payments',
2191
-            'delete_payment_from_registration_details'
2192
-        );
2193
-        if ($PAY_ID && $can_delete) {
2194
-            $delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change'])
2195
-                ? $this->_req_data['delete_txn_reg_status_change']
2196
-                : false;
2197
-            $payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2198
-            if ($payment instanceof EE_Payment) {
2199
-                $REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2200
-                /** @type EE_Transaction_Payments $transaction_payments */
2201
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2202
-                if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2203
-                    $json_response_data['return_data'] = $this->_build_payment_json_response(
2204
-                        $payment,
2205
-                        $REG_IDs,
2206
-                        $delete_txn_reg_status_change
2207
-                    );
2208
-                    if ($delete_txn_reg_status_change) {
2209
-                        $this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
2210
-                        // MAKE sure we also add the delete_txn_req_status_change to the
2211
-                        // $_REQUEST global because that's how messages will be looking for it.
2212
-                        $_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
2213
-                        $this->_maybe_send_notifications();
2214
-                        $this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2215
-                    }
2216
-                }
2217
-            } else {
2218
-                EE_Error::add_error(
2219
-                    esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2220
-                    __FILE__,
2221
-                    __FUNCTION__,
2222
-                    __LINE__
2223
-                );
2224
-            }
2225
-        } else {
2226
-            if ($can_delete) {
2227
-                EE_Error::add_error(
2228
-                    esc_html__(
2229
-                        'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2230
-                        'event_espresso'
2231
-                    ),
2232
-                    __FILE__,
2233
-                    __FUNCTION__,
2234
-                    __LINE__
2235
-                );
2236
-            } else {
2237
-                EE_Error::add_error(
2238
-                    esc_html__(
2239
-                        'You do not have access to delete a payment.',
2240
-                        'event_espresso'
2241
-                    ),
2242
-                    __FILE__,
2243
-                    __FUNCTION__,
2244
-                    __LINE__
2245
-                );
2246
-            }
2247
-        }
2248
-        $notices = EE_Error::get_notices(false, false, false);
2249
-        $this->_template_args = array(
2250
-            'data'      => $json_response_data,
2251
-            'success'   => $notices['success'],
2252
-            'error'     => $notices['errors'],
2253
-            'attention' => $notices['attention'],
2254
-        );
2255
-        $this->_return_json();
2256
-    }
2257
-
2258
-
2259
-    /**
2260
-     * _registration_payment_data_array
2261
-     * adds info for 'owing' and 'paid' for each registration to the json response
2262
-     *
2263
-     * @access protected
2264
-     * @param array $REG_IDs
2265
-     * @return array
2266
-     * @throws EE_Error
2267
-     * @throws InvalidArgumentException
2268
-     * @throws InvalidDataTypeException
2269
-     * @throws InvalidInterfaceException
2270
-     * @throws ReflectionException
2271
-     */
2272
-    protected function _registration_payment_data_array($REG_IDs)
2273
-    {
2274
-        $registration_payment_data = array();
2275
-        // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2276
-        if (! empty($REG_IDs)) {
2277
-            $registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2278
-            foreach ($registrations as $registration) {
2279
-                if ($registration instanceof EE_Registration) {
2280
-                    $registration_payment_data[ $registration->ID() ] = array(
2281
-                        'paid'  => $registration->pretty_paid(),
2282
-                        'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2283
-                    );
2284
-                }
2285
-            }
2286
-        }
2287
-
2288
-        return $registration_payment_data;
2289
-    }
2290
-
2291
-
2292
-    /**
2293
-     * _maybe_send_notifications
2294
-     * determines whether or not the admin has indicated that notifications should be sent.
2295
-     * If so, will toggle a filter switch for delivering registration notices.
2296
-     * If passed an EE_Payment object, then it will trigger payment notifications instead.
2297
-     *
2298
-     * @access protected
2299
-     * @param \EE_Payment | null $payment
2300
-     */
2301
-    protected function _maybe_send_notifications($payment = null)
2302
-    {
2303
-        switch ($payment instanceof EE_Payment) {
2304
-            // payment notifications
2305
-            case true:
2306
-                if (isset(
2307
-                    $this->_req_data['txn_payments'],
2308
-                    $this->_req_data['txn_payments']['send_notifications']
2309
-                )
2310
-                    && filter_var($this->_req_data['txn_payments']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2311
-                ) {
2312
-                    $this->_process_payment_notification($payment);
2313
-                }
2314
-                break;
2315
-            // registration notifications
2316
-            case false:
2317
-                if (isset(
2318
-                    $this->_req_data['txn_reg_status_change'],
2319
-                    $this->_req_data['txn_reg_status_change']['send_notifications']
2320
-                )
2321
-                    && filter_var($this->_req_data['txn_reg_status_change']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2322
-                ) {
2323
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2324
-                }
2325
-                break;
2326
-        }
2327
-    }
2328
-
2329
-
2330
-    /**
2331
-     * _send_payment_reminder
2332
-     *    generates HTML for the View Transaction Details Admin page
2333
-     *
2334
-     * @access protected
2335
-     * @return void
2336
-     * @throws EE_Error
2337
-     * @throws InvalidArgumentException
2338
-     * @throws InvalidDataTypeException
2339
-     * @throws InvalidInterfaceException
2340
-     */
2341
-    protected function _send_payment_reminder()
2342
-    {
2343
-        $TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2344
-        $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2345
-        $query_args = isset($this->_req_data['redirect_to']) ? array(
2346
-            'action' => $this->_req_data['redirect_to'],
2347
-            'TXN_ID' => $this->_req_data['TXN_ID'],
2348
-        ) : array();
2349
-        do_action(
2350
-            'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2351
-            $transaction
2352
-        );
2353
-        $this->_redirect_after_action(
2354
-            false,
2355
-            esc_html__('payment reminder', 'event_espresso'),
2356
-            esc_html__('sent', 'event_espresso'),
2357
-            $query_args,
2358
-            true
2359
-        );
2360
-    }
2361
-
2362
-
2363
-    /**
2364
-     *  get_transactions
2365
-     *    get transactions for given parameters (used by list table)
2366
-     *
2367
-     * @param  int     $perpage how many transactions displayed per page
2368
-     * @param  boolean $count   return the count or objects
2369
-     * @param string   $view
2370
-     * @return mixed int = count || array of transaction objects
2371
-     * @throws EE_Error
2372
-     * @throws InvalidArgumentException
2373
-     * @throws InvalidDataTypeException
2374
-     * @throws InvalidInterfaceException
2375
-     */
2376
-    public function get_transactions($perpage, $count = false, $view = '')
2377
-    {
2378
-
2379
-        $TXN = EEM_Transaction::instance();
2380
-
2381
-        $start_date = isset($this->_req_data['txn-filter-start-date'])
2382
-            ? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
2383
-            : date(
2384
-                'm/d/Y',
2385
-                strtotime('-10 year')
2386
-            );
2387
-        $end_date = isset($this->_req_data['txn-filter-end-date'])
2388
-            ? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
2389
-            : date('m/d/Y');
2390
-
2391
-        // make sure our timestamps start and end right at the boundaries for each day
2392
-        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2393
-        $end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2394
-
2395
-
2396
-        // convert to timestamps
2397
-        $start_date = strtotime($start_date);
2398
-        $end_date = strtotime($end_date);
2399
-
2400
-        // makes sure start date is the lowest value and vice versa
2401
-        $start_date = min($start_date, $end_date);
2402
-        $end_date = max($start_date, $end_date);
2403
-
2404
-        // convert to correct format for query
2405
-        $start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2406
-            'TXN_timestamp',
2407
-            date('Y-m-d H:i:s', $start_date),
2408
-            'Y-m-d H:i:s'
2409
-        );
2410
-        $end_date = EEM_Transaction::instance()->convert_datetime_for_query(
2411
-            'TXN_timestamp',
2412
-            date('Y-m-d H:i:s', $end_date),
2413
-            'Y-m-d H:i:s'
2414
-        );
2415
-
2416
-
2417
-        // set orderby
2418
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2419
-
2420
-        switch ($this->_req_data['orderby']) {
2421
-            case 'TXN_ID':
2422
-                $orderby = 'TXN_ID';
2423
-                break;
2424
-            case 'ATT_fname':
2425
-                $orderby = 'Registration.Attendee.ATT_fname';
2426
-                break;
2427
-            case 'event_name':
2428
-                $orderby = 'Registration.Event.EVT_name';
2429
-                break;
2430
-            default: // 'TXN_timestamp'
2431
-                $orderby = 'TXN_timestamp';
2432
-        }
2433
-
2434
-        $sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2435
-        $current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
2436
-        $per_page = ! empty($perpage) ? $perpage : 10;
2437
-        $per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
2438
-
2439
-        $offset = ($current_page - 1) * $per_page;
2440
-        $limit = array($offset, $per_page);
2441
-
2442
-        $_where = array(
2443
-            'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
2444
-            'Registration.REG_count' => 1,
2445
-        );
2446
-
2447
-        if (isset($this->_req_data['EVT_ID'])) {
2448
-            $_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
2449
-        }
2450
-
2451
-        if (isset($this->_req_data['s'])) {
2452
-            $search_string = '%' . $this->_req_data['s'] . '%';
2453
-            $_where['OR'] = array(
2454
-                'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2455
-                'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
2456
-                'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
2457
-                'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
2458
-                'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
2459
-                'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
2460
-                'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
2461
-                'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
2462
-                'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
2463
-                'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
2464
-                'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
2465
-                'Registration.REG_final_price'        => array('LIKE', $search_string),
2466
-                'Registration.REG_code'               => array('LIKE', $search_string),
2467
-                'Registration.REG_count'              => array('LIKE', $search_string),
2468
-                'Registration.REG_group_size'         => array('LIKE', $search_string),
2469
-                'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
2470
-                'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
2471
-                'Payment.PAY_source'                  => array('LIKE', $search_string),
2472
-                'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
2473
-                'TXN_session_data'                    => array('LIKE', $search_string),
2474
-                'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string),
2475
-            );
2476
-        }
2477
-
2478
-        // failed transactions
2479
-        $failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2480
-                  || ($count && $view === 'failed');
2481
-        $abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2482
-                     || ($count && $view === 'abandoned');
2483
-        $incomplete = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count)
2484
-                      || ($count && $view === 'incomplete');
2485
-
2486
-        if ($failed) {
2487
-            $_where['STS_ID'] = EEM_Transaction::failed_status_code;
2488
-        } elseif ($abandoned) {
2489
-            $_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2490
-        } elseif ($incomplete) {
2491
-            $_where['STS_ID'] = EEM_Transaction::incomplete_status_code;
2492
-        } else {
2493
-            $_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code);
2494
-            $_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
2495
-        }
2496
-
2497
-        $query_params = apply_filters(
2498
-            'FHEE__Transactions_Admin_Page___get_transactions_query_params',
2499
-            array(
2500
-                $_where,
2501
-                'order_by'                 => array($orderby => $sort),
2502
-                'limit'                    => $limit,
2503
-                'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2504
-            ),
2505
-            $this->_req_data,
2506
-            $view,
2507
-            $count
2508
-        );
2509
-
2510
-        $transactions = $count
2511
-            ? $TXN->count(array($query_params[0]), 'TXN_ID', true)
2512
-            : $TXN->get_all($query_params);
2513
-
2514
-        return $transactions;
2515
-    }
17
+	/**
18
+	 * @var EE_Transaction
19
+	 */
20
+	private $_transaction;
21
+
22
+	/**
23
+	 * @var EE_Session
24
+	 */
25
+	private $_session;
26
+
27
+	/**
28
+	 * @var array $_txn_status
29
+	 */
30
+	private static $_txn_status;
31
+
32
+	/**
33
+	 * @var array $_pay_status
34
+	 */
35
+	private static $_pay_status;
36
+
37
+	/**
38
+	 * @var array $_existing_reg_payment_REG_IDs
39
+	 */
40
+	protected $_existing_reg_payment_REG_IDs = null;
41
+
42
+
43
+	/**
44
+	 * @Constructor
45
+	 * @access public
46
+	 * @param bool $routing
47
+	 * @throws EE_Error
48
+	 * @throws InvalidArgumentException
49
+	 * @throws ReflectionException
50
+	 * @throws InvalidDataTypeException
51
+	 * @throws InvalidInterfaceException
52
+	 */
53
+	public function __construct($routing = true)
54
+	{
55
+		parent::__construct($routing);
56
+	}
57
+
58
+
59
+	/**
60
+	 *    _init_page_props
61
+	 *
62
+	 * @return void
63
+	 */
64
+	protected function _init_page_props()
65
+	{
66
+		$this->page_slug = TXN_PG_SLUG;
67
+		$this->page_label = esc_html__('Transactions', 'event_espresso');
68
+		$this->_admin_base_url = TXN_ADMIN_URL;
69
+		$this->_admin_base_path = TXN_ADMIN;
70
+	}
71
+
72
+
73
+	/**
74
+	 *    _ajax_hooks
75
+	 *
76
+	 * @return void
77
+	 */
78
+	protected function _ajax_hooks()
79
+	{
80
+		add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
81
+		add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
82
+		add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
83
+	}
84
+
85
+
86
+	/**
87
+	 *    _define_page_props
88
+	 *
89
+	 * @return void
90
+	 */
91
+	protected function _define_page_props()
92
+	{
93
+		$this->_admin_page_title = $this->page_label;
94
+		$this->_labels = array(
95
+			'buttons' => array(
96
+				'add'    => esc_html__('Add New Transaction', 'event_espresso'),
97
+				'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
98
+				'delete' => esc_html__('Delete Transaction', 'event_espresso'),
99
+			),
100
+		);
101
+	}
102
+
103
+
104
+	/**
105
+	 *        grab url requests and route them
106
+	 *
107
+	 * @access private
108
+	 * @return void
109
+	 * @throws EE_Error
110
+	 * @throws InvalidArgumentException
111
+	 * @throws InvalidDataTypeException
112
+	 * @throws InvalidInterfaceException
113
+	 */
114
+	public function _set_page_routes()
115
+	{
116
+
117
+		$this->_set_transaction_status_array();
118
+
119
+		$txn_id = ! empty($this->_req_data['TXN_ID'])
120
+				  && ! is_array($this->_req_data['TXN_ID'])
121
+			? $this->_req_data['TXN_ID']
122
+			: 0;
123
+
124
+		$this->_page_routes = array(
125
+
126
+			'default' => array(
127
+				'func'       => '_transactions_overview_list_table',
128
+				'capability' => 'ee_read_transactions',
129
+			),
130
+
131
+			'view_transaction' => array(
132
+				'func'       => '_transaction_details',
133
+				'capability' => 'ee_read_transaction',
134
+				'obj_id'     => $txn_id,
135
+			),
136
+
137
+			'send_payment_reminder' => array(
138
+				'func'       => '_send_payment_reminder',
139
+				'noheader'   => true,
140
+				'capability' => 'ee_send_message',
141
+			),
142
+
143
+			'espresso_apply_payment' => array(
144
+				'func'       => 'apply_payments_or_refunds',
145
+				'noheader'   => true,
146
+				'capability' => 'ee_edit_payments',
147
+			),
148
+
149
+			'espresso_apply_refund' => array(
150
+				'func'       => 'apply_payments_or_refunds',
151
+				'noheader'   => true,
152
+				'capability' => 'ee_edit_payments',
153
+			),
154
+
155
+			'espresso_delete_payment' => array(
156
+				'func'       => 'delete_payment',
157
+				'noheader'   => true,
158
+				'capability' => 'ee_delete_payments',
159
+			),
160
+
161
+		);
162
+	}
163
+
164
+
165
+	protected function _set_page_config()
166
+	{
167
+		$this->_page_config = array(
168
+			'default'          => array(
169
+				'nav'           => array(
170
+					'label' => esc_html__('Overview', 'event_espresso'),
171
+					'order' => 10,
172
+				),
173
+				'list_table'    => 'EE_Admin_Transactions_List_Table',
174
+				'help_tabs'     => array(
175
+					'transactions_overview_help_tab'                       => array(
176
+						'title'    => esc_html__('Transactions Overview', 'event_espresso'),
177
+						'filename' => 'transactions_overview',
178
+					),
179
+					'transactions_overview_table_column_headings_help_tab' => array(
180
+						'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
181
+						'filename' => 'transactions_overview_table_column_headings',
182
+					),
183
+					'transactions_overview_views_filters_help_tab'         => array(
184
+						'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
185
+						'filename' => 'transactions_overview_views_filters_search',
186
+					),
187
+				),
188
+				'help_tour'     => array('Transactions_Overview_Help_Tour'),
189
+				/**
190
+				 * commented out because currently we are not displaying tips for transaction list table status but this
191
+				 * may change in a later iteration so want to keep the code for then.
192
+				 */
193
+				// 'qtips' => array( 'Transactions_List_Table_Tips' ),
194
+				'require_nonce' => false,
195
+			),
196
+			'view_transaction' => array(
197
+				'nav'       => array(
198
+					'label'      => esc_html__('View Transaction', 'event_espresso'),
199
+					'order'      => 5,
200
+					'url'        => isset($this->_req_data['TXN_ID'])
201
+						? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']), $this->_current_page_view_url)
202
+						: $this->_admin_base_url,
203
+					'persistent' => false,
204
+				),
205
+				'help_tabs' => array(
206
+					'transactions_view_transaction_help_tab'                                              => array(
207
+						'title'    => esc_html__('View Transaction', 'event_espresso'),
208
+						'filename' => 'transactions_view_transaction',
209
+					),
210
+					'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
211
+						'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
212
+						'filename' => 'transactions_view_transaction_transaction_details_table',
213
+					),
214
+					'transactions_view_transaction_attendees_registered_help_tab'                         => array(
215
+						'title'    => esc_html__('Attendees Registered', 'event_espresso'),
216
+						'filename' => 'transactions_view_transaction_attendees_registered',
217
+					),
218
+					'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
219
+						'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
220
+						'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
221
+					),
222
+				),
223
+				'qtips'     => array('Transaction_Details_Tips'),
224
+				'help_tour' => array('Transaction_Details_Help_Tour'),
225
+				'metaboxes' => array('_transaction_details_metaboxes'),
226
+
227
+				'require_nonce' => false,
228
+			),
229
+		);
230
+	}
231
+
232
+
233
+	/**
234
+	 * The below methods aren't used by this class currently
235
+	 */
236
+	protected function _add_screen_options()
237
+	{
238
+		// noop
239
+	}
240
+
241
+	protected function _add_feature_pointers()
242
+	{
243
+		// noop
244
+	}
245
+
246
+	public function admin_init()
247
+	{
248
+		// IF a registration was JUST added via the admin...
249
+		if (isset(
250
+			$this->_req_data['redirect_from'],
251
+			$this->_req_data['EVT_ID'],
252
+			$this->_req_data['event_name']
253
+		)) {
254
+			// then set a cookie so that we can block any attempts to use
255
+			// the back button as a way to enter another registration.
256
+			setcookie(
257
+				'ee_registration_added',
258
+				$this->_req_data['EVT_ID'],
259
+				time() + WEEK_IN_SECONDS,
260
+				'/'
261
+			);
262
+			// and update the global
263
+			$_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
264
+		}
265
+		EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
266
+			'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
267
+			'event_espresso'
268
+		);
269
+		EE_Registry::$i18n_js_strings['error_occurred'] = esc_html__(
270
+			'An error occurred! Please refresh the page and try again.',
271
+			'event_espresso'
272
+		);
273
+		EE_Registry::$i18n_js_strings['txn_status_array'] = self::$_txn_status;
274
+		EE_Registry::$i18n_js_strings['pay_status_array'] = self::$_pay_status;
275
+		EE_Registry::$i18n_js_strings['payments_total'] = esc_html__('Payments Total', 'event_espresso');
276
+		EE_Registry::$i18n_js_strings['transaction_overpaid'] = esc_html__(
277
+			'This transaction has been overpaid ! Payments Total',
278
+			'event_espresso'
279
+		);
280
+	}
281
+
282
+	public function admin_notices()
283
+	{
284
+		// noop
285
+	}
286
+
287
+	public function admin_footer_scripts()
288
+	{
289
+		// noop
290
+	}
291
+
292
+
293
+	/**
294
+	 * _set_transaction_status_array
295
+	 * sets list of transaction statuses
296
+	 *
297
+	 * @access private
298
+	 * @return void
299
+	 * @throws EE_Error
300
+	 * @throws InvalidArgumentException
301
+	 * @throws InvalidDataTypeException
302
+	 * @throws InvalidInterfaceException
303
+	 */
304
+	private function _set_transaction_status_array()
305
+	{
306
+		self::$_txn_status = EEM_Transaction::instance()->status_array(true);
307
+	}
308
+
309
+
310
+	/**
311
+	 * get_transaction_status_array
312
+	 * return the transaction status array for wp_list_table
313
+	 *
314
+	 * @access public
315
+	 * @return array
316
+	 */
317
+	public function get_transaction_status_array()
318
+	{
319
+		return self::$_txn_status;
320
+	}
321
+
322
+
323
+	/**
324
+	 *    get list of payment statuses
325
+	 *
326
+	 * @access private
327
+	 * @return void
328
+	 * @throws EE_Error
329
+	 * @throws InvalidArgumentException
330
+	 * @throws InvalidDataTypeException
331
+	 * @throws InvalidInterfaceException
332
+	 */
333
+	private function _get_payment_status_array()
334
+	{
335
+		self::$_pay_status = EEM_Payment::instance()->status_array(true);
336
+		$this->_template_args['payment_status'] = self::$_pay_status;
337
+	}
338
+
339
+
340
+	/**
341
+	 *    _add_screen_options_default
342
+	 *
343
+	 * @access protected
344
+	 * @return void
345
+	 * @throws InvalidArgumentException
346
+	 * @throws InvalidDataTypeException
347
+	 * @throws InvalidInterfaceException
348
+	 */
349
+	protected function _add_screen_options_default()
350
+	{
351
+		$this->_per_page_screen_option();
352
+	}
353
+
354
+
355
+	/**
356
+	 * load_scripts_styles
357
+	 *
358
+	 * @access public
359
+	 * @return void
360
+	 */
361
+	public function load_scripts_styles()
362
+	{
363
+		// enqueue style
364
+		wp_register_style(
365
+			'espresso_txn',
366
+			TXN_ASSETS_URL . 'espresso_transactions_admin.css',
367
+			array(),
368
+			EVENT_ESPRESSO_VERSION
369
+		);
370
+		wp_enqueue_style('espresso_txn');
371
+		// scripts
372
+		wp_register_script(
373
+			'espresso_txn',
374
+			TXN_ASSETS_URL . 'espresso_transactions_admin.js',
375
+			array(
376
+				'ee_admin_js',
377
+				'ee-datepicker',
378
+				'jquery-ui-datepicker',
379
+				'jquery-ui-draggable',
380
+				'ee-dialog',
381
+				'ee-accounting',
382
+				'ee-serialize-full-array',
383
+			),
384
+			EVENT_ESPRESSO_VERSION,
385
+			true
386
+		);
387
+		wp_enqueue_script('espresso_txn');
388
+	}
389
+
390
+
391
+	/**
392
+	 *    load_scripts_styles_view_transaction
393
+	 *
394
+	 * @access public
395
+	 * @return void
396
+	 */
397
+	public function load_scripts_styles_view_transaction()
398
+	{
399
+		// styles
400
+		wp_enqueue_style('espresso-ui-theme');
401
+	}
402
+
403
+
404
+	/**
405
+	 *    load_scripts_styles_default
406
+	 *
407
+	 * @access public
408
+	 * @return void
409
+	 */
410
+	public function load_scripts_styles_default()
411
+	{
412
+		// styles
413
+		wp_enqueue_style('espresso-ui-theme');
414
+	}
415
+
416
+
417
+	/**
418
+	 *    _set_list_table_views_default
419
+	 *
420
+	 * @access protected
421
+	 * @return void
422
+	 */
423
+	protected function _set_list_table_views_default()
424
+	{
425
+		$this->_views = array(
426
+			'all'       => array(
427
+				'slug'  => 'all',
428
+				'label' => esc_html__('View All Transactions', 'event_espresso'),
429
+				'count' => 0,
430
+			),
431
+			'abandoned' => array(
432
+				'slug'  => 'abandoned',
433
+				'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
434
+				'count' => 0,
435
+			),
436
+			'incomplete' => array(
437
+				'slug'  => 'incomplete',
438
+				'label' => esc_html__('Incomplete Transactions', 'event_espresso'),
439
+				'count' => 0,
440
+			)
441
+		);
442
+		if (/**
443
+		 * Filters whether a link to the "Failed Transactions" list table
444
+		 * appears on the Transactions Admin Page list table.
445
+		 * List display can be turned back on via the following:
446
+		 * add_filter(
447
+		 *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
448
+		 *     '__return_true'
449
+		 * );
450
+		 *
451
+		 * @since 4.9.70.p
452
+		 * @param boolean                 $display_failed_txns_list
453
+		 * @param Transactions_Admin_Page $this
454
+		 */
455
+			apply_filters(
456
+				'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
457
+				false,
458
+				$this
459
+			)
460
+		) {
461
+			$this->_views['failed'] = array(
462
+				'slug'  => 'failed',
463
+				'label' => esc_html__('Failed Transactions', 'event_espresso'),
464
+				'count' => 0,
465
+			);
466
+		}
467
+	}
468
+
469
+
470
+	/**
471
+	 * _set_transaction_object
472
+	 * This sets the _transaction property for the transaction details screen
473
+	 *
474
+	 * @access private
475
+	 * @return void
476
+	 * @throws EE_Error
477
+	 * @throws InvalidArgumentException
478
+	 * @throws RuntimeException
479
+	 * @throws InvalidDataTypeException
480
+	 * @throws InvalidInterfaceException
481
+	 * @throws ReflectionException
482
+	 */
483
+	private function _set_transaction_object()
484
+	{
485
+		if ($this->_transaction instanceof EE_Transaction) {
486
+			return;
487
+		} //get out we've already set the object
488
+
489
+		$TXN_ID = ! empty($this->_req_data['TXN_ID'])
490
+			? absint($this->_req_data['TXN_ID'])
491
+			: false;
492
+
493
+		// get transaction object
494
+		$this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
495
+		$this->_session = $this->_transaction instanceof EE_Transaction
496
+			? $this->_transaction->get('TXN_session_data')
497
+			: null;
498
+		if ($this->_transaction instanceof EE_Transaction) {
499
+			$this->_transaction->verify_abandoned_transaction_status();
500
+		}
501
+
502
+		if (! $this->_transaction instanceof EE_Transaction) {
503
+			$error_msg = sprintf(
504
+				esc_html__(
505
+					'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
506
+					'event_espresso'
507
+				),
508
+				$TXN_ID
509
+			);
510
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
511
+		}
512
+	}
513
+
514
+
515
+	/**
516
+	 *    _transaction_legend_items
517
+	 *
518
+	 * @access protected
519
+	 * @return array
520
+	 * @throws EE_Error
521
+	 * @throws InvalidArgumentException
522
+	 * @throws ReflectionException
523
+	 * @throws InvalidDataTypeException
524
+	 * @throws InvalidInterfaceException
525
+	 */
526
+	protected function _transaction_legend_items()
527
+	{
528
+		EE_Registry::instance()->load_helper('MSG_Template');
529
+		$items = array();
530
+
531
+		if (EE_Registry::instance()->CAP->current_user_can(
532
+			'ee_read_global_messages',
533
+			'view_filtered_messages'
534
+		)) {
535
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
536
+			if (is_array($related_for_icon)
537
+				&& isset($related_for_icon['css_class'], $related_for_icon['label'])
538
+			) {
539
+				$items['view_related_messages'] = array(
540
+					'class' => $related_for_icon['css_class'],
541
+					'desc'  => $related_for_icon['label'],
542
+				);
543
+			}
544
+		}
545
+
546
+		$items = apply_filters(
547
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
548
+			array_merge(
549
+				$items,
550
+				array(
551
+					'view_details'          => array(
552
+						'class' => 'dashicons dashicons-cart',
553
+						'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
554
+					),
555
+					'view_invoice'          => array(
556
+						'class' => 'dashicons dashicons-media-spreadsheet',
557
+						'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
558
+					),
559
+					'view_receipt'          => array(
560
+						'class' => 'dashicons dashicons-media-default',
561
+						'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
562
+					),
563
+					'view_registration'     => array(
564
+						'class' => 'dashicons dashicons-clipboard',
565
+						'desc'  => esc_html__('View Registration Details', 'event_espresso'),
566
+					),
567
+					'payment_overview_link' => array(
568
+						'class' => 'dashicons dashicons-money',
569
+						'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
570
+					),
571
+				)
572
+			)
573
+		);
574
+
575
+		if (EE_Registry::instance()->CAP->current_user_can(
576
+			'ee_send_message',
577
+			'espresso_transactions_send_payment_reminder'
578
+		)) {
579
+			if (EEH_MSG_Template::is_mt_active('payment_reminder')) {
580
+				$items['send_payment_reminder'] = array(
581
+					'class' => 'dashicons dashicons-email-alt',
582
+					'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
583
+				);
584
+			} else {
585
+				$items['blank*'] = array(
586
+					'class' => '',
587
+					'desc'  => '',
588
+				);
589
+			}
590
+		} else {
591
+			$items['blank*'] = array(
592
+				'class' => '',
593
+				'desc'  => '',
594
+			);
595
+		}
596
+		$more_items = apply_filters(
597
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
598
+			array(
599
+				'overpaid'   => array(
600
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
601
+					'desc'  => EEH_Template::pretty_status(
602
+						EEM_Transaction::overpaid_status_code,
603
+						false,
604
+						'sentence'
605
+					),
606
+				),
607
+				'complete'   => array(
608
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
609
+					'desc'  => EEH_Template::pretty_status(
610
+						EEM_Transaction::complete_status_code,
611
+						false,
612
+						'sentence'
613
+					),
614
+				),
615
+				'incomplete' => array(
616
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
617
+					'desc'  => EEH_Template::pretty_status(
618
+						EEM_Transaction::incomplete_status_code,
619
+						false,
620
+						'sentence'
621
+					),
622
+				),
623
+				'abandoned'  => array(
624
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
625
+					'desc'  => EEH_Template::pretty_status(
626
+						EEM_Transaction::abandoned_status_code,
627
+						false,
628
+						'sentence'
629
+					),
630
+				),
631
+				'failed'     => array(
632
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
633
+					'desc'  => EEH_Template::pretty_status(
634
+						EEM_Transaction::failed_status_code,
635
+						false,
636
+						'sentence'
637
+					),
638
+				),
639
+			)
640
+		);
641
+
642
+		return array_merge($items, $more_items);
643
+	}
644
+
645
+
646
+	/**
647
+	 *    _transactions_overview_list_table
648
+	 *
649
+	 * @access protected
650
+	 * @return void
651
+	 * @throws DomainException
652
+	 * @throws EE_Error
653
+	 * @throws InvalidArgumentException
654
+	 * @throws InvalidDataTypeException
655
+	 * @throws InvalidInterfaceException
656
+	 * @throws ReflectionException
657
+	 */
658
+	protected function _transactions_overview_list_table()
659
+	{
660
+		$this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
661
+		$event = isset($this->_req_data['EVT_ID'])
662
+			? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID'])
663
+			: null;
664
+		$this->_template_args['admin_page_header'] = $event instanceof EE_Event
665
+			? sprintf(
666
+				esc_html__(
667
+					'%sViewing Transactions for the Event: %s%s',
668
+					'event_espresso'
669
+				),
670
+				'<h3>',
671
+				'<a href="'
672
+				. EE_Admin_Page::add_query_args_and_nonce(
673
+					array('action' => 'edit', 'post' => $event->ID()),
674
+					EVENTS_ADMIN_URL
675
+				)
676
+				. '" title="'
677
+				. esc_attr__(
678
+					'Click to Edit event',
679
+					'event_espresso'
680
+				)
681
+				. '">' . $event->get('EVT_name') . '</a>',
682
+				'</h3>'
683
+			)
684
+			: '';
685
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_transaction_legend_items());
686
+		$this->display_admin_list_table_page_with_no_sidebar();
687
+	}
688
+
689
+
690
+	/**
691
+	 *    _transaction_details
692
+	 * generates HTML for the View Transaction Details Admin page
693
+	 *
694
+	 * @access protected
695
+	 * @return void
696
+	 * @throws DomainException
697
+	 * @throws EE_Error
698
+	 * @throws InvalidArgumentException
699
+	 * @throws InvalidDataTypeException
700
+	 * @throws InvalidInterfaceException
701
+	 * @throws RuntimeException
702
+	 * @throws ReflectionException
703
+	 */
704
+	protected function _transaction_details()
705
+	{
706
+		do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
707
+
708
+		$this->_set_transaction_status_array();
709
+
710
+		$this->_template_args = array();
711
+		$this->_template_args['transactions_page'] = $this->_wp_page_slug;
712
+
713
+		$this->_set_transaction_object();
714
+
715
+		if (! $this->_transaction instanceof EE_Transaction) {
716
+			return;
717
+		}
718
+		$primary_registration = $this->_transaction->primary_registration();
719
+		$attendee = $primary_registration instanceof EE_Registration
720
+			? $primary_registration->attendee()
721
+			: null;
722
+
723
+		$this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
724
+		$this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
725
+
726
+		$this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
727
+		$this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
728
+
729
+		$this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->get('STS_ID') ];
730
+		$this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
731
+		$this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID');
732
+
733
+		$this->_template_args['grand_total'] = $this->_transaction->get('TXN_total');
734
+		$this->_template_args['total_paid'] = $this->_transaction->get('TXN_paid');
735
+
736
+		$amount_due = $this->_transaction->get('TXN_total') - $this->_transaction->get('TXN_paid');
737
+		$this->_template_args['amount_due'] = EEH_Template::format_currency(
738
+			$amount_due,
739
+			true
740
+		);
741
+		if (EE_Registry::instance()->CFG->currency->sign_b4) {
742
+			$this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign
743
+												  . $this->_template_args['amount_due'];
744
+		} else {
745
+			$this->_template_args['amount_due'] .= EE_Registry::instance()->CFG->currency->sign;
746
+		}
747
+		$this->_template_args['amount_due_class'] = '';
748
+
749
+		if ($this->_transaction->get('TXN_paid') == $this->_transaction->get('TXN_total')) {
750
+			// paid in full
751
+			$this->_template_args['amount_due'] = false;
752
+		} elseif ($this->_transaction->get('TXN_paid') > $this->_transaction->get('TXN_total')) {
753
+			// overpaid
754
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
755
+		} elseif ($this->_transaction->get('TXN_total') > 0
756
+				  && $this->_transaction->get('TXN_paid') > 0
757
+		) {
758
+			// monies owing
759
+			$this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
760
+		} elseif ($this->_transaction->get('TXN_total') > 0
761
+				  && $this->_transaction->get('TXN_paid') == 0
762
+		) {
763
+			// no payments made yet
764
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
765
+		} elseif ($this->_transaction->get('TXN_total') == 0) {
766
+			// free event
767
+			$this->_template_args['amount_due'] = false;
768
+		}
769
+
770
+		$payment_method = $this->_transaction->payment_method();
771
+
772
+		$this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
773
+			? $payment_method->admin_name()
774
+			: esc_html__('Unknown', 'event_espresso');
775
+
776
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
777
+		// link back to overview
778
+		$this->_template_args['txn_overview_url'] = ! empty($_SERVER['HTTP_REFERER'])
779
+			? $_SERVER['HTTP_REFERER']
780
+			: TXN_ADMIN_URL;
781
+
782
+
783
+		// next link
784
+		$next_txn = $this->_transaction->next(
785
+			null,
786
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
787
+			'TXN_ID'
788
+		);
789
+		$this->_template_args['next_transaction'] = $next_txn
790
+			? $this->_next_link(
791
+				EE_Admin_Page::add_query_args_and_nonce(
792
+					array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
793
+					TXN_ADMIN_URL
794
+				),
795
+				'dashicons dashicons-arrow-right ee-icon-size-22'
796
+			)
797
+			: '';
798
+		// previous link
799
+		$previous_txn = $this->_transaction->previous(
800
+			null,
801
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
802
+			'TXN_ID'
803
+		);
804
+		$this->_template_args['previous_transaction'] = $previous_txn
805
+			? $this->_previous_link(
806
+				EE_Admin_Page::add_query_args_and_nonce(
807
+					array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
808
+					TXN_ADMIN_URL
809
+				),
810
+				'dashicons dashicons-arrow-left ee-icon-size-22'
811
+			)
812
+			: '';
813
+
814
+		// were we just redirected here after adding a new registration ???
815
+		if (isset(
816
+			$this->_req_data['redirect_from'],
817
+			$this->_req_data['EVT_ID'],
818
+			$this->_req_data['event_name']
819
+		)) {
820
+			if (EE_Registry::instance()->CAP->current_user_can(
821
+				'ee_edit_registrations',
822
+				'espresso_registrations_new_registration',
823
+				$this->_req_data['EVT_ID']
824
+			)) {
825
+				$this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
826
+				$this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
827
+					array(
828
+						'page'     => 'espresso_registrations',
829
+						'action'   => 'new_registration',
830
+						'return'   => 'default',
831
+						'TXN_ID'   => $this->_transaction->ID(),
832
+						'event_id' => $this->_req_data['EVT_ID'],
833
+					),
834
+					REG_ADMIN_URL
835
+				);
836
+				$this->_admin_page_title .= '">';
837
+
838
+				$this->_admin_page_title .= sprintf(
839
+					esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
840
+					htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
841
+				);
842
+				$this->_admin_page_title .= '</a>';
843
+			}
844
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
845
+		}
846
+		// grab messages at the last second
847
+		$this->_template_args['notices'] = EE_Error::get_notices();
848
+		// path to template
849
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
850
+		$this->_template_args['admin_page_header'] = EEH_Template::display_template(
851
+			$template_path,
852
+			$this->_template_args,
853
+			true
854
+		);
855
+
856
+		// the details template wrapper
857
+		$this->display_admin_page_with_sidebar();
858
+	}
859
+
860
+
861
+	/**
862
+	 *        _transaction_details_metaboxes
863
+	 *
864
+	 * @access protected
865
+	 * @return void
866
+	 * @throws EE_Error
867
+	 * @throws InvalidArgumentException
868
+	 * @throws InvalidDataTypeException
869
+	 * @throws InvalidInterfaceException
870
+	 * @throws RuntimeException
871
+	 * @throws ReflectionException
872
+	 */
873
+	protected function _transaction_details_metaboxes()
874
+	{
875
+
876
+		$this->_set_transaction_object();
877
+
878
+		if (! $this->_transaction instanceof EE_Transaction) {
879
+			return;
880
+		}
881
+		add_meta_box(
882
+			'edit-txn-details-mbox',
883
+			esc_html__('Transaction Details', 'event_espresso'),
884
+			array($this, 'txn_details_meta_box'),
885
+			$this->_wp_page_slug,
886
+			'normal',
887
+			'high'
888
+		);
889
+		add_meta_box(
890
+			'edit-txn-attendees-mbox',
891
+			esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
892
+			array($this, 'txn_attendees_meta_box'),
893
+			$this->_wp_page_slug,
894
+			'normal',
895
+			'high',
896
+			array('TXN_ID' => $this->_transaction->ID())
897
+		);
898
+		add_meta_box(
899
+			'edit-txn-registrant-mbox',
900
+			esc_html__('Primary Contact', 'event_espresso'),
901
+			array($this, 'txn_registrant_side_meta_box'),
902
+			$this->_wp_page_slug,
903
+			'side',
904
+			'high'
905
+		);
906
+		add_meta_box(
907
+			'edit-txn-billing-info-mbox',
908
+			esc_html__('Billing Information', 'event_espresso'),
909
+			array($this, 'txn_billing_info_side_meta_box'),
910
+			$this->_wp_page_slug,
911
+			'side',
912
+			'high'
913
+		);
914
+	}
915
+
916
+
917
+	/**
918
+	 * Callback for transaction actions metabox.
919
+	 *
920
+	 * @param EE_Transaction|null $transaction
921
+	 * @throws DomainException
922
+	 * @throws EE_Error
923
+	 * @throws InvalidArgumentException
924
+	 * @throws InvalidDataTypeException
925
+	 * @throws InvalidInterfaceException
926
+	 * @throws ReflectionException
927
+	 * @throws RuntimeException
928
+	 */
929
+	public function getActionButtons(EE_Transaction $transaction = null)
930
+	{
931
+		$content = '';
932
+		$actions = array();
933
+		if (! $transaction instanceof EE_Transaction) {
934
+			return $content;
935
+		}
936
+		/** @var EE_Registration $primary_registration */
937
+		$primary_registration = $transaction->primary_registration();
938
+		$attendee = $primary_registration instanceof EE_Registration
939
+			? $primary_registration->attendee()
940
+			: null;
941
+
942
+		if ($attendee instanceof EE_Attendee
943
+			&& EE_Registry::instance()->CAP->current_user_can(
944
+				'ee_send_message',
945
+				'espresso_transactions_send_payment_reminder'
946
+			)
947
+		) {
948
+			$actions['payment_reminder'] =
949
+				EEH_MSG_Template::is_mt_active('payment_reminder')
950
+				&& $this->_transaction->get('STS_ID') !== EEM_Transaction::complete_status_code
951
+				&& $this->_transaction->get('STS_ID') !== EEM_Transaction::overpaid_status_code
952
+					? EEH_Template::get_button_or_link(
953
+						EE_Admin_Page::add_query_args_and_nonce(
954
+							array(
955
+								'action'      => 'send_payment_reminder',
956
+								'TXN_ID'      => $this->_transaction->ID(),
957
+								'redirect_to' => 'view_transaction',
958
+							),
959
+							TXN_ADMIN_URL
960
+						),
961
+						esc_html__(' Send Payment Reminder', 'event_espresso'),
962
+						'button secondary-button',
963
+						'dashicons dashicons-email-alt'
964
+					)
965
+					: '';
966
+		}
967
+
968
+		if ($primary_registration instanceof EE_Registration
969
+			&& EEH_MSG_Template::is_mt_active('receipt')
970
+		) {
971
+			$actions['receipt'] = EEH_Template::get_button_or_link(
972
+				$primary_registration->receipt_url(),
973
+				esc_html__('View Receipt', 'event_espresso'),
974
+				'button secondary-button',
975
+				'dashicons dashicons-media-default'
976
+			);
977
+		}
978
+
979
+		if ($primary_registration instanceof EE_Registration
980
+			&& EEH_MSG_Template::is_mt_active('invoice')
981
+		) {
982
+			$actions['invoice'] = EEH_Template::get_button_or_link(
983
+				$primary_registration->invoice_url(),
984
+				esc_html__('View Invoice', 'event_espresso'),
985
+				'button secondary-button',
986
+				'dashicons dashicons-media-spreadsheet'
987
+			);
988
+		}
989
+		$actions = array_filter(
990
+			apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
991
+		);
992
+		if ($actions) {
993
+			$content = '<ul>';
994
+			$content .= '<li>' . implode('</li><li>', $actions) . '</li>';
995
+			$content .= '</uL>';
996
+		}
997
+		return $content;
998
+	}
999
+
1000
+
1001
+	/**
1002
+	 * txn_details_meta_box
1003
+	 * generates HTML for the Transaction main meta box
1004
+	 *
1005
+	 * @return void
1006
+	 * @throws DomainException
1007
+	 * @throws EE_Error
1008
+	 * @throws InvalidArgumentException
1009
+	 * @throws InvalidDataTypeException
1010
+	 * @throws InvalidInterfaceException
1011
+	 * @throws RuntimeException
1012
+	 * @throws ReflectionException
1013
+	 */
1014
+	public function txn_details_meta_box()
1015
+	{
1016
+		$this->_set_transaction_object();
1017
+		$this->_template_args['TXN_ID'] = $this->_transaction->ID();
1018
+		$this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration
1019
+			? $this->_transaction->primary_registration()->attendee()
1020
+			: null;
1021
+		$this->_template_args['can_edit_payments'] = EE_Registry::instance()->CAP->current_user_can(
1022
+			'ee_edit_payments',
1023
+			'apply_payment_or_refund_from_registration_details'
1024
+		);
1025
+		$this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1026
+			'ee_delete_payments',
1027
+			'delete_payment_from_registration_details'
1028
+		);
1029
+
1030
+		// get line table
1031
+		EEH_Autoloader::register_line_item_display_autoloaders();
1032
+		$Line_Item_Display = new EE_Line_Item_Display(
1033
+			'admin_table',
1034
+			'EE_Admin_Table_Line_Item_Display_Strategy'
1035
+		);
1036
+		$this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1037
+			$this->_transaction->total_line_item()
1038
+		);
1039
+		$this->_template_args['REG_code'] = $this->_transaction->get_first_related('Registration')
1040
+															   ->get('REG_code');
1041
+
1042
+		// process taxes
1043
+		$taxes = $this->_transaction->get_many_related(
1044
+			'Line_Item',
1045
+			array(array('LIN_type' => EEM_Line_Item::type_tax))
1046
+		);
1047
+		$this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1048
+
1049
+		$this->_template_args['grand_total'] = EEH_Template::format_currency(
1050
+			$this->_transaction->get('TXN_total'),
1051
+			false,
1052
+			false
1053
+		);
1054
+		$this->_template_args['grand_raw_total'] = $this->_transaction->get('TXN_total');
1055
+		$this->_template_args['TXN_status'] = $this->_transaction->get('STS_ID');
1056
+
1057
+		// process payment details
1058
+		$payments = $this->_transaction->get_many_related('Payment');
1059
+		if (! empty($payments)) {
1060
+			$this->_template_args['payments'] = $payments;
1061
+			$this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1062
+		} else {
1063
+			$this->_template_args['payments'] = false;
1064
+			$this->_template_args['existing_reg_payments'] = array();
1065
+		}
1066
+
1067
+		$this->_template_args['edit_payment_url'] = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
1068
+		$this->_template_args['delete_payment_url'] = add_query_arg(
1069
+			array('action' => 'espresso_delete_payment'),
1070
+			TXN_ADMIN_URL
1071
+		);
1072
+
1073
+		if (isset($txn_details['invoice_number'])) {
1074
+			$this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1075
+			$this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1076
+				'Invoice Number',
1077
+				'event_espresso'
1078
+			);
1079
+		}
1080
+
1081
+		$this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction
1082
+			->get_first_related('Registration')
1083
+			->get('REG_session');
1084
+		$this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1085
+			'Registration Session',
1086
+			'event_espresso'
1087
+		);
1088
+
1089
+		$this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address'])
1090
+			? $this->_session['ip_address']
1091
+			: '';
1092
+		$this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1093
+			'Transaction placed from IP',
1094
+			'event_espresso'
1095
+		);
1096
+
1097
+		$this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent'])
1098
+			? $this->_session['user_agent']
1099
+			: '';
1100
+		$this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1101
+			'Registrant User Agent',
1102
+			'event_espresso'
1103
+		);
1104
+
1105
+		$reg_steps = '<ul>';
1106
+		foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1107
+			if ($reg_step_status === true) {
1108
+				$reg_steps .= '<li style="color:#70cc50">'
1109
+							  . sprintf(
1110
+								  esc_html__('%1$s : Completed', 'event_espresso'),
1111
+								  ucwords(str_replace('_', ' ', $reg_step))
1112
+							  )
1113
+							  . '</li>';
1114
+			} elseif (is_numeric($reg_step_status) && $reg_step_status !== false) {
1115
+				$reg_steps .= '<li style="color:#2EA2CC">'
1116
+							  . sprintf(
1117
+								  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1118
+								  ucwords(str_replace('_', ' ', $reg_step)),
1119
+								  date(
1120
+									  get_option('date_format') . ' ' . get_option('time_format'),
1121
+									  ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS))
1122
+								  )
1123
+							  )
1124
+							  . '</li>';
1125
+			} else {
1126
+				$reg_steps .= '<li style="color:#E76700">'
1127
+							  . sprintf(
1128
+								  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1129
+								  ucwords(str_replace('_', ' ', $reg_step))
1130
+							  )
1131
+							  . '</li>';
1132
+			}
1133
+		}
1134
+		$reg_steps .= '</ul>';
1135
+		$this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1136
+		$this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1137
+			'Registration Step Progress',
1138
+			'event_espresso'
1139
+		);
1140
+
1141
+
1142
+		$this->_get_registrations_to_apply_payment_to();
1143
+		$this->_get_payment_methods($payments);
1144
+		$this->_get_payment_status_array();
1145
+		$this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1146
+
1147
+		$this->_template_args['transaction_form_url'] = add_query_arg(
1148
+			array(
1149
+				'action'  => 'edit_transaction',
1150
+				'process' => 'transaction',
1151
+			),
1152
+			TXN_ADMIN_URL
1153
+		);
1154
+		$this->_template_args['apply_payment_form_url'] = add_query_arg(
1155
+			array(
1156
+				'page'   => 'espresso_transactions',
1157
+				'action' => 'espresso_apply_payment',
1158
+			),
1159
+			WP_AJAX_URL
1160
+		);
1161
+		$this->_template_args['delete_payment_form_url'] = add_query_arg(
1162
+			array(
1163
+				'page'   => 'espresso_transactions',
1164
+				'action' => 'espresso_delete_payment',
1165
+			),
1166
+			WP_AJAX_URL
1167
+		);
1168
+
1169
+		$this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1170
+
1171
+		// 'espresso_delete_payment_nonce'
1172
+
1173
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1174
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1175
+	}
1176
+
1177
+
1178
+	/**
1179
+	 * _get_registration_payment_IDs
1180
+	 *    generates an array of Payment IDs and their corresponding Registration IDs
1181
+	 *
1182
+	 * @access protected
1183
+	 * @param EE_Payment[] $payments
1184
+	 * @return array
1185
+	 * @throws EE_Error
1186
+	 * @throws InvalidArgumentException
1187
+	 * @throws InvalidDataTypeException
1188
+	 * @throws InvalidInterfaceException
1189
+	 * @throws ReflectionException
1190
+	 */
1191
+	protected function _get_registration_payment_IDs($payments = array())
1192
+	{
1193
+		$existing_reg_payments = array();
1194
+		// get all reg payments for these payments
1195
+		$reg_payments = EEM_Registration_Payment::instance()->get_all(
1196
+			array(
1197
+				array(
1198
+					'PAY_ID' => array(
1199
+						'IN',
1200
+						array_keys($payments),
1201
+					),
1202
+				),
1203
+			)
1204
+		);
1205
+		if (! empty($reg_payments)) {
1206
+			foreach ($payments as $payment) {
1207
+				if (! $payment instanceof EE_Payment) {
1208
+					continue;
1209
+				} elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1210
+					$existing_reg_payments[ $payment->ID() ] = array();
1211
+				}
1212
+				foreach ($reg_payments as $reg_payment) {
1213
+					if ($reg_payment instanceof EE_Registration_Payment
1214
+						&& $reg_payment->payment_ID() === $payment->ID()
1215
+					) {
1216
+						$existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1217
+					}
1218
+				}
1219
+			}
1220
+		}
1221
+
1222
+		return $existing_reg_payments;
1223
+	}
1224
+
1225
+
1226
+	/**
1227
+	 * _get_registrations_to_apply_payment_to
1228
+	 *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1229
+	 * which allows the admin to only apply the payment to the specific registrations
1230
+	 *
1231
+	 * @access protected
1232
+	 * @return void
1233
+	 * @throws \EE_Error
1234
+	 */
1235
+	protected function _get_registrations_to_apply_payment_to()
1236
+	{
1237
+		// we want any registration with an active status (ie: not deleted or cancelled)
1238
+		$query_params = array(
1239
+			array(
1240
+				'STS_ID' => array(
1241
+					'IN',
1242
+					array(
1243
+						EEM_Registration::status_id_approved,
1244
+						EEM_Registration::status_id_pending_payment,
1245
+						EEM_Registration::status_id_not_approved,
1246
+					),
1247
+				),
1248
+			),
1249
+		);
1250
+		$registrations_to_apply_payment_to = EEH_HTML::br()
1251
+											 . EEH_HTML::div(
1252
+												 '',
1253
+												 'txn-admin-apply-payment-to-registrations-dv',
1254
+												 '',
1255
+												 'clear: both; margin: 1.5em 0 0; display: none;'
1256
+											 );
1257
+		$registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1258
+		$registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
1259
+		$registrations_to_apply_payment_to .= EEH_HTML::thead(
1260
+			EEH_HTML::tr(
1261
+				EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1262
+				EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1263
+				EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1264
+				EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1265
+				EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1266
+				EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1267
+				EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1268
+			)
1269
+		);
1270
+		$registrations_to_apply_payment_to .= EEH_HTML::tbody();
1271
+		// get registrations for TXN
1272
+		$registrations = $this->_transaction->registrations($query_params);
1273
+		$existing_reg_payments = $this->_template_args['existing_reg_payments'];
1274
+		foreach ($registrations as $registration) {
1275
+			if ($registration instanceof EE_Registration) {
1276
+				$attendee_name = $registration->attendee() instanceof EE_Attendee
1277
+					? $registration->attendee()->full_name()
1278
+					: esc_html__('Unknown Attendee', 'event_espresso');
1279
+				$owing = $registration->final_price() - $registration->paid();
1280
+				$taxable = $registration->ticket()->taxable()
1281
+					? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1282
+					: '';
1283
+				$checked = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments)
1284
+					? ' checked="checked"'
1285
+					: '';
1286
+				$disabled = $registration->final_price() > 0 ? '' : ' disabled';
1287
+				$registrations_to_apply_payment_to .= EEH_HTML::tr(
1288
+					EEH_HTML::td($registration->ID()) .
1289
+					EEH_HTML::td($attendee_name) .
1290
+					EEH_HTML::td(
1291
+						$registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1292
+					) .
1293
+					EEH_HTML::td($registration->event_name()) .
1294
+					EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1295
+					EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') .
1296
+					EEH_HTML::td(
1297
+						'<input type="checkbox" value="' . $registration->ID()
1298
+						. '" name="txn_admin_payment[registrations]"'
1299
+						. $checked . $disabled . '>',
1300
+						'',
1301
+						'jst-cntr'
1302
+					),
1303
+					'apply-payment-registration-row-' . $registration->ID()
1304
+				);
1305
+			}
1306
+		}
1307
+		$registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1308
+		$registrations_to_apply_payment_to .= EEH_HTML::tablex();
1309
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1310
+		$registrations_to_apply_payment_to .= EEH_HTML::p(
1311
+			esc_html__(
1312
+				'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1313
+				'event_espresso'
1314
+			),
1315
+			'',
1316
+			'clear description'
1317
+		);
1318
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1319
+		$this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * _get_reg_status_selection
1325
+	 *
1326
+	 * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1327
+	 *         instead of events.
1328
+	 * @access protected
1329
+	 * @return void
1330
+	 * @throws EE_Error
1331
+	 */
1332
+	protected function _get_reg_status_selection()
1333
+	{
1334
+		// first get all possible statuses
1335
+		$statuses = EEM_Registration::reg_status_array(array(), true);
1336
+		// let's add a "don't change" option.
1337
+		$status_array['NAN'] = esc_html__('Leave the Same', 'event_espresso');
1338
+		$status_array = array_merge($status_array, $statuses);
1339
+		$this->_template_args['status_change_select'] = EEH_Form_Fields::select_input(
1340
+			'txn_reg_status_change[reg_status]',
1341
+			$status_array,
1342
+			'NAN',
1343
+			'id="txn-admin-payment-reg-status-inp"',
1344
+			'txn-reg-status-change-reg-status'
1345
+		);
1346
+		$this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1347
+			'delete_txn_reg_status_change[reg_status]',
1348
+			$status_array,
1349
+			'NAN',
1350
+			'delete-txn-admin-payment-reg-status-inp',
1351
+			'delete-txn-reg-status-change-reg-status'
1352
+		);
1353
+	}
1354
+
1355
+
1356
+	/**
1357
+	 *    _get_payment_methods
1358
+	 * Gets all the payment methods available generally, or the ones that are already
1359
+	 * selected on these payments (in case their payment methods are no longer active).
1360
+	 * Has the side-effect of updating the template args' payment_methods item
1361
+	 *
1362
+	 * @access private
1363
+	 * @param EE_Payment[] to show on this page
1364
+	 * @return void
1365
+	 * @throws EE_Error
1366
+	 * @throws InvalidArgumentException
1367
+	 * @throws InvalidDataTypeException
1368
+	 * @throws InvalidInterfaceException
1369
+	 * @throws ReflectionException
1370
+	 */
1371
+	private function _get_payment_methods($payments = array())
1372
+	{
1373
+		$payment_methods_of_payments = array();
1374
+		foreach ($payments as $payment) {
1375
+			if ($payment instanceof EE_Payment) {
1376
+				$payment_methods_of_payments[] = $payment->get('PMD_ID');
1377
+			}
1378
+		}
1379
+		if ($payment_methods_of_payments) {
1380
+			$query_args = array(
1381
+				array(
1382
+					'OR*payment_method_for_payment' => array(
1383
+						'PMD_ID'    => array('IN', $payment_methods_of_payments),
1384
+						'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%'),
1385
+					),
1386
+				),
1387
+			);
1388
+		} else {
1389
+			$query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1390
+		}
1391
+		$this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1392
+	}
1393
+
1394
+
1395
+	/**
1396
+	 * txn_attendees_meta_box
1397
+	 *    generates HTML for the Attendees Transaction main meta box
1398
+	 *
1399
+	 * @access public
1400
+	 * @param WP_Post $post
1401
+	 * @param array   $metabox
1402
+	 * @return void
1403
+	 * @throws DomainException
1404
+	 * @throws EE_Error
1405
+	 */
1406
+	public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1407
+	{
1408
+
1409
+		/** @noinspection NonSecureExtractUsageInspection */
1410
+		extract($metabox['args']);
1411
+		$this->_template_args['post'] = $post;
1412
+		$this->_template_args['event_attendees'] = array();
1413
+		// process items in cart
1414
+		$line_items = $this->_transaction->get_many_related(
1415
+			'Line_Item',
1416
+			array(array('LIN_type' => 'line-item'))
1417
+		);
1418
+		if (! empty($line_items)) {
1419
+			foreach ($line_items as $item) {
1420
+				if ($item instanceof EE_Line_Item) {
1421
+					switch ($item->OBJ_type()) {
1422
+						case 'Event':
1423
+							break;
1424
+						case 'Ticket':
1425
+							$ticket = $item->ticket();
1426
+							// right now we're only handling tickets here.
1427
+							// Cause its expected that only tickets will have attendees right?
1428
+							if (! $ticket instanceof EE_Ticket) {
1429
+								continue;
1430
+							}
1431
+							try {
1432
+								$event_name = $ticket->get_event_name();
1433
+							} catch (Exception $e) {
1434
+								EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1435
+								$event_name = esc_html__('Unknown Event', 'event_espresso');
1436
+							}
1437
+							$event_name .= ' - ' . $item->get('LIN_name');
1438
+							$ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price'));
1439
+							// now get all of the registrations for this transaction that use this ticket
1440
+							$registrations = $ticket->get_many_related(
1441
+								'Registration',
1442
+								array(array('TXN_ID' => $this->_transaction->ID()))
1443
+							);
1444
+							foreach ($registrations as $registration) {
1445
+								if (! $registration instanceof EE_Registration) {
1446
+									continue;
1447
+								}
1448
+								$this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1449
+									= $registration->status_ID();
1450
+								$this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1451
+									= $registration->count();
1452
+								$this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1453
+									= $event_name;
1454
+								$this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1455
+									= $ticket_price;
1456
+								// attendee info
1457
+								$attendee = $registration->get_first_related('Attendee');
1458
+								if ($attendee instanceof EE_Attendee) {
1459
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1460
+										= $attendee->ID();
1461
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1462
+										= $attendee->full_name();
1463
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email']
1464
+										= '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1465
+										  . esc_html__(
1466
+											  ' Event',
1467
+											  'event_espresso'
1468
+										  )
1469
+										  . '">' . $attendee->email() . '</a>';
1470
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address']
1471
+										= EEH_Address::format($attendee, 'inline', false, false);
1472
+								} else {
1473
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id'] = '';
1474
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1475
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email'] = '';
1476
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address'] = '';
1477
+								}
1478
+							}
1479
+							break;
1480
+					}
1481
+				}
1482
+			}
1483
+
1484
+			$this->_template_args['transaction_form_url'] = add_query_arg(
1485
+				array(
1486
+					'action'  => 'edit_transaction',
1487
+					'process' => 'attendees',
1488
+				),
1489
+				TXN_ADMIN_URL
1490
+			);
1491
+			echo EEH_Template::display_template(
1492
+				TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1493
+				$this->_template_args,
1494
+				true
1495
+			);
1496
+		} else {
1497
+			echo sprintf(
1498
+				esc_html__(
1499
+					'%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1500
+					'event_espresso'
1501
+				),
1502
+				'<p class="important-notice">',
1503
+				'</p>'
1504
+			);
1505
+		}
1506
+	}
1507
+
1508
+
1509
+	/**
1510
+	 * txn_registrant_side_meta_box
1511
+	 * generates HTML for the Edit Transaction side meta box
1512
+	 *
1513
+	 * @access public
1514
+	 * @return void
1515
+	 * @throws DomainException
1516
+	 * @throws EE_Error
1517
+	 * @throws InvalidArgumentException
1518
+	 * @throws InvalidDataTypeException
1519
+	 * @throws InvalidInterfaceException
1520
+	 * @throws ReflectionException
1521
+	 */
1522
+	public function txn_registrant_side_meta_box()
1523
+	{
1524
+		$primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1525
+			? $this->_transaction->primary_registration()->get_first_related('Attendee')
1526
+			: null;
1527
+		if (! $primary_att instanceof EE_Attendee) {
1528
+			$this->_template_args['no_attendee_message'] = esc_html__(
1529
+				'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1530
+				'event_espresso'
1531
+			);
1532
+			$primary_att = EEM_Attendee::instance()->create_default_object();
1533
+		}
1534
+		$this->_template_args['ATT_ID'] = $primary_att->ID();
1535
+		$this->_template_args['prime_reg_fname'] = $primary_att->fname();
1536
+		$this->_template_args['prime_reg_lname'] = $primary_att->lname();
1537
+		$this->_template_args['prime_reg_email'] = $primary_att->email();
1538
+		$this->_template_args['prime_reg_phone'] = $primary_att->phone();
1539
+		$this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1540
+			array(
1541
+				'action' => 'edit_attendee',
1542
+				'post'   => $primary_att->ID(),
1543
+			),
1544
+			REG_ADMIN_URL
1545
+		);
1546
+		// get formatted address for registrant
1547
+		$this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1548
+		echo EEH_Template::display_template(
1549
+			TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1550
+			$this->_template_args,
1551
+			true
1552
+		);
1553
+	}
1554
+
1555
+
1556
+	/**
1557
+	 * txn_billing_info_side_meta_box
1558
+	 *    generates HTML for the Edit Transaction side meta box
1559
+	 *
1560
+	 * @access public
1561
+	 * @return void
1562
+	 * @throws DomainException
1563
+	 * @throws EE_Error
1564
+	 */
1565
+	public function txn_billing_info_side_meta_box()
1566
+	{
1567
+
1568
+		$this->_template_args['billing_form'] = $this->_transaction->billing_info();
1569
+		$this->_template_args['billing_form_url'] = add_query_arg(
1570
+			array('action' => 'edit_transaction', 'process' => 'billing'),
1571
+			TXN_ADMIN_URL
1572
+		);
1573
+
1574
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1575
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/
1576
+	}
1577
+
1578
+
1579
+	/**
1580
+	 * apply_payments_or_refunds
1581
+	 *    registers a payment or refund made towards a transaction
1582
+	 *
1583
+	 * @access public
1584
+	 * @return void
1585
+	 * @throws EE_Error
1586
+	 * @throws InvalidArgumentException
1587
+	 * @throws ReflectionException
1588
+	 * @throws RuntimeException
1589
+	 * @throws InvalidDataTypeException
1590
+	 * @throws InvalidInterfaceException
1591
+	 */
1592
+	public function apply_payments_or_refunds()
1593
+	{
1594
+		$json_response_data = array('return_data' => false);
1595
+		$valid_data = $this->_validate_payment_request_data();
1596
+		$has_access = EE_Registry::instance()->CAP->current_user_can(
1597
+			'ee_edit_payments',
1598
+			'apply_payment_or_refund_from_registration_details'
1599
+		);
1600
+		if (! empty($valid_data) && $has_access) {
1601
+			$PAY_ID = $valid_data['PAY_ID'];
1602
+			// save  the new payment
1603
+			$payment = $this->_create_payment_from_request_data($valid_data);
1604
+			// get the TXN for this payment
1605
+			$transaction = $payment->transaction();
1606
+			// verify transaction
1607
+			if ($transaction instanceof EE_Transaction) {
1608
+				// calculate_total_payments_and_update_status
1609
+				$this->_process_transaction_payments($transaction);
1610
+				$REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1611
+				$this->_remove_existing_registration_payments($payment, $PAY_ID);
1612
+				// apply payment to registrations (if applicable)
1613
+				if (! empty($REG_IDs)) {
1614
+					$this->_update_registration_payments($transaction, $payment, $REG_IDs);
1615
+					$this->_maybe_send_notifications();
1616
+					// now process status changes for the same registrations
1617
+					$this->_process_registration_status_change($transaction, $REG_IDs);
1618
+				}
1619
+				$this->_maybe_send_notifications($payment);
1620
+				// prepare to render page
1621
+				$json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1622
+				do_action(
1623
+					'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1624
+					$transaction,
1625
+					$payment
1626
+				);
1627
+			} else {
1628
+				EE_Error::add_error(
1629
+					esc_html__(
1630
+						'A valid Transaction for this payment could not be retrieved.',
1631
+						'event_espresso'
1632
+					),
1633
+					__FILE__,
1634
+					__FUNCTION__,
1635
+					__LINE__
1636
+				);
1637
+			}
1638
+		} else {
1639
+			if ($has_access) {
1640
+				EE_Error::add_error(
1641
+					esc_html__(
1642
+						'The payment form data could not be processed. Please try again.',
1643
+						'event_espresso'
1644
+					),
1645
+					__FILE__,
1646
+					__FUNCTION__,
1647
+					__LINE__
1648
+				);
1649
+			} else {
1650
+				EE_Error::add_error(
1651
+					esc_html__(
1652
+						'You do not have access to apply payments or refunds to a registration.',
1653
+						'event_espresso'
1654
+					),
1655
+					__FILE__,
1656
+					__FUNCTION__,
1657
+					__LINE__
1658
+				);
1659
+			}
1660
+		}
1661
+		$notices = EE_Error::get_notices(
1662
+			false,
1663
+			false,
1664
+			false
1665
+		);
1666
+		$this->_template_args = array(
1667
+			'data'    => $json_response_data,
1668
+			'error'   => $notices['errors'],
1669
+			'success' => $notices['success'],
1670
+		);
1671
+		$this->_return_json();
1672
+	}
1673
+
1674
+
1675
+	/**
1676
+	 * _validate_payment_request_data
1677
+	 *
1678
+	 * @return array
1679
+	 * @throws EE_Error
1680
+	 */
1681
+	protected function _validate_payment_request_data()
1682
+	{
1683
+		if (! isset($this->_req_data['txn_admin_payment'])) {
1684
+			return false;
1685
+		}
1686
+		$payment_form = $this->_generate_payment_form_section();
1687
+		try {
1688
+			if ($payment_form->was_submitted()) {
1689
+				$payment_form->receive_form_submission();
1690
+				if (! $payment_form->is_valid()) {
1691
+					$submission_error_messages = array();
1692
+					foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1693
+						if ($validation_error instanceof EE_Validation_Error) {
1694
+							$submission_error_messages[] = sprintf(
1695
+								_x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1696
+								$validation_error->get_form_section()->html_label_text(),
1697
+								$validation_error->getMessage()
1698
+							);
1699
+						}
1700
+					}
1701
+					EE_Error::add_error(
1702
+						implode('<br />', $submission_error_messages),
1703
+						__FILE__,
1704
+						__FUNCTION__,
1705
+						__LINE__
1706
+					);
1707
+
1708
+					return array();
1709
+				}
1710
+			}
1711
+		} catch (EE_Error $e) {
1712
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1713
+
1714
+			return array();
1715
+		}
1716
+
1717
+		return $payment_form->valid_data();
1718
+	}
1719
+
1720
+
1721
+	/**
1722
+	 * _generate_payment_form_section
1723
+	 *
1724
+	 * @return EE_Form_Section_Proper
1725
+	 * @throws EE_Error
1726
+	 */
1727
+	protected function _generate_payment_form_section()
1728
+	{
1729
+		return new EE_Form_Section_Proper(
1730
+			array(
1731
+				'name'        => 'txn_admin_payment',
1732
+				'subsections' => array(
1733
+					'PAY_ID'          => new EE_Text_Input(
1734
+						array(
1735
+							'default'               => 0,
1736
+							'required'              => false,
1737
+							'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1738
+							'validation_strategies' => array(new EE_Int_Normalization()),
1739
+						)
1740
+					),
1741
+					'TXN_ID'          => new EE_Text_Input(
1742
+						array(
1743
+							'default'               => 0,
1744
+							'required'              => true,
1745
+							'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1746
+							'validation_strategies' => array(new EE_Int_Normalization()),
1747
+						)
1748
+					),
1749
+					'type'            => new EE_Text_Input(
1750
+						array(
1751
+							'default'               => 1,
1752
+							'required'              => true,
1753
+							'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1754
+							'validation_strategies' => array(new EE_Int_Normalization()),
1755
+						)
1756
+					),
1757
+					'amount'          => new EE_Text_Input(
1758
+						array(
1759
+							'default'               => 0,
1760
+							'required'              => true,
1761
+							'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1762
+							'validation_strategies' => array(new EE_Float_Normalization()),
1763
+						)
1764
+					),
1765
+					'status'          => new EE_Text_Input(
1766
+						array(
1767
+							'default'         => EEM_Payment::status_id_approved,
1768
+							'required'        => true,
1769
+							'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1770
+						)
1771
+					),
1772
+					'PMD_ID'          => new EE_Text_Input(
1773
+						array(
1774
+							'default'               => 2,
1775
+							'required'              => true,
1776
+							'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1777
+							'validation_strategies' => array(new EE_Int_Normalization()),
1778
+						)
1779
+					),
1780
+					'date'            => new EE_Text_Input(
1781
+						array(
1782
+							'default'         => time(),
1783
+							'required'        => true,
1784
+							'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1785
+						)
1786
+					),
1787
+					'txn_id_chq_nmbr' => new EE_Text_Input(
1788
+						array(
1789
+							'default'               => '',
1790
+							'required'              => false,
1791
+							'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1792
+							'validation_strategies' => array(
1793
+								new EE_Max_Length_Validation_Strategy(
1794
+									esc_html__('Input too long', 'event_espresso'),
1795
+									100
1796
+								),
1797
+							),
1798
+						)
1799
+					),
1800
+					'po_number'       => new EE_Text_Input(
1801
+						array(
1802
+							'default'               => '',
1803
+							'required'              => false,
1804
+							'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1805
+							'validation_strategies' => array(
1806
+								new EE_Max_Length_Validation_Strategy(
1807
+									esc_html__('Input too long', 'event_espresso'),
1808
+									100
1809
+								),
1810
+							),
1811
+						)
1812
+					),
1813
+					'accounting'      => new EE_Text_Input(
1814
+						array(
1815
+							'default'               => '',
1816
+							'required'              => false,
1817
+							'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1818
+							'validation_strategies' => array(
1819
+								new EE_Max_Length_Validation_Strategy(
1820
+									esc_html__('Input too long', 'event_espresso'),
1821
+									100
1822
+								),
1823
+							),
1824
+						)
1825
+					),
1826
+				),
1827
+			)
1828
+		);
1829
+	}
1830
+
1831
+
1832
+	/**
1833
+	 * _create_payment_from_request_data
1834
+	 *
1835
+	 * @param array $valid_data
1836
+	 * @return EE_Payment
1837
+	 * @throws EE_Error
1838
+	 */
1839
+	protected function _create_payment_from_request_data($valid_data)
1840
+	{
1841
+		$PAY_ID = $valid_data['PAY_ID'];
1842
+		// get payment amount
1843
+		$amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1844
+		// payments have a type value of 1 and refunds have a type value of -1
1845
+		// so multiplying amount by type will give a positive value for payments, and negative values for refunds
1846
+		$amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1847
+		// for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1848
+		$date = $valid_data['date']
1849
+			? preg_replace('/\s+/', ' ', $valid_data['date'])
1850
+			: date('Y-m-d g:i a', current_time('timestamp'));
1851
+		$payment = EE_Payment::new_instance(
1852
+			array(
1853
+				'TXN_ID'              => $valid_data['TXN_ID'],
1854
+				'STS_ID'              => $valid_data['status'],
1855
+				'PAY_timestamp'       => $date,
1856
+				'PAY_source'          => EEM_Payment_Method::scope_admin,
1857
+				'PMD_ID'              => $valid_data['PMD_ID'],
1858
+				'PAY_amount'          => $amount,
1859
+				'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1860
+				'PAY_po_number'       => $valid_data['po_number'],
1861
+				'PAY_extra_accntng'   => $valid_data['accounting'],
1862
+				'PAY_details'         => $valid_data,
1863
+				'PAY_ID'              => $PAY_ID,
1864
+			),
1865
+			'',
1866
+			array('Y-m-d', 'g:i a')
1867
+		);
1868
+
1869
+		if (! $payment->save()) {
1870
+			EE_Error::add_error(
1871
+				sprintf(
1872
+					esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1873
+					$payment->ID()
1874
+				),
1875
+				__FILE__,
1876
+				__FUNCTION__,
1877
+				__LINE__
1878
+			);
1879
+		}
1880
+
1881
+		return $payment;
1882
+	}
1883
+
1884
+
1885
+	/**
1886
+	 * _process_transaction_payments
1887
+	 *
1888
+	 * @param \EE_Transaction $transaction
1889
+	 * @return void
1890
+	 * @throws EE_Error
1891
+	 * @throws InvalidArgumentException
1892
+	 * @throws ReflectionException
1893
+	 * @throws InvalidDataTypeException
1894
+	 * @throws InvalidInterfaceException
1895
+	 */
1896
+	protected function _process_transaction_payments(EE_Transaction $transaction)
1897
+	{
1898
+		/** @type EE_Transaction_Payments $transaction_payments */
1899
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1900
+		// update the transaction with this payment
1901
+		if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1902
+			EE_Error::add_success(
1903
+				esc_html__(
1904
+					'The payment has been processed successfully.',
1905
+					'event_espresso'
1906
+				),
1907
+				__FILE__,
1908
+				__FUNCTION__,
1909
+				__LINE__
1910
+			);
1911
+		} else {
1912
+			EE_Error::add_error(
1913
+				esc_html__(
1914
+					'The payment was processed successfully but the amount paid for the transaction was not updated.',
1915
+					'event_espresso'
1916
+				),
1917
+				__FILE__,
1918
+				__FUNCTION__,
1919
+				__LINE__
1920
+			);
1921
+		}
1922
+	}
1923
+
1924
+
1925
+	/**
1926
+	 * _get_REG_IDs_to_apply_payment_to
1927
+	 * returns a list of registration IDs that the payment will apply to
1928
+	 *
1929
+	 * @param \EE_Payment $payment
1930
+	 * @return array
1931
+	 * @throws EE_Error
1932
+	 */
1933
+	protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1934
+	{
1935
+		$REG_IDs = array();
1936
+		// grab array of IDs for specific registrations to apply changes to
1937
+		if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1938
+			$REG_IDs = (array) $this->_req_data['txn_admin_payment']['registrations'];
1939
+		}
1940
+		// nothing specified ? then get all reg IDs
1941
+		if (empty($REG_IDs)) {
1942
+			$registrations = $payment->transaction()->registrations();
1943
+			$REG_IDs = ! empty($registrations)
1944
+				? array_keys($registrations)
1945
+				: $this->_get_existing_reg_payment_REG_IDs($payment);
1946
+		}
1947
+
1948
+		// ensure that REG_IDs are integers and NOT strings
1949
+		return array_map('intval', $REG_IDs);
1950
+	}
1951
+
1952
+
1953
+	/**
1954
+	 * @return array
1955
+	 */
1956
+	public function existing_reg_payment_REG_IDs()
1957
+	{
1958
+		return $this->_existing_reg_payment_REG_IDs;
1959
+	}
1960
+
1961
+
1962
+	/**
1963
+	 * @param array $existing_reg_payment_REG_IDs
1964
+	 */
1965
+	public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1966
+	{
1967
+		$this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1968
+	}
1969
+
1970
+
1971
+	/**
1972
+	 * _get_existing_reg_payment_REG_IDs
1973
+	 * returns a list of registration IDs that the payment is currently related to
1974
+	 * as recorded in the database
1975
+	 *
1976
+	 * @param \EE_Payment $payment
1977
+	 * @return array
1978
+	 * @throws EE_Error
1979
+	 */
1980
+	protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1981
+	{
1982
+		if ($this->existing_reg_payment_REG_IDs() === null) {
1983
+			// let's get any existing reg payment records for this payment
1984
+			$existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
1985
+			// but we only want the REG IDs, so grab the array keys
1986
+			$existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
1987
+				? array_keys($existing_reg_payment_REG_IDs)
1988
+				: array();
1989
+			$this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
1990
+		}
1991
+
1992
+		return $this->existing_reg_payment_REG_IDs();
1993
+	}
1994
+
1995
+
1996
+	/**
1997
+	 * _remove_existing_registration_payments
1998
+	 * this calculates the difference between existing relations
1999
+	 * to the supplied payment and the new list registration IDs,
2000
+	 * removes any related registrations that no longer apply,
2001
+	 * and then updates the registration paid fields
2002
+	 *
2003
+	 * @param \EE_Payment $payment
2004
+	 * @param int         $PAY_ID
2005
+	 * @return bool;
2006
+	 * @throws EE_Error
2007
+	 * @throws InvalidArgumentException
2008
+	 * @throws ReflectionException
2009
+	 * @throws InvalidDataTypeException
2010
+	 * @throws InvalidInterfaceException
2011
+	 */
2012
+	protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2013
+	{
2014
+		// newly created payments will have nothing recorded for $PAY_ID
2015
+		if ($PAY_ID == 0) {
2016
+			return false;
2017
+		}
2018
+		$existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2019
+		if (empty($existing_reg_payment_REG_IDs)) {
2020
+			return false;
2021
+		}
2022
+		/** @type EE_Transaction_Payments $transaction_payments */
2023
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2024
+
2025
+		return $transaction_payments->delete_registration_payments_and_update_registrations(
2026
+			$payment,
2027
+			array(
2028
+				array(
2029
+					'PAY_ID' => $payment->ID(),
2030
+					'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
2031
+				),
2032
+			)
2033
+		);
2034
+	}
2035
+
2036
+
2037
+	/**
2038
+	 * _update_registration_payments
2039
+	 * this applies the payments to the selected registrations
2040
+	 * but only if they have not already been paid for
2041
+	 *
2042
+	 * @param  EE_Transaction $transaction
2043
+	 * @param \EE_Payment     $payment
2044
+	 * @param array           $REG_IDs
2045
+	 * @return void
2046
+	 * @throws EE_Error
2047
+	 * @throws InvalidArgumentException
2048
+	 * @throws ReflectionException
2049
+	 * @throws RuntimeException
2050
+	 * @throws InvalidDataTypeException
2051
+	 * @throws InvalidInterfaceException
2052
+	 */
2053
+	protected function _update_registration_payments(
2054
+		EE_Transaction $transaction,
2055
+		EE_Payment $payment,
2056
+		$REG_IDs = array()
2057
+	) {
2058
+		// we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2059
+		// so let's do that using our set of REG_IDs from the form
2060
+		$registration_query_where_params = array(
2061
+			'REG_ID' => array('IN', $REG_IDs),
2062
+		);
2063
+		// but add in some conditions regarding payment,
2064
+		// so that we don't apply payments to registrations that are free or have already been paid for
2065
+		// but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2066
+		if (! $payment->is_a_refund()) {
2067
+			$registration_query_where_params['REG_final_price'] = array('!=', 0);
2068
+			$registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
2069
+		}
2070
+		$registrations = $transaction->registrations(array($registration_query_where_params));
2071
+		if (! empty($registrations)) {
2072
+			/** @type EE_Payment_Processor $payment_processor */
2073
+			$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2074
+			$payment_processor->process_registration_payments($transaction, $payment, $registrations);
2075
+		}
2076
+	}
2077
+
2078
+
2079
+	/**
2080
+	 * _process_registration_status_change
2081
+	 * This processes requested registration status changes for all the registrations
2082
+	 * on a given transaction and (optionally) sends out notifications for the changes.
2083
+	 *
2084
+	 * @param  EE_Transaction $transaction
2085
+	 * @param array           $REG_IDs
2086
+	 * @return bool
2087
+	 * @throws EE_Error
2088
+	 * @throws InvalidArgumentException
2089
+	 * @throws ReflectionException
2090
+	 * @throws InvalidDataTypeException
2091
+	 * @throws InvalidInterfaceException
2092
+	 */
2093
+	protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
2094
+	{
2095
+		// first if there is no change in status then we get out.
2096
+		if (! isset($this->_req_data['txn_reg_status_change']['reg_status'])
2097
+			|| $this->_req_data['txn_reg_status_change']['reg_status'] === 'NAN'
2098
+		) {
2099
+			// no error message, no change requested, just nothing to do man.
2100
+			return false;
2101
+		}
2102
+		/** @type EE_Transaction_Processor $transaction_processor */
2103
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2104
+
2105
+		// made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2106
+		return $transaction_processor->manually_update_registration_statuses(
2107
+			$transaction,
2108
+			sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
2109
+			array(array('REG_ID' => array('IN', $REG_IDs)))
2110
+		);
2111
+	}
2112
+
2113
+
2114
+	/**
2115
+	 * _build_payment_json_response
2116
+	 *
2117
+	 * @access public
2118
+	 * @param \EE_Payment $payment
2119
+	 * @param array       $REG_IDs
2120
+	 * @param bool | null $delete_txn_reg_status_change
2121
+	 * @return array
2122
+	 * @throws EE_Error
2123
+	 * @throws InvalidArgumentException
2124
+	 * @throws InvalidDataTypeException
2125
+	 * @throws InvalidInterfaceException
2126
+	 * @throws ReflectionException
2127
+	 */
2128
+	protected function _build_payment_json_response(
2129
+		EE_Payment $payment,
2130
+		$REG_IDs = array(),
2131
+		$delete_txn_reg_status_change = null
2132
+	) {
2133
+		// was the payment deleted ?
2134
+		if (is_bool($delete_txn_reg_status_change)) {
2135
+			return array(
2136
+				'PAY_ID'                       => $payment->ID(),
2137
+				'amount'                       => $payment->amount(),
2138
+				'total_paid'                   => $payment->transaction()->paid(),
2139
+				'txn_status'                   => $payment->transaction()->status_ID(),
2140
+				'pay_status'                   => $payment->STS_ID(),
2141
+				'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2142
+				'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2143
+			);
2144
+		} else {
2145
+			$this->_get_payment_status_array();
2146
+
2147
+			return array(
2148
+				'amount'           => $payment->amount(),
2149
+				'total_paid'       => $payment->transaction()->paid(),
2150
+				'txn_status'       => $payment->transaction()->status_ID(),
2151
+				'pay_status'       => $payment->STS_ID(),
2152
+				'PAY_ID'           => $payment->ID(),
2153
+				'STS_ID'           => $payment->STS_ID(),
2154
+				'status'           => self::$_pay_status[ $payment->STS_ID() ],
2155
+				'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2156
+				'method'           => strtoupper($payment->source()),
2157
+				'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2158
+				'gateway'          => $payment->payment_method()
2159
+					? $payment->payment_method()->admin_name()
2160
+					: esc_html__("Unknown", 'event_espresso'),
2161
+				'gateway_response' => $payment->gateway_response(),
2162
+				'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2163
+				'po_number'        => $payment->po_number(),
2164
+				'extra_accntng'    => $payment->extra_accntng(),
2165
+				'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2166
+			);
2167
+		}
2168
+	}
2169
+
2170
+
2171
+	/**
2172
+	 * delete_payment
2173
+	 *    delete a payment or refund made towards a transaction
2174
+	 *
2175
+	 * @access public
2176
+	 * @return void
2177
+	 * @throws EE_Error
2178
+	 * @throws InvalidArgumentException
2179
+	 * @throws ReflectionException
2180
+	 * @throws InvalidDataTypeException
2181
+	 * @throws InvalidInterfaceException
2182
+	 */
2183
+	public function delete_payment()
2184
+	{
2185
+		$json_response_data = array('return_data' => false);
2186
+		$PAY_ID = isset($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2187
+			? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID'])
2188
+			: 0;
2189
+		$can_delete = EE_Registry::instance()->CAP->current_user_can(
2190
+			'ee_delete_payments',
2191
+			'delete_payment_from_registration_details'
2192
+		);
2193
+		if ($PAY_ID && $can_delete) {
2194
+			$delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change'])
2195
+				? $this->_req_data['delete_txn_reg_status_change']
2196
+				: false;
2197
+			$payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2198
+			if ($payment instanceof EE_Payment) {
2199
+				$REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2200
+				/** @type EE_Transaction_Payments $transaction_payments */
2201
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2202
+				if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2203
+					$json_response_data['return_data'] = $this->_build_payment_json_response(
2204
+						$payment,
2205
+						$REG_IDs,
2206
+						$delete_txn_reg_status_change
2207
+					);
2208
+					if ($delete_txn_reg_status_change) {
2209
+						$this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
2210
+						// MAKE sure we also add the delete_txn_req_status_change to the
2211
+						// $_REQUEST global because that's how messages will be looking for it.
2212
+						$_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
2213
+						$this->_maybe_send_notifications();
2214
+						$this->_process_registration_status_change($payment->transaction(), $REG_IDs);
2215
+					}
2216
+				}
2217
+			} else {
2218
+				EE_Error::add_error(
2219
+					esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2220
+					__FILE__,
2221
+					__FUNCTION__,
2222
+					__LINE__
2223
+				);
2224
+			}
2225
+		} else {
2226
+			if ($can_delete) {
2227
+				EE_Error::add_error(
2228
+					esc_html__(
2229
+						'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2230
+						'event_espresso'
2231
+					),
2232
+					__FILE__,
2233
+					__FUNCTION__,
2234
+					__LINE__
2235
+				);
2236
+			} else {
2237
+				EE_Error::add_error(
2238
+					esc_html__(
2239
+						'You do not have access to delete a payment.',
2240
+						'event_espresso'
2241
+					),
2242
+					__FILE__,
2243
+					__FUNCTION__,
2244
+					__LINE__
2245
+				);
2246
+			}
2247
+		}
2248
+		$notices = EE_Error::get_notices(false, false, false);
2249
+		$this->_template_args = array(
2250
+			'data'      => $json_response_data,
2251
+			'success'   => $notices['success'],
2252
+			'error'     => $notices['errors'],
2253
+			'attention' => $notices['attention'],
2254
+		);
2255
+		$this->_return_json();
2256
+	}
2257
+
2258
+
2259
+	/**
2260
+	 * _registration_payment_data_array
2261
+	 * adds info for 'owing' and 'paid' for each registration to the json response
2262
+	 *
2263
+	 * @access protected
2264
+	 * @param array $REG_IDs
2265
+	 * @return array
2266
+	 * @throws EE_Error
2267
+	 * @throws InvalidArgumentException
2268
+	 * @throws InvalidDataTypeException
2269
+	 * @throws InvalidInterfaceException
2270
+	 * @throws ReflectionException
2271
+	 */
2272
+	protected function _registration_payment_data_array($REG_IDs)
2273
+	{
2274
+		$registration_payment_data = array();
2275
+		// if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2276
+		if (! empty($REG_IDs)) {
2277
+			$registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
2278
+			foreach ($registrations as $registration) {
2279
+				if ($registration instanceof EE_Registration) {
2280
+					$registration_payment_data[ $registration->ID() ] = array(
2281
+						'paid'  => $registration->pretty_paid(),
2282
+						'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2283
+					);
2284
+				}
2285
+			}
2286
+		}
2287
+
2288
+		return $registration_payment_data;
2289
+	}
2290
+
2291
+
2292
+	/**
2293
+	 * _maybe_send_notifications
2294
+	 * determines whether or not the admin has indicated that notifications should be sent.
2295
+	 * If so, will toggle a filter switch for delivering registration notices.
2296
+	 * If passed an EE_Payment object, then it will trigger payment notifications instead.
2297
+	 *
2298
+	 * @access protected
2299
+	 * @param \EE_Payment | null $payment
2300
+	 */
2301
+	protected function _maybe_send_notifications($payment = null)
2302
+	{
2303
+		switch ($payment instanceof EE_Payment) {
2304
+			// payment notifications
2305
+			case true:
2306
+				if (isset(
2307
+					$this->_req_data['txn_payments'],
2308
+					$this->_req_data['txn_payments']['send_notifications']
2309
+				)
2310
+					&& filter_var($this->_req_data['txn_payments']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2311
+				) {
2312
+					$this->_process_payment_notification($payment);
2313
+				}
2314
+				break;
2315
+			// registration notifications
2316
+			case false:
2317
+				if (isset(
2318
+					$this->_req_data['txn_reg_status_change'],
2319
+					$this->_req_data['txn_reg_status_change']['send_notifications']
2320
+				)
2321
+					&& filter_var($this->_req_data['txn_reg_status_change']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
2322
+				) {
2323
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2324
+				}
2325
+				break;
2326
+		}
2327
+	}
2328
+
2329
+
2330
+	/**
2331
+	 * _send_payment_reminder
2332
+	 *    generates HTML for the View Transaction Details Admin page
2333
+	 *
2334
+	 * @access protected
2335
+	 * @return void
2336
+	 * @throws EE_Error
2337
+	 * @throws InvalidArgumentException
2338
+	 * @throws InvalidDataTypeException
2339
+	 * @throws InvalidInterfaceException
2340
+	 */
2341
+	protected function _send_payment_reminder()
2342
+	{
2343
+		$TXN_ID = ! empty($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : false;
2344
+		$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2345
+		$query_args = isset($this->_req_data['redirect_to']) ? array(
2346
+			'action' => $this->_req_data['redirect_to'],
2347
+			'TXN_ID' => $this->_req_data['TXN_ID'],
2348
+		) : array();
2349
+		do_action(
2350
+			'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2351
+			$transaction
2352
+		);
2353
+		$this->_redirect_after_action(
2354
+			false,
2355
+			esc_html__('payment reminder', 'event_espresso'),
2356
+			esc_html__('sent', 'event_espresso'),
2357
+			$query_args,
2358
+			true
2359
+		);
2360
+	}
2361
+
2362
+
2363
+	/**
2364
+	 *  get_transactions
2365
+	 *    get transactions for given parameters (used by list table)
2366
+	 *
2367
+	 * @param  int     $perpage how many transactions displayed per page
2368
+	 * @param  boolean $count   return the count or objects
2369
+	 * @param string   $view
2370
+	 * @return mixed int = count || array of transaction objects
2371
+	 * @throws EE_Error
2372
+	 * @throws InvalidArgumentException
2373
+	 * @throws InvalidDataTypeException
2374
+	 * @throws InvalidInterfaceException
2375
+	 */
2376
+	public function get_transactions($perpage, $count = false, $view = '')
2377
+	{
2378
+
2379
+		$TXN = EEM_Transaction::instance();
2380
+
2381
+		$start_date = isset($this->_req_data['txn-filter-start-date'])
2382
+			? wp_strip_all_tags($this->_req_data['txn-filter-start-date'])
2383
+			: date(
2384
+				'm/d/Y',
2385
+				strtotime('-10 year')
2386
+			);
2387
+		$end_date = isset($this->_req_data['txn-filter-end-date'])
2388
+			? wp_strip_all_tags($this->_req_data['txn-filter-end-date'])
2389
+			: date('m/d/Y');
2390
+
2391
+		// make sure our timestamps start and end right at the boundaries for each day
2392
+		$start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2393
+		$end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2394
+
2395
+
2396
+		// convert to timestamps
2397
+		$start_date = strtotime($start_date);
2398
+		$end_date = strtotime($end_date);
2399
+
2400
+		// makes sure start date is the lowest value and vice versa
2401
+		$start_date = min($start_date, $end_date);
2402
+		$end_date = max($start_date, $end_date);
2403
+
2404
+		// convert to correct format for query
2405
+		$start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2406
+			'TXN_timestamp',
2407
+			date('Y-m-d H:i:s', $start_date),
2408
+			'Y-m-d H:i:s'
2409
+		);
2410
+		$end_date = EEM_Transaction::instance()->convert_datetime_for_query(
2411
+			'TXN_timestamp',
2412
+			date('Y-m-d H:i:s', $end_date),
2413
+			'Y-m-d H:i:s'
2414
+		);
2415
+
2416
+
2417
+		// set orderby
2418
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2419
+
2420
+		switch ($this->_req_data['orderby']) {
2421
+			case 'TXN_ID':
2422
+				$orderby = 'TXN_ID';
2423
+				break;
2424
+			case 'ATT_fname':
2425
+				$orderby = 'Registration.Attendee.ATT_fname';
2426
+				break;
2427
+			case 'event_name':
2428
+				$orderby = 'Registration.Event.EVT_name';
2429
+				break;
2430
+			default: // 'TXN_timestamp'
2431
+				$orderby = 'TXN_timestamp';
2432
+		}
2433
+
2434
+		$sort = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'DESC';
2435
+		$current_page = ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
2436
+		$per_page = ! empty($perpage) ? $perpage : 10;
2437
+		$per_page = ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
2438
+
2439
+		$offset = ($current_page - 1) * $per_page;
2440
+		$limit = array($offset, $per_page);
2441
+
2442
+		$_where = array(
2443
+			'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
2444
+			'Registration.REG_count' => 1,
2445
+		);
2446
+
2447
+		if (isset($this->_req_data['EVT_ID'])) {
2448
+			$_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
2449
+		}
2450
+
2451
+		if (isset($this->_req_data['s'])) {
2452
+			$search_string = '%' . $this->_req_data['s'] . '%';
2453
+			$_where['OR'] = array(
2454
+				'Registration.Event.EVT_name'         => array('LIKE', $search_string),
2455
+				'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
2456
+				'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
2457
+				'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
2458
+				'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
2459
+				'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
2460
+				'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
2461
+				'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
2462
+				'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
2463
+				'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
2464
+				'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
2465
+				'Registration.REG_final_price'        => array('LIKE', $search_string),
2466
+				'Registration.REG_code'               => array('LIKE', $search_string),
2467
+				'Registration.REG_count'              => array('LIKE', $search_string),
2468
+				'Registration.REG_group_size'         => array('LIKE', $search_string),
2469
+				'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
2470
+				'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
2471
+				'Payment.PAY_source'                  => array('LIKE', $search_string),
2472
+				'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
2473
+				'TXN_session_data'                    => array('LIKE', $search_string),
2474
+				'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string),
2475
+			);
2476
+		}
2477
+
2478
+		// failed transactions
2479
+		$failed = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'failed' && ! $count)
2480
+				  || ($count && $view === 'failed');
2481
+		$abandoned = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'abandoned' && ! $count)
2482
+					 || ($count && $view === 'abandoned');
2483
+		$incomplete = (! empty($this->_req_data['status']) && $this->_req_data['status'] === 'incomplete' && ! $count)
2484
+					  || ($count && $view === 'incomplete');
2485
+
2486
+		if ($failed) {
2487
+			$_where['STS_ID'] = EEM_Transaction::failed_status_code;
2488
+		} elseif ($abandoned) {
2489
+			$_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2490
+		} elseif ($incomplete) {
2491
+			$_where['STS_ID'] = EEM_Transaction::incomplete_status_code;
2492
+		} else {
2493
+			$_where['STS_ID'] = array('!=', EEM_Transaction::failed_status_code);
2494
+			$_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
2495
+		}
2496
+
2497
+		$query_params = apply_filters(
2498
+			'FHEE__Transactions_Admin_Page___get_transactions_query_params',
2499
+			array(
2500
+				$_where,
2501
+				'order_by'                 => array($orderby => $sort),
2502
+				'limit'                    => $limit,
2503
+				'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2504
+			),
2505
+			$this->_req_data,
2506
+			$view,
2507
+			$count
2508
+		);
2509
+
2510
+		$transactions = $count
2511
+			? $TXN->count(array($query_params[0]), 'TXN_ID', true)
2512
+			: $TXN->get_all($query_params);
2513
+
2514
+		return $transactions;
2515
+	}
2516 2516
 }
Please login to merge, or discard this patch.
core/domain/services/assets/CoreAssetManager.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -330,11 +330,11 @@  discard block
 block discarded – undo
330 330
 
331 331
         $this->addJavascript(
332 332
             CoreAssetManager::JS_HANDLE_CORE,
333
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
333
+            EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
334 334
             array(CoreAssetManager::JS_HANDLE_JQUERY)
335 335
         )
336 336
         ->setInlineDataCallback(
337
-            function () {
337
+            function() {
338 338
                 wp_localize_script(
339 339
                     CoreAssetManager::JS_HANDLE_CORE,
340 340
                     CoreAssetManager::JS_HANDLE_I18N,
@@ -438,16 +438,16 @@  discard block
 block discarded – undo
438 438
         if ($this->template_config->enable_default_style && ! is_admin()) {
439 439
             $this->addStylesheet(
440 440
                 CoreAssetManager::CSS_HANDLE_DEFAULT,
441
-                is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css')
441
+                is_readable(EVENT_ESPRESSO_UPLOAD_DIR.'css/style.css')
442 442
                     ? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css'
443
-                    : EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
443
+                    : EE_GLOBAL_ASSETS_URL.'css/espresso_default.css',
444 444
                 array('dashicons')
445 445
             );
446 446
             //Load custom style sheet if available
447 447
             if ($this->template_config->custom_style_sheet !== null) {
448 448
                 $this->addStylesheet(
449 449
                     CoreAssetManager::CSS_HANDLE_CUSTOM,
450
-                    EVENT_ESPRESSO_UPLOAD_URL . 'css/' . $this->template_config->custom_style_sheet,
450
+                    EVENT_ESPRESSO_UPLOAD_URL.'css/'.$this->template_config->custom_style_sheet,
451 451
                     array(CoreAssetManager::CSS_HANDLE_DEFAULT)
452 452
                 );
453 453
             }
@@ -475,14 +475,14 @@  discard block
 block discarded – undo
475 475
     {
476 476
         $this->addJavascript(
477 477
             CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE,
478
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
478
+            EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.min.js',
479 479
             array(CoreAssetManager::JS_HANDLE_JQUERY)
480 480
         )
481 481
         ->setVersion('1.15.0');
482 482
 
483 483
         $this->addJavascript(
484 484
             CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE_EXTRA,
485
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
485
+            EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.additional-methods.min.js',
486 486
             array(CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE)
487 487
         )
488 488
         ->setVersion('1.15.0');
@@ -504,18 +504,18 @@  discard block
 block discarded – undo
504 504
         // @link http://josscrowcroft.github.io/accounting.js/
505 505
         $this->addJavascript(
506 506
             CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE,
507
-            EE_THIRD_PARTY_URL . 'accounting/accounting.js',
507
+            EE_THIRD_PARTY_URL.'accounting/accounting.js',
508 508
             array(CoreAssetManager::JS_HANDLE_UNDERSCORE)
509 509
         )
510 510
         ->setVersion('0.3.2');
511 511
 
512 512
         $this->addJavascript(
513 513
             CoreAssetManager::JS_HANDLE_ACCOUNTING,
514
-            EE_GLOBAL_ASSETS_URL . 'scripts/ee-accounting-config.js',
514
+            EE_GLOBAL_ASSETS_URL.'scripts/ee-accounting-config.js',
515 515
             array(CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE)
516 516
         )
517 517
         ->setInlineDataCallback(
518
-            function () {
518
+            function() {
519 519
                  wp_localize_script(
520 520
                      CoreAssetManager::JS_HANDLE_ACCOUNTING,
521 521
                      'EE_ACCOUNTING_CFG',
Please login to merge, or discard this patch.
Indentation   +521 added lines, -521 removed lines patch added patch discarded remove patch
@@ -31,544 +31,544 @@
 block discarded – undo
31 31
 class CoreAssetManager extends AssetManager
32 32
 {
33 33
 
34
-    // WordPress core / Third party JS asset handles
35
-    const JS_HANDLE_JQUERY = 'jquery';
34
+	// WordPress core / Third party JS asset handles
35
+	const JS_HANDLE_JQUERY = 'jquery';
36 36
 
37
-    const JS_HANDLE_JQUERY_VALIDATE = 'jquery-validate';
37
+	const JS_HANDLE_JQUERY_VALIDATE = 'jquery-validate';
38 38
 
39
-    const JS_HANDLE_JQUERY_VALIDATE_EXTRA = 'jquery-validate-extra-methods';
39
+	const JS_HANDLE_JQUERY_VALIDATE_EXTRA = 'jquery-validate-extra-methods';
40 40
 
41
-    const JS_HANDLE_UNDERSCORE = 'underscore';
41
+	const JS_HANDLE_UNDERSCORE = 'underscore';
42 42
 
43
-    const JS_HANDLE_ACCOUNTING_CORE = 'ee-accounting-core';
43
+	const JS_HANDLE_ACCOUNTING_CORE = 'ee-accounting-core';
44 44
 
45
-    /**
46
-     * @since $VID:$
47
-     */
48
-    const JS_HANDLE_REACT = 'react';
45
+	/**
46
+	 * @since $VID:$
47
+	 */
48
+	const JS_HANDLE_REACT = 'react';
49 49
 
50
-    /**
51
-     * @since $VID:$
52
-     */
53
-    const JS_HANDLE_REACT_DOM = 'react-dom';
50
+	/**
51
+	 * @since $VID:$
52
+	 */
53
+	const JS_HANDLE_REACT_DOM = 'react-dom';
54 54
 
55
-    /**
56
-     * @since $VID:$
57
-     */
58
-    const JS_HANDLE_LODASH = 'lodash';
55
+	/**
56
+	 * @since $VID:$
57
+	 */
58
+	const JS_HANDLE_LODASH = 'lodash';
59 59
 
60
-    // EE JS assets handles
61
-    const JS_HANDLE_MANIFEST = 'ee-manifest';
60
+	// EE JS assets handles
61
+	const JS_HANDLE_MANIFEST = 'ee-manifest';
62 62
 
63
-    const JS_HANDLE_JS_CORE = 'eejs-core';
63
+	const JS_HANDLE_JS_CORE = 'eejs-core';
64 64
 
65
-    const JS_HANDLE_VENDOR = 'eventespresso-vendor';
65
+	const JS_HANDLE_VENDOR = 'eventespresso-vendor';
66 66
 
67
-    const JS_HANDLE_DATA_STORES = 'eventespresso-data-stores';
67
+	const JS_HANDLE_DATA_STORES = 'eventespresso-data-stores';
68 68
 
69
-    const JS_HANDLE_HELPERS = 'eventespresso-helpers';
69
+	const JS_HANDLE_HELPERS = 'eventespresso-helpers';
70 70
 
71
-    const JS_HANDLE_MODEL = 'eventespresso-model';
71
+	const JS_HANDLE_MODEL = 'eventespresso-model';
72 72
 
73
-    const JS_HANDLE_VALUE_OBJECTS = 'eventespresso-value-objects';
73
+	const JS_HANDLE_VALUE_OBJECTS = 'eventespresso-value-objects';
74 74
 
75
-    const JS_HANDLE_HOCS = 'eventespresso-hocs';
75
+	const JS_HANDLE_HOCS = 'eventespresso-hocs';
76 76
 
77
-    const JS_HANDLE_COMPONENTS = 'eventespresso-components';
78
-
79
-    const JS_HANDLE_EDITOR_HOCS = 'eventespresso-editor-hocs';
77
+	const JS_HANDLE_COMPONENTS = 'eventespresso-components';
78
+
79
+	const JS_HANDLE_EDITOR_HOCS = 'eventespresso-editor-hocs';
80 80
 
81
-    const JS_HANDLE_VALIDATORS = 'eventespresso-validators';
81
+	const JS_HANDLE_VALIDATORS = 'eventespresso-validators';
82 82
 
83
-    const JS_HANDLE_CORE = 'espresso_core';
83
+	const JS_HANDLE_CORE = 'espresso_core';
84 84
 
85
-    const JS_HANDLE_I18N = 'eei18n';
86
-
87
-    const JS_HANDLE_ACCOUNTING = 'ee-accounting';
88
-
89
-    const JS_HANDLE_WP_PLUGINS_PAGE = 'ee-wp-plugins-page';
90
-
91
-    // EE CSS assets handles
92
-    const CSS_HANDLE_DEFAULT = 'espresso_default';
93
-
94
-    const CSS_HANDLE_CUSTOM = 'espresso_custom_css';
95
-
96
-    const CSS_HANDLE_COMPONENTS = 'eventespresso-components';
97
-
98
-    /**
99
-     * @var EE_Currency_Config $currency_config
100
-     */
101
-    protected $currency_config;
102
-
103
-    /**
104
-     * @var EE_Template_Config $template_config
105
-     */
106
-    protected $template_config;
107
-
108
-
109
-    /**
110
-     * CoreAssetRegister constructor.
111
-     *
112
-     * @param AssetCollection    $assets
113
-     * @param EE_Currency_Config $currency_config
114
-     * @param EE_Template_Config $template_config
115
-     * @param DomainInterface    $domain
116
-     * @param Registry           $registry
117
-     */
118
-    public function __construct(
119
-        AssetCollection $assets,
120
-        EE_Currency_Config $currency_config,
121
-        EE_Template_Config $template_config,
122
-        DomainInterface $domain,
123
-        Registry $registry
124
-    ) {
125
-        $this->currency_config = $currency_config;
126
-        $this->template_config = $template_config;
127
-        parent::__construct($domain, $assets, $registry);
128
-    }
129
-
130
-
131
-    /**
132
-     * @since 4.9.62.p
133
-     * @throws DomainException
134
-     * @throws DuplicateCollectionIdentifierException
135
-     * @throws InvalidArgumentException
136
-     * @throws InvalidDataTypeException
137
-     * @throws InvalidEntityException
138
-     * @throws InvalidInterfaceException
139
-     */
140
-    public function addAssets()
141
-    {
142
-        $this->addJavascriptFiles();
143
-        $this->addStylesheetFiles();
144
-    }
145
-
146
-
147
-    /**
148
-     * @since 4.9.62.p
149
-     * @throws DomainException
150
-     * @throws DuplicateCollectionIdentifierException
151
-     * @throws InvalidArgumentException
152
-     * @throws InvalidDataTypeException
153
-     * @throws InvalidEntityException
154
-     * @throws InvalidInterfaceException
155
-     */
156
-    public function addJavascriptFiles()
157
-    {
158
-        $this->loadCoreJs();
159
-        $this->loadJqueryValidate();
160
-        $this->loadAccountingJs();
161
-        add_action(
162
-            'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__before_script',
163
-            array($this, 'loadQtipJs')
164
-        );
165
-        $this->registerAdminAssets();
166
-    }
167
-
168
-
169
-    /**
170
-     * @since 4.9.62.p
171
-     * @throws DuplicateCollectionIdentifierException
172
-     * @throws InvalidDataTypeException
173
-     * @throws InvalidEntityException
174
-     */
175
-    public function addStylesheetFiles()
176
-    {
177
-        $this->loadCoreCss();
178
-    }
179
-
180
-
181
-    /**
182
-     * core default javascript
183
-     *
184
-     * @since 4.9.62.p
185
-     * @throws DomainException
186
-     * @throws DuplicateCollectionIdentifierException
187
-     * @throws InvalidArgumentException
188
-     * @throws InvalidDataTypeException
189
-     * @throws InvalidEntityException
190
-     * @throws InvalidInterfaceException
191
-     */
192
-    private function loadCoreJs()
193
-    {
194
-        // conditionally load third-party libraries that WP core MIGHT have.
195
-        $this->registerWpAssets();
196
-
197
-        $this->addJavascript(
198
-            CoreAssetManager::JS_HANDLE_MANIFEST,
199
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'manifest')
200
-        );
201
-
202
-        $this->addJavascript(
203
-            CoreAssetManager::JS_HANDLE_JS_CORE,
204
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'eejs'),
205
-            array(CoreAssetManager::JS_HANDLE_MANIFEST)
206
-        )
207
-        ->setHasInlineData();
208
-
209
-        $this->addJavascript(
210
-            CoreAssetManager::JS_HANDLE_VENDOR,
211
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'vendor'),
212
-            array(
213
-                CoreAssetManager::JS_HANDLE_JS_CORE,
214
-                CoreAssetManager::JS_HANDLE_REACT,
215
-                CoreAssetManager::JS_HANDLE_REACT_DOM,
216
-                CoreAssetManager::JS_HANDLE_LODASH,
217
-            )
218
-        );
219
-
220
-        $this->addJavascript(
221
-            CoreAssetManager::JS_HANDLE_VALIDATORS,
222
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'validators')
223
-        )->setRequiresTranslation();
224
-
225
-        $this->addJavascript(
226
-            CoreAssetManager::JS_HANDLE_HELPERS,
227
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'helpers'),
228
-            array(
229
-                CoreAssetManager::JS_HANDLE_VALIDATORS
230
-            )
231
-        )->setRequiresTranslation();
232
-
233
-        $this->addJavascript(
234
-            CoreAssetManager::JS_HANDLE_MODEL,
235
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'model'),
236
-            array(
237
-                CoreAssetManager::JS_HANDLE_HELPERS
238
-            )
239
-        )->setRequiresTranslation();
240
-
241
-        $this->addJavascript(
242
-            CoreAssetManager::JS_HANDLE_VALUE_OBJECTS,
243
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'valueObjects'),
244
-            array(
245
-                CoreAssetManager::JS_HANDLE_MODEL
246
-            )
247
-        )->setRequiresTranslation();
248
-
249
-        $this->addJavascript(
250
-            CoreAssetManager::JS_HANDLE_DATA_STORES,
251
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'data-stores'),
252
-            array(
253
-                CoreAssetManager::JS_HANDLE_VENDOR,
254
-                'wp-data',
255
-                'wp-api-request',
256
-                CoreAssetManager::JS_HANDLE_VALUE_OBJECTS
257
-            )
258
-        )
259
-             ->setRequiresTranslation();
260
-
261
-        $this->addJavascript(
262
-            CoreAssetManager::JS_HANDLE_HOCS,
263
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'hocs'),
264
-            array(
265
-                CoreAssetManager::JS_HANDLE_DATA_STORES,
266
-                CoreAssetManager::JS_HANDLE_VALUE_OBJECTS,
267
-                'wp-components',
268
-            )
269
-        )->setRequiresTranslation();
270
-
271
-        $this->addJavascript(
272
-            CoreAssetManager::JS_HANDLE_COMPONENTS,
273
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'components'),
274
-            array(
275
-                CoreAssetManager::JS_HANDLE_DATA_STORES,
276
-                CoreAssetManager::JS_HANDLE_VALUE_OBJECTS,
277
-                'wp-components',
278
-            )
279
-        )
280
-        ->setRequiresTranslation();
281
-
282
-        $this->addJavascript(
283
-            CoreAssetManager::JS_HANDLE_EDITOR_HOCS,
284
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'editor-hocs'),
285
-            array(
286
-                CoreAssetManager::JS_HANDLE_COMPONENTS
287
-            )
288
-        )->setRequiresTranslation();
289
-
290
-        $this->registry->addData('eejs_api_nonce', wp_create_nonce('wp_rest'));
291
-        $this->registry->addData(
292
-            'paths',
293
-            array(
294
-                'rest_route' => rest_url('ee/v4.8.36/'),
295
-                'collection_endpoints' => EED_Core_Rest_Api::getCollectionRoutesIndexedByModelName(),
296
-                'primary_keys' => EED_Core_Rest_Api::getPrimaryKeyNamesIndexedByModelName(),
297
-                'site_url' => site_url('/'),
298
-                'admin_url' => admin_url('/'),
299
-            )
300
-        );
301
-        /** site formatting values **/
302
-        $this->registry->addData(
303
-            'site_formats',
304
-            array(
305
-                'date_formats' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats()
306
-            )
307
-        );
308
-        /** currency data **/
309
-        $this->registry->addData(
310
-            'currency_config',
311
-            $this->getCurrencySettings()
312
-        );
313
-        /** site timezone */
314
-        $this->registry->addData(
315
-            'default_timezone',
316
-            array(
317
-                'pretty' => EEH_DTT_Helper::get_timezone_string_for_display(),
318
-                'string' => get_option('timezone_string'),
319
-                'offset' => EEH_DTT_Helper::get_site_timezone_gmt_offset(),
320
-            )
321
-        );
322
-        /** site locale (user locale if user logged in) */
323
-        $this->registry->addData(
324
-            'locale',
325
-            array(
326
-                'user' => get_user_locale(),
327
-                'site' => get_locale()
328
-            )
329
-        );
330
-
331
-        $this->addJavascript(
332
-            CoreAssetManager::JS_HANDLE_CORE,
333
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
334
-            array(CoreAssetManager::JS_HANDLE_JQUERY)
335
-        )
336
-        ->setInlineDataCallback(
337
-            function () {
338
-                wp_localize_script(
339
-                    CoreAssetManager::JS_HANDLE_CORE,
340
-                    CoreAssetManager::JS_HANDLE_I18N,
341
-                    EE_Registry::$i18n_js_strings
342
-                );
343
-            }
344
-        );
345
-    }
346
-
347
-
348
-    /**
349
-     * Registers vendor files that are bundled with a later version WP but might not be for the current version of
350
-     * WordPress in the running environment.
351
-     *
352
-     * @throws DuplicateCollectionIdentifierException
353
-     * @throws InvalidDataTypeException
354
-     * @throws InvalidEntityException
355
-     * @throws DomainException
356
-     * @since $VID:$
357
-     */
358
-    private function registerWpAssets()
359
-    {
360
-        global $wp_version;
361
-        if (version_compare($wp_version, '5.0.beta', '>=')) {
362
-            return;
363
-        }
364
-        $this->addVendorJavascript(CoreAssetManager::JS_HANDLE_REACT)
365
-            ->setVersion('16.6.0');
366
-        $this->addVendorJavascript(
367
-            CoreAssetManager::JS_HANDLE_REACT_DOM,
368
-            array(CoreAssetManager::JS_HANDLE_REACT)
369
-        )->setVersion('16.6.0');
370
-        $this->addVendorJavascript(CoreAssetManager::JS_HANDLE_LODASH)
371
-            ->setInlineDataCallback(
372
-                function() {
373
-                    wp_add_inline_script(
374
-                        CoreAssetManager::JS_HANDLE_LODASH,
375
-                        'window.lodash = _.noConflict();'
376
-                    );
377
-                }
378
-            )
379
-            ->setVersion('4.17.11');
380
-    }
381
-
382
-
383
-    /**
384
-     * Returns configuration data for the accounting-js library.
385
-     * @since $VID:$
386
-     * @return array
387
-     */
388
-    private function getAccountingSettings() {
389
-        return array(
390
-            'currency' => array(
391
-                'symbol'    => $this->currency_config->sign,
392
-                'format'    => array(
393
-                    'pos'  => $this->currency_config->sign_b4 ? '%s%v' : '%v%s',
394
-                    'neg'  => $this->currency_config->sign_b4 ? '- %s%v' : '- %v%s',
395
-                    'zero' => $this->currency_config->sign_b4 ? '%s--' : '--%s',
396
-                ),
397
-                'decimal'   => $this->currency_config->dec_mrk,
398
-                'thousand'  => $this->currency_config->thsnds,
399
-                'precision' => $this->currency_config->dec_plc,
400
-            ),
401
-            'number'   => array(
402
-                'precision' => $this->currency_config->dec_plc,
403
-                'thousand'  => $this->currency_config->thsnds,
404
-                'decimal'   => $this->currency_config->dec_mrk,
405
-            ),
406
-        );
407
-    }
408
-
409
-
410
-    /**
411
-     * Returns configuration data for the js Currency VO.
412
-     * @since $VID:$
413
-     * @return array
414
-     */
415
-    private function getCurrencySettings()
416
-    {
417
-        return array(
418
-            'code' => $this->currency_config->code,
419
-            'singularLabel' => $this->currency_config->name,
420
-            'pluralLabel' => $this->currency_config->plural,
421
-            'sign' => $this->currency_config->sign,
422
-            'signB4' => $this->currency_config->sign_b4,
423
-            'decimalPlaces' => $this->currency_config->dec_plc,
424
-            'decimalMark' => $this->currency_config->dec_mrk,
425
-            'thousandsSeparator' => $this->currency_config->thsnds,
426
-        );
427
-    }
428
-
429
-
430
-    /**
431
-     * @since 4.9.62.p
432
-     * @throws DuplicateCollectionIdentifierException
433
-     * @throws InvalidDataTypeException
434
-     * @throws InvalidEntityException
435
-     */
436
-    private function loadCoreCss()
437
-    {
438
-        if ($this->template_config->enable_default_style && ! is_admin()) {
439
-            $this->addStylesheet(
440
-                CoreAssetManager::CSS_HANDLE_DEFAULT,
441
-                is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css')
442
-                    ? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css'
443
-                    : EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
444
-                array('dashicons')
445
-            );
446
-            //Load custom style sheet if available
447
-            if ($this->template_config->custom_style_sheet !== null) {
448
-                $this->addStylesheet(
449
-                    CoreAssetManager::CSS_HANDLE_CUSTOM,
450
-                    EVENT_ESPRESSO_UPLOAD_URL . 'css/' . $this->template_config->custom_style_sheet,
451
-                    array(CoreAssetManager::CSS_HANDLE_DEFAULT)
452
-                );
453
-            }
454
-        }
455
-        $this->addStylesheet(
456
-            CoreAssetManager::CSS_HANDLE_COMPONENTS,
457
-            $this->registry->getCssUrl(
458
-                $this->domain->assetNamespace(),
459
-                'components'
460
-            ),
461
-            ['wp-components']
462
-        );
463
-    }
464
-
465
-
466
-    /**
467
-     * jQuery Validate for form validation
468
-     *
469
-     * @since 4.9.62.p
470
-     * @throws DomainException
471
-     * @throws DuplicateCollectionIdentifierException
472
-     * @throws InvalidDataTypeException
473
-     * @throws InvalidEntityException
474
-     */
475
-    private function loadJqueryValidate()
476
-    {
477
-        $this->addJavascript(
478
-            CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE,
479
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
480
-            array(CoreAssetManager::JS_HANDLE_JQUERY)
481
-        )
482
-        ->setVersion('1.15.0');
483
-
484
-        $this->addJavascript(
485
-            CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE_EXTRA,
486
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
487
-            array(CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE)
488
-        )
489
-        ->setVersion('1.15.0');
490
-    }
491
-
492
-
493
-    /**
494
-     * accounting.js for performing client-side calculations
495
-     *
496
-     * @since 4.9.62.p
497
-     * @throws DomainException
498
-     * @throws DuplicateCollectionIdentifierException
499
-     * @throws InvalidDataTypeException
500
-     * @throws InvalidEntityException
501
-     */
502
-    private function loadAccountingJs()
503
-    {
504
-        //accounting.js library
505
-        // @link http://josscrowcroft.github.io/accounting.js/
506
-        $this->addJavascript(
507
-            CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE,
508
-            EE_THIRD_PARTY_URL . 'accounting/accounting.js',
509
-            array(CoreAssetManager::JS_HANDLE_UNDERSCORE)
510
-        )
511
-        ->setVersion('0.3.2');
512
-
513
-        $this->addJavascript(
514
-            CoreAssetManager::JS_HANDLE_ACCOUNTING,
515
-            EE_GLOBAL_ASSETS_URL . 'scripts/ee-accounting-config.js',
516
-            array(CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE)
517
-        )
518
-        ->setInlineDataCallback(
519
-            function () {
520
-                 wp_localize_script(
521
-                     CoreAssetManager::JS_HANDLE_ACCOUNTING,
522
-                     'EE_ACCOUNTING_CFG',
523
-                     $this->getAccountingSettings()
524
-                 );
525
-            }
526
-        )
527
-        ->setVersion();
528
-    }
529
-
530
-
531
-    /**
532
-     * registers assets for cleaning your ears
533
-     *
534
-     * @param JavascriptAsset $script
535
-     */
536
-    public function loadQtipJs(JavascriptAsset $script)
537
-    {
538
-        // qtip is turned OFF by default, but prior to the wp_enqueue_scripts hook,
539
-        // can be turned back on again via: add_filter('FHEE_load_qtip', '__return_true' );
540
-        if (
541
-            $script->handle() === CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE
542
-            && apply_filters('FHEE_load_qtip', false)
543
-        ) {
544
-            EEH_Qtip_Loader::instance()->register_and_enqueue();
545
-        }
546
-    }
547
-
548
-
549
-    /**
550
-     * assets that are used in the WordPress admin
551
-     *
552
-     * @since 4.9.62.p
553
-     * @throws DuplicateCollectionIdentifierException
554
-     * @throws InvalidDataTypeException
555
-     * @throws InvalidEntityException
556
-     */
557
-    private function registerAdminAssets()
558
-    {
559
-        $this->addJavascript(
560
-            CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE,
561
-            $this->registry->getJsUrl($this->domain->assetNamespace(), 'wp-plugins-page'),
562
-            array(
563
-                CoreAssetManager::JS_HANDLE_JQUERY,
564
-                CoreAssetManager::JS_HANDLE_VENDOR,
565
-            )
566
-        )
567
-        ->setRequiresTranslation();
568
-
569
-        $this->addStylesheet(
570
-            CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE,
571
-            $this->registry->getCssUrl($this->domain->assetNamespace(), 'wp-plugins-page')
572
-        );
573
-    }
85
+	const JS_HANDLE_I18N = 'eei18n';
86
+
87
+	const JS_HANDLE_ACCOUNTING = 'ee-accounting';
88
+
89
+	const JS_HANDLE_WP_PLUGINS_PAGE = 'ee-wp-plugins-page';
90
+
91
+	// EE CSS assets handles
92
+	const CSS_HANDLE_DEFAULT = 'espresso_default';
93
+
94
+	const CSS_HANDLE_CUSTOM = 'espresso_custom_css';
95
+
96
+	const CSS_HANDLE_COMPONENTS = 'eventespresso-components';
97
+
98
+	/**
99
+	 * @var EE_Currency_Config $currency_config
100
+	 */
101
+	protected $currency_config;
102
+
103
+	/**
104
+	 * @var EE_Template_Config $template_config
105
+	 */
106
+	protected $template_config;
107
+
108
+
109
+	/**
110
+	 * CoreAssetRegister constructor.
111
+	 *
112
+	 * @param AssetCollection    $assets
113
+	 * @param EE_Currency_Config $currency_config
114
+	 * @param EE_Template_Config $template_config
115
+	 * @param DomainInterface    $domain
116
+	 * @param Registry           $registry
117
+	 */
118
+	public function __construct(
119
+		AssetCollection $assets,
120
+		EE_Currency_Config $currency_config,
121
+		EE_Template_Config $template_config,
122
+		DomainInterface $domain,
123
+		Registry $registry
124
+	) {
125
+		$this->currency_config = $currency_config;
126
+		$this->template_config = $template_config;
127
+		parent::__construct($domain, $assets, $registry);
128
+	}
129
+
130
+
131
+	/**
132
+	 * @since 4.9.62.p
133
+	 * @throws DomainException
134
+	 * @throws DuplicateCollectionIdentifierException
135
+	 * @throws InvalidArgumentException
136
+	 * @throws InvalidDataTypeException
137
+	 * @throws InvalidEntityException
138
+	 * @throws InvalidInterfaceException
139
+	 */
140
+	public function addAssets()
141
+	{
142
+		$this->addJavascriptFiles();
143
+		$this->addStylesheetFiles();
144
+	}
145
+
146
+
147
+	/**
148
+	 * @since 4.9.62.p
149
+	 * @throws DomainException
150
+	 * @throws DuplicateCollectionIdentifierException
151
+	 * @throws InvalidArgumentException
152
+	 * @throws InvalidDataTypeException
153
+	 * @throws InvalidEntityException
154
+	 * @throws InvalidInterfaceException
155
+	 */
156
+	public function addJavascriptFiles()
157
+	{
158
+		$this->loadCoreJs();
159
+		$this->loadJqueryValidate();
160
+		$this->loadAccountingJs();
161
+		add_action(
162
+			'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__before_script',
163
+			array($this, 'loadQtipJs')
164
+		);
165
+		$this->registerAdminAssets();
166
+	}
167
+
168
+
169
+	/**
170
+	 * @since 4.9.62.p
171
+	 * @throws DuplicateCollectionIdentifierException
172
+	 * @throws InvalidDataTypeException
173
+	 * @throws InvalidEntityException
174
+	 */
175
+	public function addStylesheetFiles()
176
+	{
177
+		$this->loadCoreCss();
178
+	}
179
+
180
+
181
+	/**
182
+	 * core default javascript
183
+	 *
184
+	 * @since 4.9.62.p
185
+	 * @throws DomainException
186
+	 * @throws DuplicateCollectionIdentifierException
187
+	 * @throws InvalidArgumentException
188
+	 * @throws InvalidDataTypeException
189
+	 * @throws InvalidEntityException
190
+	 * @throws InvalidInterfaceException
191
+	 */
192
+	private function loadCoreJs()
193
+	{
194
+		// conditionally load third-party libraries that WP core MIGHT have.
195
+		$this->registerWpAssets();
196
+
197
+		$this->addJavascript(
198
+			CoreAssetManager::JS_HANDLE_MANIFEST,
199
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'manifest')
200
+		);
201
+
202
+		$this->addJavascript(
203
+			CoreAssetManager::JS_HANDLE_JS_CORE,
204
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'eejs'),
205
+			array(CoreAssetManager::JS_HANDLE_MANIFEST)
206
+		)
207
+		->setHasInlineData();
208
+
209
+		$this->addJavascript(
210
+			CoreAssetManager::JS_HANDLE_VENDOR,
211
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'vendor'),
212
+			array(
213
+				CoreAssetManager::JS_HANDLE_JS_CORE,
214
+				CoreAssetManager::JS_HANDLE_REACT,
215
+				CoreAssetManager::JS_HANDLE_REACT_DOM,
216
+				CoreAssetManager::JS_HANDLE_LODASH,
217
+			)
218
+		);
219
+
220
+		$this->addJavascript(
221
+			CoreAssetManager::JS_HANDLE_VALIDATORS,
222
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'validators')
223
+		)->setRequiresTranslation();
224
+
225
+		$this->addJavascript(
226
+			CoreAssetManager::JS_HANDLE_HELPERS,
227
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'helpers'),
228
+			array(
229
+				CoreAssetManager::JS_HANDLE_VALIDATORS
230
+			)
231
+		)->setRequiresTranslation();
232
+
233
+		$this->addJavascript(
234
+			CoreAssetManager::JS_HANDLE_MODEL,
235
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'model'),
236
+			array(
237
+				CoreAssetManager::JS_HANDLE_HELPERS
238
+			)
239
+		)->setRequiresTranslation();
240
+
241
+		$this->addJavascript(
242
+			CoreAssetManager::JS_HANDLE_VALUE_OBJECTS,
243
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'valueObjects'),
244
+			array(
245
+				CoreAssetManager::JS_HANDLE_MODEL
246
+			)
247
+		)->setRequiresTranslation();
248
+
249
+		$this->addJavascript(
250
+			CoreAssetManager::JS_HANDLE_DATA_STORES,
251
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'data-stores'),
252
+			array(
253
+				CoreAssetManager::JS_HANDLE_VENDOR,
254
+				'wp-data',
255
+				'wp-api-request',
256
+				CoreAssetManager::JS_HANDLE_VALUE_OBJECTS
257
+			)
258
+		)
259
+			 ->setRequiresTranslation();
260
+
261
+		$this->addJavascript(
262
+			CoreAssetManager::JS_HANDLE_HOCS,
263
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'hocs'),
264
+			array(
265
+				CoreAssetManager::JS_HANDLE_DATA_STORES,
266
+				CoreAssetManager::JS_HANDLE_VALUE_OBJECTS,
267
+				'wp-components',
268
+			)
269
+		)->setRequiresTranslation();
270
+
271
+		$this->addJavascript(
272
+			CoreAssetManager::JS_HANDLE_COMPONENTS,
273
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'components'),
274
+			array(
275
+				CoreAssetManager::JS_HANDLE_DATA_STORES,
276
+				CoreAssetManager::JS_HANDLE_VALUE_OBJECTS,
277
+				'wp-components',
278
+			)
279
+		)
280
+		->setRequiresTranslation();
281
+
282
+		$this->addJavascript(
283
+			CoreAssetManager::JS_HANDLE_EDITOR_HOCS,
284
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'editor-hocs'),
285
+			array(
286
+				CoreAssetManager::JS_HANDLE_COMPONENTS
287
+			)
288
+		)->setRequiresTranslation();
289
+
290
+		$this->registry->addData('eejs_api_nonce', wp_create_nonce('wp_rest'));
291
+		$this->registry->addData(
292
+			'paths',
293
+			array(
294
+				'rest_route' => rest_url('ee/v4.8.36/'),
295
+				'collection_endpoints' => EED_Core_Rest_Api::getCollectionRoutesIndexedByModelName(),
296
+				'primary_keys' => EED_Core_Rest_Api::getPrimaryKeyNamesIndexedByModelName(),
297
+				'site_url' => site_url('/'),
298
+				'admin_url' => admin_url('/'),
299
+			)
300
+		);
301
+		/** site formatting values **/
302
+		$this->registry->addData(
303
+			'site_formats',
304
+			array(
305
+				'date_formats' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats()
306
+			)
307
+		);
308
+		/** currency data **/
309
+		$this->registry->addData(
310
+			'currency_config',
311
+			$this->getCurrencySettings()
312
+		);
313
+		/** site timezone */
314
+		$this->registry->addData(
315
+			'default_timezone',
316
+			array(
317
+				'pretty' => EEH_DTT_Helper::get_timezone_string_for_display(),
318
+				'string' => get_option('timezone_string'),
319
+				'offset' => EEH_DTT_Helper::get_site_timezone_gmt_offset(),
320
+			)
321
+		);
322
+		/** site locale (user locale if user logged in) */
323
+		$this->registry->addData(
324
+			'locale',
325
+			array(
326
+				'user' => get_user_locale(),
327
+				'site' => get_locale()
328
+			)
329
+		);
330
+
331
+		$this->addJavascript(
332
+			CoreAssetManager::JS_HANDLE_CORE,
333
+			EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
334
+			array(CoreAssetManager::JS_HANDLE_JQUERY)
335
+		)
336
+		->setInlineDataCallback(
337
+			function () {
338
+				wp_localize_script(
339
+					CoreAssetManager::JS_HANDLE_CORE,
340
+					CoreAssetManager::JS_HANDLE_I18N,
341
+					EE_Registry::$i18n_js_strings
342
+				);
343
+			}
344
+		);
345
+	}
346
+
347
+
348
+	/**
349
+	 * Registers vendor files that are bundled with a later version WP but might not be for the current version of
350
+	 * WordPress in the running environment.
351
+	 *
352
+	 * @throws DuplicateCollectionIdentifierException
353
+	 * @throws InvalidDataTypeException
354
+	 * @throws InvalidEntityException
355
+	 * @throws DomainException
356
+	 * @since $VID:$
357
+	 */
358
+	private function registerWpAssets()
359
+	{
360
+		global $wp_version;
361
+		if (version_compare($wp_version, '5.0.beta', '>=')) {
362
+			return;
363
+		}
364
+		$this->addVendorJavascript(CoreAssetManager::JS_HANDLE_REACT)
365
+			->setVersion('16.6.0');
366
+		$this->addVendorJavascript(
367
+			CoreAssetManager::JS_HANDLE_REACT_DOM,
368
+			array(CoreAssetManager::JS_HANDLE_REACT)
369
+		)->setVersion('16.6.0');
370
+		$this->addVendorJavascript(CoreAssetManager::JS_HANDLE_LODASH)
371
+			->setInlineDataCallback(
372
+				function() {
373
+					wp_add_inline_script(
374
+						CoreAssetManager::JS_HANDLE_LODASH,
375
+						'window.lodash = _.noConflict();'
376
+					);
377
+				}
378
+			)
379
+			->setVersion('4.17.11');
380
+	}
381
+
382
+
383
+	/**
384
+	 * Returns configuration data for the accounting-js library.
385
+	 * @since $VID:$
386
+	 * @return array
387
+	 */
388
+	private function getAccountingSettings() {
389
+		return array(
390
+			'currency' => array(
391
+				'symbol'    => $this->currency_config->sign,
392
+				'format'    => array(
393
+					'pos'  => $this->currency_config->sign_b4 ? '%s%v' : '%v%s',
394
+					'neg'  => $this->currency_config->sign_b4 ? '- %s%v' : '- %v%s',
395
+					'zero' => $this->currency_config->sign_b4 ? '%s--' : '--%s',
396
+				),
397
+				'decimal'   => $this->currency_config->dec_mrk,
398
+				'thousand'  => $this->currency_config->thsnds,
399
+				'precision' => $this->currency_config->dec_plc,
400
+			),
401
+			'number'   => array(
402
+				'precision' => $this->currency_config->dec_plc,
403
+				'thousand'  => $this->currency_config->thsnds,
404
+				'decimal'   => $this->currency_config->dec_mrk,
405
+			),
406
+		);
407
+	}
408
+
409
+
410
+	/**
411
+	 * Returns configuration data for the js Currency VO.
412
+	 * @since $VID:$
413
+	 * @return array
414
+	 */
415
+	private function getCurrencySettings()
416
+	{
417
+		return array(
418
+			'code' => $this->currency_config->code,
419
+			'singularLabel' => $this->currency_config->name,
420
+			'pluralLabel' => $this->currency_config->plural,
421
+			'sign' => $this->currency_config->sign,
422
+			'signB4' => $this->currency_config->sign_b4,
423
+			'decimalPlaces' => $this->currency_config->dec_plc,
424
+			'decimalMark' => $this->currency_config->dec_mrk,
425
+			'thousandsSeparator' => $this->currency_config->thsnds,
426
+		);
427
+	}
428
+
429
+
430
+	/**
431
+	 * @since 4.9.62.p
432
+	 * @throws DuplicateCollectionIdentifierException
433
+	 * @throws InvalidDataTypeException
434
+	 * @throws InvalidEntityException
435
+	 */
436
+	private function loadCoreCss()
437
+	{
438
+		if ($this->template_config->enable_default_style && ! is_admin()) {
439
+			$this->addStylesheet(
440
+				CoreAssetManager::CSS_HANDLE_DEFAULT,
441
+				is_readable(EVENT_ESPRESSO_UPLOAD_DIR . 'css/style.css')
442
+					? EVENT_ESPRESSO_UPLOAD_DIR . 'css/espresso_default.css'
443
+					: EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
444
+				array('dashicons')
445
+			);
446
+			//Load custom style sheet if available
447
+			if ($this->template_config->custom_style_sheet !== null) {
448
+				$this->addStylesheet(
449
+					CoreAssetManager::CSS_HANDLE_CUSTOM,
450
+					EVENT_ESPRESSO_UPLOAD_URL . 'css/' . $this->template_config->custom_style_sheet,
451
+					array(CoreAssetManager::CSS_HANDLE_DEFAULT)
452
+				);
453
+			}
454
+		}
455
+		$this->addStylesheet(
456
+			CoreAssetManager::CSS_HANDLE_COMPONENTS,
457
+			$this->registry->getCssUrl(
458
+				$this->domain->assetNamespace(),
459
+				'components'
460
+			),
461
+			['wp-components']
462
+		);
463
+	}
464
+
465
+
466
+	/**
467
+	 * jQuery Validate for form validation
468
+	 *
469
+	 * @since 4.9.62.p
470
+	 * @throws DomainException
471
+	 * @throws DuplicateCollectionIdentifierException
472
+	 * @throws InvalidDataTypeException
473
+	 * @throws InvalidEntityException
474
+	 */
475
+	private function loadJqueryValidate()
476
+	{
477
+		$this->addJavascript(
478
+			CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE,
479
+			EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
480
+			array(CoreAssetManager::JS_HANDLE_JQUERY)
481
+		)
482
+		->setVersion('1.15.0');
483
+
484
+		$this->addJavascript(
485
+			CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE_EXTRA,
486
+			EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
487
+			array(CoreAssetManager::JS_HANDLE_JQUERY_VALIDATE)
488
+		)
489
+		->setVersion('1.15.0');
490
+	}
491
+
492
+
493
+	/**
494
+	 * accounting.js for performing client-side calculations
495
+	 *
496
+	 * @since 4.9.62.p
497
+	 * @throws DomainException
498
+	 * @throws DuplicateCollectionIdentifierException
499
+	 * @throws InvalidDataTypeException
500
+	 * @throws InvalidEntityException
501
+	 */
502
+	private function loadAccountingJs()
503
+	{
504
+		//accounting.js library
505
+		// @link http://josscrowcroft.github.io/accounting.js/
506
+		$this->addJavascript(
507
+			CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE,
508
+			EE_THIRD_PARTY_URL . 'accounting/accounting.js',
509
+			array(CoreAssetManager::JS_HANDLE_UNDERSCORE)
510
+		)
511
+		->setVersion('0.3.2');
512
+
513
+		$this->addJavascript(
514
+			CoreAssetManager::JS_HANDLE_ACCOUNTING,
515
+			EE_GLOBAL_ASSETS_URL . 'scripts/ee-accounting-config.js',
516
+			array(CoreAssetManager::JS_HANDLE_ACCOUNTING_CORE)
517
+		)
518
+		->setInlineDataCallback(
519
+			function () {
520
+				 wp_localize_script(
521
+					 CoreAssetManager::JS_HANDLE_ACCOUNTING,
522
+					 'EE_ACCOUNTING_CFG',
523
+					 $this->getAccountingSettings()
524
+				 );
525
+			}
526
+		)
527
+		->setVersion();
528
+	}
529
+
530
+
531
+	/**
532
+	 * registers assets for cleaning your ears
533
+	 *
534
+	 * @param JavascriptAsset $script
535
+	 */
536
+	public function loadQtipJs(JavascriptAsset $script)
537
+	{
538
+		// qtip is turned OFF by default, but prior to the wp_enqueue_scripts hook,
539
+		// can be turned back on again via: add_filter('FHEE_load_qtip', '__return_true' );
540
+		if (
541
+			$script->handle() === CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE
542
+			&& apply_filters('FHEE_load_qtip', false)
543
+		) {
544
+			EEH_Qtip_Loader::instance()->register_and_enqueue();
545
+		}
546
+	}
547
+
548
+
549
+	/**
550
+	 * assets that are used in the WordPress admin
551
+	 *
552
+	 * @since 4.9.62.p
553
+	 * @throws DuplicateCollectionIdentifierException
554
+	 * @throws InvalidDataTypeException
555
+	 * @throws InvalidEntityException
556
+	 */
557
+	private function registerAdminAssets()
558
+	{
559
+		$this->addJavascript(
560
+			CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE,
561
+			$this->registry->getJsUrl($this->domain->assetNamespace(), 'wp-plugins-page'),
562
+			array(
563
+				CoreAssetManager::JS_HANDLE_JQUERY,
564
+				CoreAssetManager::JS_HANDLE_VENDOR,
565
+			)
566
+		)
567
+		->setRequiresTranslation();
568
+
569
+		$this->addStylesheet(
570
+			CoreAssetManager::JS_HANDLE_WP_PLUGINS_PAGE,
571
+			$this->registry->getCssUrl($this->domain->assetNamespace(), 'wp-plugins-page')
572
+		);
573
+	}
574 574
 }
Please login to merge, or discard this patch.
admin_pages/messages/Messages_Admin_Page.core.php 1 patch
Indentation   +4484 added lines, -4484 removed lines patch added patch discarded remove patch
@@ -19,2588 +19,2588 @@  discard block
 block discarded – undo
19 19
 class Messages_Admin_Page extends EE_Admin_Page
20 20
 {
21 21
 
22
-    /**
23
-     * @type EE_Message_Resource_Manager $_message_resource_manager
24
-     */
25
-    protected $_message_resource_manager;
26
-
27
-    /**
28
-     * @type string $_active_message_type_name
29
-     */
30
-    protected $_active_message_type_name = '';
31
-
32
-    /**
33
-     * @type EE_messenger $_active_messenger
34
-     */
35
-    protected $_active_messenger;
36
-    protected $_activate_state;
37
-    protected $_activate_meta_box_type;
38
-    protected $_current_message_meta_box;
39
-    protected $_current_message_meta_box_object;
40
-    protected $_context_switcher;
41
-    protected $_shortcodes = array();
42
-    protected $_active_messengers = array();
43
-    protected $_active_message_types = array();
44
-
45
-    /**
46
-     * @var EE_Message_Template_Group $_message_template_group
47
-     */
48
-    protected $_message_template_group;
49
-    protected $_m_mt_settings = array();
50
-
51
-
52
-    /**
53
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
-     * IF there is no group then it gets automatically set to the Default template pack.
55
-     *
56
-     * @since 4.5.0
57
-     *
58
-     * @var EE_Messages_Template_Pack
59
-     */
60
-    protected $_template_pack;
61
-
62
-
63
-    /**
64
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
-     * group is.  If there is no group then it automatically gets set to default.
66
-     *
67
-     * @since 4.5.0
68
-     *
69
-     * @var string
70
-     */
71
-    protected $_variation;
72
-
73
-
74
-    /**
75
-     * @param bool $routing
76
-     * @throws EE_Error
77
-     */
78
-    public function __construct($routing = true)
79
-    {
80
-        // make sure messages autoloader is running
81
-        EED_Messages::set_autoloaders();
82
-        parent::__construct($routing);
83
-    }
84
-
85
-
86
-    protected function _init_page_props()
87
-    {
88
-        $this->page_slug = EE_MSG_PG_SLUG;
89
-        $this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
-        $this->_admin_base_url = EE_MSG_ADMIN_URL;
91
-        $this->_admin_base_path = EE_MSG_ADMIN;
92
-
93
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
-            : array();
95
-
96
-        $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
-        $this->_load_message_resource_manager();
98
-    }
99
-
100
-
101
-    /**
102
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
-     *
104
-     * @throws EE_Error
105
-     * @throws InvalidDataTypeException
106
-     * @throws InvalidInterfaceException
107
-     * @throws InvalidArgumentException
108
-     * @throws ReflectionException
109
-     */
110
-    protected function _load_message_resource_manager()
111
-    {
112
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
-    }
114
-
115
-
116
-    /**
117
-     * @deprecated 4.9.9.rc.014
118
-     * @return array
119
-     * @throws EE_Error
120
-     * @throws InvalidArgumentException
121
-     * @throws InvalidDataTypeException
122
-     * @throws InvalidInterfaceException
123
-     */
124
-    public function get_messengers_for_list_table()
125
-    {
126
-        EE_Error::doing_it_wrong(
127
-            __METHOD__,
128
-            sprintf(
129
-                esc_html__(
130
-                    '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',
131
-                    'event_espresso'
132
-                ),
133
-                'Messages_Admin_Page::get_messengers_select_input()'
134
-            ),
135
-            '4.9.9.rc.014'
136
-        );
137
-
138
-        $m_values = array();
139
-        $active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
-        // setup messengers for selects
141
-        $i = 1;
142
-        foreach ($active_messengers as $active_messenger) {
143
-            if ($active_messenger instanceof EE_Message) {
144
-                $m_values[ $i ]['id'] = $active_messenger->messenger();
145
-                $m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
-                $i++;
147
-            }
148
-        }
149
-
150
-        return $m_values;
151
-    }
152
-
153
-
154
-    /**
155
-     * @deprecated 4.9.9.rc.014
156
-     * @return array
157
-     * @throws EE_Error
158
-     * @throws InvalidArgumentException
159
-     * @throws InvalidDataTypeException
160
-     * @throws InvalidInterfaceException
161
-     */
162
-    public function get_message_types_for_list_table()
163
-    {
164
-        EE_Error::doing_it_wrong(
165
-            __METHOD__,
166
-            sprintf(
167
-                esc_html__(
168
-                    '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',
169
-                    'event_espresso'
170
-                ),
171
-                'Messages_Admin_Page::get_message_types_select_input()'
172
-            ),
173
-            '4.9.9.rc.014'
174
-        );
175
-
176
-        $mt_values = array();
177
-        $active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
-        $i = 1;
179
-        foreach ($active_messages as $active_message) {
180
-            if ($active_message instanceof EE_Message) {
181
-                $mt_values[ $i ]['id'] = $active_message->message_type();
182
-                $mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
-                $i++;
184
-            }
185
-        }
186
-
187
-        return $mt_values;
188
-    }
189
-
190
-
191
-    /**
192
-     * @deprecated 4.9.9.rc.014
193
-     * @return array
194
-     * @throws EE_Error
195
-     * @throws InvalidArgumentException
196
-     * @throws InvalidDataTypeException
197
-     * @throws InvalidInterfaceException
198
-     */
199
-    public function get_contexts_for_message_types_for_list_table()
200
-    {
201
-        EE_Error::doing_it_wrong(
202
-            __METHOD__,
203
-            sprintf(
204
-                esc_html__(
205
-                    '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',
206
-                    'event_espresso'
207
-                ),
208
-                'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
-            ),
210
-            '4.9.9.rc.014'
211
-        );
212
-
213
-        $contexts = array();
214
-        $active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
-        foreach ($active_message_contexts as $active_message) {
216
-            if ($active_message instanceof EE_Message) {
217
-                $message_type = $active_message->message_type_object();
218
-                if ($message_type instanceof EE_message_type) {
219
-                    $message_type_contexts = $message_type->get_contexts();
220
-                    foreach ($message_type_contexts as $context => $context_details) {
221
-                        $contexts[ $context ] = $context_details['label'];
222
-                    }
223
-                }
224
-            }
225
-        }
226
-
227
-        return $contexts;
228
-    }
229
-
230
-
231
-    /**
232
-     * Generate select input with provided messenger options array.
233
-     *
234
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
-     *                                 labels.
236
-     * @return string
237
-     * @throws EE_Error
238
-     */
239
-    public function get_messengers_select_input($messenger_options)
240
-    {
241
-        // if empty or just one value then just return an empty string
242
-        if (empty($messenger_options)
243
-            || ! is_array($messenger_options)
244
-            || count($messenger_options) === 1
245
-        ) {
246
-            return '';
247
-        }
248
-        // merge in default
249
-        $messenger_options = array_merge(
250
-            array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
-            $messenger_options
252
-        );
253
-        $input = new EE_Select_Input(
254
-            $messenger_options,
255
-            array(
256
-                'html_name'  => 'ee_messenger_filter_by',
257
-                'html_id'    => 'ee_messenger_filter_by',
258
-                'html_class' => 'wide',
259
-                'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
-                    ? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
-                    : 'none_selected',
262
-            )
263
-        );
264
-
265
-        return $input->get_html_for_input();
266
-    }
267
-
268
-
269
-    /**
270
-     * Generate select input with provided message type options array.
271
-     *
272
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
-     *                                    message type labels
274
-     * @return string
275
-     * @throws EE_Error
276
-     */
277
-    public function get_message_types_select_input($message_type_options)
278
-    {
279
-        // if empty or count of options is 1 then just return an empty string
280
-        if (empty($message_type_options)
281
-            || ! is_array($message_type_options)
282
-            || count($message_type_options) === 1
283
-        ) {
284
-            return '';
285
-        }
286
-        // merge in default
287
-        $message_type_options = array_merge(
288
-            array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
-            $message_type_options
290
-        );
291
-        $input = new EE_Select_Input(
292
-            $message_type_options,
293
-            array(
294
-                'html_name'  => 'ee_message_type_filter_by',
295
-                'html_id'    => 'ee_message_type_filter_by',
296
-                'html_class' => 'wide',
297
-                'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
-                    ? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
-                    : 'none_selected',
300
-            )
301
-        );
302
-
303
-        return $input->get_html_for_input();
304
-    }
305
-
306
-
307
-    /**
308
-     * Generate select input with provide message type contexts array.
309
-     *
310
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
-     *                               context label.
312
-     * @return string
313
-     * @throws EE_Error
314
-     */
315
-    public function get_contexts_for_message_types_select_input($context_options)
316
-    {
317
-        // if empty or count of options is one then just return empty string
318
-        if (empty($context_options)
319
-            || ! is_array($context_options)
320
-            || count($context_options) === 1
321
-        ) {
322
-            return '';
323
-        }
324
-        // merge in default
325
-        $context_options = array_merge(
326
-            array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
-            $context_options
328
-        );
329
-        $input = new EE_Select_Input(
330
-            $context_options,
331
-            array(
332
-                'html_name'  => 'ee_context_filter_by',
333
-                'html_id'    => 'ee_context_filter_by',
334
-                'html_class' => 'wide',
335
-                'default'    => isset($this->_req_data['ee_context_filter_by'])
336
-                    ? sanitize_title($this->_req_data['ee_context_filter_by'])
337
-                    : 'none_selected',
338
-            )
339
-        );
340
-
341
-        return $input->get_html_for_input();
342
-    }
343
-
344
-
345
-    protected function _ajax_hooks()
346
-    {
347
-        add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
-        add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
-        add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
-        add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
-        add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
-        add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
-    }
354
-
355
-
356
-    protected function _define_page_props()
357
-    {
358
-        $this->_admin_page_title = $this->page_label;
359
-        $this->_labels = array(
360
-            'buttons'    => array(
361
-                'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
-                'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
-                'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
-            ),
365
-            'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
-        );
367
-    }
368
-
369
-
370
-    /**
371
-     *        an array for storing key => value pairs of request actions and their corresponding methods
372
-     *
373
-     * @access protected
374
-     * @return void
375
-     */
376
-    protected function _set_page_routes()
377
-    {
378
-        $grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
-            ? $this->_req_data['GRP_ID']
380
-            : 0;
381
-        $grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
-            ? $this->_req_data['id']
383
-            : $grp_id;
384
-        $msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
-            ? $this->_req_data['MSG_ID']
386
-            : 0;
387
-
388
-        $this->_page_routes = array(
389
-            'default'                          => array(
390
-                'func'       => '_message_queue_list_table',
391
-                'capability' => 'ee_read_global_messages',
392
-            ),
393
-            'global_mtps'                      => array(
394
-                'func'       => '_ee_default_messages_overview_list_table',
395
-                'capability' => 'ee_read_global_messages',
396
-            ),
397
-            'custom_mtps'                      => array(
398
-                'func'       => '_custom_mtps_preview',
399
-                'capability' => 'ee_read_messages',
400
-            ),
401
-            'add_new_message_template'         => array(
402
-                'func'       => '_add_message_template',
403
-                'capability' => 'ee_edit_messages',
404
-                'noheader'   => true,
405
-            ),
406
-            'edit_message_template'            => array(
407
-                'func'       => '_edit_message_template',
408
-                'capability' => 'ee_edit_message',
409
-                'obj_id'     => $grp_id,
410
-            ),
411
-            'preview_message'                  => array(
412
-                'func'               => '_preview_message',
413
-                'capability'         => 'ee_read_message',
414
-                'obj_id'             => $grp_id,
415
-                'noheader'           => true,
416
-                'headers_sent_route' => 'display_preview_message',
417
-            ),
418
-            'display_preview_message'          => array(
419
-                'func'       => '_display_preview_message',
420
-                'capability' => 'ee_read_message',
421
-                'obj_id'     => $grp_id,
422
-            ),
423
-            'insert_message_template'          => array(
424
-                'func'       => '_insert_or_update_message_template',
425
-                'capability' => 'ee_edit_messages',
426
-                'args'       => array('new_template' => true),
427
-                'noheader'   => true,
428
-            ),
429
-            'update_message_template'          => array(
430
-                'func'       => '_insert_or_update_message_template',
431
-                'capability' => 'ee_edit_message',
432
-                'obj_id'     => $grp_id,
433
-                'args'       => array('new_template' => false),
434
-                'noheader'   => true,
435
-            ),
436
-            'trash_message_template'           => array(
437
-                'func'       => '_trash_or_restore_message_template',
438
-                'capability' => 'ee_delete_message',
439
-                'obj_id'     => $grp_id,
440
-                'args'       => array('trash' => true, 'all' => true),
441
-                'noheader'   => true,
442
-            ),
443
-            'trash_message_template_context'   => array(
444
-                'func'       => '_trash_or_restore_message_template',
445
-                'capability' => 'ee_delete_message',
446
-                'obj_id'     => $grp_id,
447
-                'args'       => array('trash' => true),
448
-                'noheader'   => true,
449
-            ),
450
-            'restore_message_template'         => array(
451
-                'func'       => '_trash_or_restore_message_template',
452
-                'capability' => 'ee_delete_message',
453
-                'obj_id'     => $grp_id,
454
-                'args'       => array('trash' => false, 'all' => true),
455
-                'noheader'   => true,
456
-            ),
457
-            'restore_message_template_context' => array(
458
-                'func'       => '_trash_or_restore_message_template',
459
-                'capability' => 'ee_delete_message',
460
-                'obj_id'     => $grp_id,
461
-                'args'       => array('trash' => false),
462
-                'noheader'   => true,
463
-            ),
464
-            'delete_message_template'          => array(
465
-                'func'       => '_delete_message_template',
466
-                'capability' => 'ee_delete_message',
467
-                'obj_id'     => $grp_id,
468
-                'noheader'   => true,
469
-            ),
470
-            'reset_to_default'                 => array(
471
-                'func'       => '_reset_to_default_template',
472
-                'capability' => 'ee_edit_message',
473
-                'obj_id'     => $grp_id,
474
-                'noheader'   => true,
475
-            ),
476
-            'settings'                         => array(
477
-                'func'       => '_settings',
478
-                'capability' => 'manage_options',
479
-            ),
480
-            'update_global_settings'           => array(
481
-                'func'       => '_update_global_settings',
482
-                'capability' => 'manage_options',
483
-                'noheader'   => true,
484
-            ),
485
-            'generate_now'                     => array(
486
-                'func'       => '_generate_now',
487
-                'capability' => 'ee_send_message',
488
-                'noheader'   => true,
489
-            ),
490
-            'generate_and_send_now'            => array(
491
-                'func'       => '_generate_and_send_now',
492
-                'capability' => 'ee_send_message',
493
-                'noheader'   => true,
494
-            ),
495
-            'queue_for_resending'              => array(
496
-                'func'       => '_queue_for_resending',
497
-                'capability' => 'ee_send_message',
498
-                'noheader'   => true,
499
-            ),
500
-            'send_now'                         => array(
501
-                'func'       => '_send_now',
502
-                'capability' => 'ee_send_message',
503
-                'noheader'   => true,
504
-            ),
505
-            'delete_ee_message'                => array(
506
-                'func'       => '_delete_ee_messages',
507
-                'capability' => 'ee_delete_messages',
508
-                'noheader'   => true,
509
-            ),
510
-            'delete_ee_messages'               => array(
511
-                'func'       => '_delete_ee_messages',
512
-                'capability' => 'ee_delete_messages',
513
-                'noheader'   => true,
514
-                'obj_id'     => $msg_id,
515
-            ),
516
-        );
517
-    }
518
-
519
-
520
-    protected function _set_page_config()
521
-    {
522
-        $this->_page_config = array(
523
-            'default'                  => array(
524
-                'nav'           => array(
525
-                    'label' => esc_html__('Message Activity', 'event_espresso'),
526
-                    'order' => 10,
527
-                ),
528
-                'list_table'    => 'EE_Message_List_Table',
529
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
-                'require_nonce' => false,
531
-            ),
532
-            'global_mtps'              => array(
533
-                'nav'           => array(
534
-                    'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
-                    'order' => 20,
536
-                ),
537
-                'list_table'    => 'Messages_Template_List_Table',
538
-                'help_tabs'     => array(
539
-                    'messages_overview_help_tab'                                => array(
540
-                        'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
-                        'filename' => 'messages_overview',
542
-                    ),
543
-                    'messages_overview_messages_table_column_headings_help_tab' => array(
544
-                        'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
-                        'filename' => 'messages_overview_table_column_headings',
546
-                    ),
547
-                    'messages_overview_messages_filters_help_tab'               => array(
548
-                        'title'    => esc_html__('Message Filters', 'event_espresso'),
549
-                        'filename' => 'messages_overview_filters',
550
-                    ),
551
-                    'messages_overview_messages_views_help_tab'                 => array(
552
-                        'title'    => esc_html__('Message Views', 'event_espresso'),
553
-                        'filename' => 'messages_overview_views',
554
-                    ),
555
-                    'message_overview_message_types_help_tab'                   => array(
556
-                        'title'    => esc_html__('Message Types', 'event_espresso'),
557
-                        'filename' => 'messages_overview_types',
558
-                    ),
559
-                    'messages_overview_messengers_help_tab'                     => array(
560
-                        'title'    => esc_html__('Messengers', 'event_espresso'),
561
-                        'filename' => 'messages_overview_messengers',
562
-                    ),
563
-                ),
564
-                'help_tour'     => array('Messages_Overview_Help_Tour'),
565
-                'require_nonce' => false,
566
-            ),
567
-            'custom_mtps'              => array(
568
-                'nav'           => array(
569
-                    'label' => esc_html__('Custom Message Templates', 'event_espresso'),
570
-                    'order' => 30,
571
-                ),
572
-                'help_tabs'     => array(),
573
-                'help_tour'     => array(),
574
-                'require_nonce' => false,
575
-            ),
576
-            'add_new_message_template' => array(
577
-                'nav'           => array(
578
-                    'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
579
-                    'order'      => 5,
580
-                    'persistent' => false,
581
-                ),
582
-                'require_nonce' => false,
583
-            ),
584
-            'edit_message_template'    => array(
585
-                'labels'        => array(
586
-                    'buttons'    => array(
587
-                        'reset' => esc_html__('Reset Templates', 'event_espresso'),
588
-                    ),
589
-                    'publishbox' => esc_html__('Update Actions', 'event_espresso'),
590
-                ),
591
-                'nav'           => array(
592
-                    'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
593
-                    'order'      => 5,
594
-                    'persistent' => false,
595
-                    'url'        => '',
596
-                ),
597
-                'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
598
-                'has_metaboxes' => true,
599
-                'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
600
-                'help_tabs'     => array(
601
-                    'edit_message_template'            => array(
602
-                        'title'    => esc_html__('Message Template Editor', 'event_espresso'),
603
-                        'callback' => 'edit_message_template_help_tab',
604
-                    ),
605
-                    'message_templates_help_tab'       => array(
606
-                        'title'    => esc_html__('Message Templates', 'event_espresso'),
607
-                        'filename' => 'messages_templates',
608
-                    ),
609
-                    'message_template_shortcodes'      => array(
610
-                        'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
611
-                        'callback' => 'message_template_shortcodes_help_tab',
612
-                    ),
613
-                    'message_preview_help_tab'         => array(
614
-                        'title'    => esc_html__('Message Preview', 'event_espresso'),
615
-                        'filename' => 'messages_preview',
616
-                    ),
617
-                    'messages_overview_other_help_tab' => array(
618
-                        'title'    => esc_html__('Messages Other', 'event_espresso'),
619
-                        'filename' => 'messages_overview_other',
620
-                    ),
621
-                ),
622
-                'require_nonce' => false,
623
-            ),
624
-            'display_preview_message'  => array(
625
-                'nav'           => array(
626
-                    'label'      => esc_html__('Message Preview', 'event_espresso'),
627
-                    'order'      => 5,
628
-                    'url'        => '',
629
-                    'persistent' => false,
630
-                ),
631
-                'help_tabs'     => array(
632
-                    'preview_message' => array(
633
-                        'title'    => esc_html__('About Previews', 'event_espresso'),
634
-                        'callback' => 'preview_message_help_tab',
635
-                    ),
636
-                ),
637
-                'require_nonce' => false,
638
-            ),
639
-            'settings'                 => array(
640
-                'nav'           => array(
641
-                    'label' => esc_html__('Settings', 'event_espresso'),
642
-                    'order' => 40,
643
-                ),
644
-                'metaboxes'     => array('_messages_settings_metaboxes'),
645
-                'help_tabs'     => array(
646
-                    'messages_settings_help_tab'               => array(
647
-                        'title'    => esc_html__('Messages Settings', 'event_espresso'),
648
-                        'filename' => 'messages_settings',
649
-                    ),
650
-                    'messages_settings_message_types_help_tab' => array(
651
-                        'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
652
-                        'filename' => 'messages_settings_message_types',
653
-                    ),
654
-                    'messages_settings_messengers_help_tab'    => array(
655
-                        'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
656
-                        'filename' => 'messages_settings_messengers',
657
-                    ),
658
-                ),
659
-                'help_tour'     => array('Messages_Settings_Help_Tour'),
660
-                'require_nonce' => false,
661
-            ),
662
-        );
663
-    }
664
-
665
-
666
-    protected function _add_screen_options()
667
-    {
668
-        // todo
669
-    }
670
-
671
-
672
-    protected function _add_screen_options_global_mtps()
673
-    {
674
-        /**
675
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
676
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
677
-         */
678
-        $page_title = $this->_admin_page_title;
679
-        $this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
680
-        $this->_per_page_screen_option();
681
-        $this->_admin_page_title = $page_title;
682
-    }
683
-
684
-
685
-    protected function _add_screen_options_default()
686
-    {
687
-        $this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
688
-        $this->_per_page_screen_option();
689
-    }
690
-
691
-
692
-    // none of the below group are currently used for Messages
693
-    protected function _add_feature_pointers()
694
-    {
695
-    }
696
-
697
-    public function admin_init()
698
-    {
699
-    }
700
-
701
-    public function admin_notices()
702
-    {
703
-    }
704
-
705
-    public function admin_footer_scripts()
706
-    {
707
-    }
708
-
709
-
710
-    public function messages_help_tab()
711
-    {
712
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
713
-    }
714
-
715
-
716
-    public function messengers_help_tab()
717
-    {
718
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
719
-    }
720
-
721
-
722
-    public function message_types_help_tab()
723
-    {
724
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
725
-    }
726
-
727
-
728
-    public function messages_overview_help_tab()
729
-    {
730
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
731
-    }
732
-
733
-
734
-    public function message_templates_help_tab()
735
-    {
736
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
737
-    }
738
-
739
-
740
-    public function edit_message_template_help_tab()
741
-    {
742
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
743
-                        . esc_attr__('Editor Title', 'event_espresso')
744
-                        . '" />';
745
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
746
-                        . esc_attr__('Context Switcher and Preview', 'event_espresso')
747
-                        . '" />';
748
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
749
-                        . esc_attr__('Message Template Form Fields', 'event_espresso')
750
-                        . '" />';
751
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
752
-                        . esc_attr__('Shortcodes Metabox', 'event_espresso')
753
-                        . '" />';
754
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
755
-                        . esc_attr__('Publish Metabox', 'event_espresso')
756
-                        . '" />';
757
-        EEH_Template::display_template(
758
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
759
-            $args
760
-        );
761
-    }
762
-
763
-
764
-    public function message_template_shortcodes_help_tab()
765
-    {
766
-        $this->_set_shortcodes();
767
-        $args['shortcodes'] = $this->_shortcodes;
768
-        EEH_Template::display_template(
769
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
770
-            $args
771
-        );
772
-    }
773
-
774
-
775
-    public function preview_message_help_tab()
776
-    {
777
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
778
-    }
779
-
780
-
781
-    public function settings_help_tab()
782
-    {
783
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
784
-                        . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
785
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
786
-                        . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
787
-        $args['img3'] = '<div class="switch">'
788
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
789
-                        . ' type="checkbox" checked="checked">'
790
-                        . '<label for="ee-on-off-toggle-on"></label>'
791
-                        . '</div>';
792
-        $args['img4'] = '<div class="switch">'
793
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
794
-                        . ' type="checkbox">'
795
-                        . '<label for="ee-on-off-toggle-on"></label>'
796
-                        . '</div>';
797
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
798
-    }
799
-
800
-
801
-    public function load_scripts_styles()
802
-    {
803
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
804
-        wp_enqueue_style('espresso_ee_msg');
805
-
806
-        wp_register_script(
807
-            'ee-messages-settings',
808
-            EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
809
-            array('jquery-ui-droppable', 'ee-serialize-full-array'),
810
-            EVENT_ESPRESSO_VERSION,
811
-            true
812
-        );
813
-        wp_register_script(
814
-            'ee-msg-list-table-js',
815
-            EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
816
-            array('ee-dialog'),
817
-            EVENT_ESPRESSO_VERSION
818
-        );
819
-    }
820
-
821
-
822
-    public function load_scripts_styles_default()
823
-    {
824
-        wp_enqueue_script('ee-msg-list-table-js');
825
-    }
826
-
827
-
828
-    public function wp_editor_css($mce_css)
829
-    {
830
-        // if we're on the edit_message_template route
831
-        if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
832
-            $message_type_name = $this->_active_message_type_name;
833
-
834
-            // we're going to REPLACE the existing mce css
835
-            // we need to get the css file location from the active messenger
836
-            $mce_css = $this->_active_messenger->get_variation(
837
-                $this->_template_pack,
838
-                $message_type_name,
839
-                true,
840
-                'wpeditor',
841
-                $this->_variation
842
-            );
843
-        }
844
-
845
-        return $mce_css;
846
-    }
847
-
848
-
849
-    public function load_scripts_styles_edit_message_template()
850
-    {
851
-
852
-        $this->_set_shortcodes();
853
-
854
-        EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
855
-            esc_html__(
856
-                '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.',
857
-                'event_espresso'
858
-            ),
859
-            $this->_message_template_group->messenger_obj()->label['singular'],
860
-            $this->_message_template_group->message_type_obj()->label['singular']
861
-        );
862
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
863
-            '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?',
864
-            'event_espresso'
865
-        );
866
-        EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
867
-            'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
868
-            'event_espresso'
869
-        );
870
-
871
-        wp_register_script(
872
-            'ee_msgs_edit_js',
873
-            EE_MSG_ASSETS_URL . 'ee_message_editor.js',
874
-            array('jquery'),
875
-            EVENT_ESPRESSO_VERSION
876
-        );
877
-
878
-        wp_enqueue_script('ee_admin_js');
879
-        wp_enqueue_script('ee_msgs_edit_js');
880
-
881
-        // add in special css for tiny_mce
882
-        add_filter('mce_css', array($this, 'wp_editor_css'));
883
-    }
884
-
885
-
886
-    public function load_scripts_styles_display_preview_message()
887
-    {
888
-
889
-        $this->_set_message_template_group();
890
-
891
-        if (isset($this->_req_data['messenger'])) {
892
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
893
-                $this->_req_data['messenger']
894
-            );
895
-        }
896
-
897
-        $message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
898
-
899
-
900
-        wp_enqueue_style(
901
-            'espresso_preview_css',
902
-            $this->_active_messenger->get_variation(
903
-                $this->_template_pack,
904
-                $message_type_name,
905
-                true,
906
-                'preview',
907
-                $this->_variation
908
-            )
909
-        );
910
-    }
911
-
912
-
913
-    public function load_scripts_styles_settings()
914
-    {
915
-        wp_register_style(
916
-            'ee-message-settings',
917
-            EE_MSG_ASSETS_URL . 'ee_message_settings.css',
918
-            array(),
919
-            EVENT_ESPRESSO_VERSION
920
-        );
921
-        wp_enqueue_style('ee-text-links');
922
-        wp_enqueue_style('ee-message-settings');
923
-        wp_enqueue_script('ee-messages-settings');
924
-    }
925
-
926
-
927
-    /**
928
-     * set views array for List Table
929
-     */
930
-    public function _set_list_table_views_global_mtps()
931
-    {
932
-        $this->_views = array(
933
-            'in_use' => array(
934
-                'slug'  => 'in_use',
935
-                'label' => esc_html__('In Use', 'event_espresso'),
936
-                'count' => 0,
937
-            ),
938
-        );
939
-    }
940
-
941
-
942
-    /**
943
-     * Set views array for the Custom Template List Table
944
-     */
945
-    public function _set_list_table_views_custom_mtps()
946
-    {
947
-        $this->_set_list_table_views_global_mtps();
948
-        $this->_views['in_use']['bulk_action'] = array(
949
-            'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
950
-        );
951
-    }
952
-
953
-
954
-    /**
955
-     * set views array for message queue list table
956
-     *
957
-     * @throws InvalidDataTypeException
958
-     * @throws InvalidInterfaceException
959
-     * @throws InvalidArgumentException
960
-     * @throws EE_Error
961
-     * @throws ReflectionException
962
-     */
963
-    public function _set_list_table_views_default()
964
-    {
965
-        EE_Registry::instance()->load_helper('Template');
966
-
967
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
968
-            'ee_send_message',
969
-            'message_list_table_bulk_actions'
970
-        )
971
-            ? array(
972
-                'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
973
-                'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
974
-                'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
975
-                'send_now'              => esc_html__('Send Now', 'event_espresso'),
976
-            )
977
-            : array();
978
-
979
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
980
-            'ee_delete_messages',
981
-            'message_list_table_bulk_actions'
982
-        )
983
-            ? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
984
-            : array();
985
-
986
-
987
-        $this->_views = array(
988
-            'all' => array(
989
-                'slug'        => 'all',
990
-                'label'       => esc_html__('All', 'event_espresso'),
991
-                'count'       => 0,
992
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
993
-            ),
994
-        );
995
-
996
-
997
-        foreach (EEM_Message::instance()->all_statuses() as $status) {
998
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
999
-                continue;
1000
-            }
1001
-            $status_bulk_actions = $common_bulk_actions;
1002
-            // unset bulk actions not applying to status
1003
-            if (! empty($status_bulk_actions)) {
1004
-                switch ($status) {
1005
-                    case EEM_Message::status_idle:
1006
-                    case EEM_Message::status_resend:
1007
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1008
-                        break;
1009
-
1010
-                    case EEM_Message::status_failed:
1011
-                    case EEM_Message::status_debug_only:
1012
-                    case EEM_Message::status_messenger_executing:
1013
-                        $status_bulk_actions = array();
1014
-                        break;
1015
-
1016
-                    case EEM_Message::status_incomplete:
1017
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1018
-                        break;
1019
-
1020
-                    case EEM_Message::status_retry:
1021
-                    case EEM_Message::status_sent:
1022
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1023
-                        break;
1024
-                }
1025
-            }
1026
-
1027
-            // skip adding messenger executing status to views because it will be included with the Failed view.
1028
-            if ($status === EEM_Message::status_messenger_executing) {
1029
-                continue;
1030
-            }
1031
-
1032
-            $this->_views[ strtolower($status) ] = array(
1033
-                'slug'        => strtolower($status),
1034
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1035
-                'count'       => 0,
1036
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1037
-            );
1038
-        }
1039
-    }
1040
-
1041
-
1042
-    protected function _ee_default_messages_overview_list_table()
1043
-    {
1044
-        $this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1045
-        $this->display_admin_list_table_page_with_no_sidebar();
1046
-    }
1047
-
1048
-
1049
-    protected function _message_queue_list_table()
1050
-    {
1051
-        $this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1052
-        $this->_template_args['per_column'] = 6;
1053
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1054
-        $this->_template_args['before_list_table'] = '<h3>'
1055
-                                                     . EEM_Message::instance()->get_pretty_label_for_results()
1056
-                                                     . '</h3>';
1057
-        $this->display_admin_list_table_page_with_no_sidebar();
1058
-    }
1059
-
1060
-
1061
-    protected function _message_legend_items()
1062
-    {
1063
-
1064
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
1065
-        $action_items = array();
1066
-
1067
-        foreach ($action_css_classes as $action_item => $action_details) {
1068
-            if ($action_item === 'see_notifications_for') {
1069
-                continue;
1070
-            }
1071
-            $action_items[ $action_item ] = array(
1072
-                'class' => $action_details['css_class'],
1073
-                'desc'  => $action_details['label'],
1074
-            );
1075
-        }
1076
-
1077
-        /** @type array $status_items status legend setup */
1078
-        $status_items = array(
1079
-            'sent_status'                => array(
1080
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1081
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1082
-            ),
1083
-            'idle_status'                => array(
1084
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1085
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1086
-            ),
1087
-            'failed_status'              => array(
1088
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1089
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1090
-            ),
1091
-            'messenger_executing_status' => array(
1092
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1093
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1094
-            ),
1095
-            'resend_status'              => array(
1096
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1097
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1098
-            ),
1099
-            'incomplete_status'          => array(
1100
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1101
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1102
-            ),
1103
-            'retry_status'               => array(
1104
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1105
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1106
-            ),
1107
-        );
1108
-        if (EEM_Message::debug()) {
1109
-            $status_items['debug_only_status'] = array(
1110
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1111
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1112
-            );
1113
-        }
1114
-
1115
-        return array_merge($action_items, $status_items);
1116
-    }
1117
-
1118
-
1119
-    protected function _custom_mtps_preview()
1120
-    {
1121
-        $this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1122
-        $this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1123
-                                               . ' alt="' . esc_attr__(
1124
-                                                   'Preview Custom Message Templates screenshot',
1125
-                                                   'event_espresso'
1126
-                                               ) . '" />';
1127
-        $this->_template_args['preview_text'] = '<strong>'
1128
-                                                . esc_html__(
1129
-                                                    '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.',
1130
-                                                    'event_espresso'
1131
-                                                )
1132
-                                                . '</strong>';
1133
-
1134
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1135
-    }
1136
-
1137
-
1138
-    /**
1139
-     * get_message_templates
1140
-     * This gets all the message templates for listing on the overview list.
1141
-     *
1142
-     * @access public
1143
-     * @param int    $perpage the amount of templates groups to show per page
1144
-     * @param string $type    the current _view we're getting templates for
1145
-     * @param bool   $count   return count?
1146
-     * @param bool   $all     disregard any paging info (get all data);
1147
-     * @param bool   $global  whether to return just global (true) or custom templates (false)
1148
-     * @return array
1149
-     * @throws EE_Error
1150
-     * @throws InvalidArgumentException
1151
-     * @throws InvalidDataTypeException
1152
-     * @throws InvalidInterfaceException
1153
-     */
1154
-    public function get_message_templates(
1155
-        $perpage = 10,
1156
-        $type = 'in_use',
1157
-        $count = false,
1158
-        $all = false,
1159
-        $global = true
1160
-    ) {
1161
-
1162
-        $MTP = EEM_Message_Template_Group::instance();
1163
-
1164
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1165
-        $orderby = $this->_req_data['orderby'];
1166
-
1167
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1168
-            ? $this->_req_data['order']
1169
-            : 'ASC';
1170
-
1171
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1172
-            ? $this->_req_data['paged']
1173
-            : 1;
1174
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1175
-            ? $this->_req_data['perpage']
1176
-            : $perpage;
1177
-
1178
-        $offset = ($current_page - 1) * $per_page;
1179
-        $limit = $all ? null : array($offset, $per_page);
1180
-
1181
-
1182
-        // options will match what is in the _views array property
1183
-        switch ($type) {
1184
-            case 'in_use':
1185
-                $templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1186
-                break;
1187
-            default:
1188
-                $templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1189
-        }
1190
-
1191
-        return $templates;
1192
-    }
1193
-
1194
-
1195
-    /**
1196
-     * filters etc might need a list of installed message_types
1197
-     *
1198
-     * @return array an array of message type objects
1199
-     */
1200
-    public function get_installed_message_types()
1201
-    {
1202
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1203
-        $installed = array();
1204
-
1205
-        foreach ($installed_message_types as $message_type) {
1206
-            $installed[ $message_type->name ] = $message_type;
1207
-        }
1208
-
1209
-        return $installed;
1210
-    }
1211
-
1212
-
1213
-    /**
1214
-     * _add_message_template
1215
-     *
1216
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1217
-     *
1218
-     * @param string $message_type
1219
-     * @param string $messenger
1220
-     * @param string $GRP_ID
1221
-     *
1222
-     * @throws EE_error
1223
-     */
1224
-    protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1225
-    {
1226
-        // set values override any request data
1227
-        $message_type = ! empty($message_type) ? $message_type : '';
1228
-        $message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1229
-            ? $this->_req_data['message_type']
1230
-            : $message_type;
1231
-
1232
-        $messenger = ! empty($messenger) ? $messenger : '';
1233
-        $messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1234
-            ? $this->_req_data['messenger']
1235
-            : $messenger;
1236
-
1237
-        $GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1238
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1239
-
1240
-        // we need messenger and message type.  They should be coming from the event editor. If not here then return error
1241
-        if (empty($message_type) || empty($messenger)) {
1242
-            throw new EE_Error(
1243
-                esc_html__(
1244
-                    'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1245
-                    'event_espresso'
1246
-                )
1247
-            );
1248
-        }
1249
-
1250
-        // we need the GRP_ID for the template being used as the base for the new template
1251
-        if (empty($GRP_ID)) {
1252
-            throw new EE_Error(
1253
-                esc_html__(
1254
-                    'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1255
-                    'event_espresso'
1256
-                )
1257
-            );
1258
-        }
1259
-
1260
-        // let's just make sure the template gets generated!
1261
-
1262
-        // we need to reassign some variables for what the insert is expecting
1263
-        $this->_req_data['MTP_messenger'] = $messenger;
1264
-        $this->_req_data['MTP_message_type'] = $message_type;
1265
-        $this->_req_data['GRP_ID'] = $GRP_ID;
1266
-        $this->_insert_or_update_message_template(true);
1267
-    }
1268
-
1269
-
1270
-    /**
1271
-     * public wrapper for the _add_message_template method
1272
-     *
1273
-     * @param string $message_type     message type slug
1274
-     * @param string $messenger        messenger slug
1275
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1276
-     *                                 off of.
1277
-     * @throws EE_error
1278
-     */
1279
-    public function add_message_template($message_type, $messenger, $GRP_ID)
1280
-    {
1281
-        $this->_add_message_template($message_type, $messenger, $GRP_ID);
1282
-    }
1283
-
1284
-
1285
-    /**
1286
-     * _edit_message_template
1287
-     *
1288
-     * @access protected
1289
-     * @return void
1290
-     * @throws InvalidIdentifierException
1291
-     * @throws DomainException
1292
-     * @throws EE_Error
1293
-     * @throws InvalidArgumentException
1294
-     * @throws ReflectionException
1295
-     * @throws InvalidDataTypeException
1296
-     * @throws InvalidInterfaceException
1297
-     */
1298
-    protected function _edit_message_template()
1299
-    {
1300
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1301
-        $template_fields = '';
1302
-        $sidebar_fields = '';
1303
-        // we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1304
-        // valid html in the templates.
1305
-        add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1306
-
1307
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1308
-            ? absint($this->_req_data['id'])
1309
-            : false;
1310
-
1311
-        $this->_set_shortcodes(); // this also sets the _message_template property.
1312
-        $message_template_group = $this->_message_template_group;
1313
-        $c_label = $message_template_group->context_label();
1314
-        $c_config = $message_template_group->contexts_config();
1315
-
1316
-        reset($c_config);
1317
-        $context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1318
-            ? strtolower($this->_req_data['context'])
1319
-            : key($c_config);
1320
-
1321
-
1322
-        if (empty($GRP_ID)) {
1323
-            $action = 'insert_message_template';
1324
-            $edit_message_template_form_url = add_query_arg(
1325
-                array('action' => $action, 'noheader' => true),
1326
-                EE_MSG_ADMIN_URL
1327
-            );
1328
-        } else {
1329
-            $action = 'update_message_template';
1330
-            $edit_message_template_form_url = add_query_arg(
1331
-                array('action' => $action, 'noheader' => true),
1332
-                EE_MSG_ADMIN_URL
1333
-            );
1334
-        }
1335
-
1336
-        // set active messenger for this view
1337
-        $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1338
-            $message_template_group->messenger()
1339
-        );
1340
-        $this->_active_message_type_name = $message_template_group->message_type();
1341
-
1342
-
1343
-        // Do we have any validation errors?
1344
-        $validators = $this->_get_transient();
1345
-        $v_fields = ! empty($validators) ? array_keys($validators) : array();
1346
-
1347
-
1348
-        // we need to assemble the title from Various details
1349
-        $context_label = sprintf(
1350
-            esc_html__('(%s %s)', 'event_espresso'),
1351
-            $c_config[ $context ]['label'],
1352
-            ucwords($c_label['label'])
1353
-        );
1354
-
1355
-        $title = sprintf(
1356
-            esc_html__(' %s %s Template %s', 'event_espresso'),
1357
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1358
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1359
-            $context_label
1360
-        );
1361
-
1362
-        $this->_template_args['GRP_ID'] = $GRP_ID;
1363
-        $this->_template_args['message_template'] = $message_template_group;
1364
-        $this->_template_args['is_extra_fields'] = false;
1365
-
1366
-
1367
-        // let's get EEH_MSG_Template so we can get template form fields
1368
-        $template_field_structure = EEH_MSG_Template::get_fields(
1369
-            $message_template_group->messenger(),
1370
-            $message_template_group->message_type()
1371
-        );
1372
-
1373
-        if (! $template_field_structure) {
1374
-            $template_field_structure = false;
1375
-            $template_fields = esc_html__(
1376
-                'There was an error in assembling the fields for this display (you should see an error message)',
1377
-                'event_espresso'
1378
-            );
1379
-        }
1380
-
1381
-
1382
-        $message_templates = $message_template_group->context_templates();
1383
-
1384
-
1385
-        // if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1386
-        // will get handled in the "extra" array.
1387
-        if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1388
-            foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1389
-                unset($template_field_structure[ $context ][ $reference_field ]);
1390
-            }
1391
-        }
1392
-
1393
-        // let's loop through the template_field_structure and actually assemble the input fields!
1394
-        if (! empty($template_field_structure)) {
1395
-            foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1396
-                // if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1397
-                // the extra array and reset them.
1398
-                if ($template_field === 'extra') {
1399
-                    $this->_template_args['is_extra_fields'] = true;
1400
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1401
-                        $message_template = $message_templates[ $context ][ $reference_field ];
1402
-                        $content = $message_template instanceof EE_Message_Template
1403
-                            ? $message_template->get('MTP_content')
1404
-                            : '';
1405
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1406
-                            // let's verify if we need this extra field via the shortcodes parameter.
1407
-                            $continue = false;
1408
-                            if (isset($extra_array['shortcodes_required'])) {
1409
-                                foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1410
-                                    if (! array_key_exists($shortcode, $this->_shortcodes)) {
1411
-                                        $continue = true;
1412
-                                    }
1413
-                                }
1414
-                                if ($continue) {
1415
-                                    continue;
1416
-                                }
1417
-                            }
1418
-
1419
-                            $field_id = $reference_field
1420
-                                        . '-'
1421
-                                        . $extra_field
1422
-                                        . '-content';
1423
-                            $template_form_fields[ $field_id ] = $extra_array;
1424
-                            $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1425
-                                                                         . $reference_field
1426
-                                                                         . '][content]['
1427
-                                                                         . $extra_field . ']';
1428
-                            $css_class = isset($extra_array['css_class'])
1429
-                                ? $extra_array['css_class']
1430
-                                : '';
1431
-
1432
-                            $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1433
-                                                                              && in_array($extra_field, $v_fields, true)
1434
-                                                                              &&
1435
-                                                                              (
1436
-                                                                                  is_array($validators[ $extra_field ])
1437
-                                                                                  && isset($validators[ $extra_field ]['msg'])
1438
-                                                                              )
1439
-                                ? 'validate-error ' . $css_class
1440
-                                : $css_class;
1441
-
1442
-                            $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1443
-                                                                          && isset($content[ $extra_field ])
1444
-                                ? $content[ $extra_field ]
1445
-                                : '';
1446
-
1447
-                            // do we have a validation error?  if we do then let's use that value instead
1448
-                            $template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1449
-                                ? $validators[ $extra_field ]['value']
1450
-                                : $template_form_fields[ $field_id ]['value'];
1451
-
1452
-
1453
-                            $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1454
-
1455
-                            // shortcode selector
1456
-                            $field_name_to_use = $extra_field === 'main'
1457
-                                ? 'content'
1458
-                                : $extra_field;
1459
-                            $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1460
-                                $field_name_to_use,
1461
-                                $field_id
1462
-                            );
1463
-
1464
-                            if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1465
-                                // we want to decode the entities
1466
-                                $template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1467
-                            }/**/
1468
-                        }
1469
-                        $templatefield_MTP_id = $reference_field . '-MTP_ID';
1470
-                        $templatefield_templatename_id = $reference_field . '-name';
1471
-
1472
-                        $template_form_fields[ $templatefield_MTP_id ] = array(
1473
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1474
-                            'label'      => null,
1475
-                            'input'      => 'hidden',
1476
-                            'type'       => 'int',
1477
-                            'required'   => false,
1478
-                            'validation' => false,
1479
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1480
-                            'css_class'  => '',
1481
-                            'format'     => '%d',
1482
-                            'db-col'     => 'MTP_ID',
1483
-                        );
1484
-
1485
-                        $template_form_fields[ $templatefield_templatename_id ] = array(
1486
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1487
-                            'label'      => null,
1488
-                            'input'      => 'hidden',
1489
-                            'type'       => 'string',
1490
-                            'required'   => false,
1491
-                            'validation' => true,
1492
-                            'value'      => $reference_field,
1493
-                            'css_class'  => '',
1494
-                            'format'     => '%s',
1495
-                            'db-col'     => 'MTP_template_field',
1496
-                        );
1497
-                    }
1498
-                    continue; // skip the next stuff, we got the necessary fields here for this dataset.
1499
-                } else {
1500
-                    $field_id = $template_field . '-content';
1501
-                    $template_form_fields[ $field_id ] = $field_setup_array;
1502
-                    $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1503
-                    $message_template = isset($message_templates[ $context ][ $template_field ])
1504
-                        ? $message_templates[ $context ][ $template_field ]
1505
-                        : null;
1506
-                    $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1507
-                                                                  && is_array($message_templates[ $context ])
1508
-                                                                  && $message_template instanceof EE_Message_Template
1509
-                        ? $message_template->get('MTP_content')
1510
-                        : '';
1511
-
1512
-                    // do we have a validator error for this field?  if we do then we'll use that value instead
1513
-                    $template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1514
-                        ? $validators[ $template_field ]['value']
1515
-                        : $template_form_fields[ $field_id ]['value'];
1516
-
1517
-
1518
-                    $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1519
-                    $css_class = isset($field_setup_array['css_class'])
1520
-                        ? $field_setup_array['css_class']
1521
-                        : '';
1522
-                    $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1523
-                                                                      && in_array($template_field, $v_fields, true)
1524
-                                                                      && isset($validators[ $template_field ]['msg'])
1525
-                        ? 'validate-error ' . $css_class
1526
-                        : $css_class;
1527
-
1528
-                    // shortcode selector
1529
-                    $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1530
-                        $template_field,
1531
-                        $field_id
1532
-                    );
1533
-                }
1534
-
1535
-                // k took care of content field(s) now let's take care of others.
1536
-
1537
-                $templatefield_MTP_id = $template_field . '-MTP_ID';
1538
-                $templatefield_field_templatename_id = $template_field . '-name';
1539
-
1540
-                // foreach template field there are actually two form fields created
1541
-                $template_form_fields[ $templatefield_MTP_id ] = array(
1542
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1543
-                    'label'      => null,
1544
-                    'input'      => 'hidden',
1545
-                    'type'       => 'int',
1546
-                    'required'   => false,
1547
-                    'validation' => true,
1548
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1549
-                    'css_class'  => '',
1550
-                    'format'     => '%d',
1551
-                    'db-col'     => 'MTP_ID',
1552
-                );
1553
-
1554
-                $template_form_fields[ $templatefield_field_templatename_id ] = array(
1555
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1556
-                    'label'      => null,
1557
-                    'input'      => 'hidden',
1558
-                    'type'       => 'string',
1559
-                    'required'   => false,
1560
-                    'validation' => true,
1561
-                    'value'      => $template_field,
1562
-                    'css_class'  => '',
1563
-                    'format'     => '%s',
1564
-                    'db-col'     => 'MTP_template_field',
1565
-                );
1566
-            }
1567
-
1568
-            // add other fields
1569
-            $template_form_fields['ee-msg-current-context'] = array(
1570
-                'name'       => 'MTP_context',
1571
-                'label'      => null,
1572
-                'input'      => 'hidden',
1573
-                'type'       => 'string',
1574
-                'required'   => false,
1575
-                'validation' => true,
1576
-                'value'      => $context,
1577
-                'css_class'  => '',
1578
-                'format'     => '%s',
1579
-                'db-col'     => 'MTP_context',
1580
-            );
1581
-
1582
-            $template_form_fields['ee-msg-grp-id'] = array(
1583
-                'name'       => 'GRP_ID',
1584
-                'label'      => null,
1585
-                'input'      => 'hidden',
1586
-                'type'       => 'int',
1587
-                'required'   => false,
1588
-                'validation' => true,
1589
-                'value'      => $GRP_ID,
1590
-                'css_class'  => '',
1591
-                'format'     => '%d',
1592
-                'db-col'     => 'GRP_ID',
1593
-            );
1594
-
1595
-            $template_form_fields['ee-msg-messenger'] = array(
1596
-                'name'       => 'MTP_messenger',
1597
-                'label'      => null,
1598
-                'input'      => 'hidden',
1599
-                'type'       => 'string',
1600
-                'required'   => false,
1601
-                'validation' => true,
1602
-                'value'      => $message_template_group->messenger(),
1603
-                'css_class'  => '',
1604
-                'format'     => '%s',
1605
-                'db-col'     => 'MTP_messenger',
1606
-            );
1607
-
1608
-            $template_form_fields['ee-msg-message-type'] = array(
1609
-                'name'       => 'MTP_message_type',
1610
-                'label'      => null,
1611
-                'input'      => 'hidden',
1612
-                'type'       => 'string',
1613
-                'required'   => false,
1614
-                'validation' => true,
1615
-                'value'      => $message_template_group->message_type(),
1616
-                'css_class'  => '',
1617
-                'format'     => '%s',
1618
-                'db-col'     => 'MTP_message_type',
1619
-            );
1620
-
1621
-            $sidebar_form_fields['ee-msg-is-global'] = array(
1622
-                'name'       => 'MTP_is_global',
1623
-                'label'      => esc_html__('Global Template', 'event_espresso'),
1624
-                'input'      => 'hidden',
1625
-                'type'       => 'int',
1626
-                'required'   => false,
1627
-                'validation' => true,
1628
-                'value'      => $message_template_group->get('MTP_is_global'),
1629
-                'css_class'  => '',
1630
-                'format'     => '%d',
1631
-                'db-col'     => 'MTP_is_global',
1632
-            );
1633
-
1634
-            $sidebar_form_fields['ee-msg-is-override'] = array(
1635
-                'name'       => 'MTP_is_override',
1636
-                'label'      => esc_html__('Override all custom', 'event_espresso'),
1637
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1638
-                'type'       => 'int',
1639
-                'required'   => false,
1640
-                'validation' => true,
1641
-                'value'      => $message_template_group->get('MTP_is_override'),
1642
-                'css_class'  => '',
1643
-                'format'     => '%d',
1644
-                'db-col'     => 'MTP_is_override',
1645
-            );
1646
-
1647
-            $sidebar_form_fields['ee-msg-is-active'] = array(
1648
-                'name'       => 'MTP_is_active',
1649
-                'label'      => esc_html__('Active Template', 'event_espresso'),
1650
-                'input'      => 'hidden',
1651
-                'type'       => 'int',
1652
-                'required'   => false,
1653
-                'validation' => true,
1654
-                'value'      => $message_template_group->is_active(),
1655
-                'css_class'  => '',
1656
-                'format'     => '%d',
1657
-                'db-col'     => 'MTP_is_active',
1658
-            );
1659
-
1660
-            $sidebar_form_fields['ee-msg-deleted'] = array(
1661
-                'name'       => 'MTP_deleted',
1662
-                'label'      => null,
1663
-                'input'      => 'hidden',
1664
-                'type'       => 'int',
1665
-                'required'   => false,
1666
-                'validation' => true,
1667
-                'value'      => $message_template_group->get('MTP_deleted'),
1668
-                'css_class'  => '',
1669
-                'format'     => '%d',
1670
-                'db-col'     => 'MTP_deleted',
1671
-            );
1672
-            $sidebar_form_fields['ee-msg-author'] = array(
1673
-                'name'       => 'MTP_user_id',
1674
-                'label'      => esc_html__('Author', 'event_espresso'),
1675
-                'input'      => 'hidden',
1676
-                'type'       => 'int',
1677
-                'required'   => false,
1678
-                'validation' => false,
1679
-                'value'      => $message_template_group->user(),
1680
-                'format'     => '%d',
1681
-                'db-col'     => 'MTP_user_id',
1682
-            );
1683
-
1684
-            $sidebar_form_fields['ee-msg-route'] = array(
1685
-                'name'  => 'action',
1686
-                'input' => 'hidden',
1687
-                'type'  => 'string',
1688
-                'value' => $action,
1689
-            );
1690
-
1691
-            $sidebar_form_fields['ee-msg-id'] = array(
1692
-                'name'  => 'id',
1693
-                'input' => 'hidden',
1694
-                'type'  => 'int',
1695
-                'value' => $GRP_ID,
1696
-            );
1697
-            $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1698
-                'name'  => $action . '_nonce',
1699
-                'input' => 'hidden',
1700
-                'type'  => 'string',
1701
-                'value' => wp_create_nonce($action . '_nonce'),
1702
-            );
1703
-
1704
-            if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1705
-                $sidebar_form_fields['ee-msg-template-switch'] = array(
1706
-                    'name'  => 'template_switch',
1707
-                    'input' => 'hidden',
1708
-                    'type'  => 'int',
1709
-                    'value' => 1,
1710
-                );
1711
-            }
1712
-
1713
-
1714
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1715
-            $sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1716
-        } //end if ( !empty($template_field_structure) )
1717
-
1718
-        // set extra content for publish box
1719
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1720
-        $this->_set_publish_post_box_vars(
1721
-            'id',
1722
-            $GRP_ID,
1723
-            false,
1724
-            add_query_arg(
1725
-                array('action' => 'global_mtps'),
1726
-                $this->_admin_base_url
1727
-            )
1728
-        );
1729
-
1730
-        // add preview button
1731
-        $preview_url = parent::add_query_args_and_nonce(
1732
-            array(
1733
-                'message_type' => $message_template_group->message_type(),
1734
-                'messenger'    => $message_template_group->messenger(),
1735
-                'context'      => $context,
1736
-                'GRP_ID'       => $GRP_ID,
1737
-                'action'       => 'preview_message',
1738
-            ),
1739
-            $this->_admin_base_url
1740
-        );
1741
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1742
-                          . esc_html__('Preview', 'event_espresso')
1743
-                          . '</a>';
1744
-
1745
-
1746
-        // setup context switcher
1747
-        $context_switcher_args = array(
1748
-            'page'    => 'espresso_messages',
1749
-            'action'  => 'edit_message_template',
1750
-            'id'      => $GRP_ID,
1751
-            'context' => $context,
1752
-            'extra'   => $preview_button,
1753
-        );
1754
-        $this->_set_context_switcher($message_template_group, $context_switcher_args);
1755
-
1756
-
1757
-        // main box
1758
-        $this->_template_args['template_fields'] = $template_fields;
1759
-        $this->_template_args['sidebar_box_id'] = 'details';
1760
-        $this->_template_args['action'] = $action;
1761
-        $this->_template_args['context'] = $context;
1762
-        $this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1763
-        $this->_template_args['learn_more_about_message_templates_link'] =
1764
-            $this->_learn_more_about_message_templates_link();
1765
-
1766
-
1767
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1768
-        $this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1769
-            $message_template_group,
1770
-            $context,
1771
-            $context_label
1772
-        );
1773
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1774
-        $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1775
-
1776
-        $this->_template_path = $this->_template_args['GRP_ID']
1777
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1778
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1779
-
1780
-        // send along EE_Message_Template_Group object for further template use.
1781
-        $this->_template_args['MTP'] = $message_template_group;
1782
-
1783
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1784
-            $this->_template_path,
1785
-            $this->_template_args,
1786
-            true
1787
-        );
1788
-
1789
-
1790
-        // finally, let's set the admin_page title
1791
-        $this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1792
-
1793
-
1794
-        // we need to take care of setting the shortcodes property for use elsewhere.
1795
-        $this->_set_shortcodes();
1796
-
1797
-
1798
-        // final template wrapper
1799
-        $this->display_admin_page_with_sidebar();
1800
-    }
1801
-
1802
-
1803
-    public function filter_tinymce_init($mceInit, $editor_id)
1804
-    {
1805
-        return $mceInit;
1806
-    }
1807
-
1808
-
1809
-    public function add_context_switcher()
1810
-    {
1811
-        return $this->_context_switcher;
1812
-    }
1813
-
1814
-
1815
-    /**
1816
-     * Adds the activation/deactivation toggle for the message template context.
1817
-     *
1818
-     * @param EE_Message_Template_Group $message_template_group
1819
-     * @param string                    $context
1820
-     * @param string                    $context_label
1821
-     * @return string
1822
-     * @throws DomainException
1823
-     * @throws EE_Error
1824
-     * @throws InvalidIdentifierException
1825
-     */
1826
-    protected function add_active_context_element(
1827
-        EE_Message_Template_Group $message_template_group,
1828
-        $context,
1829
-        $context_label
1830
-    ) {
1831
-        $template_args = array(
1832
-            'context'                   => $context,
1833
-            'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1834
-            'is_active'                 => $message_template_group->is_context_active($context),
1835
-            'on_off_action'             => $message_template_group->is_context_active($context)
1836
-                ? 'context-off'
1837
-                : 'context-on',
1838
-            'context_label'             => str_replace(array('(', ')'), '', $context_label),
1839
-            'message_template_group_id' => $message_template_group->ID(),
1840
-        );
1841
-        return EEH_Template::display_template(
1842
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1843
-            $template_args,
1844
-            true
1845
-        );
1846
-    }
1847
-
1848
-
1849
-    /**
1850
-     * Ajax callback for `toggle_context_template` ajax action.
1851
-     * Handles toggling the message context on or off.
1852
-     *
1853
-     * @throws EE_Error
1854
-     * @throws InvalidArgumentException
1855
-     * @throws InvalidDataTypeException
1856
-     * @throws InvalidIdentifierException
1857
-     * @throws InvalidInterfaceException
1858
-     */
1859
-    public function toggle_context_template()
1860
-    {
1861
-        $success = true;
1862
-        // check for required data
1863
-        if (! isset(
1864
-            $this->_req_data['message_template_group_id'],
1865
-            $this->_req_data['context'],
1866
-            $this->_req_data['status']
1867
-        )) {
1868
-            EE_Error::add_error(
1869
-                esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1870
-                __FILE__,
1871
-                __FUNCTION__,
1872
-                __LINE__
1873
-            );
1874
-            $success = false;
1875
-        }
1876
-
1877
-        $nonce = isset($this->_req_data['toggle_context_nonce'])
1878
-            ? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1879
-            : '';
1880
-        $nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1881
-        $this->_verify_nonce($nonce, $nonce_ref);
1882
-        $status = $this->_req_data['status'];
1883
-        if ($status !== 'off' && $status !== 'on') {
1884
-            EE_Error::add_error(
1885
-                sprintf(
1886
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1887
-                    $this->_req_data['status']
1888
-                ),
1889
-                __FILE__,
1890
-                __FUNCTION__,
1891
-                __LINE__
1892
-            );
1893
-            $success = false;
1894
-        }
1895
-        $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1896
-            $this->_req_data['message_template_group_id']
1897
-        );
1898
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1899
-            EE_Error::add_error(
1900
-                sprintf(
1901
-                    esc_html__(
1902
-                        'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1903
-                        'event_espresso'
1904
-                    ),
1905
-                    $this->_req_data['message_template_group_id'],
1906
-                    'EE_Message_Template_Group'
1907
-                ),
1908
-                __FILE__,
1909
-                __FUNCTION__,
1910
-                __LINE__
1911
-            );
1912
-            $success = false;
1913
-        }
1914
-        if ($success) {
1915
-            $success = $status === 'off'
1916
-                ? $message_template_group->deactivate_context($this->_req_data['context'])
1917
-                : $message_template_group->activate_context($this->_req_data['context']);
1918
-        }
1919
-        $this->_template_args['success'] = $success;
1920
-        $this->_return_json();
1921
-    }
1922
-
1923
-
1924
-    public function _add_form_element_before()
1925
-    {
1926
-        return '<form method="post" action="'
1927
-               . $this->_template_args["edit_message_template_form_url"]
1928
-               . '" id="ee-msg-edit-frm">';
1929
-    }
1930
-
1931
-    public function _add_form_element_after()
1932
-    {
1933
-        return '</form>';
1934
-    }
1935
-
1936
-
1937
-    /**
1938
-     * This executes switching the template pack for a message template.
1939
-     *
1940
-     * @since 4.5.0
1941
-     * @throws EE_Error
1942
-     * @throws InvalidDataTypeException
1943
-     * @throws InvalidInterfaceException
1944
-     * @throws InvalidArgumentException
1945
-     * @throws ReflectionException
1946
-     */
1947
-    public function switch_template_pack()
1948
-    {
1949
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1950
-        $template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1951
-
1952
-        // verify we have needed values.
1953
-        if (empty($GRP_ID) || empty($template_pack)) {
1954
-            $this->_template_args['error'] = true;
1955
-            EE_Error::add_error(
1956
-                esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1957
-                __FILE__,
1958
-                __FUNCTION__,
1959
-                __LINE__
1960
-            );
1961
-        } else {
1962
-            // get template, set the new template_pack and then reset to default
1963
-            /** @type EE_Message_Template_Group $message_template_group */
1964
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1965
-
1966
-            $message_template_group->set_template_pack_name($template_pack);
1967
-            $this->_req_data['msgr'] = $message_template_group->messenger();
1968
-            $this->_req_data['mt'] = $message_template_group->message_type();
1969
-
1970
-            $query_args = $this->_reset_to_default_template();
1971
-
1972
-            if (empty($query_args['id'])) {
1973
-                EE_Error::add_error(
1974
-                    esc_html__(
1975
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
1976
-                        'event_espresso'
1977
-                    ),
1978
-                    __FILE__,
1979
-                    __FUNCTION__,
1980
-                    __LINE__
1981
-                );
1982
-                $this->_template_args['error'] = true;
1983
-            } else {
1984
-                $template_label = $message_template_group->get_template_pack()->label;
1985
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1986
-                EE_Error::add_success(
1987
-                    sprintf(
1988
-                        esc_html__(
1989
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1990
-                            'event_espresso'
1991
-                        ),
1992
-                        $template_label,
1993
-                        $template_pack_labels->template_pack
1994
-                    )
1995
-                );
1996
-                // generate the redirect url for js.
1997
-                $url = self::add_query_args_and_nonce(
1998
-                    $query_args,
1999
-                    $this->_admin_base_url
2000
-                );
2001
-                $this->_template_args['data']['redirect_url'] = $url;
2002
-                $this->_template_args['success'] = true;
2003
-            }
2004
-
2005
-            $this->_return_json();
2006
-        }
2007
-    }
2008
-
2009
-
2010
-    /**
2011
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2012
-     * they want.
2013
-     *
2014
-     * @access protected
2015
-     * @return array|null
2016
-     * @throws EE_Error
2017
-     * @throws InvalidArgumentException
2018
-     * @throws InvalidDataTypeException
2019
-     * @throws InvalidInterfaceException
2020
-     */
2021
-    protected function _reset_to_default_template()
2022
-    {
2023
-
2024
-        $templates = array();
2025
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2026
-        // we need to make sure we've got the info we need.
2027
-        if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2028
-            EE_Error::add_error(
2029
-                esc_html__(
2030
-                    '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.',
2031
-                    'event_espresso'
2032
-                ),
2033
-                __FILE__,
2034
-                __FUNCTION__,
2035
-                __LINE__
2036
-            );
2037
-        }
2038
-
2039
-        // all templates will be reset to whatever the defaults are
2040
-        // for the global template matching the messenger and message type.
2041
-        $success = ! empty($GRP_ID) ? true : false;
2042
-
2043
-        if ($success) {
2044
-            // let's first determine if the incoming template is a global template,
2045
-            // if it isn't then we need to get the global template matching messenger and message type.
2046
-            // $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2047
-
2048
-
2049
-            // note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2050
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
2051
-
2052
-            if ($success) {
2053
-                // if successfully deleted, lets generate the new ones.
2054
-                // Note. We set GLOBAL to true, because resets on ANY template
2055
-                // will use the related global template defaults for regeneration.
2056
-                // This means that if a custom template is reset it resets to whatever the related global template is.
2057
-                // HOWEVER, we DO keep the template pack and template variation set
2058
-                // for the current custom template when resetting.
2059
-                $templates = $this->_generate_new_templates(
2060
-                    $this->_req_data['msgr'],
2061
-                    $this->_req_data['mt'],
2062
-                    $GRP_ID,
2063
-                    true
2064
-                );
2065
-            }
2066
-        }
2067
-
2068
-        // any error messages?
2069
-        if (! $success) {
2070
-            EE_Error::add_error(
2071
-                esc_html__(
2072
-                    'Something went wrong with deleting existing templates. Unable to reset to default',
2073
-                    'event_espresso'
2074
-                ),
2075
-                __FILE__,
2076
-                __FUNCTION__,
2077
-                __LINE__
2078
-            );
2079
-        }
2080
-
2081
-        // all good, let's add a success message!
2082
-        if ($success && ! empty($templates)) {
2083
-            // the info for the template we generated is the first element in the returned array
2084
-            // $templates = $templates[0];
2085
-            EE_Error::overwrite_success();
2086
-            EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2087
-        }
2088
-
2089
-
2090
-        $query_args = array(
2091
-            'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2092
-            'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2093
-            'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2094
-        );
2095
-
2096
-        // if called via ajax then we return query args otherwise redirect
2097
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2098
-            return $query_args;
2099
-        } else {
2100
-            $this->_redirect_after_action(false, '', '', $query_args, true);
2101
-
2102
-            return null;
2103
-        }
2104
-    }
2105
-
2106
-
2107
-    /**
2108
-     * Retrieve and set the message preview for display.
2109
-     *
2110
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2111
-     * @return string
2112
-     * @throws ReflectionException
2113
-     * @throws EE_Error
2114
-     * @throws InvalidArgumentException
2115
-     * @throws InvalidDataTypeException
2116
-     * @throws InvalidInterfaceException
2117
-     */
2118
-    public function _preview_message($send = false)
2119
-    {
2120
-        // first make sure we've got the necessary parameters
2121
-        if (! isset(
2122
-            $this->_req_data['message_type'],
2123
-            $this->_req_data['messenger'],
2124
-            $this->_req_data['messenger'],
2125
-            $this->_req_data['GRP_ID']
2126
-        )) {
2127
-            EE_Error::add_error(
2128
-                esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2129
-                __FILE__,
2130
-                __FUNCTION__,
2131
-                __LINE__
2132
-            );
2133
-        }
2134
-
2135
-        EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
2136
-
2137
-
2138
-        // get the preview!
2139
-        $preview = EED_Messages::preview_message(
2140
-            $this->_req_data['message_type'],
2141
-            $this->_req_data['context'],
2142
-            $this->_req_data['messenger'],
2143
-            $send
2144
-        );
2145
-
2146
-        if ($send) {
2147
-            return $preview;
2148
-        }
2149
-
2150
-        // let's add a button to go back to the edit view
2151
-        $query_args = array(
2152
-            'id'      => $this->_req_data['GRP_ID'],
2153
-            'context' => $this->_req_data['context'],
2154
-            'action'  => 'edit_message_template',
2155
-        );
2156
-        $go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2157
-        $preview_button = '<a href="'
2158
-                          . $go_back_url
2159
-                          . '" class="button-secondary messages-preview-go-back-button">'
2160
-                          . esc_html__('Go Back to Edit', 'event_espresso')
2161
-                          . '</a>';
2162
-        $message_types = $this->get_installed_message_types();
2163
-        $active_messenger = $this->_message_resource_manager->get_active_messenger(
2164
-            $this->_req_data['messenger']
2165
-        );
2166
-        $active_messenger_label = $active_messenger instanceof EE_messenger
2167
-            ? ucwords($active_messenger->label['singular'])
2168
-            : esc_html__('Unknown Messenger', 'event_espresso');
2169
-        // let's provide a helpful title for context
2170
-        $preview_title = sprintf(
2171
-            esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2172
-            $active_messenger_label,
2173
-            ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2174
-        );
2175
-        // setup display of preview.
2176
-        $this->_admin_page_title = $preview_title;
2177
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2178
-        $this->_template_args['data']['force_json'] = true;
2179
-
2180
-        return '';
2181
-    }
2182
-
2183
-
2184
-    /**
2185
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2186
-     * gets called automatically.
2187
-     *
2188
-     * @since 4.5.0
2189
-     *
2190
-     * @return string
2191
-     */
2192
-    protected function _display_preview_message()
2193
-    {
2194
-        $this->display_admin_page_with_no_sidebar();
2195
-    }
2196
-
2197
-
2198
-    /**
2199
-     * registers metaboxes that should show up on the "edit_message_template" page
2200
-     *
2201
-     * @access protected
2202
-     * @return void
2203
-     */
2204
-    protected function _register_edit_meta_boxes()
2205
-    {
2206
-        add_meta_box(
2207
-            'mtp_valid_shortcodes',
2208
-            esc_html__('Valid Shortcodes', 'event_espresso'),
2209
-            array($this, 'shortcode_meta_box'),
2210
-            $this->_current_screen->id,
2211
-            'side',
2212
-            'default'
2213
-        );
2214
-        add_meta_box(
2215
-            'mtp_extra_actions',
2216
-            esc_html__('Extra Actions', 'event_espresso'),
2217
-            array($this, 'extra_actions_meta_box'),
2218
-            $this->_current_screen->id,
2219
-            'side',
2220
-            'high'
2221
-        );
2222
-        add_meta_box(
2223
-            'mtp_templates',
2224
-            esc_html__('Template Styles', 'event_espresso'),
2225
-            array($this, 'template_pack_meta_box'),
2226
-            $this->_current_screen->id,
2227
-            'side',
2228
-            'high'
2229
-        );
2230
-    }
2231
-
2232
-
2233
-    /**
2234
-     * metabox content for all template pack and variation selection.
2235
-     *
2236
-     * @since 4.5.0
2237
-     * @return string
2238
-     * @throws DomainException
2239
-     * @throws EE_Error
2240
-     * @throws InvalidArgumentException
2241
-     * @throws ReflectionException
2242
-     * @throws InvalidDataTypeException
2243
-     * @throws InvalidInterfaceException
2244
-     */
2245
-    public function template_pack_meta_box()
2246
-    {
2247
-        $this->_set_message_template_group();
2248
-
2249
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
2250
-
2251
-        $tp_select_values = array();
2252
-
2253
-        foreach ($tp_collection as $tp) {
2254
-            // only include template packs that support this messenger and message type!
2255
-            $supports = $tp->get_supports();
2256
-            if (! isset($supports[ $this->_message_template_group->messenger() ])
2257
-                || ! in_array(
2258
-                    $this->_message_template_group->message_type(),
2259
-                    $supports[ $this->_message_template_group->messenger() ],
2260
-                    true
2261
-                )
2262
-            ) {
2263
-                // not supported
2264
-                continue;
2265
-            }
2266
-
2267
-            $tp_select_values[] = array(
2268
-                'text' => $tp->label,
2269
-                'id'   => $tp->dbref,
2270
-            );
2271
-        }
2272
-
2273
-        // if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2274
-        // the default template pack.  This still allows for the odd template pack to override.
2275
-        if (empty($tp_select_values)) {
2276
-            $tp_select_values[] = array(
2277
-                'text' => esc_html__('Default', 'event_espresso'),
2278
-                'id'   => 'default',
2279
-            );
2280
-        }
2281
-
2282
-        // setup variation select values for the currently selected template.
2283
-        $variations = $this->_message_template_group->get_template_pack()->get_variations(
2284
-            $this->_message_template_group->messenger(),
2285
-            $this->_message_template_group->message_type()
2286
-        );
2287
-        $variations_select_values = array();
2288
-        foreach ($variations as $variation => $label) {
2289
-            $variations_select_values[] = array(
2290
-                'text' => $label,
2291
-                'id'   => $variation,
2292
-            );
2293
-        }
2294
-
2295
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2296
-
2297
-        $template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2298
-            'MTP_template_pack',
2299
-            $tp_select_values,
2300
-            $this->_message_template_group->get_template_pack_name()
2301
-        );
2302
-        $template_args['variations_selector'] = EEH_Form_Fields::select_input(
2303
-            'MTP_template_variation',
2304
-            $variations_select_values,
2305
-            $this->_message_template_group->get_template_pack_variation()
2306
-        );
2307
-        $template_args['template_pack_label'] = $template_pack_labels->template_pack;
2308
-        $template_args['template_variation_label'] = $template_pack_labels->template_variation;
2309
-        $template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2310
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2311
-
2312
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2313
-
2314
-        EEH_Template::display_template($template, $template_args);
2315
-    }
2316
-
2317
-
2318
-    /**
2319
-     * This meta box holds any extra actions related to Message Templates
2320
-     * For now, this includes Resetting templates to defaults and sending a test email.
2321
-     *
2322
-     * @access  public
2323
-     * @return void
2324
-     * @throws EE_Error
2325
-     */
2326
-    public function extra_actions_meta_box()
2327
-    {
2328
-        $template_form_fields = array();
2329
-
2330
-        $extra_args = array(
2331
-            'msgr'   => $this->_message_template_group->messenger(),
2332
-            'mt'     => $this->_message_template_group->message_type(),
2333
-            'GRP_ID' => $this->_message_template_group->GRP_ID(),
2334
-        );
2335
-        // first we need to see if there are any fields
2336
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2337
-
2338
-        if (! empty($fields)) {
2339
-            // yup there be fields
2340
-            foreach ($fields as $field => $config) {
2341
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2342
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2343
-                $default = isset($config['default']) ? $config['default'] : '';
2344
-                $default = isset($config['value']) ? $config['value'] : $default;
2345
-
2346
-                // if type is hidden and the value is empty
2347
-                // something may have gone wrong so let's correct with the defaults
2348
-                $fix = $config['input'] === 'hidden'
2349
-                       && isset($existing[ $field ])
2350
-                       && empty($existing[ $field ])
2351
-                    ? $default
2352
-                    : '';
2353
-                $existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2354
-                    ? $existing[ $field ]
2355
-                    : $fix;
2356
-
2357
-                $template_form_fields[ $field_id ] = array(
2358
-                    'name'       => 'test_settings_fld[' . $field . ']',
2359
-                    'label'      => $config['label'],
2360
-                    'input'      => $config['input'],
2361
-                    'type'       => $config['type'],
2362
-                    'required'   => $config['required'],
2363
-                    'validation' => $config['validation'],
2364
-                    'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2365
-                    'css_class'  => $config['css_class'],
2366
-                    'options'    => isset($config['options']) ? $config['options'] : array(),
2367
-                    'default'    => $default,
2368
-                    'format'     => $config['format'],
2369
-                );
2370
-            }
2371
-        }
2372
-
2373
-        $test_settings_fields = ! empty($template_form_fields)
2374
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2375
-            : '';
2376
-
2377
-        $test_settings_html = '';
2378
-        // print out $test_settings_fields
2379
-        if (! empty($test_settings_fields)) {
2380
-            echo $test_settings_fields;
2381
-            $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2382
-            $test_settings_html .= 'name="test_button" value="';
2383
-            $test_settings_html .= esc_html__('Test Send', 'event_espresso');
2384
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2385
-        }
2386
-
2387
-        // and button
2388
-        $test_settings_html .= '<p>'
2389
-                               . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2390
-                               . '</p>';
2391
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2392
-        $test_settings_html .= $this->get_action_link_or_button(
2393
-            'reset_to_default',
2394
-            'reset',
2395
-            $extra_args,
2396
-            'button-primary reset-default-button'
2397
-        );
2398
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2399
-        echo $test_settings_html;
2400
-    }
2401
-
2402
-
2403
-    /**
2404
-     * This returns the shortcode selector skeleton for a given context and field.
2405
-     *
2406
-     * @since 4.9.rc.000
2407
-     * @param string $field           The name of the field retrieving shortcodes for.
2408
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2409
-     * @return string
2410
-     * @throws DomainException
2411
-     * @throws EE_Error
2412
-     * @throws InvalidArgumentException
2413
-     * @throws ReflectionException
2414
-     * @throws InvalidDataTypeException
2415
-     * @throws InvalidInterfaceException
2416
-     */
2417
-    protected function _get_shortcode_selector($field, $linked_input_id)
2418
-    {
2419
-        $template_args = array(
2420
-            'shortcodes'      => $this->_get_shortcodes(array($field), true),
2421
-            'fieldname'       => $field,
2422
-            'linked_input_id' => $linked_input_id,
2423
-        );
2424
-
2425
-        return EEH_Template::display_template(
2426
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2427
-            $template_args,
2428
-            true
2429
-        );
2430
-    }
2431
-
2432
-
2433
-    /**
2434
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2435
-     * page)
2436
-     *
2437
-     * @access public
2438
-     * @return void
2439
-     * @throws EE_Error
2440
-     * @throws InvalidArgumentException
2441
-     * @throws ReflectionException
2442
-     * @throws InvalidDataTypeException
2443
-     * @throws InvalidInterfaceException
2444
-     */
2445
-    public function shortcode_meta_box()
2446
-    {
2447
-        $shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2448
-        // $messenger = $this->_message_template_group->messenger_obj();
2449
-        // now let's set the content depending on the status of the shortcodes array
2450
-        if (empty($shortcodes)) {
2451
-            $content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2452
-            echo $content;
2453
-        } else {
2454
-            // $alt = 0;
2455
-            ?>
22
+	/**
23
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
24
+	 */
25
+	protected $_message_resource_manager;
26
+
27
+	/**
28
+	 * @type string $_active_message_type_name
29
+	 */
30
+	protected $_active_message_type_name = '';
31
+
32
+	/**
33
+	 * @type EE_messenger $_active_messenger
34
+	 */
35
+	protected $_active_messenger;
36
+	protected $_activate_state;
37
+	protected $_activate_meta_box_type;
38
+	protected $_current_message_meta_box;
39
+	protected $_current_message_meta_box_object;
40
+	protected $_context_switcher;
41
+	protected $_shortcodes = array();
42
+	protected $_active_messengers = array();
43
+	protected $_active_message_types = array();
44
+
45
+	/**
46
+	 * @var EE_Message_Template_Group $_message_template_group
47
+	 */
48
+	protected $_message_template_group;
49
+	protected $_m_mt_settings = array();
50
+
51
+
52
+	/**
53
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
+	 * IF there is no group then it gets automatically set to the Default template pack.
55
+	 *
56
+	 * @since 4.5.0
57
+	 *
58
+	 * @var EE_Messages_Template_Pack
59
+	 */
60
+	protected $_template_pack;
61
+
62
+
63
+	/**
64
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
+	 * group is.  If there is no group then it automatically gets set to default.
66
+	 *
67
+	 * @since 4.5.0
68
+	 *
69
+	 * @var string
70
+	 */
71
+	protected $_variation;
72
+
73
+
74
+	/**
75
+	 * @param bool $routing
76
+	 * @throws EE_Error
77
+	 */
78
+	public function __construct($routing = true)
79
+	{
80
+		// make sure messages autoloader is running
81
+		EED_Messages::set_autoloaders();
82
+		parent::__construct($routing);
83
+	}
84
+
85
+
86
+	protected function _init_page_props()
87
+	{
88
+		$this->page_slug = EE_MSG_PG_SLUG;
89
+		$this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
+		$this->_admin_base_url = EE_MSG_ADMIN_URL;
91
+		$this->_admin_base_path = EE_MSG_ADMIN;
92
+
93
+		$this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
+			: array();
95
+
96
+		$this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
+		$this->_load_message_resource_manager();
98
+	}
99
+
100
+
101
+	/**
102
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
+	 *
104
+	 * @throws EE_Error
105
+	 * @throws InvalidDataTypeException
106
+	 * @throws InvalidInterfaceException
107
+	 * @throws InvalidArgumentException
108
+	 * @throws ReflectionException
109
+	 */
110
+	protected function _load_message_resource_manager()
111
+	{
112
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
+	}
114
+
115
+
116
+	/**
117
+	 * @deprecated 4.9.9.rc.014
118
+	 * @return array
119
+	 * @throws EE_Error
120
+	 * @throws InvalidArgumentException
121
+	 * @throws InvalidDataTypeException
122
+	 * @throws InvalidInterfaceException
123
+	 */
124
+	public function get_messengers_for_list_table()
125
+	{
126
+		EE_Error::doing_it_wrong(
127
+			__METHOD__,
128
+			sprintf(
129
+				esc_html__(
130
+					'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',
131
+					'event_espresso'
132
+				),
133
+				'Messages_Admin_Page::get_messengers_select_input()'
134
+			),
135
+			'4.9.9.rc.014'
136
+		);
137
+
138
+		$m_values = array();
139
+		$active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
+		// setup messengers for selects
141
+		$i = 1;
142
+		foreach ($active_messengers as $active_messenger) {
143
+			if ($active_messenger instanceof EE_Message) {
144
+				$m_values[ $i ]['id'] = $active_messenger->messenger();
145
+				$m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
+				$i++;
147
+			}
148
+		}
149
+
150
+		return $m_values;
151
+	}
152
+
153
+
154
+	/**
155
+	 * @deprecated 4.9.9.rc.014
156
+	 * @return array
157
+	 * @throws EE_Error
158
+	 * @throws InvalidArgumentException
159
+	 * @throws InvalidDataTypeException
160
+	 * @throws InvalidInterfaceException
161
+	 */
162
+	public function get_message_types_for_list_table()
163
+	{
164
+		EE_Error::doing_it_wrong(
165
+			__METHOD__,
166
+			sprintf(
167
+				esc_html__(
168
+					'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',
169
+					'event_espresso'
170
+				),
171
+				'Messages_Admin_Page::get_message_types_select_input()'
172
+			),
173
+			'4.9.9.rc.014'
174
+		);
175
+
176
+		$mt_values = array();
177
+		$active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
+		$i = 1;
179
+		foreach ($active_messages as $active_message) {
180
+			if ($active_message instanceof EE_Message) {
181
+				$mt_values[ $i ]['id'] = $active_message->message_type();
182
+				$mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
+				$i++;
184
+			}
185
+		}
186
+
187
+		return $mt_values;
188
+	}
189
+
190
+
191
+	/**
192
+	 * @deprecated 4.9.9.rc.014
193
+	 * @return array
194
+	 * @throws EE_Error
195
+	 * @throws InvalidArgumentException
196
+	 * @throws InvalidDataTypeException
197
+	 * @throws InvalidInterfaceException
198
+	 */
199
+	public function get_contexts_for_message_types_for_list_table()
200
+	{
201
+		EE_Error::doing_it_wrong(
202
+			__METHOD__,
203
+			sprintf(
204
+				esc_html__(
205
+					'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',
206
+					'event_espresso'
207
+				),
208
+				'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
+			),
210
+			'4.9.9.rc.014'
211
+		);
212
+
213
+		$contexts = array();
214
+		$active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
+		foreach ($active_message_contexts as $active_message) {
216
+			if ($active_message instanceof EE_Message) {
217
+				$message_type = $active_message->message_type_object();
218
+				if ($message_type instanceof EE_message_type) {
219
+					$message_type_contexts = $message_type->get_contexts();
220
+					foreach ($message_type_contexts as $context => $context_details) {
221
+						$contexts[ $context ] = $context_details['label'];
222
+					}
223
+				}
224
+			}
225
+		}
226
+
227
+		return $contexts;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Generate select input with provided messenger options array.
233
+	 *
234
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
+	 *                                 labels.
236
+	 * @return string
237
+	 * @throws EE_Error
238
+	 */
239
+	public function get_messengers_select_input($messenger_options)
240
+	{
241
+		// if empty or just one value then just return an empty string
242
+		if (empty($messenger_options)
243
+			|| ! is_array($messenger_options)
244
+			|| count($messenger_options) === 1
245
+		) {
246
+			return '';
247
+		}
248
+		// merge in default
249
+		$messenger_options = array_merge(
250
+			array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
+			$messenger_options
252
+		);
253
+		$input = new EE_Select_Input(
254
+			$messenger_options,
255
+			array(
256
+				'html_name'  => 'ee_messenger_filter_by',
257
+				'html_id'    => 'ee_messenger_filter_by',
258
+				'html_class' => 'wide',
259
+				'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
+					? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
+					: 'none_selected',
262
+			)
263
+		);
264
+
265
+		return $input->get_html_for_input();
266
+	}
267
+
268
+
269
+	/**
270
+	 * Generate select input with provided message type options array.
271
+	 *
272
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
+	 *                                    message type labels
274
+	 * @return string
275
+	 * @throws EE_Error
276
+	 */
277
+	public function get_message_types_select_input($message_type_options)
278
+	{
279
+		// if empty or count of options is 1 then just return an empty string
280
+		if (empty($message_type_options)
281
+			|| ! is_array($message_type_options)
282
+			|| count($message_type_options) === 1
283
+		) {
284
+			return '';
285
+		}
286
+		// merge in default
287
+		$message_type_options = array_merge(
288
+			array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
+			$message_type_options
290
+		);
291
+		$input = new EE_Select_Input(
292
+			$message_type_options,
293
+			array(
294
+				'html_name'  => 'ee_message_type_filter_by',
295
+				'html_id'    => 'ee_message_type_filter_by',
296
+				'html_class' => 'wide',
297
+				'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
+					? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
+					: 'none_selected',
300
+			)
301
+		);
302
+
303
+		return $input->get_html_for_input();
304
+	}
305
+
306
+
307
+	/**
308
+	 * Generate select input with provide message type contexts array.
309
+	 *
310
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
+	 *                               context label.
312
+	 * @return string
313
+	 * @throws EE_Error
314
+	 */
315
+	public function get_contexts_for_message_types_select_input($context_options)
316
+	{
317
+		// if empty or count of options is one then just return empty string
318
+		if (empty($context_options)
319
+			|| ! is_array($context_options)
320
+			|| count($context_options) === 1
321
+		) {
322
+			return '';
323
+		}
324
+		// merge in default
325
+		$context_options = array_merge(
326
+			array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
+			$context_options
328
+		);
329
+		$input = new EE_Select_Input(
330
+			$context_options,
331
+			array(
332
+				'html_name'  => 'ee_context_filter_by',
333
+				'html_id'    => 'ee_context_filter_by',
334
+				'html_class' => 'wide',
335
+				'default'    => isset($this->_req_data['ee_context_filter_by'])
336
+					? sanitize_title($this->_req_data['ee_context_filter_by'])
337
+					: 'none_selected',
338
+			)
339
+		);
340
+
341
+		return $input->get_html_for_input();
342
+	}
343
+
344
+
345
+	protected function _ajax_hooks()
346
+	{
347
+		add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
+		add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
+		add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
+		add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
+		add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
+		add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
+	}
354
+
355
+
356
+	protected function _define_page_props()
357
+	{
358
+		$this->_admin_page_title = $this->page_label;
359
+		$this->_labels = array(
360
+			'buttons'    => array(
361
+				'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
+				'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
+				'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
+			),
365
+			'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
+		);
367
+	}
368
+
369
+
370
+	/**
371
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
372
+	 *
373
+	 * @access protected
374
+	 * @return void
375
+	 */
376
+	protected function _set_page_routes()
377
+	{
378
+		$grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
+			? $this->_req_data['GRP_ID']
380
+			: 0;
381
+		$grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
+			? $this->_req_data['id']
383
+			: $grp_id;
384
+		$msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
+			? $this->_req_data['MSG_ID']
386
+			: 0;
387
+
388
+		$this->_page_routes = array(
389
+			'default'                          => array(
390
+				'func'       => '_message_queue_list_table',
391
+				'capability' => 'ee_read_global_messages',
392
+			),
393
+			'global_mtps'                      => array(
394
+				'func'       => '_ee_default_messages_overview_list_table',
395
+				'capability' => 'ee_read_global_messages',
396
+			),
397
+			'custom_mtps'                      => array(
398
+				'func'       => '_custom_mtps_preview',
399
+				'capability' => 'ee_read_messages',
400
+			),
401
+			'add_new_message_template'         => array(
402
+				'func'       => '_add_message_template',
403
+				'capability' => 'ee_edit_messages',
404
+				'noheader'   => true,
405
+			),
406
+			'edit_message_template'            => array(
407
+				'func'       => '_edit_message_template',
408
+				'capability' => 'ee_edit_message',
409
+				'obj_id'     => $grp_id,
410
+			),
411
+			'preview_message'                  => array(
412
+				'func'               => '_preview_message',
413
+				'capability'         => 'ee_read_message',
414
+				'obj_id'             => $grp_id,
415
+				'noheader'           => true,
416
+				'headers_sent_route' => 'display_preview_message',
417
+			),
418
+			'display_preview_message'          => array(
419
+				'func'       => '_display_preview_message',
420
+				'capability' => 'ee_read_message',
421
+				'obj_id'     => $grp_id,
422
+			),
423
+			'insert_message_template'          => array(
424
+				'func'       => '_insert_or_update_message_template',
425
+				'capability' => 'ee_edit_messages',
426
+				'args'       => array('new_template' => true),
427
+				'noheader'   => true,
428
+			),
429
+			'update_message_template'          => array(
430
+				'func'       => '_insert_or_update_message_template',
431
+				'capability' => 'ee_edit_message',
432
+				'obj_id'     => $grp_id,
433
+				'args'       => array('new_template' => false),
434
+				'noheader'   => true,
435
+			),
436
+			'trash_message_template'           => array(
437
+				'func'       => '_trash_or_restore_message_template',
438
+				'capability' => 'ee_delete_message',
439
+				'obj_id'     => $grp_id,
440
+				'args'       => array('trash' => true, 'all' => true),
441
+				'noheader'   => true,
442
+			),
443
+			'trash_message_template_context'   => array(
444
+				'func'       => '_trash_or_restore_message_template',
445
+				'capability' => 'ee_delete_message',
446
+				'obj_id'     => $grp_id,
447
+				'args'       => array('trash' => true),
448
+				'noheader'   => true,
449
+			),
450
+			'restore_message_template'         => array(
451
+				'func'       => '_trash_or_restore_message_template',
452
+				'capability' => 'ee_delete_message',
453
+				'obj_id'     => $grp_id,
454
+				'args'       => array('trash' => false, 'all' => true),
455
+				'noheader'   => true,
456
+			),
457
+			'restore_message_template_context' => array(
458
+				'func'       => '_trash_or_restore_message_template',
459
+				'capability' => 'ee_delete_message',
460
+				'obj_id'     => $grp_id,
461
+				'args'       => array('trash' => false),
462
+				'noheader'   => true,
463
+			),
464
+			'delete_message_template'          => array(
465
+				'func'       => '_delete_message_template',
466
+				'capability' => 'ee_delete_message',
467
+				'obj_id'     => $grp_id,
468
+				'noheader'   => true,
469
+			),
470
+			'reset_to_default'                 => array(
471
+				'func'       => '_reset_to_default_template',
472
+				'capability' => 'ee_edit_message',
473
+				'obj_id'     => $grp_id,
474
+				'noheader'   => true,
475
+			),
476
+			'settings'                         => array(
477
+				'func'       => '_settings',
478
+				'capability' => 'manage_options',
479
+			),
480
+			'update_global_settings'           => array(
481
+				'func'       => '_update_global_settings',
482
+				'capability' => 'manage_options',
483
+				'noheader'   => true,
484
+			),
485
+			'generate_now'                     => array(
486
+				'func'       => '_generate_now',
487
+				'capability' => 'ee_send_message',
488
+				'noheader'   => true,
489
+			),
490
+			'generate_and_send_now'            => array(
491
+				'func'       => '_generate_and_send_now',
492
+				'capability' => 'ee_send_message',
493
+				'noheader'   => true,
494
+			),
495
+			'queue_for_resending'              => array(
496
+				'func'       => '_queue_for_resending',
497
+				'capability' => 'ee_send_message',
498
+				'noheader'   => true,
499
+			),
500
+			'send_now'                         => array(
501
+				'func'       => '_send_now',
502
+				'capability' => 'ee_send_message',
503
+				'noheader'   => true,
504
+			),
505
+			'delete_ee_message'                => array(
506
+				'func'       => '_delete_ee_messages',
507
+				'capability' => 'ee_delete_messages',
508
+				'noheader'   => true,
509
+			),
510
+			'delete_ee_messages'               => array(
511
+				'func'       => '_delete_ee_messages',
512
+				'capability' => 'ee_delete_messages',
513
+				'noheader'   => true,
514
+				'obj_id'     => $msg_id,
515
+			),
516
+		);
517
+	}
518
+
519
+
520
+	protected function _set_page_config()
521
+	{
522
+		$this->_page_config = array(
523
+			'default'                  => array(
524
+				'nav'           => array(
525
+					'label' => esc_html__('Message Activity', 'event_espresso'),
526
+					'order' => 10,
527
+				),
528
+				'list_table'    => 'EE_Message_List_Table',
529
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
+				'require_nonce' => false,
531
+			),
532
+			'global_mtps'              => array(
533
+				'nav'           => array(
534
+					'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
+					'order' => 20,
536
+				),
537
+				'list_table'    => 'Messages_Template_List_Table',
538
+				'help_tabs'     => array(
539
+					'messages_overview_help_tab'                                => array(
540
+						'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
+						'filename' => 'messages_overview',
542
+					),
543
+					'messages_overview_messages_table_column_headings_help_tab' => array(
544
+						'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
+						'filename' => 'messages_overview_table_column_headings',
546
+					),
547
+					'messages_overview_messages_filters_help_tab'               => array(
548
+						'title'    => esc_html__('Message Filters', 'event_espresso'),
549
+						'filename' => 'messages_overview_filters',
550
+					),
551
+					'messages_overview_messages_views_help_tab'                 => array(
552
+						'title'    => esc_html__('Message Views', 'event_espresso'),
553
+						'filename' => 'messages_overview_views',
554
+					),
555
+					'message_overview_message_types_help_tab'                   => array(
556
+						'title'    => esc_html__('Message Types', 'event_espresso'),
557
+						'filename' => 'messages_overview_types',
558
+					),
559
+					'messages_overview_messengers_help_tab'                     => array(
560
+						'title'    => esc_html__('Messengers', 'event_espresso'),
561
+						'filename' => 'messages_overview_messengers',
562
+					),
563
+				),
564
+				'help_tour'     => array('Messages_Overview_Help_Tour'),
565
+				'require_nonce' => false,
566
+			),
567
+			'custom_mtps'              => array(
568
+				'nav'           => array(
569
+					'label' => esc_html__('Custom Message Templates', 'event_espresso'),
570
+					'order' => 30,
571
+				),
572
+				'help_tabs'     => array(),
573
+				'help_tour'     => array(),
574
+				'require_nonce' => false,
575
+			),
576
+			'add_new_message_template' => array(
577
+				'nav'           => array(
578
+					'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
579
+					'order'      => 5,
580
+					'persistent' => false,
581
+				),
582
+				'require_nonce' => false,
583
+			),
584
+			'edit_message_template'    => array(
585
+				'labels'        => array(
586
+					'buttons'    => array(
587
+						'reset' => esc_html__('Reset Templates', 'event_espresso'),
588
+					),
589
+					'publishbox' => esc_html__('Update Actions', 'event_espresso'),
590
+				),
591
+				'nav'           => array(
592
+					'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
593
+					'order'      => 5,
594
+					'persistent' => false,
595
+					'url'        => '',
596
+				),
597
+				'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
598
+				'has_metaboxes' => true,
599
+				'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
600
+				'help_tabs'     => array(
601
+					'edit_message_template'            => array(
602
+						'title'    => esc_html__('Message Template Editor', 'event_espresso'),
603
+						'callback' => 'edit_message_template_help_tab',
604
+					),
605
+					'message_templates_help_tab'       => array(
606
+						'title'    => esc_html__('Message Templates', 'event_espresso'),
607
+						'filename' => 'messages_templates',
608
+					),
609
+					'message_template_shortcodes'      => array(
610
+						'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
611
+						'callback' => 'message_template_shortcodes_help_tab',
612
+					),
613
+					'message_preview_help_tab'         => array(
614
+						'title'    => esc_html__('Message Preview', 'event_espresso'),
615
+						'filename' => 'messages_preview',
616
+					),
617
+					'messages_overview_other_help_tab' => array(
618
+						'title'    => esc_html__('Messages Other', 'event_espresso'),
619
+						'filename' => 'messages_overview_other',
620
+					),
621
+				),
622
+				'require_nonce' => false,
623
+			),
624
+			'display_preview_message'  => array(
625
+				'nav'           => array(
626
+					'label'      => esc_html__('Message Preview', 'event_espresso'),
627
+					'order'      => 5,
628
+					'url'        => '',
629
+					'persistent' => false,
630
+				),
631
+				'help_tabs'     => array(
632
+					'preview_message' => array(
633
+						'title'    => esc_html__('About Previews', 'event_espresso'),
634
+						'callback' => 'preview_message_help_tab',
635
+					),
636
+				),
637
+				'require_nonce' => false,
638
+			),
639
+			'settings'                 => array(
640
+				'nav'           => array(
641
+					'label' => esc_html__('Settings', 'event_espresso'),
642
+					'order' => 40,
643
+				),
644
+				'metaboxes'     => array('_messages_settings_metaboxes'),
645
+				'help_tabs'     => array(
646
+					'messages_settings_help_tab'               => array(
647
+						'title'    => esc_html__('Messages Settings', 'event_espresso'),
648
+						'filename' => 'messages_settings',
649
+					),
650
+					'messages_settings_message_types_help_tab' => array(
651
+						'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
652
+						'filename' => 'messages_settings_message_types',
653
+					),
654
+					'messages_settings_messengers_help_tab'    => array(
655
+						'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
656
+						'filename' => 'messages_settings_messengers',
657
+					),
658
+				),
659
+				'help_tour'     => array('Messages_Settings_Help_Tour'),
660
+				'require_nonce' => false,
661
+			),
662
+		);
663
+	}
664
+
665
+
666
+	protected function _add_screen_options()
667
+	{
668
+		// todo
669
+	}
670
+
671
+
672
+	protected function _add_screen_options_global_mtps()
673
+	{
674
+		/**
675
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
676
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
677
+		 */
678
+		$page_title = $this->_admin_page_title;
679
+		$this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
680
+		$this->_per_page_screen_option();
681
+		$this->_admin_page_title = $page_title;
682
+	}
683
+
684
+
685
+	protected function _add_screen_options_default()
686
+	{
687
+		$this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
688
+		$this->_per_page_screen_option();
689
+	}
690
+
691
+
692
+	// none of the below group are currently used for Messages
693
+	protected function _add_feature_pointers()
694
+	{
695
+	}
696
+
697
+	public function admin_init()
698
+	{
699
+	}
700
+
701
+	public function admin_notices()
702
+	{
703
+	}
704
+
705
+	public function admin_footer_scripts()
706
+	{
707
+	}
708
+
709
+
710
+	public function messages_help_tab()
711
+	{
712
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
713
+	}
714
+
715
+
716
+	public function messengers_help_tab()
717
+	{
718
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
719
+	}
720
+
721
+
722
+	public function message_types_help_tab()
723
+	{
724
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
725
+	}
726
+
727
+
728
+	public function messages_overview_help_tab()
729
+	{
730
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
731
+	}
732
+
733
+
734
+	public function message_templates_help_tab()
735
+	{
736
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
737
+	}
738
+
739
+
740
+	public function edit_message_template_help_tab()
741
+	{
742
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
743
+						. esc_attr__('Editor Title', 'event_espresso')
744
+						. '" />';
745
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
746
+						. esc_attr__('Context Switcher and Preview', 'event_espresso')
747
+						. '" />';
748
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
749
+						. esc_attr__('Message Template Form Fields', 'event_espresso')
750
+						. '" />';
751
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
752
+						. esc_attr__('Shortcodes Metabox', 'event_espresso')
753
+						. '" />';
754
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
755
+						. esc_attr__('Publish Metabox', 'event_espresso')
756
+						. '" />';
757
+		EEH_Template::display_template(
758
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
759
+			$args
760
+		);
761
+	}
762
+
763
+
764
+	public function message_template_shortcodes_help_tab()
765
+	{
766
+		$this->_set_shortcodes();
767
+		$args['shortcodes'] = $this->_shortcodes;
768
+		EEH_Template::display_template(
769
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
770
+			$args
771
+		);
772
+	}
773
+
774
+
775
+	public function preview_message_help_tab()
776
+	{
777
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
778
+	}
779
+
780
+
781
+	public function settings_help_tab()
782
+	{
783
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
784
+						. '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
785
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
786
+						. '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
787
+		$args['img3'] = '<div class="switch">'
788
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
789
+						. ' type="checkbox" checked="checked">'
790
+						. '<label for="ee-on-off-toggle-on"></label>'
791
+						. '</div>';
792
+		$args['img4'] = '<div class="switch">'
793
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
794
+						. ' type="checkbox">'
795
+						. '<label for="ee-on-off-toggle-on"></label>'
796
+						. '</div>';
797
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
798
+	}
799
+
800
+
801
+	public function load_scripts_styles()
802
+	{
803
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
804
+		wp_enqueue_style('espresso_ee_msg');
805
+
806
+		wp_register_script(
807
+			'ee-messages-settings',
808
+			EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
809
+			array('jquery-ui-droppable', 'ee-serialize-full-array'),
810
+			EVENT_ESPRESSO_VERSION,
811
+			true
812
+		);
813
+		wp_register_script(
814
+			'ee-msg-list-table-js',
815
+			EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
816
+			array('ee-dialog'),
817
+			EVENT_ESPRESSO_VERSION
818
+		);
819
+	}
820
+
821
+
822
+	public function load_scripts_styles_default()
823
+	{
824
+		wp_enqueue_script('ee-msg-list-table-js');
825
+	}
826
+
827
+
828
+	public function wp_editor_css($mce_css)
829
+	{
830
+		// if we're on the edit_message_template route
831
+		if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
832
+			$message_type_name = $this->_active_message_type_name;
833
+
834
+			// we're going to REPLACE the existing mce css
835
+			// we need to get the css file location from the active messenger
836
+			$mce_css = $this->_active_messenger->get_variation(
837
+				$this->_template_pack,
838
+				$message_type_name,
839
+				true,
840
+				'wpeditor',
841
+				$this->_variation
842
+			);
843
+		}
844
+
845
+		return $mce_css;
846
+	}
847
+
848
+
849
+	public function load_scripts_styles_edit_message_template()
850
+	{
851
+
852
+		$this->_set_shortcodes();
853
+
854
+		EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
855
+			esc_html__(
856
+				'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.',
857
+				'event_espresso'
858
+			),
859
+			$this->_message_template_group->messenger_obj()->label['singular'],
860
+			$this->_message_template_group->message_type_obj()->label['singular']
861
+		);
862
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
863
+			'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?',
864
+			'event_espresso'
865
+		);
866
+		EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
867
+			'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
868
+			'event_espresso'
869
+		);
870
+
871
+		wp_register_script(
872
+			'ee_msgs_edit_js',
873
+			EE_MSG_ASSETS_URL . 'ee_message_editor.js',
874
+			array('jquery'),
875
+			EVENT_ESPRESSO_VERSION
876
+		);
877
+
878
+		wp_enqueue_script('ee_admin_js');
879
+		wp_enqueue_script('ee_msgs_edit_js');
880
+
881
+		// add in special css for tiny_mce
882
+		add_filter('mce_css', array($this, 'wp_editor_css'));
883
+	}
884
+
885
+
886
+	public function load_scripts_styles_display_preview_message()
887
+	{
888
+
889
+		$this->_set_message_template_group();
890
+
891
+		if (isset($this->_req_data['messenger'])) {
892
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
893
+				$this->_req_data['messenger']
894
+			);
895
+		}
896
+
897
+		$message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
898
+
899
+
900
+		wp_enqueue_style(
901
+			'espresso_preview_css',
902
+			$this->_active_messenger->get_variation(
903
+				$this->_template_pack,
904
+				$message_type_name,
905
+				true,
906
+				'preview',
907
+				$this->_variation
908
+			)
909
+		);
910
+	}
911
+
912
+
913
+	public function load_scripts_styles_settings()
914
+	{
915
+		wp_register_style(
916
+			'ee-message-settings',
917
+			EE_MSG_ASSETS_URL . 'ee_message_settings.css',
918
+			array(),
919
+			EVENT_ESPRESSO_VERSION
920
+		);
921
+		wp_enqueue_style('ee-text-links');
922
+		wp_enqueue_style('ee-message-settings');
923
+		wp_enqueue_script('ee-messages-settings');
924
+	}
925
+
926
+
927
+	/**
928
+	 * set views array for List Table
929
+	 */
930
+	public function _set_list_table_views_global_mtps()
931
+	{
932
+		$this->_views = array(
933
+			'in_use' => array(
934
+				'slug'  => 'in_use',
935
+				'label' => esc_html__('In Use', 'event_espresso'),
936
+				'count' => 0,
937
+			),
938
+		);
939
+	}
940
+
941
+
942
+	/**
943
+	 * Set views array for the Custom Template List Table
944
+	 */
945
+	public function _set_list_table_views_custom_mtps()
946
+	{
947
+		$this->_set_list_table_views_global_mtps();
948
+		$this->_views['in_use']['bulk_action'] = array(
949
+			'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
950
+		);
951
+	}
952
+
953
+
954
+	/**
955
+	 * set views array for message queue list table
956
+	 *
957
+	 * @throws InvalidDataTypeException
958
+	 * @throws InvalidInterfaceException
959
+	 * @throws InvalidArgumentException
960
+	 * @throws EE_Error
961
+	 * @throws ReflectionException
962
+	 */
963
+	public function _set_list_table_views_default()
964
+	{
965
+		EE_Registry::instance()->load_helper('Template');
966
+
967
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
968
+			'ee_send_message',
969
+			'message_list_table_bulk_actions'
970
+		)
971
+			? array(
972
+				'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
973
+				'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
974
+				'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
975
+				'send_now'              => esc_html__('Send Now', 'event_espresso'),
976
+			)
977
+			: array();
978
+
979
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
980
+			'ee_delete_messages',
981
+			'message_list_table_bulk_actions'
982
+		)
983
+			? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
984
+			: array();
985
+
986
+
987
+		$this->_views = array(
988
+			'all' => array(
989
+				'slug'        => 'all',
990
+				'label'       => esc_html__('All', 'event_espresso'),
991
+				'count'       => 0,
992
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
993
+			),
994
+		);
995
+
996
+
997
+		foreach (EEM_Message::instance()->all_statuses() as $status) {
998
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
999
+				continue;
1000
+			}
1001
+			$status_bulk_actions = $common_bulk_actions;
1002
+			// unset bulk actions not applying to status
1003
+			if (! empty($status_bulk_actions)) {
1004
+				switch ($status) {
1005
+					case EEM_Message::status_idle:
1006
+					case EEM_Message::status_resend:
1007
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1008
+						break;
1009
+
1010
+					case EEM_Message::status_failed:
1011
+					case EEM_Message::status_debug_only:
1012
+					case EEM_Message::status_messenger_executing:
1013
+						$status_bulk_actions = array();
1014
+						break;
1015
+
1016
+					case EEM_Message::status_incomplete:
1017
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1018
+						break;
1019
+
1020
+					case EEM_Message::status_retry:
1021
+					case EEM_Message::status_sent:
1022
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1023
+						break;
1024
+				}
1025
+			}
1026
+
1027
+			// skip adding messenger executing status to views because it will be included with the Failed view.
1028
+			if ($status === EEM_Message::status_messenger_executing) {
1029
+				continue;
1030
+			}
1031
+
1032
+			$this->_views[ strtolower($status) ] = array(
1033
+				'slug'        => strtolower($status),
1034
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1035
+				'count'       => 0,
1036
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1037
+			);
1038
+		}
1039
+	}
1040
+
1041
+
1042
+	protected function _ee_default_messages_overview_list_table()
1043
+	{
1044
+		$this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1045
+		$this->display_admin_list_table_page_with_no_sidebar();
1046
+	}
1047
+
1048
+
1049
+	protected function _message_queue_list_table()
1050
+	{
1051
+		$this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1052
+		$this->_template_args['per_column'] = 6;
1053
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1054
+		$this->_template_args['before_list_table'] = '<h3>'
1055
+													 . EEM_Message::instance()->get_pretty_label_for_results()
1056
+													 . '</h3>';
1057
+		$this->display_admin_list_table_page_with_no_sidebar();
1058
+	}
1059
+
1060
+
1061
+	protected function _message_legend_items()
1062
+	{
1063
+
1064
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
1065
+		$action_items = array();
1066
+
1067
+		foreach ($action_css_classes as $action_item => $action_details) {
1068
+			if ($action_item === 'see_notifications_for') {
1069
+				continue;
1070
+			}
1071
+			$action_items[ $action_item ] = array(
1072
+				'class' => $action_details['css_class'],
1073
+				'desc'  => $action_details['label'],
1074
+			);
1075
+		}
1076
+
1077
+		/** @type array $status_items status legend setup */
1078
+		$status_items = array(
1079
+			'sent_status'                => array(
1080
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1081
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1082
+			),
1083
+			'idle_status'                => array(
1084
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1085
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1086
+			),
1087
+			'failed_status'              => array(
1088
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1089
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1090
+			),
1091
+			'messenger_executing_status' => array(
1092
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1093
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1094
+			),
1095
+			'resend_status'              => array(
1096
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1097
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1098
+			),
1099
+			'incomplete_status'          => array(
1100
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1101
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1102
+			),
1103
+			'retry_status'               => array(
1104
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1105
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1106
+			),
1107
+		);
1108
+		if (EEM_Message::debug()) {
1109
+			$status_items['debug_only_status'] = array(
1110
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1111
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1112
+			);
1113
+		}
1114
+
1115
+		return array_merge($action_items, $status_items);
1116
+	}
1117
+
1118
+
1119
+	protected function _custom_mtps_preview()
1120
+	{
1121
+		$this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1122
+		$this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1123
+											   . ' alt="' . esc_attr__(
1124
+												   'Preview Custom Message Templates screenshot',
1125
+												   'event_espresso'
1126
+											   ) . '" />';
1127
+		$this->_template_args['preview_text'] = '<strong>'
1128
+												. esc_html__(
1129
+													'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.',
1130
+													'event_espresso'
1131
+												)
1132
+												. '</strong>';
1133
+
1134
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1135
+	}
1136
+
1137
+
1138
+	/**
1139
+	 * get_message_templates
1140
+	 * This gets all the message templates for listing on the overview list.
1141
+	 *
1142
+	 * @access public
1143
+	 * @param int    $perpage the amount of templates groups to show per page
1144
+	 * @param string $type    the current _view we're getting templates for
1145
+	 * @param bool   $count   return count?
1146
+	 * @param bool   $all     disregard any paging info (get all data);
1147
+	 * @param bool   $global  whether to return just global (true) or custom templates (false)
1148
+	 * @return array
1149
+	 * @throws EE_Error
1150
+	 * @throws InvalidArgumentException
1151
+	 * @throws InvalidDataTypeException
1152
+	 * @throws InvalidInterfaceException
1153
+	 */
1154
+	public function get_message_templates(
1155
+		$perpage = 10,
1156
+		$type = 'in_use',
1157
+		$count = false,
1158
+		$all = false,
1159
+		$global = true
1160
+	) {
1161
+
1162
+		$MTP = EEM_Message_Template_Group::instance();
1163
+
1164
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1165
+		$orderby = $this->_req_data['orderby'];
1166
+
1167
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1168
+			? $this->_req_data['order']
1169
+			: 'ASC';
1170
+
1171
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1172
+			? $this->_req_data['paged']
1173
+			: 1;
1174
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1175
+			? $this->_req_data['perpage']
1176
+			: $perpage;
1177
+
1178
+		$offset = ($current_page - 1) * $per_page;
1179
+		$limit = $all ? null : array($offset, $per_page);
1180
+
1181
+
1182
+		// options will match what is in the _views array property
1183
+		switch ($type) {
1184
+			case 'in_use':
1185
+				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1186
+				break;
1187
+			default:
1188
+				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1189
+		}
1190
+
1191
+		return $templates;
1192
+	}
1193
+
1194
+
1195
+	/**
1196
+	 * filters etc might need a list of installed message_types
1197
+	 *
1198
+	 * @return array an array of message type objects
1199
+	 */
1200
+	public function get_installed_message_types()
1201
+	{
1202
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1203
+		$installed = array();
1204
+
1205
+		foreach ($installed_message_types as $message_type) {
1206
+			$installed[ $message_type->name ] = $message_type;
1207
+		}
1208
+
1209
+		return $installed;
1210
+	}
1211
+
1212
+
1213
+	/**
1214
+	 * _add_message_template
1215
+	 *
1216
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1217
+	 *
1218
+	 * @param string $message_type
1219
+	 * @param string $messenger
1220
+	 * @param string $GRP_ID
1221
+	 *
1222
+	 * @throws EE_error
1223
+	 */
1224
+	protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1225
+	{
1226
+		// set values override any request data
1227
+		$message_type = ! empty($message_type) ? $message_type : '';
1228
+		$message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1229
+			? $this->_req_data['message_type']
1230
+			: $message_type;
1231
+
1232
+		$messenger = ! empty($messenger) ? $messenger : '';
1233
+		$messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1234
+			? $this->_req_data['messenger']
1235
+			: $messenger;
1236
+
1237
+		$GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1238
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1239
+
1240
+		// we need messenger and message type.  They should be coming from the event editor. If not here then return error
1241
+		if (empty($message_type) || empty($messenger)) {
1242
+			throw new EE_Error(
1243
+				esc_html__(
1244
+					'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1245
+					'event_espresso'
1246
+				)
1247
+			);
1248
+		}
1249
+
1250
+		// we need the GRP_ID for the template being used as the base for the new template
1251
+		if (empty($GRP_ID)) {
1252
+			throw new EE_Error(
1253
+				esc_html__(
1254
+					'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1255
+					'event_espresso'
1256
+				)
1257
+			);
1258
+		}
1259
+
1260
+		// let's just make sure the template gets generated!
1261
+
1262
+		// we need to reassign some variables for what the insert is expecting
1263
+		$this->_req_data['MTP_messenger'] = $messenger;
1264
+		$this->_req_data['MTP_message_type'] = $message_type;
1265
+		$this->_req_data['GRP_ID'] = $GRP_ID;
1266
+		$this->_insert_or_update_message_template(true);
1267
+	}
1268
+
1269
+
1270
+	/**
1271
+	 * public wrapper for the _add_message_template method
1272
+	 *
1273
+	 * @param string $message_type     message type slug
1274
+	 * @param string $messenger        messenger slug
1275
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1276
+	 *                                 off of.
1277
+	 * @throws EE_error
1278
+	 */
1279
+	public function add_message_template($message_type, $messenger, $GRP_ID)
1280
+	{
1281
+		$this->_add_message_template($message_type, $messenger, $GRP_ID);
1282
+	}
1283
+
1284
+
1285
+	/**
1286
+	 * _edit_message_template
1287
+	 *
1288
+	 * @access protected
1289
+	 * @return void
1290
+	 * @throws InvalidIdentifierException
1291
+	 * @throws DomainException
1292
+	 * @throws EE_Error
1293
+	 * @throws InvalidArgumentException
1294
+	 * @throws ReflectionException
1295
+	 * @throws InvalidDataTypeException
1296
+	 * @throws InvalidInterfaceException
1297
+	 */
1298
+	protected function _edit_message_template()
1299
+	{
1300
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1301
+		$template_fields = '';
1302
+		$sidebar_fields = '';
1303
+		// we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1304
+		// valid html in the templates.
1305
+		add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1306
+
1307
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1308
+			? absint($this->_req_data['id'])
1309
+			: false;
1310
+
1311
+		$this->_set_shortcodes(); // this also sets the _message_template property.
1312
+		$message_template_group = $this->_message_template_group;
1313
+		$c_label = $message_template_group->context_label();
1314
+		$c_config = $message_template_group->contexts_config();
1315
+
1316
+		reset($c_config);
1317
+		$context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1318
+			? strtolower($this->_req_data['context'])
1319
+			: key($c_config);
1320
+
1321
+
1322
+		if (empty($GRP_ID)) {
1323
+			$action = 'insert_message_template';
1324
+			$edit_message_template_form_url = add_query_arg(
1325
+				array('action' => $action, 'noheader' => true),
1326
+				EE_MSG_ADMIN_URL
1327
+			);
1328
+		} else {
1329
+			$action = 'update_message_template';
1330
+			$edit_message_template_form_url = add_query_arg(
1331
+				array('action' => $action, 'noheader' => true),
1332
+				EE_MSG_ADMIN_URL
1333
+			);
1334
+		}
1335
+
1336
+		// set active messenger for this view
1337
+		$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1338
+			$message_template_group->messenger()
1339
+		);
1340
+		$this->_active_message_type_name = $message_template_group->message_type();
1341
+
1342
+
1343
+		// Do we have any validation errors?
1344
+		$validators = $this->_get_transient();
1345
+		$v_fields = ! empty($validators) ? array_keys($validators) : array();
1346
+
1347
+
1348
+		// we need to assemble the title from Various details
1349
+		$context_label = sprintf(
1350
+			esc_html__('(%s %s)', 'event_espresso'),
1351
+			$c_config[ $context ]['label'],
1352
+			ucwords($c_label['label'])
1353
+		);
1354
+
1355
+		$title = sprintf(
1356
+			esc_html__(' %s %s Template %s', 'event_espresso'),
1357
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1358
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1359
+			$context_label
1360
+		);
1361
+
1362
+		$this->_template_args['GRP_ID'] = $GRP_ID;
1363
+		$this->_template_args['message_template'] = $message_template_group;
1364
+		$this->_template_args['is_extra_fields'] = false;
1365
+
1366
+
1367
+		// let's get EEH_MSG_Template so we can get template form fields
1368
+		$template_field_structure = EEH_MSG_Template::get_fields(
1369
+			$message_template_group->messenger(),
1370
+			$message_template_group->message_type()
1371
+		);
1372
+
1373
+		if (! $template_field_structure) {
1374
+			$template_field_structure = false;
1375
+			$template_fields = esc_html__(
1376
+				'There was an error in assembling the fields for this display (you should see an error message)',
1377
+				'event_espresso'
1378
+			);
1379
+		}
1380
+
1381
+
1382
+		$message_templates = $message_template_group->context_templates();
1383
+
1384
+
1385
+		// if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1386
+		// will get handled in the "extra" array.
1387
+		if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1388
+			foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1389
+				unset($template_field_structure[ $context ][ $reference_field ]);
1390
+			}
1391
+		}
1392
+
1393
+		// let's loop through the template_field_structure and actually assemble the input fields!
1394
+		if (! empty($template_field_structure)) {
1395
+			foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1396
+				// if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1397
+				// the extra array and reset them.
1398
+				if ($template_field === 'extra') {
1399
+					$this->_template_args['is_extra_fields'] = true;
1400
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1401
+						$message_template = $message_templates[ $context ][ $reference_field ];
1402
+						$content = $message_template instanceof EE_Message_Template
1403
+							? $message_template->get('MTP_content')
1404
+							: '';
1405
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1406
+							// let's verify if we need this extra field via the shortcodes parameter.
1407
+							$continue = false;
1408
+							if (isset($extra_array['shortcodes_required'])) {
1409
+								foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1410
+									if (! array_key_exists($shortcode, $this->_shortcodes)) {
1411
+										$continue = true;
1412
+									}
1413
+								}
1414
+								if ($continue) {
1415
+									continue;
1416
+								}
1417
+							}
1418
+
1419
+							$field_id = $reference_field
1420
+										. '-'
1421
+										. $extra_field
1422
+										. '-content';
1423
+							$template_form_fields[ $field_id ] = $extra_array;
1424
+							$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1425
+																		 . $reference_field
1426
+																		 . '][content]['
1427
+																		 . $extra_field . ']';
1428
+							$css_class = isset($extra_array['css_class'])
1429
+								? $extra_array['css_class']
1430
+								: '';
1431
+
1432
+							$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1433
+																			  && in_array($extra_field, $v_fields, true)
1434
+																			  &&
1435
+																			  (
1436
+																				  is_array($validators[ $extra_field ])
1437
+																				  && isset($validators[ $extra_field ]['msg'])
1438
+																			  )
1439
+								? 'validate-error ' . $css_class
1440
+								: $css_class;
1441
+
1442
+							$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1443
+																		  && isset($content[ $extra_field ])
1444
+								? $content[ $extra_field ]
1445
+								: '';
1446
+
1447
+							// do we have a validation error?  if we do then let's use that value instead
1448
+							$template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1449
+								? $validators[ $extra_field ]['value']
1450
+								: $template_form_fields[ $field_id ]['value'];
1451
+
1452
+
1453
+							$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1454
+
1455
+							// shortcode selector
1456
+							$field_name_to_use = $extra_field === 'main'
1457
+								? 'content'
1458
+								: $extra_field;
1459
+							$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1460
+								$field_name_to_use,
1461
+								$field_id
1462
+							);
1463
+
1464
+							if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1465
+								// we want to decode the entities
1466
+								$template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1467
+							}/**/
1468
+						}
1469
+						$templatefield_MTP_id = $reference_field . '-MTP_ID';
1470
+						$templatefield_templatename_id = $reference_field . '-name';
1471
+
1472
+						$template_form_fields[ $templatefield_MTP_id ] = array(
1473
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1474
+							'label'      => null,
1475
+							'input'      => 'hidden',
1476
+							'type'       => 'int',
1477
+							'required'   => false,
1478
+							'validation' => false,
1479
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1480
+							'css_class'  => '',
1481
+							'format'     => '%d',
1482
+							'db-col'     => 'MTP_ID',
1483
+						);
1484
+
1485
+						$template_form_fields[ $templatefield_templatename_id ] = array(
1486
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1487
+							'label'      => null,
1488
+							'input'      => 'hidden',
1489
+							'type'       => 'string',
1490
+							'required'   => false,
1491
+							'validation' => true,
1492
+							'value'      => $reference_field,
1493
+							'css_class'  => '',
1494
+							'format'     => '%s',
1495
+							'db-col'     => 'MTP_template_field',
1496
+						);
1497
+					}
1498
+					continue; // skip the next stuff, we got the necessary fields here for this dataset.
1499
+				} else {
1500
+					$field_id = $template_field . '-content';
1501
+					$template_form_fields[ $field_id ] = $field_setup_array;
1502
+					$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1503
+					$message_template = isset($message_templates[ $context ][ $template_field ])
1504
+						? $message_templates[ $context ][ $template_field ]
1505
+						: null;
1506
+					$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1507
+																  && is_array($message_templates[ $context ])
1508
+																  && $message_template instanceof EE_Message_Template
1509
+						? $message_template->get('MTP_content')
1510
+						: '';
1511
+
1512
+					// do we have a validator error for this field?  if we do then we'll use that value instead
1513
+					$template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1514
+						? $validators[ $template_field ]['value']
1515
+						: $template_form_fields[ $field_id ]['value'];
1516
+
1517
+
1518
+					$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1519
+					$css_class = isset($field_setup_array['css_class'])
1520
+						? $field_setup_array['css_class']
1521
+						: '';
1522
+					$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1523
+																	  && in_array($template_field, $v_fields, true)
1524
+																	  && isset($validators[ $template_field ]['msg'])
1525
+						? 'validate-error ' . $css_class
1526
+						: $css_class;
1527
+
1528
+					// shortcode selector
1529
+					$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1530
+						$template_field,
1531
+						$field_id
1532
+					);
1533
+				}
1534
+
1535
+				// k took care of content field(s) now let's take care of others.
1536
+
1537
+				$templatefield_MTP_id = $template_field . '-MTP_ID';
1538
+				$templatefield_field_templatename_id = $template_field . '-name';
1539
+
1540
+				// foreach template field there are actually two form fields created
1541
+				$template_form_fields[ $templatefield_MTP_id ] = array(
1542
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1543
+					'label'      => null,
1544
+					'input'      => 'hidden',
1545
+					'type'       => 'int',
1546
+					'required'   => false,
1547
+					'validation' => true,
1548
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1549
+					'css_class'  => '',
1550
+					'format'     => '%d',
1551
+					'db-col'     => 'MTP_ID',
1552
+				);
1553
+
1554
+				$template_form_fields[ $templatefield_field_templatename_id ] = array(
1555
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1556
+					'label'      => null,
1557
+					'input'      => 'hidden',
1558
+					'type'       => 'string',
1559
+					'required'   => false,
1560
+					'validation' => true,
1561
+					'value'      => $template_field,
1562
+					'css_class'  => '',
1563
+					'format'     => '%s',
1564
+					'db-col'     => 'MTP_template_field',
1565
+				);
1566
+			}
1567
+
1568
+			// add other fields
1569
+			$template_form_fields['ee-msg-current-context'] = array(
1570
+				'name'       => 'MTP_context',
1571
+				'label'      => null,
1572
+				'input'      => 'hidden',
1573
+				'type'       => 'string',
1574
+				'required'   => false,
1575
+				'validation' => true,
1576
+				'value'      => $context,
1577
+				'css_class'  => '',
1578
+				'format'     => '%s',
1579
+				'db-col'     => 'MTP_context',
1580
+			);
1581
+
1582
+			$template_form_fields['ee-msg-grp-id'] = array(
1583
+				'name'       => 'GRP_ID',
1584
+				'label'      => null,
1585
+				'input'      => 'hidden',
1586
+				'type'       => 'int',
1587
+				'required'   => false,
1588
+				'validation' => true,
1589
+				'value'      => $GRP_ID,
1590
+				'css_class'  => '',
1591
+				'format'     => '%d',
1592
+				'db-col'     => 'GRP_ID',
1593
+			);
1594
+
1595
+			$template_form_fields['ee-msg-messenger'] = array(
1596
+				'name'       => 'MTP_messenger',
1597
+				'label'      => null,
1598
+				'input'      => 'hidden',
1599
+				'type'       => 'string',
1600
+				'required'   => false,
1601
+				'validation' => true,
1602
+				'value'      => $message_template_group->messenger(),
1603
+				'css_class'  => '',
1604
+				'format'     => '%s',
1605
+				'db-col'     => 'MTP_messenger',
1606
+			);
1607
+
1608
+			$template_form_fields['ee-msg-message-type'] = array(
1609
+				'name'       => 'MTP_message_type',
1610
+				'label'      => null,
1611
+				'input'      => 'hidden',
1612
+				'type'       => 'string',
1613
+				'required'   => false,
1614
+				'validation' => true,
1615
+				'value'      => $message_template_group->message_type(),
1616
+				'css_class'  => '',
1617
+				'format'     => '%s',
1618
+				'db-col'     => 'MTP_message_type',
1619
+			);
1620
+
1621
+			$sidebar_form_fields['ee-msg-is-global'] = array(
1622
+				'name'       => 'MTP_is_global',
1623
+				'label'      => esc_html__('Global Template', 'event_espresso'),
1624
+				'input'      => 'hidden',
1625
+				'type'       => 'int',
1626
+				'required'   => false,
1627
+				'validation' => true,
1628
+				'value'      => $message_template_group->get('MTP_is_global'),
1629
+				'css_class'  => '',
1630
+				'format'     => '%d',
1631
+				'db-col'     => 'MTP_is_global',
1632
+			);
1633
+
1634
+			$sidebar_form_fields['ee-msg-is-override'] = array(
1635
+				'name'       => 'MTP_is_override',
1636
+				'label'      => esc_html__('Override all custom', 'event_espresso'),
1637
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1638
+				'type'       => 'int',
1639
+				'required'   => false,
1640
+				'validation' => true,
1641
+				'value'      => $message_template_group->get('MTP_is_override'),
1642
+				'css_class'  => '',
1643
+				'format'     => '%d',
1644
+				'db-col'     => 'MTP_is_override',
1645
+			);
1646
+
1647
+			$sidebar_form_fields['ee-msg-is-active'] = array(
1648
+				'name'       => 'MTP_is_active',
1649
+				'label'      => esc_html__('Active Template', 'event_espresso'),
1650
+				'input'      => 'hidden',
1651
+				'type'       => 'int',
1652
+				'required'   => false,
1653
+				'validation' => true,
1654
+				'value'      => $message_template_group->is_active(),
1655
+				'css_class'  => '',
1656
+				'format'     => '%d',
1657
+				'db-col'     => 'MTP_is_active',
1658
+			);
1659
+
1660
+			$sidebar_form_fields['ee-msg-deleted'] = array(
1661
+				'name'       => 'MTP_deleted',
1662
+				'label'      => null,
1663
+				'input'      => 'hidden',
1664
+				'type'       => 'int',
1665
+				'required'   => false,
1666
+				'validation' => true,
1667
+				'value'      => $message_template_group->get('MTP_deleted'),
1668
+				'css_class'  => '',
1669
+				'format'     => '%d',
1670
+				'db-col'     => 'MTP_deleted',
1671
+			);
1672
+			$sidebar_form_fields['ee-msg-author'] = array(
1673
+				'name'       => 'MTP_user_id',
1674
+				'label'      => esc_html__('Author', 'event_espresso'),
1675
+				'input'      => 'hidden',
1676
+				'type'       => 'int',
1677
+				'required'   => false,
1678
+				'validation' => false,
1679
+				'value'      => $message_template_group->user(),
1680
+				'format'     => '%d',
1681
+				'db-col'     => 'MTP_user_id',
1682
+			);
1683
+
1684
+			$sidebar_form_fields['ee-msg-route'] = array(
1685
+				'name'  => 'action',
1686
+				'input' => 'hidden',
1687
+				'type'  => 'string',
1688
+				'value' => $action,
1689
+			);
1690
+
1691
+			$sidebar_form_fields['ee-msg-id'] = array(
1692
+				'name'  => 'id',
1693
+				'input' => 'hidden',
1694
+				'type'  => 'int',
1695
+				'value' => $GRP_ID,
1696
+			);
1697
+			$sidebar_form_fields['ee-msg-evt-nonce'] = array(
1698
+				'name'  => $action . '_nonce',
1699
+				'input' => 'hidden',
1700
+				'type'  => 'string',
1701
+				'value' => wp_create_nonce($action . '_nonce'),
1702
+			);
1703
+
1704
+			if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1705
+				$sidebar_form_fields['ee-msg-template-switch'] = array(
1706
+					'name'  => 'template_switch',
1707
+					'input' => 'hidden',
1708
+					'type'  => 'int',
1709
+					'value' => 1,
1710
+				);
1711
+			}
1712
+
1713
+
1714
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1715
+			$sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1716
+		} //end if ( !empty($template_field_structure) )
1717
+
1718
+		// set extra content for publish box
1719
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1720
+		$this->_set_publish_post_box_vars(
1721
+			'id',
1722
+			$GRP_ID,
1723
+			false,
1724
+			add_query_arg(
1725
+				array('action' => 'global_mtps'),
1726
+				$this->_admin_base_url
1727
+			)
1728
+		);
1729
+
1730
+		// add preview button
1731
+		$preview_url = parent::add_query_args_and_nonce(
1732
+			array(
1733
+				'message_type' => $message_template_group->message_type(),
1734
+				'messenger'    => $message_template_group->messenger(),
1735
+				'context'      => $context,
1736
+				'GRP_ID'       => $GRP_ID,
1737
+				'action'       => 'preview_message',
1738
+			),
1739
+			$this->_admin_base_url
1740
+		);
1741
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1742
+						  . esc_html__('Preview', 'event_espresso')
1743
+						  . '</a>';
1744
+
1745
+
1746
+		// setup context switcher
1747
+		$context_switcher_args = array(
1748
+			'page'    => 'espresso_messages',
1749
+			'action'  => 'edit_message_template',
1750
+			'id'      => $GRP_ID,
1751
+			'context' => $context,
1752
+			'extra'   => $preview_button,
1753
+		);
1754
+		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1755
+
1756
+
1757
+		// main box
1758
+		$this->_template_args['template_fields'] = $template_fields;
1759
+		$this->_template_args['sidebar_box_id'] = 'details';
1760
+		$this->_template_args['action'] = $action;
1761
+		$this->_template_args['context'] = $context;
1762
+		$this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1763
+		$this->_template_args['learn_more_about_message_templates_link'] =
1764
+			$this->_learn_more_about_message_templates_link();
1765
+
1766
+
1767
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1768
+		$this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1769
+			$message_template_group,
1770
+			$context,
1771
+			$context_label
1772
+		);
1773
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1774
+		$this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1775
+
1776
+		$this->_template_path = $this->_template_args['GRP_ID']
1777
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1778
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1779
+
1780
+		// send along EE_Message_Template_Group object for further template use.
1781
+		$this->_template_args['MTP'] = $message_template_group;
1782
+
1783
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
1784
+			$this->_template_path,
1785
+			$this->_template_args,
1786
+			true
1787
+		);
1788
+
1789
+
1790
+		// finally, let's set the admin_page title
1791
+		$this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1792
+
1793
+
1794
+		// we need to take care of setting the shortcodes property for use elsewhere.
1795
+		$this->_set_shortcodes();
1796
+
1797
+
1798
+		// final template wrapper
1799
+		$this->display_admin_page_with_sidebar();
1800
+	}
1801
+
1802
+
1803
+	public function filter_tinymce_init($mceInit, $editor_id)
1804
+	{
1805
+		return $mceInit;
1806
+	}
1807
+
1808
+
1809
+	public function add_context_switcher()
1810
+	{
1811
+		return $this->_context_switcher;
1812
+	}
1813
+
1814
+
1815
+	/**
1816
+	 * Adds the activation/deactivation toggle for the message template context.
1817
+	 *
1818
+	 * @param EE_Message_Template_Group $message_template_group
1819
+	 * @param string                    $context
1820
+	 * @param string                    $context_label
1821
+	 * @return string
1822
+	 * @throws DomainException
1823
+	 * @throws EE_Error
1824
+	 * @throws InvalidIdentifierException
1825
+	 */
1826
+	protected function add_active_context_element(
1827
+		EE_Message_Template_Group $message_template_group,
1828
+		$context,
1829
+		$context_label
1830
+	) {
1831
+		$template_args = array(
1832
+			'context'                   => $context,
1833
+			'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1834
+			'is_active'                 => $message_template_group->is_context_active($context),
1835
+			'on_off_action'             => $message_template_group->is_context_active($context)
1836
+				? 'context-off'
1837
+				: 'context-on',
1838
+			'context_label'             => str_replace(array('(', ')'), '', $context_label),
1839
+			'message_template_group_id' => $message_template_group->ID(),
1840
+		);
1841
+		return EEH_Template::display_template(
1842
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1843
+			$template_args,
1844
+			true
1845
+		);
1846
+	}
1847
+
1848
+
1849
+	/**
1850
+	 * Ajax callback for `toggle_context_template` ajax action.
1851
+	 * Handles toggling the message context on or off.
1852
+	 *
1853
+	 * @throws EE_Error
1854
+	 * @throws InvalidArgumentException
1855
+	 * @throws InvalidDataTypeException
1856
+	 * @throws InvalidIdentifierException
1857
+	 * @throws InvalidInterfaceException
1858
+	 */
1859
+	public function toggle_context_template()
1860
+	{
1861
+		$success = true;
1862
+		// check for required data
1863
+		if (! isset(
1864
+			$this->_req_data['message_template_group_id'],
1865
+			$this->_req_data['context'],
1866
+			$this->_req_data['status']
1867
+		)) {
1868
+			EE_Error::add_error(
1869
+				esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1870
+				__FILE__,
1871
+				__FUNCTION__,
1872
+				__LINE__
1873
+			);
1874
+			$success = false;
1875
+		}
1876
+
1877
+		$nonce = isset($this->_req_data['toggle_context_nonce'])
1878
+			? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1879
+			: '';
1880
+		$nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1881
+		$this->_verify_nonce($nonce, $nonce_ref);
1882
+		$status = $this->_req_data['status'];
1883
+		if ($status !== 'off' && $status !== 'on') {
1884
+			EE_Error::add_error(
1885
+				sprintf(
1886
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1887
+					$this->_req_data['status']
1888
+				),
1889
+				__FILE__,
1890
+				__FUNCTION__,
1891
+				__LINE__
1892
+			);
1893
+			$success = false;
1894
+		}
1895
+		$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1896
+			$this->_req_data['message_template_group_id']
1897
+		);
1898
+		if (! $message_template_group instanceof EE_Message_Template_Group) {
1899
+			EE_Error::add_error(
1900
+				sprintf(
1901
+					esc_html__(
1902
+						'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1903
+						'event_espresso'
1904
+					),
1905
+					$this->_req_data['message_template_group_id'],
1906
+					'EE_Message_Template_Group'
1907
+				),
1908
+				__FILE__,
1909
+				__FUNCTION__,
1910
+				__LINE__
1911
+			);
1912
+			$success = false;
1913
+		}
1914
+		if ($success) {
1915
+			$success = $status === 'off'
1916
+				? $message_template_group->deactivate_context($this->_req_data['context'])
1917
+				: $message_template_group->activate_context($this->_req_data['context']);
1918
+		}
1919
+		$this->_template_args['success'] = $success;
1920
+		$this->_return_json();
1921
+	}
1922
+
1923
+
1924
+	public function _add_form_element_before()
1925
+	{
1926
+		return '<form method="post" action="'
1927
+			   . $this->_template_args["edit_message_template_form_url"]
1928
+			   . '" id="ee-msg-edit-frm">';
1929
+	}
1930
+
1931
+	public function _add_form_element_after()
1932
+	{
1933
+		return '</form>';
1934
+	}
1935
+
1936
+
1937
+	/**
1938
+	 * This executes switching the template pack for a message template.
1939
+	 *
1940
+	 * @since 4.5.0
1941
+	 * @throws EE_Error
1942
+	 * @throws InvalidDataTypeException
1943
+	 * @throws InvalidInterfaceException
1944
+	 * @throws InvalidArgumentException
1945
+	 * @throws ReflectionException
1946
+	 */
1947
+	public function switch_template_pack()
1948
+	{
1949
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1950
+		$template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1951
+
1952
+		// verify we have needed values.
1953
+		if (empty($GRP_ID) || empty($template_pack)) {
1954
+			$this->_template_args['error'] = true;
1955
+			EE_Error::add_error(
1956
+				esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1957
+				__FILE__,
1958
+				__FUNCTION__,
1959
+				__LINE__
1960
+			);
1961
+		} else {
1962
+			// get template, set the new template_pack and then reset to default
1963
+			/** @type EE_Message_Template_Group $message_template_group */
1964
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1965
+
1966
+			$message_template_group->set_template_pack_name($template_pack);
1967
+			$this->_req_data['msgr'] = $message_template_group->messenger();
1968
+			$this->_req_data['mt'] = $message_template_group->message_type();
1969
+
1970
+			$query_args = $this->_reset_to_default_template();
1971
+
1972
+			if (empty($query_args['id'])) {
1973
+				EE_Error::add_error(
1974
+					esc_html__(
1975
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
1976
+						'event_espresso'
1977
+					),
1978
+					__FILE__,
1979
+					__FUNCTION__,
1980
+					__LINE__
1981
+				);
1982
+				$this->_template_args['error'] = true;
1983
+			} else {
1984
+				$template_label = $message_template_group->get_template_pack()->label;
1985
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1986
+				EE_Error::add_success(
1987
+					sprintf(
1988
+						esc_html__(
1989
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1990
+							'event_espresso'
1991
+						),
1992
+						$template_label,
1993
+						$template_pack_labels->template_pack
1994
+					)
1995
+				);
1996
+				// generate the redirect url for js.
1997
+				$url = self::add_query_args_and_nonce(
1998
+					$query_args,
1999
+					$this->_admin_base_url
2000
+				);
2001
+				$this->_template_args['data']['redirect_url'] = $url;
2002
+				$this->_template_args['success'] = true;
2003
+			}
2004
+
2005
+			$this->_return_json();
2006
+		}
2007
+	}
2008
+
2009
+
2010
+	/**
2011
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2012
+	 * they want.
2013
+	 *
2014
+	 * @access protected
2015
+	 * @return array|null
2016
+	 * @throws EE_Error
2017
+	 * @throws InvalidArgumentException
2018
+	 * @throws InvalidDataTypeException
2019
+	 * @throws InvalidInterfaceException
2020
+	 */
2021
+	protected function _reset_to_default_template()
2022
+	{
2023
+
2024
+		$templates = array();
2025
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2026
+		// we need to make sure we've got the info we need.
2027
+		if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2028
+			EE_Error::add_error(
2029
+				esc_html__(
2030
+					'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.',
2031
+					'event_espresso'
2032
+				),
2033
+				__FILE__,
2034
+				__FUNCTION__,
2035
+				__LINE__
2036
+			);
2037
+		}
2038
+
2039
+		// all templates will be reset to whatever the defaults are
2040
+		// for the global template matching the messenger and message type.
2041
+		$success = ! empty($GRP_ID) ? true : false;
2042
+
2043
+		if ($success) {
2044
+			// let's first determine if the incoming template is a global template,
2045
+			// if it isn't then we need to get the global template matching messenger and message type.
2046
+			// $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2047
+
2048
+
2049
+			// note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2050
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
2051
+
2052
+			if ($success) {
2053
+				// if successfully deleted, lets generate the new ones.
2054
+				// Note. We set GLOBAL to true, because resets on ANY template
2055
+				// will use the related global template defaults for regeneration.
2056
+				// This means that if a custom template is reset it resets to whatever the related global template is.
2057
+				// HOWEVER, we DO keep the template pack and template variation set
2058
+				// for the current custom template when resetting.
2059
+				$templates = $this->_generate_new_templates(
2060
+					$this->_req_data['msgr'],
2061
+					$this->_req_data['mt'],
2062
+					$GRP_ID,
2063
+					true
2064
+				);
2065
+			}
2066
+		}
2067
+
2068
+		// any error messages?
2069
+		if (! $success) {
2070
+			EE_Error::add_error(
2071
+				esc_html__(
2072
+					'Something went wrong with deleting existing templates. Unable to reset to default',
2073
+					'event_espresso'
2074
+				),
2075
+				__FILE__,
2076
+				__FUNCTION__,
2077
+				__LINE__
2078
+			);
2079
+		}
2080
+
2081
+		// all good, let's add a success message!
2082
+		if ($success && ! empty($templates)) {
2083
+			// the info for the template we generated is the first element in the returned array
2084
+			// $templates = $templates[0];
2085
+			EE_Error::overwrite_success();
2086
+			EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2087
+		}
2088
+
2089
+
2090
+		$query_args = array(
2091
+			'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2092
+			'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2093
+			'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2094
+		);
2095
+
2096
+		// if called via ajax then we return query args otherwise redirect
2097
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2098
+			return $query_args;
2099
+		} else {
2100
+			$this->_redirect_after_action(false, '', '', $query_args, true);
2101
+
2102
+			return null;
2103
+		}
2104
+	}
2105
+
2106
+
2107
+	/**
2108
+	 * Retrieve and set the message preview for display.
2109
+	 *
2110
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2111
+	 * @return string
2112
+	 * @throws ReflectionException
2113
+	 * @throws EE_Error
2114
+	 * @throws InvalidArgumentException
2115
+	 * @throws InvalidDataTypeException
2116
+	 * @throws InvalidInterfaceException
2117
+	 */
2118
+	public function _preview_message($send = false)
2119
+	{
2120
+		// first make sure we've got the necessary parameters
2121
+		if (! isset(
2122
+			$this->_req_data['message_type'],
2123
+			$this->_req_data['messenger'],
2124
+			$this->_req_data['messenger'],
2125
+			$this->_req_data['GRP_ID']
2126
+		)) {
2127
+			EE_Error::add_error(
2128
+				esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2129
+				__FILE__,
2130
+				__FUNCTION__,
2131
+				__LINE__
2132
+			);
2133
+		}
2134
+
2135
+		EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
2136
+
2137
+
2138
+		// get the preview!
2139
+		$preview = EED_Messages::preview_message(
2140
+			$this->_req_data['message_type'],
2141
+			$this->_req_data['context'],
2142
+			$this->_req_data['messenger'],
2143
+			$send
2144
+		);
2145
+
2146
+		if ($send) {
2147
+			return $preview;
2148
+		}
2149
+
2150
+		// let's add a button to go back to the edit view
2151
+		$query_args = array(
2152
+			'id'      => $this->_req_data['GRP_ID'],
2153
+			'context' => $this->_req_data['context'],
2154
+			'action'  => 'edit_message_template',
2155
+		);
2156
+		$go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2157
+		$preview_button = '<a href="'
2158
+						  . $go_back_url
2159
+						  . '" class="button-secondary messages-preview-go-back-button">'
2160
+						  . esc_html__('Go Back to Edit', 'event_espresso')
2161
+						  . '</a>';
2162
+		$message_types = $this->get_installed_message_types();
2163
+		$active_messenger = $this->_message_resource_manager->get_active_messenger(
2164
+			$this->_req_data['messenger']
2165
+		);
2166
+		$active_messenger_label = $active_messenger instanceof EE_messenger
2167
+			? ucwords($active_messenger->label['singular'])
2168
+			: esc_html__('Unknown Messenger', 'event_espresso');
2169
+		// let's provide a helpful title for context
2170
+		$preview_title = sprintf(
2171
+			esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2172
+			$active_messenger_label,
2173
+			ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2174
+		);
2175
+		// setup display of preview.
2176
+		$this->_admin_page_title = $preview_title;
2177
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2178
+		$this->_template_args['data']['force_json'] = true;
2179
+
2180
+		return '';
2181
+	}
2182
+
2183
+
2184
+	/**
2185
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2186
+	 * gets called automatically.
2187
+	 *
2188
+	 * @since 4.5.0
2189
+	 *
2190
+	 * @return string
2191
+	 */
2192
+	protected function _display_preview_message()
2193
+	{
2194
+		$this->display_admin_page_with_no_sidebar();
2195
+	}
2196
+
2197
+
2198
+	/**
2199
+	 * registers metaboxes that should show up on the "edit_message_template" page
2200
+	 *
2201
+	 * @access protected
2202
+	 * @return void
2203
+	 */
2204
+	protected function _register_edit_meta_boxes()
2205
+	{
2206
+		add_meta_box(
2207
+			'mtp_valid_shortcodes',
2208
+			esc_html__('Valid Shortcodes', 'event_espresso'),
2209
+			array($this, 'shortcode_meta_box'),
2210
+			$this->_current_screen->id,
2211
+			'side',
2212
+			'default'
2213
+		);
2214
+		add_meta_box(
2215
+			'mtp_extra_actions',
2216
+			esc_html__('Extra Actions', 'event_espresso'),
2217
+			array($this, 'extra_actions_meta_box'),
2218
+			$this->_current_screen->id,
2219
+			'side',
2220
+			'high'
2221
+		);
2222
+		add_meta_box(
2223
+			'mtp_templates',
2224
+			esc_html__('Template Styles', 'event_espresso'),
2225
+			array($this, 'template_pack_meta_box'),
2226
+			$this->_current_screen->id,
2227
+			'side',
2228
+			'high'
2229
+		);
2230
+	}
2231
+
2232
+
2233
+	/**
2234
+	 * metabox content for all template pack and variation selection.
2235
+	 *
2236
+	 * @since 4.5.0
2237
+	 * @return string
2238
+	 * @throws DomainException
2239
+	 * @throws EE_Error
2240
+	 * @throws InvalidArgumentException
2241
+	 * @throws ReflectionException
2242
+	 * @throws InvalidDataTypeException
2243
+	 * @throws InvalidInterfaceException
2244
+	 */
2245
+	public function template_pack_meta_box()
2246
+	{
2247
+		$this->_set_message_template_group();
2248
+
2249
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
2250
+
2251
+		$tp_select_values = array();
2252
+
2253
+		foreach ($tp_collection as $tp) {
2254
+			// only include template packs that support this messenger and message type!
2255
+			$supports = $tp->get_supports();
2256
+			if (! isset($supports[ $this->_message_template_group->messenger() ])
2257
+				|| ! in_array(
2258
+					$this->_message_template_group->message_type(),
2259
+					$supports[ $this->_message_template_group->messenger() ],
2260
+					true
2261
+				)
2262
+			) {
2263
+				// not supported
2264
+				continue;
2265
+			}
2266
+
2267
+			$tp_select_values[] = array(
2268
+				'text' => $tp->label,
2269
+				'id'   => $tp->dbref,
2270
+			);
2271
+		}
2272
+
2273
+		// if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2274
+		// the default template pack.  This still allows for the odd template pack to override.
2275
+		if (empty($tp_select_values)) {
2276
+			$tp_select_values[] = array(
2277
+				'text' => esc_html__('Default', 'event_espresso'),
2278
+				'id'   => 'default',
2279
+			);
2280
+		}
2281
+
2282
+		// setup variation select values for the currently selected template.
2283
+		$variations = $this->_message_template_group->get_template_pack()->get_variations(
2284
+			$this->_message_template_group->messenger(),
2285
+			$this->_message_template_group->message_type()
2286
+		);
2287
+		$variations_select_values = array();
2288
+		foreach ($variations as $variation => $label) {
2289
+			$variations_select_values[] = array(
2290
+				'text' => $label,
2291
+				'id'   => $variation,
2292
+			);
2293
+		}
2294
+
2295
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2296
+
2297
+		$template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2298
+			'MTP_template_pack',
2299
+			$tp_select_values,
2300
+			$this->_message_template_group->get_template_pack_name()
2301
+		);
2302
+		$template_args['variations_selector'] = EEH_Form_Fields::select_input(
2303
+			'MTP_template_variation',
2304
+			$variations_select_values,
2305
+			$this->_message_template_group->get_template_pack_variation()
2306
+		);
2307
+		$template_args['template_pack_label'] = $template_pack_labels->template_pack;
2308
+		$template_args['template_variation_label'] = $template_pack_labels->template_variation;
2309
+		$template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2310
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2311
+
2312
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2313
+
2314
+		EEH_Template::display_template($template, $template_args);
2315
+	}
2316
+
2317
+
2318
+	/**
2319
+	 * This meta box holds any extra actions related to Message Templates
2320
+	 * For now, this includes Resetting templates to defaults and sending a test email.
2321
+	 *
2322
+	 * @access  public
2323
+	 * @return void
2324
+	 * @throws EE_Error
2325
+	 */
2326
+	public function extra_actions_meta_box()
2327
+	{
2328
+		$template_form_fields = array();
2329
+
2330
+		$extra_args = array(
2331
+			'msgr'   => $this->_message_template_group->messenger(),
2332
+			'mt'     => $this->_message_template_group->message_type(),
2333
+			'GRP_ID' => $this->_message_template_group->GRP_ID(),
2334
+		);
2335
+		// first we need to see if there are any fields
2336
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2337
+
2338
+		if (! empty($fields)) {
2339
+			// yup there be fields
2340
+			foreach ($fields as $field => $config) {
2341
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2342
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2343
+				$default = isset($config['default']) ? $config['default'] : '';
2344
+				$default = isset($config['value']) ? $config['value'] : $default;
2345
+
2346
+				// if type is hidden and the value is empty
2347
+				// something may have gone wrong so let's correct with the defaults
2348
+				$fix = $config['input'] === 'hidden'
2349
+					   && isset($existing[ $field ])
2350
+					   && empty($existing[ $field ])
2351
+					? $default
2352
+					: '';
2353
+				$existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2354
+					? $existing[ $field ]
2355
+					: $fix;
2356
+
2357
+				$template_form_fields[ $field_id ] = array(
2358
+					'name'       => 'test_settings_fld[' . $field . ']',
2359
+					'label'      => $config['label'],
2360
+					'input'      => $config['input'],
2361
+					'type'       => $config['type'],
2362
+					'required'   => $config['required'],
2363
+					'validation' => $config['validation'],
2364
+					'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2365
+					'css_class'  => $config['css_class'],
2366
+					'options'    => isset($config['options']) ? $config['options'] : array(),
2367
+					'default'    => $default,
2368
+					'format'     => $config['format'],
2369
+				);
2370
+			}
2371
+		}
2372
+
2373
+		$test_settings_fields = ! empty($template_form_fields)
2374
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2375
+			: '';
2376
+
2377
+		$test_settings_html = '';
2378
+		// print out $test_settings_fields
2379
+		if (! empty($test_settings_fields)) {
2380
+			echo $test_settings_fields;
2381
+			$test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2382
+			$test_settings_html .= 'name="test_button" value="';
2383
+			$test_settings_html .= esc_html__('Test Send', 'event_espresso');
2384
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2385
+		}
2386
+
2387
+		// and button
2388
+		$test_settings_html .= '<p>'
2389
+							   . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2390
+							   . '</p>';
2391
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2392
+		$test_settings_html .= $this->get_action_link_or_button(
2393
+			'reset_to_default',
2394
+			'reset',
2395
+			$extra_args,
2396
+			'button-primary reset-default-button'
2397
+		);
2398
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2399
+		echo $test_settings_html;
2400
+	}
2401
+
2402
+
2403
+	/**
2404
+	 * This returns the shortcode selector skeleton for a given context and field.
2405
+	 *
2406
+	 * @since 4.9.rc.000
2407
+	 * @param string $field           The name of the field retrieving shortcodes for.
2408
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2409
+	 * @return string
2410
+	 * @throws DomainException
2411
+	 * @throws EE_Error
2412
+	 * @throws InvalidArgumentException
2413
+	 * @throws ReflectionException
2414
+	 * @throws InvalidDataTypeException
2415
+	 * @throws InvalidInterfaceException
2416
+	 */
2417
+	protected function _get_shortcode_selector($field, $linked_input_id)
2418
+	{
2419
+		$template_args = array(
2420
+			'shortcodes'      => $this->_get_shortcodes(array($field), true),
2421
+			'fieldname'       => $field,
2422
+			'linked_input_id' => $linked_input_id,
2423
+		);
2424
+
2425
+		return EEH_Template::display_template(
2426
+			EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2427
+			$template_args,
2428
+			true
2429
+		);
2430
+	}
2431
+
2432
+
2433
+	/**
2434
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2435
+	 * page)
2436
+	 *
2437
+	 * @access public
2438
+	 * @return void
2439
+	 * @throws EE_Error
2440
+	 * @throws InvalidArgumentException
2441
+	 * @throws ReflectionException
2442
+	 * @throws InvalidDataTypeException
2443
+	 * @throws InvalidInterfaceException
2444
+	 */
2445
+	public function shortcode_meta_box()
2446
+	{
2447
+		$shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2448
+		// $messenger = $this->_message_template_group->messenger_obj();
2449
+		// now let's set the content depending on the status of the shortcodes array
2450
+		if (empty($shortcodes)) {
2451
+			$content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2452
+			echo $content;
2453
+		} else {
2454
+			// $alt = 0;
2455
+			?>
2456 2456
             <div style="float:right; margin-top:10px"><?php
2457
-                            echo $this->_get_help_tab_link('message_template_shortcodes');
2458
-                            ?></div>
2457
+							echo $this->_get_help_tab_link('message_template_shortcodes');
2458
+							?></div>
2459 2459
             <p class="small-text"><?php
2460
-                                  printf(
2461
-                                      esc_html__(
2462
-                                          'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2463
-                                          'event_espresso'
2464
-                                      ),
2465
-                                      '<span class="dashicons dashicons-menu"></span>'
2466
-                                  );
2467
-                                ?>
2460
+								  printf(
2461
+									  esc_html__(
2462
+										  'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2463
+										  'event_espresso'
2464
+									  ),
2465
+									  '<span class="dashicons dashicons-menu"></span>'
2466
+								  );
2467
+								?>
2468 2468
             </p>
2469 2469
             <?php
2470
-        }
2471
-    }
2472
-
2473
-
2474
-    /**
2475
-     * used to set the $_shortcodes property for when its needed elsewhere.
2476
-     *
2477
-     * @access protected
2478
-     * @return void
2479
-     * @throws EE_Error
2480
-     * @throws InvalidArgumentException
2481
-     * @throws ReflectionException
2482
-     * @throws InvalidDataTypeException
2483
-     * @throws InvalidInterfaceException
2484
-     */
2485
-    protected function _set_shortcodes()
2486
-    {
2487
-
2488
-        // no need to run this if the property is already set
2489
-        if (! empty($this->_shortcodes)) {
2490
-            return;
2491
-        }
2492
-
2493
-        $this->_shortcodes = $this->_get_shortcodes();
2494
-    }
2495
-
2496
-
2497
-    /**
2498
-     * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2499
-     * property)
2500
-     *
2501
-     * @access  protected
2502
-     * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2503
-     *                         for. Defaults to all (for the given context)
2504
-     * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2505
-     * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2506
-     *                         true just an array of shortcode/label pairs.
2507
-     * @throws EE_Error
2508
-     * @throws InvalidArgumentException
2509
-     * @throws ReflectionException
2510
-     * @throws InvalidDataTypeException
2511
-     * @throws InvalidInterfaceException
2512
-     */
2513
-    protected function _get_shortcodes($fields = array(), $merged = true)
2514
-    {
2515
-        $this->_set_message_template_group();
2516
-
2517
-        // we need the messenger and message template to retrieve the valid shortcodes array.
2518
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2519
-            ? absint($this->_req_data['id'])
2520
-            : false;
2521
-        $context = isset($this->_req_data['context'])
2522
-            ? $this->_req_data['context']
2523
-            : key($this->_message_template_group->contexts_config());
2524
-
2525
-        return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2526
-    }
2527
-
2528
-
2529
-    /**
2530
-     * This sets the _message_template property (containing the called message_template object)
2531
-     *
2532
-     * @access protected
2533
-     * @return void
2534
-     * @throws EE_Error
2535
-     * @throws InvalidArgumentException
2536
-     * @throws ReflectionException
2537
-     * @throws InvalidDataTypeException
2538
-     * @throws InvalidInterfaceException
2539
-     */
2540
-    protected function _set_message_template_group()
2541
-    {
2542
-
2543
-        if (! empty($this->_message_template_group)) {
2544
-            return;
2545
-        } //get out if this is already set.
2546
-
2547
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2548
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2549
-
2550
-        // let's get the message templates
2551
-        $MTP = EEM_Message_Template_Group::instance();
2552
-
2553
-        if (empty($GRP_ID)) {
2554
-            $this->_message_template_group = $MTP->create_default_object();
2555
-        } else {
2556
-            $this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2557
-        }
2558
-
2559
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2560
-        $this->_variation = $this->_message_template_group->get_template_pack_variation();
2561
-    }
2562
-
2563
-
2564
-    /**
2565
-     * sets up a context switcher for edit forms
2566
-     *
2567
-     * @access  protected
2568
-     * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2569
-     * @param array                      $args                  various things the context switcher needs.
2570
-     * @throws EE_Error
2571
-     */
2572
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2573
-    {
2574
-        $context_details = $template_group_object->contexts_config();
2575
-        $context_label = $template_group_object->context_label();
2576
-        ob_start();
2577
-        ?>
2470
+		}
2471
+	}
2472
+
2473
+
2474
+	/**
2475
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2476
+	 *
2477
+	 * @access protected
2478
+	 * @return void
2479
+	 * @throws EE_Error
2480
+	 * @throws InvalidArgumentException
2481
+	 * @throws ReflectionException
2482
+	 * @throws InvalidDataTypeException
2483
+	 * @throws InvalidInterfaceException
2484
+	 */
2485
+	protected function _set_shortcodes()
2486
+	{
2487
+
2488
+		// no need to run this if the property is already set
2489
+		if (! empty($this->_shortcodes)) {
2490
+			return;
2491
+		}
2492
+
2493
+		$this->_shortcodes = $this->_get_shortcodes();
2494
+	}
2495
+
2496
+
2497
+	/**
2498
+	 * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2499
+	 * property)
2500
+	 *
2501
+	 * @access  protected
2502
+	 * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2503
+	 *                         for. Defaults to all (for the given context)
2504
+	 * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2505
+	 * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2506
+	 *                         true just an array of shortcode/label pairs.
2507
+	 * @throws EE_Error
2508
+	 * @throws InvalidArgumentException
2509
+	 * @throws ReflectionException
2510
+	 * @throws InvalidDataTypeException
2511
+	 * @throws InvalidInterfaceException
2512
+	 */
2513
+	protected function _get_shortcodes($fields = array(), $merged = true)
2514
+	{
2515
+		$this->_set_message_template_group();
2516
+
2517
+		// we need the messenger and message template to retrieve the valid shortcodes array.
2518
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2519
+			? absint($this->_req_data['id'])
2520
+			: false;
2521
+		$context = isset($this->_req_data['context'])
2522
+			? $this->_req_data['context']
2523
+			: key($this->_message_template_group->contexts_config());
2524
+
2525
+		return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2526
+	}
2527
+
2528
+
2529
+	/**
2530
+	 * This sets the _message_template property (containing the called message_template object)
2531
+	 *
2532
+	 * @access protected
2533
+	 * @return void
2534
+	 * @throws EE_Error
2535
+	 * @throws InvalidArgumentException
2536
+	 * @throws ReflectionException
2537
+	 * @throws InvalidDataTypeException
2538
+	 * @throws InvalidInterfaceException
2539
+	 */
2540
+	protected function _set_message_template_group()
2541
+	{
2542
+
2543
+		if (! empty($this->_message_template_group)) {
2544
+			return;
2545
+		} //get out if this is already set.
2546
+
2547
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2548
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2549
+
2550
+		// let's get the message templates
2551
+		$MTP = EEM_Message_Template_Group::instance();
2552
+
2553
+		if (empty($GRP_ID)) {
2554
+			$this->_message_template_group = $MTP->create_default_object();
2555
+		} else {
2556
+			$this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2557
+		}
2558
+
2559
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2560
+		$this->_variation = $this->_message_template_group->get_template_pack_variation();
2561
+	}
2562
+
2563
+
2564
+	/**
2565
+	 * sets up a context switcher for edit forms
2566
+	 *
2567
+	 * @access  protected
2568
+	 * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2569
+	 * @param array                      $args                  various things the context switcher needs.
2570
+	 * @throws EE_Error
2571
+	 */
2572
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2573
+	{
2574
+		$context_details = $template_group_object->contexts_config();
2575
+		$context_label = $template_group_object->context_label();
2576
+		ob_start();
2577
+		?>
2578 2578
         <div class="ee-msg-switcher-container">
2579 2579
             <form method="get" action="<?php echo EE_MSG_ADMIN_URL; ?>" id="ee-msg-context-switcher-frm">
2580 2580
                 <?php
2581
-                foreach ($args as $name => $value) {
2582
-                    if ($name === 'context' || empty($value) || $name === 'extra') {
2583
-                        continue;
2584
-                    }
2585
-                    ?>
2581
+				foreach ($args as $name => $value) {
2582
+					if ($name === 'context' || empty($value) || $name === 'extra') {
2583
+						continue;
2584
+					}
2585
+					?>
2586 2586
                     <input type="hidden" name="<?php echo $name; ?>" value="<?php echo $value; ?>"/>
2587 2587
                     <?php
2588
-                }
2589
-                // setup nonce_url
2590
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2591
-                ?>
2588
+				}
2589
+				// setup nonce_url
2590
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2591
+				?>
2592 2592
                 <select name="context">
2593 2593
                     <?php
2594
-                    $context_templates = $template_group_object->context_templates();
2595
-                    if (is_array($context_templates)) :
2596
-                        foreach ($context_templates as $context => $template_fields) :
2597
-                            $checked = ($context === $args['context']) ? 'selected="selected"' : '';
2598
-                            ?>
2594
+					$context_templates = $template_group_object->context_templates();
2595
+					if (is_array($context_templates)) :
2596
+						foreach ($context_templates as $context => $template_fields) :
2597
+							$checked = ($context === $args['context']) ? 'selected="selected"' : '';
2598
+							?>
2599 2599
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2600 2600
                                 <?php echo $context_details[ $context ]['label']; ?>
2601 2601
                             </option>
2602 2602
                         <?php endforeach;
2603
-                    endif; ?>
2603
+					endif; ?>
2604 2604
                 </select>
2605 2605
                 <?php $button_text = sprintf(__('Switch %s', 'event_espresso'), ucwords($context_label['label'])); ?>
2606 2606
                 <input id="submit-msg-context-switcher-sbmt" class="button-secondary" type="submit"
@@ -2609,1921 +2609,1921 @@  discard block
 block discarded – undo
2609 2609
             <?php echo $args['extra']; ?>
2610 2610
         </div> <!-- end .ee-msg-switcher-container -->
2611 2611
         <?php
2612
-        $output = ob_get_contents();
2613
-        ob_clean();
2614
-        $this->_context_switcher = $output;
2615
-    }
2616
-
2617
-
2618
-    /**
2619
-     * utility for sanitizing new values coming in.
2620
-     * Note: this is only used when updating a context.
2621
-     *
2622
-     * @access protected
2623
-     *
2624
-     * @param int $index This helps us know which template field to select from the request array.
2625
-     *
2626
-     * @return array
2627
-     */
2628
-    protected function _set_message_template_column_values($index)
2629
-    {
2630
-        if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2631
-            foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2632
-                $this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2633
-            }
2634
-        }
2635
-
2636
-
2637
-        $set_column_values = array(
2638
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2639
-            'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2640
-            'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2641
-            'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2642
-            'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2643
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2644
-            'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2645
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2646
-            'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2647
-                ? absint($this->_req_data['MTP_is_global'])
2648
-                : 0,
2649
-            'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2650
-                ? absint($this->_req_data['MTP_is_override'])
2651
-                : 0,
2652
-            'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2653
-            'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2654
-        );
2655
-
2656
-
2657
-        return $set_column_values;
2658
-    }
2659
-
2660
-
2661
-    protected function _insert_or_update_message_template($new = false)
2662
-    {
2663
-
2664
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2665
-        $success = 0;
2666
-        $override = false;
2667
-
2668
-        // setup notices description
2669
-        $messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2670
-
2671
-        // need the message type and messenger objects to be able to use the labels for the notices
2672
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2673
-        $messenger_label = $messenger_object instanceof EE_messenger
2674
-            ? ucwords($messenger_object->label['singular'])
2675
-            : '';
2676
-
2677
-        $message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2678
-            ? $this->_req_data['MTP_message_type']
2679
-            : '';
2680
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2681
-
2682
-        $message_type_label = $message_type_object instanceof EE_message_type
2683
-            ? ucwords($message_type_object->label['singular'])
2684
-            : '';
2685
-
2686
-        $context_slug = ! empty($this->_req_data['MTP_context'])
2687
-            ? $this->_req_data['MTP_context']
2688
-            : '';
2689
-        $context = ucwords(str_replace('_', ' ', $context_slug));
2690
-
2691
-        $item_desc = $messenger_label && $message_type_label
2692
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2693
-            : '';
2694
-        $item_desc .= 'Message Template';
2695
-        $query_args = array();
2696
-        $edit_array = array();
2697
-        $action_desc = '';
2698
-
2699
-        // if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2700
-        // user to edit.
2701
-        if ($new) {
2702
-            $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2703
-            if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2704
-                if (empty($edit_array)) {
2705
-                    $success = 0;
2706
-                } else {
2707
-                    $success = 1;
2708
-                    $edit_array = $edit_array[0];
2709
-                    $query_args = array(
2710
-                        'id'      => $edit_array['GRP_ID'],
2711
-                        'context' => $edit_array['MTP_context'],
2712
-                        'action'  => 'edit_message_template',
2713
-                    );
2714
-                }
2715
-            }
2716
-            $action_desc = 'created';
2717
-        } else {
2718
-            $MTPG = EEM_Message_Template_Group::instance();
2719
-            $MTP = EEM_Message_Template::instance();
2720
-
2721
-
2722
-            // run update for each template field in displayed context
2723
-            if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2724
-                EE_Error::add_error(
2725
-                    esc_html__(
2726
-                        'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2727
-                        'event_espresso'
2728
-                    ),
2729
-                    __FILE__,
2730
-                    __FUNCTION__,
2731
-                    __LINE__
2732
-                );
2733
-                $success = 0;
2734
-            } else {
2735
-                // first validate all fields!
2736
-                // this filter allows client code to add its own validation to the template fields as well.
2737
-                // returning an empty array means everything passed validation.
2738
-                // errors in validation should be represented in an array with the following shape:
2739
-                // array(
2740
-                //   'fieldname' => array(
2741
-                //          'msg' => 'error message'
2742
-                //          'value' => 'value for field producing error'
2743
-                // )
2744
-                $custom_validation = (array) apply_filters(
2745
-                    'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2746
-                    array(),
2747
-                    $this->_req_data['MTP_template_fields'],
2748
-                    $context_slug,
2749
-                    $messenger_slug,
2750
-                    $message_type_slug
2751
-                );
2752
-
2753
-                $system_validation = $MTPG->validate(
2754
-                    $this->_req_data['MTP_template_fields'],
2755
-                    $context_slug,
2756
-                    $messenger_slug,
2757
-                    $message_type_slug
2758
-                );
2759
-
2760
-                $system_validation = ! is_array($system_validation) && $system_validation ? array()
2761
-                    : $system_validation;
2762
-                $validates = array_merge($custom_validation, $system_validation);
2763
-
2764
-                // if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2765
-                // appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2766
-                //  WE need to make sure there is no actual error messages in validates.
2767
-                if (is_array($validates) && ! empty($validates)) {
2768
-                    // add the transient so when the form loads we know which fields to highlight
2769
-                    $this->_add_transient('edit_message_template', $validates);
2770
-
2771
-                    $success = 0;
2772
-
2773
-                    // setup notices
2774
-                    foreach ($validates as $field => $error) {
2775
-                        if (isset($error['msg'])) {
2776
-                            EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2777
-                        }
2778
-                    }
2779
-                } else {
2780
-                    $set_column_values = array();
2781
-                    foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2782
-                        $set_column_values = $this->_set_message_template_column_values($template_field);
2783
-
2784
-                        $where_cols_n_values = array(
2785
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2786
-                        );
2787
-                        // if they aren't allowed to use all JS, restrict them to just posty-y tags
2788
-                        if (! current_user_can('unfiltered_html')) {
2789
-                            if (is_array($set_column_values['MTP_content'])) {
2790
-                                foreach ($set_column_values['MTP_content'] as $key => $value) {
2791
-                                    // remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2792
-                                    // only removes slashes from double-quotes, so attributes using single quotes always
2793
-                                    // appear invalid.) But currently the models expect slashed data, so after wp_kses
2794
-                                    // runs we need to re-slash the data. Sheesh. See
2795
-                                    // https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2796
-                                    $set_column_values['MTP_content'][ $key ] = addslashes(
2797
-                                        wp_kses(
2798
-                                            stripslashes($value),
2799
-                                            wp_kses_allowed_html('post')
2800
-                                        )
2801
-                                    );
2802
-                                }
2803
-                            } else {
2804
-                                $set_column_values['MTP_content'] = wp_kses(
2805
-                                    $set_column_values['MTP_content'],
2806
-                                    wp_kses_allowed_html('post')
2807
-                                );
2808
-                            }
2809
-                        }
2810
-                        $message_template_fields = array(
2811
-                            'GRP_ID'             => $set_column_values['GRP_ID'],
2812
-                            'MTP_template_field' => $set_column_values['MTP_template_field'],
2813
-                            'MTP_context'        => $set_column_values['MTP_context'],
2814
-                            'MTP_content'        => $set_column_values['MTP_content'],
2815
-                        );
2816
-                        if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2817
-                            if ($updated === false) {
2818
-                                EE_Error::add_error(
2819
-                                    sprintf(
2820
-                                        esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2821
-                                        $template_field
2822
-                                    ),
2823
-                                    __FILE__,
2824
-                                    __FUNCTION__,
2825
-                                    __LINE__
2826
-                                );
2827
-                            } else {
2828
-                                $success = 1;
2829
-                            }
2830
-                        } else {
2831
-                            // only do this logic if we don't have a MTP_ID for this field
2832
-                            if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2833
-                                // this has already been through the template field validator and sanitized, so it will be
2834
-                                // safe to insert this field.  Why insert?  This typically happens when we introduce a new
2835
-                                // message template field in a messenger/message type and existing users don't have the
2836
-                                // default setup for it.
2837
-                                // @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2838
-                                $updated = $MTP->insert($message_template_fields);
2839
-                                if (! $updated || is_wp_error($updated)) {
2840
-                                    EE_Error::add_error(
2841
-                                        sprintf(
2842
-                                            esc_html__('%s field could not be updated.', 'event_espresso'),
2843
-                                            $template_field
2844
-                                        ),
2845
-                                        __FILE__,
2846
-                                        __FUNCTION__,
2847
-                                        __LINE__
2848
-                                    );
2849
-                                    $success = 0;
2850
-                                } else {
2851
-                                    $success = 1;
2852
-                                }
2853
-                            }
2854
-                        }
2855
-                        $action_desc = 'updated';
2856
-                    }
2857
-
2858
-                    // we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2859
-                    $mtpg_fields = array(
2860
-                        'MTP_user_id'      => $set_column_values['MTP_user_id'],
2861
-                        'MTP_messenger'    => $set_column_values['MTP_messenger'],
2862
-                        'MTP_message_type' => $set_column_values['MTP_message_type'],
2863
-                        'MTP_is_global'    => $set_column_values['MTP_is_global'],
2864
-                        'MTP_is_override'  => $set_column_values['MTP_is_override'],
2865
-                        'MTP_deleted'      => $set_column_values['MTP_deleted'],
2866
-                        'MTP_is_active'    => $set_column_values['MTP_is_active'],
2867
-                        'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2868
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2869
-                            : '',
2870
-                        'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2871
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2872
-                            : '',
2873
-                    );
2874
-
2875
-                    $mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2876
-                    $updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2877
-
2878
-                    if ($updated === false) {
2879
-                        EE_Error::add_error(
2880
-                            sprintf(
2881
-                                esc_html__(
2882
-                                    'The Message Template Group (%d) was NOT updated for some reason',
2883
-                                    'event_espresso'
2884
-                                ),
2885
-                                $set_column_values['GRP_ID']
2886
-                            ),
2887
-                            __FILE__,
2888
-                            __FUNCTION__,
2889
-                            __LINE__
2890
-                        );
2891
-                    } else {
2892
-                        // k now we need to ensure the template_pack and template_variation fields are set.
2893
-                        $template_pack = ! empty($this->_req_data['MTP_template_pack'])
2894
-                            ? $this->_req_data['MTP_template_pack']
2895
-                            : 'default';
2896
-
2897
-                        $template_variation = ! empty($this->_req_data['MTP_template_variation'])
2898
-                            ? $this->_req_data['MTP_template_variation']
2899
-                            : 'default';
2900
-
2901
-                        $mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2902
-                        if ($mtpg_obj instanceof EE_Message_Template_Group) {
2903
-                            $mtpg_obj->set_template_pack_name($template_pack);
2904
-                            $mtpg_obj->set_template_pack_variation($template_variation);
2905
-                        }
2906
-                        $success = 1;
2907
-                    }
2908
-                }
2909
-            }
2910
-        }
2911
-
2912
-        // we return things differently if doing ajax
2913
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2914
-            $this->_template_args['success'] = $success;
2915
-            $this->_template_args['error'] = ! $success ? true : false;
2916
-            $this->_template_args['content'] = '';
2917
-            $this->_template_args['data'] = array(
2918
-                'grpID'        => $edit_array['GRP_ID'],
2919
-                'templateName' => $edit_array['template_name'],
2920
-            );
2921
-            if ($success) {
2922
-                EE_Error::overwrite_success();
2923
-                EE_Error::add_success(
2924
-                    esc_html__(
2925
-                        '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.',
2926
-                        'event_espresso'
2927
-                    )
2928
-                );
2929
-            }
2930
-
2931
-            $this->_return_json();
2932
-        }
2933
-
2934
-
2935
-        // was a test send triggered?
2936
-        if (isset($this->_req_data['test_button'])) {
2937
-            EE_Error::overwrite_success();
2938
-            $this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2939
-            $override = true;
2940
-        }
2941
-
2942
-        if (empty($query_args)) {
2943
-            $query_args = array(
2944
-                'id'      => $this->_req_data['GRP_ID'],
2945
-                'context' => $context_slug,
2946
-                'action'  => 'edit_message_template',
2947
-            );
2948
-        }
2949
-
2950
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2951
-    }
2952
-
2953
-
2954
-    /**
2955
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
2956
-     *
2957
-     * @param  string $context      what context being tested
2958
-     * @param  string $messenger    messenger being tested
2959
-     * @param  string $message_type message type being tested
2960
-     * @throws EE_Error
2961
-     * @throws InvalidArgumentException
2962
-     * @throws InvalidDataTypeException
2963
-     * @throws InvalidInterfaceException
2964
-     */
2965
-    protected function _do_test_send($context, $messenger, $message_type)
2966
-    {
2967
-        // set things up for preview
2968
-        $this->_req_data['messenger'] = $messenger;
2969
-        $this->_req_data['message_type'] = $message_type;
2970
-        $this->_req_data['context'] = $context;
2971
-        $this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2972
-        $active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
2973
-
2974
-        // let's save any existing fields that might be required by the messenger
2975
-        if (isset($this->_req_data['test_settings_fld'])
2976
-            && $active_messenger instanceof EE_messenger
2977
-            && apply_filters(
2978
-                'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
2979
-                true,
2980
-                $this->_req_data['test_settings_fld'],
2981
-                $active_messenger
2982
-            )
2983
-        ) {
2984
-            $active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2985
-        }
2986
-
2987
-        /**
2988
-         * Use filter to add additional controls on whether message can send or not
2989
-         */
2990
-        if (apply_filters(
2991
-            'FHEE__Messages_Admin_Page__do_test_send__can_send',
2992
-            true,
2993
-            $context,
2994
-            $this->_req_data,
2995
-            $messenger,
2996
-            $message_type
2997
-        )) {
2998
-            $success = $this->_preview_message(true);
2999
-            if ($success) {
3000
-                EE_Error::add_success(__('Test message sent', 'event_espresso'));
3001
-            } else {
3002
-                EE_Error::add_error(
3003
-                    esc_html__('The test message was not sent', 'event_espresso'),
3004
-                    __FILE__,
3005
-                    __FUNCTION__,
3006
-                    __LINE__
3007
-                );
3008
-            }
3009
-        }
3010
-    }
3011
-
3012
-
3013
-    /**
3014
-     * _generate_new_templates
3015
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3016
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3017
-     * for the event.
3018
-     *
3019
-     *
3020
-     * @param  string $messenger     the messenger we are generating templates for
3021
-     * @param array   $message_types array of message types that the templates are generated for.
3022
-     * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3023
-     *                               indicate the message_template_group being used as the base.
3024
-     *
3025
-     * @param bool    $global
3026
-     *
3027
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
3028
-     *                               encountering problems.
3029
-     * @throws EE_Error
3030
-     */
3031
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3032
-    {
3033
-
3034
-        // if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3035
-        // just don't generate any templates.
3036
-        if (empty($message_types)) {
3037
-            return true;
3038
-        }
3039
-
3040
-        return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3041
-    }
3042
-
3043
-
3044
-    /**
3045
-     * [_trash_or_restore_message_template]
3046
-     *
3047
-     * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3048
-     * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3049
-     *                        an individual context (FALSE).
3050
-     * @return void
3051
-     * @throws EE_Error
3052
-     * @throws InvalidArgumentException
3053
-     * @throws InvalidDataTypeException
3054
-     * @throws InvalidInterfaceException
3055
-     */
3056
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
3057
-    {
3058
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3059
-        $MTP = EEM_Message_Template_Group::instance();
3060
-
3061
-        $success = 1;
3062
-
3063
-        // incoming GRP_IDs
3064
-        if ($all) {
3065
-            // Checkboxes
3066
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3067
-                // if array has more than one element then success message should be plural.
3068
-                // todo: what about nonce?
3069
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3070
-
3071
-                // cycle through checkboxes
3072
-                while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3073
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3074
-                    if (! $trashed_or_restored) {
3075
-                        $success = 0;
3076
-                    }
3077
-                }
3078
-            } else {
3079
-                // grab single GRP_ID and handle
3080
-                $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3081
-                if (! empty($GRP_ID)) {
3082
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3083
-                    if (! $trashed_or_restored) {
3084
-                        $success = 0;
3085
-                    }
3086
-                } else {
3087
-                    $success = 0;
3088
-                }
3089
-            }
3090
-        }
3091
-
3092
-        $action_desc = $trash
3093
-            ? esc_html__('moved to the trash', 'event_espresso')
3094
-            : esc_html__('restored', 'event_espresso');
3095
-
3096
-        $action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3097
-
3098
-        $item_desc = $all ? _n(
3099
-            'Message Template Group',
3100
-            'Message Template Groups',
3101
-            $success,
3102
-            'event_espresso'
3103
-        ) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3104
-
3105
-        $item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3106
-            'template',
3107
-            'templates',
3108
-            $success,
3109
-            'event_espresso'
3110
-        ) : $item_desc;
3111
-
3112
-        $this->_redirect_after_action($success, $item_desc, $action_desc, array());
3113
-    }
3114
-
3115
-
3116
-    /**
3117
-     * [_delete_message_template]
3118
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3119
-     *
3120
-     * @return void
3121
-     * @throws EE_Error
3122
-     * @throws InvalidArgumentException
3123
-     * @throws InvalidDataTypeException
3124
-     * @throws InvalidInterfaceException
3125
-     */
3126
-    protected function _delete_message_template()
3127
-    {
3128
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3129
-
3130
-        // checkboxes
3131
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3132
-            // if array has more than one element then success message should be plural
3133
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3134
-
3135
-            // cycle through bulk action checkboxes
3136
-            while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3137
-                $success = $this->_delete_mtp_permanently($GRP_ID);
3138
-            }
3139
-        } else {
3140
-            // grab single grp_id and delete
3141
-            $GRP_ID = absint($this->_req_data['id']);
3142
-            $success = $this->_delete_mtp_permanently($GRP_ID);
3143
-        }
3144
-
3145
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3146
-    }
3147
-
3148
-
3149
-    /**
3150
-     * helper for permanently deleting a mtP group and all related message_templates
3151
-     *
3152
-     * @param  int  $GRP_ID        The group being deleted
3153
-     * @param  bool $include_group whether to delete the Message Template Group as well.
3154
-     * @return bool boolean to indicate the success of the deletes or not.
3155
-     * @throws EE_Error
3156
-     * @throws InvalidArgumentException
3157
-     * @throws InvalidDataTypeException
3158
-     * @throws InvalidInterfaceException
3159
-     */
3160
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3161
-    {
3162
-        $success = 1;
3163
-        $MTPG = EEM_Message_Template_Group::instance();
3164
-        // first let's GET this group
3165
-        $MTG = $MTPG->get_one_by_ID($GRP_ID);
3166
-        // then delete permanently all the related Message Templates
3167
-        $deleted = $MTG->delete_related_permanently('Message_Template');
3168
-
3169
-        if ($deleted === 0) {
3170
-            $success = 0;
3171
-        }
3172
-
3173
-        // now delete permanently this particular group
3174
-
3175
-        if ($include_group && ! $MTG->delete_permanently()) {
3176
-            $success = 0;
3177
-        }
3178
-
3179
-        return $success;
3180
-    }
3181
-
3182
-
3183
-    /**
3184
-     *    _learn_more_about_message_templates_link
3185
-     *
3186
-     * @access protected
3187
-     * @return string
3188
-     */
3189
-    protected function _learn_more_about_message_templates_link()
3190
-    {
3191
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3192
-               . esc_html__('learn more about how message templates works', 'event_espresso')
3193
-               . '</a>';
3194
-    }
3195
-
3196
-
3197
-    /**
3198
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3199
-     * ajax and other routes.
3200
-     *
3201
-     * @return void
3202
-     * @throws DomainException
3203
-     */
3204
-    protected function _settings()
3205
-    {
3206
-
3207
-
3208
-        $this->_set_m_mt_settings();
3209
-
3210
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3211
-            ? $this->_req_data['selected_messenger']
3212
-            : 'email';
3213
-
3214
-        // let's setup the messenger tabs
3215
-        $this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3216
-            $this->_m_mt_settings['messenger_tabs'],
3217
-            'messenger_links',
3218
-            '|',
3219
-            $selected_messenger
3220
-        );
3221
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3222
-        $this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3223
-
3224
-        $this->display_admin_page_with_sidebar();
3225
-    }
3226
-
3227
-
3228
-    /**
3229
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3230
-     *
3231
-     * @access protected
3232
-     * @return void
3233
-     * @throws DomainException
3234
-     */
3235
-    protected function _set_m_mt_settings()
3236
-    {
3237
-        // first if this is already set then lets get out no need to regenerate data.
3238
-        if (! empty($this->_m_mt_settings)) {
3239
-            return;
3240
-        }
3241
-
3242
-        // get all installed messengers and message_types
3243
-        /** @type EE_messenger[] $messengers */
3244
-        $messengers = $this->_message_resource_manager->installed_messengers();
3245
-        /** @type EE_message_type[] $message_types */
3246
-        $message_types = $this->_message_resource_manager->installed_message_types();
3247
-
3248
-
3249
-        // assemble the array for the _tab_text_links helper
3250
-
3251
-        foreach ($messengers as $messenger) {
3252
-            $this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3253
-                'label' => ucwords($messenger->label['singular']),
3254
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3255
-                    ? 'messenger-active'
3256
-                    : '',
3257
-                'href'  => $messenger->name,
3258
-                'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3259
-                'slug'  => $messenger->name,
3260
-                'obj'   => $messenger,
3261
-            );
3262
-
3263
-
3264
-            $message_types_for_messenger = $messenger->get_valid_message_types();
3265
-
3266
-            foreach ($message_types as $message_type) {
3267
-                // first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3268
-                // it shouldn't show in either the inactive OR active metabox.
3269
-                if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3270
-                    continue;
3271
-                }
3272
-
3273
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3274
-                    $messenger->name,
3275
-                    $message_type->name
3276
-                )
3277
-                    ? 'active'
3278
-                    : 'inactive';
3279
-
3280
-                $this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3281
-                    'label'    => ucwords($message_type->label['singular']),
3282
-                    'class'    => 'message-type-' . $a_or_i,
3283
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3284
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3285
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3286
-                    'title'    => $a_or_i === 'active'
3287
-                        ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3288
-                        : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3289
-                    'content'  => $a_or_i === 'active'
3290
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
3291
-                        : $this->_message_type_settings_content($message_type, $messenger),
3292
-                    'slug'     => $message_type->name,
3293
-                    'active'   => $a_or_i === 'active',
3294
-                    'obj'      => $message_type,
3295
-                );
3296
-            }
3297
-        }
3298
-    }
3299
-
3300
-
3301
-    /**
3302
-     * This just prepares the content for the message type settings
3303
-     *
3304
-     * @param  EE_message_type $message_type The message type object
3305
-     * @param  EE_messenger    $messenger    The messenger object
3306
-     * @param  boolean         $active       Whether the message type is active or not
3307
-     * @return string html output for the content
3308
-     * @throws DomainException
3309
-     */
3310
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
3311
-    {
3312
-        // get message type fields
3313
-        $fields = $message_type->get_admin_settings_fields();
3314
-        $settings_template_args['template_form_fields'] = '';
3315
-
3316
-        if (! empty($fields) && $active) {
3317
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3318
-            foreach ($fields as $fldname => $fldprops) {
3319
-                $field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3320
-                $template_form_field[ $field_id ] = array(
3321
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3322
-                    'label'      => $fldprops['label'],
3323
-                    'input'      => $fldprops['field_type'],
3324
-                    'type'       => $fldprops['value_type'],
3325
-                    'required'   => $fldprops['required'],
3326
-                    'validation' => $fldprops['validation'],
3327
-                    'value'      => isset($existing_settings[ $fldname ])
3328
-                        ? $existing_settings[ $fldname ]
3329
-                        : $fldprops['default'],
3330
-                    'options'    => isset($fldprops['options'])
3331
-                        ? $fldprops['options']
3332
-                        : array(),
3333
-                    'default'    => isset($existing_settings[ $fldname ])
3334
-                        ? $existing_settings[ $fldname ]
3335
-                        : $fldprops['default'],
3336
-                    'css_class'  => 'no-drag',
3337
-                    'format'     => $fldprops['format'],
3338
-                );
3339
-            }
3340
-
3341
-
3342
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3343
-                ? $this->_generate_admin_form_fields(
3344
-                    $template_form_field,
3345
-                    'string',
3346
-                    'ee_mt_activate_form'
3347
-                )
3348
-                : '';
3349
-        }
3350
-
3351
-        $settings_template_args['description'] = $message_type->description;
3352
-        // we also need some hidden fields
3353
-        $settings_template_args['hidden_fields'] = array(
3354
-            'message_type_settings[messenger]'    => array(
3355
-                'type'  => 'hidden',
3356
-                'value' => $messenger->name,
3357
-            ),
3358
-            'message_type_settings[message_type]' => array(
3359
-                'type'  => 'hidden',
3360
-                'value' => $message_type->name,
3361
-            ),
3362
-            'type'                                => array(
3363
-                'type'  => 'hidden',
3364
-                'value' => 'message_type',
3365
-            ),
3366
-        );
3367
-
3368
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3369
-            $settings_template_args['hidden_fields'],
3370
-            'array'
3371
-        );
3372
-        $settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3373
-            ? ' hidden'
3374
-            : '';
3375
-
3376
-
3377
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3378
-        $content = EEH_Template::display_template($template, $settings_template_args, true);
3379
-
3380
-        return $content;
3381
-    }
3382
-
3383
-
3384
-    /**
3385
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
3386
-     *
3387
-     * @access protected
3388
-     * @return void
3389
-     * @throws DomainException
3390
-     */
3391
-    protected function _messages_settings_metaboxes()
3392
-    {
3393
-        $this->_set_m_mt_settings();
3394
-        $m_boxes = $mt_boxes = array();
3395
-        $m_template_args = $mt_template_args = array();
3396
-
3397
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3398
-            ? $this->_req_data['selected_messenger']
3399
-            : 'email';
3400
-
3401
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
3402
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3403
-                $hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3404
-                $hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3405
-                // messenger meta boxes
3406
-                $active = $selected_messenger === $messenger;
3407
-                $active_mt_tabs = isset(
3408
-                    $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3409
-                )
3410
-                    ? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3411
-                    : '';
3412
-                $m_boxes[ $messenger . '_a_box' ] = sprintf(
3413
-                    esc_html__('%s Settings', 'event_espresso'),
3414
-                    $tab_array['label']
3415
-                );
3416
-                $m_template_args[ $messenger . '_a_box' ] = array(
3417
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3418
-                    'inactive_message_types' => isset(
3419
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3420
-                    )
3421
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3422
-                        : '',
3423
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3424
-                    'hidden'                 => $active ? '' : ' hidden',
3425
-                    'hide_on_message'        => $hide_on_message,
3426
-                    'messenger'              => $messenger,
3427
-                    'active'                 => $active,
3428
-                );
3429
-                // message type meta boxes
3430
-                // (which is really just the inactive container for each messenger
3431
-                // showing inactive message types for that messenger)
3432
-                $mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3433
-                $mt_template_args[ $messenger . '_i_box' ] = array(
3434
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3435
-                    'inactive_message_types' => isset(
3436
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3437
-                    )
3438
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3439
-                        : '',
3440
-                    'hidden'                 => $active ? '' : ' hidden',
3441
-                    'hide_on_message'        => $hide_on_message,
3442
-                    'hide_off_message'       => $hide_off_message,
3443
-                    'messenger'              => $messenger,
3444
-                    'active'                 => $active,
3445
-                );
3446
-            }
3447
-        }
3448
-
3449
-
3450
-        // register messenger metaboxes
3451
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3452
-        foreach ($m_boxes as $box => $label) {
3453
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3454
-            $msgr = str_replace('_a_box', '', $box);
3455
-            add_meta_box(
3456
-                'espresso_' . $msgr . '_settings',
3457
-                $label,
3458
-                function ($post, $metabox) {
3459
-                    echo EEH_Template::display_template(
3460
-                        $metabox["args"]["template_path"],
3461
-                        $metabox["args"]["template_args"],
3462
-                        true
3463
-                    );
3464
-                },
3465
-                $this->_current_screen->id,
3466
-                'normal',
3467
-                'high',
3468
-                $callback_args
3469
-            );
3470
-        }
3471
-
3472
-        // register message type metaboxes
3473
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3474
-        foreach ($mt_boxes as $box => $label) {
3475
-            $callback_args = array(
3476
-                'template_path' => $mt_template_path,
3477
-                'template_args' => $mt_template_args[ $box ],
3478
-            );
3479
-            $mt = str_replace('_i_box', '', $box);
3480
-            add_meta_box(
3481
-                'espresso_' . $mt . '_inactive_mts',
3482
-                $label,
3483
-                function ($post, $metabox) {
3484
-                    echo EEH_Template::display_template(
3485
-                        $metabox["args"]["template_path"],
3486
-                        $metabox["args"]["template_args"],
3487
-                        true
3488
-                    );
3489
-                },
3490
-                $this->_current_screen->id,
3491
-                'side',
3492
-                'high',
3493
-                $callback_args
3494
-            );
3495
-        }
3496
-
3497
-        // register metabox for global messages settings but only when on the main site.  On single site installs this
3498
-        // will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3499
-        if (is_main_site()) {
3500
-            add_meta_box(
3501
-                'espresso_global_message_settings',
3502
-                esc_html__('Global Message Settings', 'event_espresso'),
3503
-                array($this, 'global_messages_settings_metabox_content'),
3504
-                $this->_current_screen->id,
3505
-                'normal',
3506
-                'low',
3507
-                array()
3508
-            );
3509
-        }
3510
-    }
3511
-
3512
-
3513
-    /**
3514
-     *  This generates the content for the global messages settings metabox.
3515
-     *
3516
-     * @return string
3517
-     * @throws EE_Error
3518
-     * @throws InvalidArgumentException
3519
-     * @throws ReflectionException
3520
-     * @throws InvalidDataTypeException
3521
-     * @throws InvalidInterfaceException
3522
-     */
3523
-    public function global_messages_settings_metabox_content()
3524
-    {
3525
-        $form = $this->_generate_global_settings_form();
3526
-        echo $form->form_open(
3527
-            $this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3528
-            'POST'
3529
-        )
3530
-             . $form->get_html()
3531
-             . $form->form_close();
3532
-    }
3533
-
3534
-
3535
-    /**
3536
-     * This generates and returns the form object for the global messages settings.
3537
-     *
3538
-     * @return EE_Form_Section_Proper
3539
-     * @throws EE_Error
3540
-     * @throws InvalidArgumentException
3541
-     * @throws ReflectionException
3542
-     * @throws InvalidDataTypeException
3543
-     * @throws InvalidInterfaceException
3544
-     */
3545
-    protected function _generate_global_settings_form()
3546
-    {
3547
-        EE_Registry::instance()->load_helper('HTML');
3548
-        /** @var EE_Network_Core_Config $network_config */
3549
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3550
-
3551
-        return new EE_Form_Section_Proper(
3552
-            array(
3553
-                'name'            => 'global_messages_settings',
3554
-                'html_id'         => 'global_messages_settings',
3555
-                'html_class'      => 'form-table',
3556
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3557
-                'subsections'     => apply_filters(
3558
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3559
-                    array(
3560
-                        'do_messages_on_same_request' => new EE_Select_Input(
3561
-                            array(
3562
-                                true  => esc_html__("On the same request", "event_espresso"),
3563
-                                false => esc_html__("On a separate request", "event_espresso"),
3564
-                            ),
3565
-                            array(
3566
-                                'default'         => $network_config->do_messages_on_same_request,
3567
-                                'html_label_text' => esc_html__(
3568
-                                    'Generate and send all messages:',
3569
-                                    'event_espresso'
3570
-                                ),
3571
-                                'html_help_text'  => esc_html__(
3572
-                                    '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.',
3573
-                                    'event_espresso'
3574
-                                ),
3575
-                            )
3576
-                        ),
3577
-                        'delete_threshold'            => new EE_Select_Input(
3578
-                            array(
3579
-                                0  => esc_html__('Forever', 'event_espresso'),
3580
-                                3  => esc_html__('3 Months', 'event_espresso'),
3581
-                                6  => esc_html__('6 Months', 'event_espresso'),
3582
-                                9  => esc_html__('9 Months', 'event_espresso'),
3583
-                                12 => esc_html__('12 Months', 'event_espresso'),
3584
-                                24 => esc_html__('24 Months', 'event_espresso'),
3585
-                                36 => esc_html__('36 Months', 'event_espresso'),
3586
-                            ),
3587
-                            array(
3588
-                                'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3589
-                                'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3590
-                                'html_help_text'  => esc_html__(
3591
-                                    'You can control how long a record of processed messages is kept via this option.',
3592
-                                    'event_espresso'
3593
-                                ),
3594
-                            )
3595
-                        ),
3596
-                        'update_settings'             => new EE_Submit_Input(
3597
-                            array(
3598
-                                'default'         => esc_html__('Update', 'event_espresso'),
3599
-                                'html_label_text' => '&nbsp',
3600
-                            )
3601
-                        ),
3602
-                    )
3603
-                ),
3604
-            )
3605
-        );
3606
-    }
3607
-
3608
-
3609
-    /**
3610
-     * This handles updating the global settings set on the admin page.
3611
-     *
3612
-     * @throws EE_Error
3613
-     * @throws InvalidDataTypeException
3614
-     * @throws InvalidInterfaceException
3615
-     * @throws InvalidArgumentException
3616
-     * @throws ReflectionException
3617
-     */
3618
-    protected function _update_global_settings()
3619
-    {
3620
-        /** @var EE_Network_Core_Config $network_config */
3621
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3622
-        $messages_config = EE_Registry::instance()->CFG->messages;
3623
-        $form = $this->_generate_global_settings_form();
3624
-        if ($form->was_submitted()) {
3625
-            $form->receive_form_submission();
3626
-            if ($form->is_valid()) {
3627
-                $valid_data = $form->valid_data();
3628
-                foreach ($valid_data as $property => $value) {
3629
-                    $setter = 'set_' . $property;
3630
-                    if (method_exists($network_config, $setter)) {
3631
-                        $network_config->{$setter}($value);
3632
-                    } elseif (property_exists($network_config, $property)
3633
-                        && $network_config->{$property} !== $value
3634
-                    ) {
3635
-                        $network_config->{$property} = $value;
3636
-                    } elseif (property_exists($messages_config, $property)
3637
-                        && $messages_config->{$property} !== $value
3638
-                    ) {
3639
-                        $messages_config->{$property} = $value;
3640
-                    }
3641
-                }
3642
-                // only update if the form submission was valid!
3643
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3644
-                EE_Registry::instance()->CFG->update_espresso_config();
3645
-                EE_Error::overwrite_success();
3646
-                EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3647
-            }
3648
-        }
3649
-        $this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3650
-    }
3651
-
3652
-
3653
-    /**
3654
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3655
-     *
3656
-     * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3657
-     * @return string html formatted tabs
3658
-     * @throws DomainException
3659
-     */
3660
-    protected function _get_mt_tabs($tab_array)
3661
-    {
3662
-        $tab_array = (array) $tab_array;
3663
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3664
-        $tabs = '';
3665
-
3666
-        foreach ($tab_array as $tab) {
3667
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3668
-        }
3669
-
3670
-        return $tabs;
3671
-    }
3672
-
3673
-
3674
-    /**
3675
-     * This prepares the content of the messenger meta box admin settings
3676
-     *
3677
-     * @param  EE_messenger $messenger The messenger we're setting up content for
3678
-     * @return string html formatted content
3679
-     * @throws DomainException
3680
-     */
3681
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3682
-    {
3683
-
3684
-        $fields = $messenger->get_admin_settings_fields();
3685
-        $settings_template_args['template_form_fields'] = '';
3686
-
3687
-        // is $messenger active?
3688
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3689
-
3690
-
3691
-        if (! empty($fields)) {
3692
-            $existing_settings = $messenger->get_existing_admin_settings();
3693
-
3694
-            foreach ($fields as $fldname => $fldprops) {
3695
-                $field_id = $messenger->name . '-' . $fldname;
3696
-                $template_form_field[ $field_id ] = array(
3697
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3698
-                    'label'      => $fldprops['label'],
3699
-                    'input'      => $fldprops['field_type'],
3700
-                    'type'       => $fldprops['value_type'],
3701
-                    'required'   => $fldprops['required'],
3702
-                    'validation' => $fldprops['validation'],
3703
-                    'value'      => isset($existing_settings[ $field_id ])
3704
-                        ? $existing_settings[ $field_id ]
3705
-                        : $fldprops['default'],
3706
-                    'css_class'  => '',
3707
-                    'format'     => $fldprops['format'],
3708
-                );
3709
-            }
3710
-
3711
-
3712
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3713
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3714
-                : '';
3715
-        }
3716
-
3717
-        // we also need some hidden fields
3718
-        $settings_template_args['hidden_fields'] = array(
3719
-            'messenger_settings[messenger]' => array(
3720
-                'type'  => 'hidden',
3721
-                'value' => $messenger->name,
3722
-            ),
3723
-            'type'                          => array(
3724
-                'type'  => 'hidden',
3725
-                'value' => 'messenger',
3726
-            ),
3727
-        );
3728
-
3729
-        // make sure any active message types that are existing are included in the hidden fields
3730
-        if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3731
-            foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3732
-                $settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3733
-                    'type'  => 'hidden',
3734
-                    'value' => $mt,
3735
-                );
3736
-            }
3737
-        }
3738
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3739
-            $settings_template_args['hidden_fields'],
3740
-            'array'
3741
-        );
3742
-        $active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3743
-
3744
-        $settings_template_args['messenger'] = $messenger->name;
3745
-        $settings_template_args['description'] = $messenger->description;
3746
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3747
-
3748
-
3749
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3750
-            $messenger->name
3751
-        )
3752
-            ? $settings_template_args['show_hide_edit_form']
3753
-            : ' hidden';
3754
-
3755
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3756
-            ? ' hidden'
3757
-            : $settings_template_args['show_hide_edit_form'];
3758
-
3759
-
3760
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3761
-        $settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3762
-        $settings_template_args['on_off_status'] = $active ? true : false;
3763
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3764
-        $content = EEH_Template::display_template(
3765
-            $template,
3766
-            $settings_template_args,
3767
-            true
3768
-        );
3769
-
3770
-        return $content;
3771
-    }
3772
-
3773
-
3774
-    /**
3775
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3776
-     *
3777
-     * @throws DomainException
3778
-     * @throws EE_Error
3779
-     * @throws InvalidDataTypeException
3780
-     * @throws InvalidInterfaceException
3781
-     * @throws InvalidArgumentException
3782
-     * @throws ReflectionException
3783
-     */
3784
-    public function activate_messenger_toggle()
3785
-    {
3786
-        $success = true;
3787
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3788
-        // let's check that we have required data
3789
-        if (! isset($this->_req_data['messenger'])) {
3790
-            EE_Error::add_error(
3791
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3792
-                __FILE__,
3793
-                __FUNCTION__,
3794
-                __LINE__
3795
-            );
3796
-            $success = false;
3797
-        }
3798
-
3799
-        // do a nonce check here since we're not arriving via a normal route
3800
-        $nonce = isset($this->_req_data['activate_nonce'])
3801
-            ? sanitize_text_field($this->_req_data['activate_nonce'])
3802
-            : '';
3803
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3804
-
3805
-        $this->_verify_nonce($nonce, $nonce_ref);
3806
-
3807
-
3808
-        if (! isset($this->_req_data['status'])) {
3809
-            EE_Error::add_error(
3810
-                esc_html__(
3811
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3812
-                    'event_espresso'
3813
-                ),
3814
-                __FILE__,
3815
-                __FUNCTION__,
3816
-                __LINE__
3817
-            );
3818
-            $success = false;
3819
-        }
3820
-
3821
-        // do check to verify we have a valid status.
3822
-        $status = $this->_req_data['status'];
3823
-
3824
-        if ($status !== 'off' && $status !== 'on') {
3825
-            EE_Error::add_error(
3826
-                sprintf(
3827
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3828
-                    $this->_req_data['status']
3829
-                ),
3830
-                __FILE__,
3831
-                __FUNCTION__,
3832
-                __LINE__
3833
-            );
3834
-            $success = false;
3835
-        }
3836
-
3837
-        if ($success) {
3838
-            // made it here?  Stop dawdling then!!
3839
-            $success = $status === 'off'
3840
-                ? $this->_deactivate_messenger($this->_req_data['messenger'])
3841
-                : $this->_activate_messenger($this->_req_data['messenger']);
3842
-        }
3843
-
3844
-        $this->_template_args['success'] = $success;
3845
-
3846
-        // no special instructions so let's just do the json return (which should automatically do all the special stuff).
3847
-        $this->_return_json();
3848
-    }
3849
-
3850
-
3851
-    /**
3852
-     * used by ajax from the messages settings page to activate|deactivate a message type
3853
-     *
3854
-     * @throws DomainException
3855
-     * @throws EE_Error
3856
-     * @throws ReflectionException
3857
-     * @throws InvalidDataTypeException
3858
-     * @throws InvalidInterfaceException
3859
-     * @throws InvalidArgumentException
3860
-     */
3861
-    public function activate_mt_toggle()
3862
-    {
3863
-        $success = true;
3864
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3865
-
3866
-        // let's make sure we have the necessary data
3867
-        if (! isset($this->_req_data['message_type'])) {
3868
-            EE_Error::add_error(
3869
-                esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3870
-                __FILE__,
3871
-                __FUNCTION__,
3872
-                __LINE__
3873
-            );
3874
-            $success = false;
3875
-        }
3876
-
3877
-        if (! isset($this->_req_data['messenger'])) {
3878
-            EE_Error::add_error(
3879
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3880
-                __FILE__,
3881
-                __FUNCTION__,
3882
-                __LINE__
3883
-            );
3884
-            $success = false;
3885
-        }
3886
-
3887
-        if (! isset($this->_req_data['status'])) {
3888
-            EE_Error::add_error(
3889
-                esc_html__(
3890
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3891
-                    'event_espresso'
3892
-                ),
3893
-                __FILE__,
3894
-                __FUNCTION__,
3895
-                __LINE__
3896
-            );
3897
-            $success = false;
3898
-        }
3899
-
3900
-
3901
-        // do check to verify we have a valid status.
3902
-        $status = $this->_req_data['status'];
3903
-
3904
-        if ($status !== 'activate' && $status !== 'deactivate') {
3905
-            EE_Error::add_error(
3906
-                sprintf(
3907
-                    esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3908
-                    $this->_req_data['status']
3909
-                ),
3910
-                __FILE__,
3911
-                __FUNCTION__,
3912
-                __LINE__
3913
-            );
3914
-            $success = false;
3915
-        }
3916
-
3917
-
3918
-        // do a nonce check here since we're not arriving via a normal route
3919
-        $nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3920
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3921
-
3922
-        $this->_verify_nonce($nonce, $nonce_ref);
3923
-
3924
-        if ($success) {
3925
-            // made it here? um, what are you waiting for then?
3926
-            $success = $status === 'deactivate'
3927
-                ? $this->_deactivate_message_type_for_messenger(
3928
-                    $this->_req_data['messenger'],
3929
-                    $this->_req_data['message_type']
3930
-                )
3931
-                : $this->_activate_message_type_for_messenger(
3932
-                    $this->_req_data['messenger'],
3933
-                    $this->_req_data['message_type']
3934
-                );
3935
-        }
3936
-
3937
-        $this->_template_args['success'] = $success;
3938
-        $this->_return_json();
3939
-    }
3940
-
3941
-
3942
-    /**
3943
-     * Takes care of processing activating a messenger and preparing the appropriate response.
3944
-     *
3945
-     * @param string $messenger_name The name of the messenger being activated
3946
-     * @return bool
3947
-     * @throws DomainException
3948
-     * @throws EE_Error
3949
-     * @throws InvalidArgumentException
3950
-     * @throws ReflectionException
3951
-     * @throws InvalidDataTypeException
3952
-     * @throws InvalidInterfaceException
3953
-     */
3954
-    protected function _activate_messenger($messenger_name)
3955
-    {
3956
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3957
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3958
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger
3959
-            ? $active_messenger->get_default_message_types()
3960
-            : array();
3961
-
3962
-        // ensure is active
3963
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3964
-
3965
-        // set response_data for reload
3966
-        foreach ($message_types_to_activate as $message_type_name) {
3967
-            /** @var EE_message_type $message_type */
3968
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3969
-            if ($this->_message_resource_manager->is_message_type_active_for_messenger(
3970
-                $messenger_name,
3971
-                $message_type_name
3972
-            )
3973
-                && $message_type instanceof EE_message_type
3974
-            ) {
3975
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
3976
-                if ($message_type->get_admin_settings_fields()) {
3977
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
3978
-                }
3979
-            }
3980
-        }
3981
-
3982
-        // add success message for activating messenger
3983
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3984
-    }
3985
-
3986
-
3987
-    /**
3988
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
3989
-     *
3990
-     * @param string $messenger_name The name of the messenger being activated
3991
-     * @return bool
3992
-     * @throws DomainException
3993
-     * @throws EE_Error
3994
-     * @throws InvalidArgumentException
3995
-     * @throws ReflectionException
3996
-     * @throws InvalidDataTypeException
3997
-     * @throws InvalidInterfaceException
3998
-     */
3999
-    protected function _deactivate_messenger($messenger_name)
4000
-    {
4001
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4002
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4003
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
4004
-
4005
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4006
-    }
4007
-
4008
-
4009
-    /**
4010
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4011
-     *
4012
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
4013
-     * @param string $message_type_name The name of the message type being activated for the messenger
4014
-     * @return bool
4015
-     * @throws DomainException
4016
-     * @throws EE_Error
4017
-     * @throws InvalidArgumentException
4018
-     * @throws ReflectionException
4019
-     * @throws InvalidDataTypeException
4020
-     * @throws InvalidInterfaceException
4021
-     */
4022
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4023
-    {
4024
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4025
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4026
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4027
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4028
-
4029
-        // ensure is active
4030
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
4031
-
4032
-        // set response for load
4033
-        if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4034
-            $messenger_name,
4035
-            $message_type_name
4036
-        )
4037
-        ) {
4038
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
4039
-            if ($message_type_to_activate->get_admin_settings_fields()) {
4040
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
4041
-            }
4042
-        }
4043
-
4044
-        return $this->_setup_response_message_for_activating_messenger_with_message_types(
4045
-            $active_messenger,
4046
-            $message_type_to_activate
4047
-        );
4048
-    }
4049
-
4050
-
4051
-    /**
4052
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4053
-     *
4054
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4055
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
4056
-     * @return bool
4057
-     * @throws DomainException
4058
-     * @throws EE_Error
4059
-     * @throws InvalidArgumentException
4060
-     * @throws ReflectionException
4061
-     * @throws InvalidDataTypeException
4062
-     * @throws InvalidInterfaceException
4063
-     */
4064
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4065
-    {
4066
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4067
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4068
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4069
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4070
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4071
-
4072
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4073
-            $active_messenger,
4074
-            $message_type_to_deactivate
4075
-        );
4076
-    }
4077
-
4078
-
4079
-    /**
4080
-     * This just initializes the defaults for activating messenger and message type responses.
4081
-     */
4082
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
4083
-    {
4084
-        $this->_template_args['data']['active_mts'] = array();
4085
-        $this->_template_args['data']['mt_reload'] = array();
4086
-    }
4087
-
4088
-
4089
-    /**
4090
-     * Setup appropriate response for activating a messenger and/or message types
4091
-     *
4092
-     * @param EE_messenger         $messenger
4093
-     * @param EE_message_type|null $message_type
4094
-     * @return bool
4095
-     * @throws DomainException
4096
-     * @throws EE_Error
4097
-     * @throws InvalidArgumentException
4098
-     * @throws ReflectionException
4099
-     * @throws InvalidDataTypeException
4100
-     * @throws InvalidInterfaceException
4101
-     */
4102
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
4103
-        $messenger,
4104
-        EE_Message_Type $message_type = null
4105
-    ) {
4106
-        // if $messenger isn't a valid messenger object then get out.
4107
-        if (! $messenger instanceof EE_Messenger) {
4108
-            EE_Error::add_error(
4109
-                esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4110
-                __FILE__,
4111
-                __FUNCTION__,
4112
-                __LINE__
4113
-            );
4114
-
4115
-            return false;
4116
-        }
4117
-        // activated
4118
-        if ($this->_template_args['data']['active_mts']) {
4119
-            EE_Error::overwrite_success();
4120
-            // activated a message type with the messenger
4121
-            if ($message_type instanceof EE_message_type) {
4122
-                EE_Error::add_success(
4123
-                    sprintf(
4124
-                        esc_html__(
4125
-                            '%s message type has been successfully activated with the %s messenger',
4126
-                            'event_espresso'
4127
-                        ),
4128
-                        ucwords($message_type->label['singular']),
4129
-                        ucwords($messenger->label['singular'])
4130
-                    )
4131
-                );
4132
-
4133
-                // if message type was invoice then let's make sure we activate the invoice payment method.
4134
-                if ($message_type->name === 'invoice') {
4135
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
4136
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4137
-                    if ($pm instanceof EE_Payment_Method) {
4138
-                        EE_Error::add_attention(
4139
-                            esc_html__(
4140
-                                '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.',
4141
-                                'event_espresso'
4142
-                            )
4143
-                        );
4144
-                    }
4145
-                }
4146
-                // just toggles the entire messenger
4147
-            } else {
4148
-                EE_Error::add_success(
4149
-                    sprintf(
4150
-                        esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4151
-                        ucwords($messenger->label['singular'])
4152
-                    )
4153
-                );
4154
-            }
4155
-
4156
-            return true;
4157
-
4158
-            // possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4159
-            // message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4160
-            // in which case we just give a success message for the messenger being successfully activated.
4161
-        } else {
4162
-            if (! $messenger->get_default_message_types()) {
4163
-                // messenger doesn't have any default message types so still a success.
4164
-                EE_Error::add_success(
4165
-                    sprintf(
4166
-                        esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4167
-                        ucwords($messenger->label['singular'])
4168
-                    )
4169
-                );
4170
-
4171
-                return true;
4172
-            } else {
4173
-                EE_Error::add_error(
4174
-                    $message_type instanceof EE_message_type
4175
-                        ? sprintf(
4176
-                            esc_html__(
4177
-                                '%s message type was not successfully activated with the %s messenger',
4178
-                                'event_espresso'
4179
-                            ),
4180
-                            ucwords($message_type->label['singular']),
4181
-                            ucwords($messenger->label['singular'])
4182
-                        )
4183
-                        : sprintf(
4184
-                            esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4185
-                            ucwords($messenger->label['singular'])
4186
-                        ),
4187
-                    __FILE__,
4188
-                    __FUNCTION__,
4189
-                    __LINE__
4190
-                );
4191
-
4192
-                return false;
4193
-            }
4194
-        }
4195
-    }
4196
-
4197
-
4198
-    /**
4199
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
4200
-     *
4201
-     * @param EE_messenger         $messenger
4202
-     * @param EE_message_type|null $message_type
4203
-     * @return bool
4204
-     * @throws DomainException
4205
-     * @throws EE_Error
4206
-     * @throws InvalidArgumentException
4207
-     * @throws ReflectionException
4208
-     * @throws InvalidDataTypeException
4209
-     * @throws InvalidInterfaceException
4210
-     */
4211
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4212
-        $messenger,
4213
-        EE_message_type $message_type = null
4214
-    ) {
4215
-        EE_Error::overwrite_success();
4216
-
4217
-        // if $messenger isn't a valid messenger object then get out.
4218
-        if (! $messenger instanceof EE_Messenger) {
4219
-            EE_Error::add_error(
4220
-                esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4221
-                __FILE__,
4222
-                __FUNCTION__,
4223
-                __LINE__
4224
-            );
4225
-
4226
-            return false;
4227
-        }
4228
-
4229
-        if ($message_type instanceof EE_message_type) {
4230
-            $message_type_name = $message_type->name;
4231
-            EE_Error::add_success(
4232
-                sprintf(
4233
-                    esc_html__(
4234
-                        '%s message type has been successfully deactivated for the %s messenger.',
4235
-                        'event_espresso'
4236
-                    ),
4237
-                    ucwords($message_type->label['singular']),
4238
-                    ucwords($messenger->label['singular'])
4239
-                )
4240
-            );
4241
-        } else {
4242
-            $message_type_name = '';
4243
-            EE_Error::add_success(
4244
-                sprintf(
4245
-                    esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4246
-                    ucwords($messenger->label['singular'])
4247
-                )
4248
-            );
4249
-        }
4250
-
4251
-        // if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4252
-        if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4253
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
4254
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4255
-            if ($count_updated > 0) {
4256
-                $msg = $message_type_name === 'invoice'
4257
-                    ? esc_html__(
4258
-                        '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.',
4259
-                        'event_espresso'
4260
-                    )
4261
-                    : esc_html__(
4262
-                        '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.',
4263
-                        'event_espresso'
4264
-                    );
4265
-                EE_Error::add_attention($msg);
4266
-            }
4267
-        }
4268
-
4269
-        return true;
4270
-    }
4271
-
4272
-
4273
-    /**
4274
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4275
-     *
4276
-     * @throws DomainException
4277
-     */
4278
-    public function update_mt_form()
4279
-    {
4280
-        if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4281
-            EE_Error::add_error(
4282
-                esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4283
-                __FILE__,
4284
-                __FUNCTION__,
4285
-                __LINE__
4286
-            );
4287
-            $this->_return_json();
4288
-        }
4289
-
4290
-        $message_types = $this->get_installed_message_types();
4291
-
4292
-        $message_type = $message_types[ $this->_req_data['message_type'] ];
4293
-        $messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4294
-
4295
-        $content = $this->_message_type_settings_content(
4296
-            $message_type,
4297
-            $messenger,
4298
-            true
4299
-        );
4300
-        $this->_template_args['success'] = true;
4301
-        $this->_template_args['content'] = $content;
4302
-        $this->_return_json();
4303
-    }
4304
-
4305
-
4306
-    /**
4307
-     * this handles saving the settings for a messenger or message type
4308
-     *
4309
-     */
4310
-    public function save_settings()
4311
-    {
4312
-        if (! isset($this->_req_data['type'])) {
4313
-            EE_Error::add_error(
4314
-                esc_html__(
4315
-                    'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4316
-                    'event_espresso'
4317
-                ),
4318
-                __FILE__,
4319
-                __FUNCTION__,
4320
-                __LINE__
4321
-            );
4322
-            $this->_template_args['error'] = true;
4323
-            $this->_return_json();
4324
-        }
4325
-
4326
-
4327
-        if ($this->_req_data['type'] === 'messenger') {
4328
-            // this should be an array.
4329
-            $settings = $this->_req_data['messenger_settings'];
4330
-            $messenger = $settings['messenger'];
4331
-            // let's setup the settings data
4332
-            foreach ($settings as $key => $value) {
4333
-                switch ($key) {
4334
-                    case 'messenger':
4335
-                        unset($settings['messenger']);
4336
-                        break;
4337
-                    case 'message_types':
4338
-                        unset($settings['message_types']);
4339
-                        break;
4340
-                    default:
4341
-                        $settings[ $key ] = $value;
4342
-                        break;
4343
-                }
4344
-            }
4345
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4346
-        } elseif ($this->_req_data['type'] === 'message_type') {
4347
-            $settings = $this->_req_data['message_type_settings'];
4348
-            $messenger = $settings['messenger'];
4349
-            $message_type = $settings['message_type'];
4350
-
4351
-            foreach ($settings as $key => $value) {
4352
-                switch ($key) {
4353
-                    case 'messenger':
4354
-                        unset($settings['messenger']);
4355
-                        break;
4356
-                    case 'message_type':
4357
-                        unset($settings['message_type']);
4358
-                        break;
4359
-                    default:
4360
-                        $settings[ $key ] = $value;
4361
-                        break;
4362
-                }
4363
-            }
4364
-
4365
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4366
-        }
4367
-
4368
-        // okay we should have the data all setup.  Now we just update!
4369
-        $success = $this->_message_resource_manager->update_active_messengers_option();
4370
-
4371
-        if ($success) {
4372
-            EE_Error::add_success(__('Settings updated', 'event_espresso'));
4373
-        } else {
4374
-            EE_Error::add_error(
4375
-                esc_html__(
4376
-                    'Settings did not get updated',
4377
-                    'event_espresso'
4378
-                ),
4379
-                __FILE__,
4380
-                __FUNCTION__,
4381
-                __LINE__
4382
-            );
4383
-        }
4384
-
4385
-        $this->_template_args['success'] = $success;
4386
-        $this->_return_json();
4387
-    }
4388
-
4389
-
4390
-
4391
-
4392
-    /**  EE MESSAGE PROCESSING ACTIONS **/
4393
-
4394
-
4395
-    /**
4396
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4397
-     * However, this does not send immediately, it just queues for sending.
4398
-     *
4399
-     * @since 4.9.0
4400
-     * @throws EE_Error
4401
-     * @throws InvalidDataTypeException
4402
-     * @throws InvalidInterfaceException
4403
-     * @throws InvalidArgumentException
4404
-     * @throws ReflectionException
4405
-     */
4406
-    protected function _generate_now()
4407
-    {
4408
-        EED_Messages::generate_now($this->_get_msg_ids_from_request());
4409
-        $this->_redirect_after_action(false, '', '', array(), true);
4410
-    }
4411
-
4412
-
4413
-    /**
4414
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4415
-     * are EEM_Message::status_resend or EEM_Message::status_idle
4416
-     *
4417
-     * @since 4.9.0
4418
-     * @throws EE_Error
4419
-     * @throws InvalidDataTypeException
4420
-     * @throws InvalidInterfaceException
4421
-     * @throws InvalidArgumentException
4422
-     * @throws ReflectionException
4423
-     */
4424
-    protected function _generate_and_send_now()
4425
-    {
4426
-        EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4427
-        $this->_redirect_after_action(false, '', '', array(), true);
4428
-    }
4429
-
4430
-
4431
-    /**
4432
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4433
-     *
4434
-     * @since 4.9.0
4435
-     * @throws EE_Error
4436
-     * @throws InvalidDataTypeException
4437
-     * @throws InvalidInterfaceException
4438
-     * @throws InvalidArgumentException
4439
-     * @throws ReflectionException
4440
-     */
4441
-    protected function _queue_for_resending()
4442
-    {
4443
-        EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4444
-        $this->_redirect_after_action(false, '', '', array(), true);
4445
-    }
4446
-
4447
-
4448
-    /**
4449
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4450
-     *
4451
-     * @since 4.9.0
4452
-     * @throws EE_Error
4453
-     * @throws InvalidDataTypeException
4454
-     * @throws InvalidInterfaceException
4455
-     * @throws InvalidArgumentException
4456
-     * @throws ReflectionException
4457
-     */
4458
-    protected function _send_now()
4459
-    {
4460
-        EED_Messages::send_now($this->_get_msg_ids_from_request());
4461
-        $this->_redirect_after_action(false, '', '', array(), true);
4462
-    }
4463
-
4464
-
4465
-    /**
4466
-     * Deletes EE_messages for IDs in the request.
4467
-     *
4468
-     * @since 4.9.0
4469
-     * @throws EE_Error
4470
-     * @throws InvalidDataTypeException
4471
-     * @throws InvalidInterfaceException
4472
-     * @throws InvalidArgumentException
4473
-     */
4474
-    protected function _delete_ee_messages()
4475
-    {
4476
-        $msg_ids = $this->_get_msg_ids_from_request();
4477
-        $deleted_count = 0;
4478
-        foreach ($msg_ids as $msg_id) {
4479
-            if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4480
-                $deleted_count++;
4481
-            }
4482
-        }
4483
-        if ($deleted_count) {
4484
-            EE_Error::add_success(
4485
-                esc_html(
4486
-                    _n(
4487
-                        'Message successfully deleted',
4488
-                        'Messages successfully deleted',
4489
-                        $deleted_count,
4490
-                        'event_espresso'
4491
-                    )
4492
-                )
4493
-            );
4494
-            $this->_redirect_after_action(
4495
-                false,
4496
-                '',
4497
-                '',
4498
-                array(),
4499
-                true
4500
-            );
4501
-        } else {
4502
-            EE_Error::add_error(
4503
-                _n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4504
-                __FILE__,
4505
-                __FUNCTION__,
4506
-                __LINE__
4507
-            );
4508
-            $this->_redirect_after_action(false, '', '', array(), true);
4509
-        }
4510
-    }
4511
-
4512
-
4513
-    /**
4514
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4515
-     *
4516
-     * @since 4.9.0
4517
-     * @return array
4518
-     */
4519
-    protected function _get_msg_ids_from_request()
4520
-    {
4521
-        if (! isset($this->_req_data['MSG_ID'])) {
4522
-            return array();
4523
-        }
4524
-
4525
-        return is_array($this->_req_data['MSG_ID'])
4526
-            ? array_keys($this->_req_data['MSG_ID'])
4527
-            : array($this->_req_data['MSG_ID']);
4528
-    }
2612
+		$output = ob_get_contents();
2613
+		ob_clean();
2614
+		$this->_context_switcher = $output;
2615
+	}
2616
+
2617
+
2618
+	/**
2619
+	 * utility for sanitizing new values coming in.
2620
+	 * Note: this is only used when updating a context.
2621
+	 *
2622
+	 * @access protected
2623
+	 *
2624
+	 * @param int $index This helps us know which template field to select from the request array.
2625
+	 *
2626
+	 * @return array
2627
+	 */
2628
+	protected function _set_message_template_column_values($index)
2629
+	{
2630
+		if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2631
+			foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2632
+				$this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2633
+			}
2634
+		}
2635
+
2636
+
2637
+		$set_column_values = array(
2638
+			'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2639
+			'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2640
+			'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2641
+			'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2642
+			'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2643
+			'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2644
+			'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2645
+			'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2646
+			'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2647
+				? absint($this->_req_data['MTP_is_global'])
2648
+				: 0,
2649
+			'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2650
+				? absint($this->_req_data['MTP_is_override'])
2651
+				: 0,
2652
+			'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2653
+			'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2654
+		);
2655
+
2656
+
2657
+		return $set_column_values;
2658
+	}
2659
+
2660
+
2661
+	protected function _insert_or_update_message_template($new = false)
2662
+	{
2663
+
2664
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2665
+		$success = 0;
2666
+		$override = false;
2667
+
2668
+		// setup notices description
2669
+		$messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2670
+
2671
+		// need the message type and messenger objects to be able to use the labels for the notices
2672
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2673
+		$messenger_label = $messenger_object instanceof EE_messenger
2674
+			? ucwords($messenger_object->label['singular'])
2675
+			: '';
2676
+
2677
+		$message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2678
+			? $this->_req_data['MTP_message_type']
2679
+			: '';
2680
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2681
+
2682
+		$message_type_label = $message_type_object instanceof EE_message_type
2683
+			? ucwords($message_type_object->label['singular'])
2684
+			: '';
2685
+
2686
+		$context_slug = ! empty($this->_req_data['MTP_context'])
2687
+			? $this->_req_data['MTP_context']
2688
+			: '';
2689
+		$context = ucwords(str_replace('_', ' ', $context_slug));
2690
+
2691
+		$item_desc = $messenger_label && $message_type_label
2692
+			? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2693
+			: '';
2694
+		$item_desc .= 'Message Template';
2695
+		$query_args = array();
2696
+		$edit_array = array();
2697
+		$action_desc = '';
2698
+
2699
+		// if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2700
+		// user to edit.
2701
+		if ($new) {
2702
+			$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2703
+			if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2704
+				if (empty($edit_array)) {
2705
+					$success = 0;
2706
+				} else {
2707
+					$success = 1;
2708
+					$edit_array = $edit_array[0];
2709
+					$query_args = array(
2710
+						'id'      => $edit_array['GRP_ID'],
2711
+						'context' => $edit_array['MTP_context'],
2712
+						'action'  => 'edit_message_template',
2713
+					);
2714
+				}
2715
+			}
2716
+			$action_desc = 'created';
2717
+		} else {
2718
+			$MTPG = EEM_Message_Template_Group::instance();
2719
+			$MTP = EEM_Message_Template::instance();
2720
+
2721
+
2722
+			// run update for each template field in displayed context
2723
+			if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2724
+				EE_Error::add_error(
2725
+					esc_html__(
2726
+						'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2727
+						'event_espresso'
2728
+					),
2729
+					__FILE__,
2730
+					__FUNCTION__,
2731
+					__LINE__
2732
+				);
2733
+				$success = 0;
2734
+			} else {
2735
+				// first validate all fields!
2736
+				// this filter allows client code to add its own validation to the template fields as well.
2737
+				// returning an empty array means everything passed validation.
2738
+				// errors in validation should be represented in an array with the following shape:
2739
+				// array(
2740
+				//   'fieldname' => array(
2741
+				//          'msg' => 'error message'
2742
+				//          'value' => 'value for field producing error'
2743
+				// )
2744
+				$custom_validation = (array) apply_filters(
2745
+					'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2746
+					array(),
2747
+					$this->_req_data['MTP_template_fields'],
2748
+					$context_slug,
2749
+					$messenger_slug,
2750
+					$message_type_slug
2751
+				);
2752
+
2753
+				$system_validation = $MTPG->validate(
2754
+					$this->_req_data['MTP_template_fields'],
2755
+					$context_slug,
2756
+					$messenger_slug,
2757
+					$message_type_slug
2758
+				);
2759
+
2760
+				$system_validation = ! is_array($system_validation) && $system_validation ? array()
2761
+					: $system_validation;
2762
+				$validates = array_merge($custom_validation, $system_validation);
2763
+
2764
+				// if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2765
+				// appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2766
+				//  WE need to make sure there is no actual error messages in validates.
2767
+				if (is_array($validates) && ! empty($validates)) {
2768
+					// add the transient so when the form loads we know which fields to highlight
2769
+					$this->_add_transient('edit_message_template', $validates);
2770
+
2771
+					$success = 0;
2772
+
2773
+					// setup notices
2774
+					foreach ($validates as $field => $error) {
2775
+						if (isset($error['msg'])) {
2776
+							EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2777
+						}
2778
+					}
2779
+				} else {
2780
+					$set_column_values = array();
2781
+					foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2782
+						$set_column_values = $this->_set_message_template_column_values($template_field);
2783
+
2784
+						$where_cols_n_values = array(
2785
+							'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2786
+						);
2787
+						// if they aren't allowed to use all JS, restrict them to just posty-y tags
2788
+						if (! current_user_can('unfiltered_html')) {
2789
+							if (is_array($set_column_values['MTP_content'])) {
2790
+								foreach ($set_column_values['MTP_content'] as $key => $value) {
2791
+									// remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2792
+									// only removes slashes from double-quotes, so attributes using single quotes always
2793
+									// appear invalid.) But currently the models expect slashed data, so after wp_kses
2794
+									// runs we need to re-slash the data. Sheesh. See
2795
+									// https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2796
+									$set_column_values['MTP_content'][ $key ] = addslashes(
2797
+										wp_kses(
2798
+											stripslashes($value),
2799
+											wp_kses_allowed_html('post')
2800
+										)
2801
+									);
2802
+								}
2803
+							} else {
2804
+								$set_column_values['MTP_content'] = wp_kses(
2805
+									$set_column_values['MTP_content'],
2806
+									wp_kses_allowed_html('post')
2807
+								);
2808
+							}
2809
+						}
2810
+						$message_template_fields = array(
2811
+							'GRP_ID'             => $set_column_values['GRP_ID'],
2812
+							'MTP_template_field' => $set_column_values['MTP_template_field'],
2813
+							'MTP_context'        => $set_column_values['MTP_context'],
2814
+							'MTP_content'        => $set_column_values['MTP_content'],
2815
+						);
2816
+						if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2817
+							if ($updated === false) {
2818
+								EE_Error::add_error(
2819
+									sprintf(
2820
+										esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2821
+										$template_field
2822
+									),
2823
+									__FILE__,
2824
+									__FUNCTION__,
2825
+									__LINE__
2826
+								);
2827
+							} else {
2828
+								$success = 1;
2829
+							}
2830
+						} else {
2831
+							// only do this logic if we don't have a MTP_ID for this field
2832
+							if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2833
+								// this has already been through the template field validator and sanitized, so it will be
2834
+								// safe to insert this field.  Why insert?  This typically happens when we introduce a new
2835
+								// message template field in a messenger/message type and existing users don't have the
2836
+								// default setup for it.
2837
+								// @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2838
+								$updated = $MTP->insert($message_template_fields);
2839
+								if (! $updated || is_wp_error($updated)) {
2840
+									EE_Error::add_error(
2841
+										sprintf(
2842
+											esc_html__('%s field could not be updated.', 'event_espresso'),
2843
+											$template_field
2844
+										),
2845
+										__FILE__,
2846
+										__FUNCTION__,
2847
+										__LINE__
2848
+									);
2849
+									$success = 0;
2850
+								} else {
2851
+									$success = 1;
2852
+								}
2853
+							}
2854
+						}
2855
+						$action_desc = 'updated';
2856
+					}
2857
+
2858
+					// we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2859
+					$mtpg_fields = array(
2860
+						'MTP_user_id'      => $set_column_values['MTP_user_id'],
2861
+						'MTP_messenger'    => $set_column_values['MTP_messenger'],
2862
+						'MTP_message_type' => $set_column_values['MTP_message_type'],
2863
+						'MTP_is_global'    => $set_column_values['MTP_is_global'],
2864
+						'MTP_is_override'  => $set_column_values['MTP_is_override'],
2865
+						'MTP_deleted'      => $set_column_values['MTP_deleted'],
2866
+						'MTP_is_active'    => $set_column_values['MTP_is_active'],
2867
+						'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2868
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2869
+							: '',
2870
+						'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2871
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2872
+							: '',
2873
+					);
2874
+
2875
+					$mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2876
+					$updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2877
+
2878
+					if ($updated === false) {
2879
+						EE_Error::add_error(
2880
+							sprintf(
2881
+								esc_html__(
2882
+									'The Message Template Group (%d) was NOT updated for some reason',
2883
+									'event_espresso'
2884
+								),
2885
+								$set_column_values['GRP_ID']
2886
+							),
2887
+							__FILE__,
2888
+							__FUNCTION__,
2889
+							__LINE__
2890
+						);
2891
+					} else {
2892
+						// k now we need to ensure the template_pack and template_variation fields are set.
2893
+						$template_pack = ! empty($this->_req_data['MTP_template_pack'])
2894
+							? $this->_req_data['MTP_template_pack']
2895
+							: 'default';
2896
+
2897
+						$template_variation = ! empty($this->_req_data['MTP_template_variation'])
2898
+							? $this->_req_data['MTP_template_variation']
2899
+							: 'default';
2900
+
2901
+						$mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2902
+						if ($mtpg_obj instanceof EE_Message_Template_Group) {
2903
+							$mtpg_obj->set_template_pack_name($template_pack);
2904
+							$mtpg_obj->set_template_pack_variation($template_variation);
2905
+						}
2906
+						$success = 1;
2907
+					}
2908
+				}
2909
+			}
2910
+		}
2911
+
2912
+		// we return things differently if doing ajax
2913
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2914
+			$this->_template_args['success'] = $success;
2915
+			$this->_template_args['error'] = ! $success ? true : false;
2916
+			$this->_template_args['content'] = '';
2917
+			$this->_template_args['data'] = array(
2918
+				'grpID'        => $edit_array['GRP_ID'],
2919
+				'templateName' => $edit_array['template_name'],
2920
+			);
2921
+			if ($success) {
2922
+				EE_Error::overwrite_success();
2923
+				EE_Error::add_success(
2924
+					esc_html__(
2925
+						'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.',
2926
+						'event_espresso'
2927
+					)
2928
+				);
2929
+			}
2930
+
2931
+			$this->_return_json();
2932
+		}
2933
+
2934
+
2935
+		// was a test send triggered?
2936
+		if (isset($this->_req_data['test_button'])) {
2937
+			EE_Error::overwrite_success();
2938
+			$this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2939
+			$override = true;
2940
+		}
2941
+
2942
+		if (empty($query_args)) {
2943
+			$query_args = array(
2944
+				'id'      => $this->_req_data['GRP_ID'],
2945
+				'context' => $context_slug,
2946
+				'action'  => 'edit_message_template',
2947
+			);
2948
+		}
2949
+
2950
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2951
+	}
2952
+
2953
+
2954
+	/**
2955
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
2956
+	 *
2957
+	 * @param  string $context      what context being tested
2958
+	 * @param  string $messenger    messenger being tested
2959
+	 * @param  string $message_type message type being tested
2960
+	 * @throws EE_Error
2961
+	 * @throws InvalidArgumentException
2962
+	 * @throws InvalidDataTypeException
2963
+	 * @throws InvalidInterfaceException
2964
+	 */
2965
+	protected function _do_test_send($context, $messenger, $message_type)
2966
+	{
2967
+		// set things up for preview
2968
+		$this->_req_data['messenger'] = $messenger;
2969
+		$this->_req_data['message_type'] = $message_type;
2970
+		$this->_req_data['context'] = $context;
2971
+		$this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2972
+		$active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
2973
+
2974
+		// let's save any existing fields that might be required by the messenger
2975
+		if (isset($this->_req_data['test_settings_fld'])
2976
+			&& $active_messenger instanceof EE_messenger
2977
+			&& apply_filters(
2978
+				'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
2979
+				true,
2980
+				$this->_req_data['test_settings_fld'],
2981
+				$active_messenger
2982
+			)
2983
+		) {
2984
+			$active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2985
+		}
2986
+
2987
+		/**
2988
+		 * Use filter to add additional controls on whether message can send or not
2989
+		 */
2990
+		if (apply_filters(
2991
+			'FHEE__Messages_Admin_Page__do_test_send__can_send',
2992
+			true,
2993
+			$context,
2994
+			$this->_req_data,
2995
+			$messenger,
2996
+			$message_type
2997
+		)) {
2998
+			$success = $this->_preview_message(true);
2999
+			if ($success) {
3000
+				EE_Error::add_success(__('Test message sent', 'event_espresso'));
3001
+			} else {
3002
+				EE_Error::add_error(
3003
+					esc_html__('The test message was not sent', 'event_espresso'),
3004
+					__FILE__,
3005
+					__FUNCTION__,
3006
+					__LINE__
3007
+				);
3008
+			}
3009
+		}
3010
+	}
3011
+
3012
+
3013
+	/**
3014
+	 * _generate_new_templates
3015
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3016
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3017
+	 * for the event.
3018
+	 *
3019
+	 *
3020
+	 * @param  string $messenger     the messenger we are generating templates for
3021
+	 * @param array   $message_types array of message types that the templates are generated for.
3022
+	 * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3023
+	 *                               indicate the message_template_group being used as the base.
3024
+	 *
3025
+	 * @param bool    $global
3026
+	 *
3027
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
3028
+	 *                               encountering problems.
3029
+	 * @throws EE_Error
3030
+	 */
3031
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3032
+	{
3033
+
3034
+		// if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3035
+		// just don't generate any templates.
3036
+		if (empty($message_types)) {
3037
+			return true;
3038
+		}
3039
+
3040
+		return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3041
+	}
3042
+
3043
+
3044
+	/**
3045
+	 * [_trash_or_restore_message_template]
3046
+	 *
3047
+	 * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3048
+	 * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3049
+	 *                        an individual context (FALSE).
3050
+	 * @return void
3051
+	 * @throws EE_Error
3052
+	 * @throws InvalidArgumentException
3053
+	 * @throws InvalidDataTypeException
3054
+	 * @throws InvalidInterfaceException
3055
+	 */
3056
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
3057
+	{
3058
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3059
+		$MTP = EEM_Message_Template_Group::instance();
3060
+
3061
+		$success = 1;
3062
+
3063
+		// incoming GRP_IDs
3064
+		if ($all) {
3065
+			// Checkboxes
3066
+			if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3067
+				// if array has more than one element then success message should be plural.
3068
+				// todo: what about nonce?
3069
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3070
+
3071
+				// cycle through checkboxes
3072
+				while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3073
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3074
+					if (! $trashed_or_restored) {
3075
+						$success = 0;
3076
+					}
3077
+				}
3078
+			} else {
3079
+				// grab single GRP_ID and handle
3080
+				$GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3081
+				if (! empty($GRP_ID)) {
3082
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3083
+					if (! $trashed_or_restored) {
3084
+						$success = 0;
3085
+					}
3086
+				} else {
3087
+					$success = 0;
3088
+				}
3089
+			}
3090
+		}
3091
+
3092
+		$action_desc = $trash
3093
+			? esc_html__('moved to the trash', 'event_espresso')
3094
+			: esc_html__('restored', 'event_espresso');
3095
+
3096
+		$action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3097
+
3098
+		$item_desc = $all ? _n(
3099
+			'Message Template Group',
3100
+			'Message Template Groups',
3101
+			$success,
3102
+			'event_espresso'
3103
+		) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3104
+
3105
+		$item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3106
+			'template',
3107
+			'templates',
3108
+			$success,
3109
+			'event_espresso'
3110
+		) : $item_desc;
3111
+
3112
+		$this->_redirect_after_action($success, $item_desc, $action_desc, array());
3113
+	}
3114
+
3115
+
3116
+	/**
3117
+	 * [_delete_message_template]
3118
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3119
+	 *
3120
+	 * @return void
3121
+	 * @throws EE_Error
3122
+	 * @throws InvalidArgumentException
3123
+	 * @throws InvalidDataTypeException
3124
+	 * @throws InvalidInterfaceException
3125
+	 */
3126
+	protected function _delete_message_template()
3127
+	{
3128
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3129
+
3130
+		// checkboxes
3131
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3132
+			// if array has more than one element then success message should be plural
3133
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3134
+
3135
+			// cycle through bulk action checkboxes
3136
+			while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3137
+				$success = $this->_delete_mtp_permanently($GRP_ID);
3138
+			}
3139
+		} else {
3140
+			// grab single grp_id and delete
3141
+			$GRP_ID = absint($this->_req_data['id']);
3142
+			$success = $this->_delete_mtp_permanently($GRP_ID);
3143
+		}
3144
+
3145
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3146
+	}
3147
+
3148
+
3149
+	/**
3150
+	 * helper for permanently deleting a mtP group and all related message_templates
3151
+	 *
3152
+	 * @param  int  $GRP_ID        The group being deleted
3153
+	 * @param  bool $include_group whether to delete the Message Template Group as well.
3154
+	 * @return bool boolean to indicate the success of the deletes or not.
3155
+	 * @throws EE_Error
3156
+	 * @throws InvalidArgumentException
3157
+	 * @throws InvalidDataTypeException
3158
+	 * @throws InvalidInterfaceException
3159
+	 */
3160
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3161
+	{
3162
+		$success = 1;
3163
+		$MTPG = EEM_Message_Template_Group::instance();
3164
+		// first let's GET this group
3165
+		$MTG = $MTPG->get_one_by_ID($GRP_ID);
3166
+		// then delete permanently all the related Message Templates
3167
+		$deleted = $MTG->delete_related_permanently('Message_Template');
3168
+
3169
+		if ($deleted === 0) {
3170
+			$success = 0;
3171
+		}
3172
+
3173
+		// now delete permanently this particular group
3174
+
3175
+		if ($include_group && ! $MTG->delete_permanently()) {
3176
+			$success = 0;
3177
+		}
3178
+
3179
+		return $success;
3180
+	}
3181
+
3182
+
3183
+	/**
3184
+	 *    _learn_more_about_message_templates_link
3185
+	 *
3186
+	 * @access protected
3187
+	 * @return string
3188
+	 */
3189
+	protected function _learn_more_about_message_templates_link()
3190
+	{
3191
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3192
+			   . esc_html__('learn more about how message templates works', 'event_espresso')
3193
+			   . '</a>';
3194
+	}
3195
+
3196
+
3197
+	/**
3198
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3199
+	 * ajax and other routes.
3200
+	 *
3201
+	 * @return void
3202
+	 * @throws DomainException
3203
+	 */
3204
+	protected function _settings()
3205
+	{
3206
+
3207
+
3208
+		$this->_set_m_mt_settings();
3209
+
3210
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3211
+			? $this->_req_data['selected_messenger']
3212
+			: 'email';
3213
+
3214
+		// let's setup the messenger tabs
3215
+		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3216
+			$this->_m_mt_settings['messenger_tabs'],
3217
+			'messenger_links',
3218
+			'|',
3219
+			$selected_messenger
3220
+		);
3221
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3222
+		$this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3223
+
3224
+		$this->display_admin_page_with_sidebar();
3225
+	}
3226
+
3227
+
3228
+	/**
3229
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3230
+	 *
3231
+	 * @access protected
3232
+	 * @return void
3233
+	 * @throws DomainException
3234
+	 */
3235
+	protected function _set_m_mt_settings()
3236
+	{
3237
+		// first if this is already set then lets get out no need to regenerate data.
3238
+		if (! empty($this->_m_mt_settings)) {
3239
+			return;
3240
+		}
3241
+
3242
+		// get all installed messengers and message_types
3243
+		/** @type EE_messenger[] $messengers */
3244
+		$messengers = $this->_message_resource_manager->installed_messengers();
3245
+		/** @type EE_message_type[] $message_types */
3246
+		$message_types = $this->_message_resource_manager->installed_message_types();
3247
+
3248
+
3249
+		// assemble the array for the _tab_text_links helper
3250
+
3251
+		foreach ($messengers as $messenger) {
3252
+			$this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3253
+				'label' => ucwords($messenger->label['singular']),
3254
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3255
+					? 'messenger-active'
3256
+					: '',
3257
+				'href'  => $messenger->name,
3258
+				'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3259
+				'slug'  => $messenger->name,
3260
+				'obj'   => $messenger,
3261
+			);
3262
+
3263
+
3264
+			$message_types_for_messenger = $messenger->get_valid_message_types();
3265
+
3266
+			foreach ($message_types as $message_type) {
3267
+				// first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3268
+				// it shouldn't show in either the inactive OR active metabox.
3269
+				if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3270
+					continue;
3271
+				}
3272
+
3273
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3274
+					$messenger->name,
3275
+					$message_type->name
3276
+				)
3277
+					? 'active'
3278
+					: 'inactive';
3279
+
3280
+				$this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3281
+					'label'    => ucwords($message_type->label['singular']),
3282
+					'class'    => 'message-type-' . $a_or_i,
3283
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3284
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3285
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3286
+					'title'    => $a_or_i === 'active'
3287
+						? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3288
+						: esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3289
+					'content'  => $a_or_i === 'active'
3290
+						? $this->_message_type_settings_content($message_type, $messenger, true)
3291
+						: $this->_message_type_settings_content($message_type, $messenger),
3292
+					'slug'     => $message_type->name,
3293
+					'active'   => $a_or_i === 'active',
3294
+					'obj'      => $message_type,
3295
+				);
3296
+			}
3297
+		}
3298
+	}
3299
+
3300
+
3301
+	/**
3302
+	 * This just prepares the content for the message type settings
3303
+	 *
3304
+	 * @param  EE_message_type $message_type The message type object
3305
+	 * @param  EE_messenger    $messenger    The messenger object
3306
+	 * @param  boolean         $active       Whether the message type is active or not
3307
+	 * @return string html output for the content
3308
+	 * @throws DomainException
3309
+	 */
3310
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
3311
+	{
3312
+		// get message type fields
3313
+		$fields = $message_type->get_admin_settings_fields();
3314
+		$settings_template_args['template_form_fields'] = '';
3315
+
3316
+		if (! empty($fields) && $active) {
3317
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3318
+			foreach ($fields as $fldname => $fldprops) {
3319
+				$field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3320
+				$template_form_field[ $field_id ] = array(
3321
+					'name'       => 'message_type_settings[' . $fldname . ']',
3322
+					'label'      => $fldprops['label'],
3323
+					'input'      => $fldprops['field_type'],
3324
+					'type'       => $fldprops['value_type'],
3325
+					'required'   => $fldprops['required'],
3326
+					'validation' => $fldprops['validation'],
3327
+					'value'      => isset($existing_settings[ $fldname ])
3328
+						? $existing_settings[ $fldname ]
3329
+						: $fldprops['default'],
3330
+					'options'    => isset($fldprops['options'])
3331
+						? $fldprops['options']
3332
+						: array(),
3333
+					'default'    => isset($existing_settings[ $fldname ])
3334
+						? $existing_settings[ $fldname ]
3335
+						: $fldprops['default'],
3336
+					'css_class'  => 'no-drag',
3337
+					'format'     => $fldprops['format'],
3338
+				);
3339
+			}
3340
+
3341
+
3342
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3343
+				? $this->_generate_admin_form_fields(
3344
+					$template_form_field,
3345
+					'string',
3346
+					'ee_mt_activate_form'
3347
+				)
3348
+				: '';
3349
+		}
3350
+
3351
+		$settings_template_args['description'] = $message_type->description;
3352
+		// we also need some hidden fields
3353
+		$settings_template_args['hidden_fields'] = array(
3354
+			'message_type_settings[messenger]'    => array(
3355
+				'type'  => 'hidden',
3356
+				'value' => $messenger->name,
3357
+			),
3358
+			'message_type_settings[message_type]' => array(
3359
+				'type'  => 'hidden',
3360
+				'value' => $message_type->name,
3361
+			),
3362
+			'type'                                => array(
3363
+				'type'  => 'hidden',
3364
+				'value' => 'message_type',
3365
+			),
3366
+		);
3367
+
3368
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3369
+			$settings_template_args['hidden_fields'],
3370
+			'array'
3371
+		);
3372
+		$settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3373
+			? ' hidden'
3374
+			: '';
3375
+
3376
+
3377
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3378
+		$content = EEH_Template::display_template($template, $settings_template_args, true);
3379
+
3380
+		return $content;
3381
+	}
3382
+
3383
+
3384
+	/**
3385
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
3386
+	 *
3387
+	 * @access protected
3388
+	 * @return void
3389
+	 * @throws DomainException
3390
+	 */
3391
+	protected function _messages_settings_metaboxes()
3392
+	{
3393
+		$this->_set_m_mt_settings();
3394
+		$m_boxes = $mt_boxes = array();
3395
+		$m_template_args = $mt_template_args = array();
3396
+
3397
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3398
+			? $this->_req_data['selected_messenger']
3399
+			: 'email';
3400
+
3401
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
3402
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3403
+				$hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3404
+				$hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3405
+				// messenger meta boxes
3406
+				$active = $selected_messenger === $messenger;
3407
+				$active_mt_tabs = isset(
3408
+					$this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3409
+				)
3410
+					? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3411
+					: '';
3412
+				$m_boxes[ $messenger . '_a_box' ] = sprintf(
3413
+					esc_html__('%s Settings', 'event_espresso'),
3414
+					$tab_array['label']
3415
+				);
3416
+				$m_template_args[ $messenger . '_a_box' ] = array(
3417
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3418
+					'inactive_message_types' => isset(
3419
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3420
+					)
3421
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3422
+						: '',
3423
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3424
+					'hidden'                 => $active ? '' : ' hidden',
3425
+					'hide_on_message'        => $hide_on_message,
3426
+					'messenger'              => $messenger,
3427
+					'active'                 => $active,
3428
+				);
3429
+				// message type meta boxes
3430
+				// (which is really just the inactive container for each messenger
3431
+				// showing inactive message types for that messenger)
3432
+				$mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3433
+				$mt_template_args[ $messenger . '_i_box' ] = array(
3434
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3435
+					'inactive_message_types' => isset(
3436
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3437
+					)
3438
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3439
+						: '',
3440
+					'hidden'                 => $active ? '' : ' hidden',
3441
+					'hide_on_message'        => $hide_on_message,
3442
+					'hide_off_message'       => $hide_off_message,
3443
+					'messenger'              => $messenger,
3444
+					'active'                 => $active,
3445
+				);
3446
+			}
3447
+		}
3448
+
3449
+
3450
+		// register messenger metaboxes
3451
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3452
+		foreach ($m_boxes as $box => $label) {
3453
+			$callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3454
+			$msgr = str_replace('_a_box', '', $box);
3455
+			add_meta_box(
3456
+				'espresso_' . $msgr . '_settings',
3457
+				$label,
3458
+				function ($post, $metabox) {
3459
+					echo EEH_Template::display_template(
3460
+						$metabox["args"]["template_path"],
3461
+						$metabox["args"]["template_args"],
3462
+						true
3463
+					);
3464
+				},
3465
+				$this->_current_screen->id,
3466
+				'normal',
3467
+				'high',
3468
+				$callback_args
3469
+			);
3470
+		}
3471
+
3472
+		// register message type metaboxes
3473
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3474
+		foreach ($mt_boxes as $box => $label) {
3475
+			$callback_args = array(
3476
+				'template_path' => $mt_template_path,
3477
+				'template_args' => $mt_template_args[ $box ],
3478
+			);
3479
+			$mt = str_replace('_i_box', '', $box);
3480
+			add_meta_box(
3481
+				'espresso_' . $mt . '_inactive_mts',
3482
+				$label,
3483
+				function ($post, $metabox) {
3484
+					echo EEH_Template::display_template(
3485
+						$metabox["args"]["template_path"],
3486
+						$metabox["args"]["template_args"],
3487
+						true
3488
+					);
3489
+				},
3490
+				$this->_current_screen->id,
3491
+				'side',
3492
+				'high',
3493
+				$callback_args
3494
+			);
3495
+		}
3496
+
3497
+		// register metabox for global messages settings but only when on the main site.  On single site installs this
3498
+		// will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3499
+		if (is_main_site()) {
3500
+			add_meta_box(
3501
+				'espresso_global_message_settings',
3502
+				esc_html__('Global Message Settings', 'event_espresso'),
3503
+				array($this, 'global_messages_settings_metabox_content'),
3504
+				$this->_current_screen->id,
3505
+				'normal',
3506
+				'low',
3507
+				array()
3508
+			);
3509
+		}
3510
+	}
3511
+
3512
+
3513
+	/**
3514
+	 *  This generates the content for the global messages settings metabox.
3515
+	 *
3516
+	 * @return string
3517
+	 * @throws EE_Error
3518
+	 * @throws InvalidArgumentException
3519
+	 * @throws ReflectionException
3520
+	 * @throws InvalidDataTypeException
3521
+	 * @throws InvalidInterfaceException
3522
+	 */
3523
+	public function global_messages_settings_metabox_content()
3524
+	{
3525
+		$form = $this->_generate_global_settings_form();
3526
+		echo $form->form_open(
3527
+			$this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3528
+			'POST'
3529
+		)
3530
+			 . $form->get_html()
3531
+			 . $form->form_close();
3532
+	}
3533
+
3534
+
3535
+	/**
3536
+	 * This generates and returns the form object for the global messages settings.
3537
+	 *
3538
+	 * @return EE_Form_Section_Proper
3539
+	 * @throws EE_Error
3540
+	 * @throws InvalidArgumentException
3541
+	 * @throws ReflectionException
3542
+	 * @throws InvalidDataTypeException
3543
+	 * @throws InvalidInterfaceException
3544
+	 */
3545
+	protected function _generate_global_settings_form()
3546
+	{
3547
+		EE_Registry::instance()->load_helper('HTML');
3548
+		/** @var EE_Network_Core_Config $network_config */
3549
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3550
+
3551
+		return new EE_Form_Section_Proper(
3552
+			array(
3553
+				'name'            => 'global_messages_settings',
3554
+				'html_id'         => 'global_messages_settings',
3555
+				'html_class'      => 'form-table',
3556
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3557
+				'subsections'     => apply_filters(
3558
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3559
+					array(
3560
+						'do_messages_on_same_request' => new EE_Select_Input(
3561
+							array(
3562
+								true  => esc_html__("On the same request", "event_espresso"),
3563
+								false => esc_html__("On a separate request", "event_espresso"),
3564
+							),
3565
+							array(
3566
+								'default'         => $network_config->do_messages_on_same_request,
3567
+								'html_label_text' => esc_html__(
3568
+									'Generate and send all messages:',
3569
+									'event_espresso'
3570
+								),
3571
+								'html_help_text'  => esc_html__(
3572
+									'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.',
3573
+									'event_espresso'
3574
+								),
3575
+							)
3576
+						),
3577
+						'delete_threshold'            => new EE_Select_Input(
3578
+							array(
3579
+								0  => esc_html__('Forever', 'event_espresso'),
3580
+								3  => esc_html__('3 Months', 'event_espresso'),
3581
+								6  => esc_html__('6 Months', 'event_espresso'),
3582
+								9  => esc_html__('9 Months', 'event_espresso'),
3583
+								12 => esc_html__('12 Months', 'event_espresso'),
3584
+								24 => esc_html__('24 Months', 'event_espresso'),
3585
+								36 => esc_html__('36 Months', 'event_espresso'),
3586
+							),
3587
+							array(
3588
+								'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3589
+								'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3590
+								'html_help_text'  => esc_html__(
3591
+									'You can control how long a record of processed messages is kept via this option.',
3592
+									'event_espresso'
3593
+								),
3594
+							)
3595
+						),
3596
+						'update_settings'             => new EE_Submit_Input(
3597
+							array(
3598
+								'default'         => esc_html__('Update', 'event_espresso'),
3599
+								'html_label_text' => '&nbsp',
3600
+							)
3601
+						),
3602
+					)
3603
+				),
3604
+			)
3605
+		);
3606
+	}
3607
+
3608
+
3609
+	/**
3610
+	 * This handles updating the global settings set on the admin page.
3611
+	 *
3612
+	 * @throws EE_Error
3613
+	 * @throws InvalidDataTypeException
3614
+	 * @throws InvalidInterfaceException
3615
+	 * @throws InvalidArgumentException
3616
+	 * @throws ReflectionException
3617
+	 */
3618
+	protected function _update_global_settings()
3619
+	{
3620
+		/** @var EE_Network_Core_Config $network_config */
3621
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3622
+		$messages_config = EE_Registry::instance()->CFG->messages;
3623
+		$form = $this->_generate_global_settings_form();
3624
+		if ($form->was_submitted()) {
3625
+			$form->receive_form_submission();
3626
+			if ($form->is_valid()) {
3627
+				$valid_data = $form->valid_data();
3628
+				foreach ($valid_data as $property => $value) {
3629
+					$setter = 'set_' . $property;
3630
+					if (method_exists($network_config, $setter)) {
3631
+						$network_config->{$setter}($value);
3632
+					} elseif (property_exists($network_config, $property)
3633
+						&& $network_config->{$property} !== $value
3634
+					) {
3635
+						$network_config->{$property} = $value;
3636
+					} elseif (property_exists($messages_config, $property)
3637
+						&& $messages_config->{$property} !== $value
3638
+					) {
3639
+						$messages_config->{$property} = $value;
3640
+					}
3641
+				}
3642
+				// only update if the form submission was valid!
3643
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3644
+				EE_Registry::instance()->CFG->update_espresso_config();
3645
+				EE_Error::overwrite_success();
3646
+				EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3647
+			}
3648
+		}
3649
+		$this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3650
+	}
3651
+
3652
+
3653
+	/**
3654
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3655
+	 *
3656
+	 * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3657
+	 * @return string html formatted tabs
3658
+	 * @throws DomainException
3659
+	 */
3660
+	protected function _get_mt_tabs($tab_array)
3661
+	{
3662
+		$tab_array = (array) $tab_array;
3663
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3664
+		$tabs = '';
3665
+
3666
+		foreach ($tab_array as $tab) {
3667
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3668
+		}
3669
+
3670
+		return $tabs;
3671
+	}
3672
+
3673
+
3674
+	/**
3675
+	 * This prepares the content of the messenger meta box admin settings
3676
+	 *
3677
+	 * @param  EE_messenger $messenger The messenger we're setting up content for
3678
+	 * @return string html formatted content
3679
+	 * @throws DomainException
3680
+	 */
3681
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3682
+	{
3683
+
3684
+		$fields = $messenger->get_admin_settings_fields();
3685
+		$settings_template_args['template_form_fields'] = '';
3686
+
3687
+		// is $messenger active?
3688
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3689
+
3690
+
3691
+		if (! empty($fields)) {
3692
+			$existing_settings = $messenger->get_existing_admin_settings();
3693
+
3694
+			foreach ($fields as $fldname => $fldprops) {
3695
+				$field_id = $messenger->name . '-' . $fldname;
3696
+				$template_form_field[ $field_id ] = array(
3697
+					'name'       => 'messenger_settings[' . $field_id . ']',
3698
+					'label'      => $fldprops['label'],
3699
+					'input'      => $fldprops['field_type'],
3700
+					'type'       => $fldprops['value_type'],
3701
+					'required'   => $fldprops['required'],
3702
+					'validation' => $fldprops['validation'],
3703
+					'value'      => isset($existing_settings[ $field_id ])
3704
+						? $existing_settings[ $field_id ]
3705
+						: $fldprops['default'],
3706
+					'css_class'  => '',
3707
+					'format'     => $fldprops['format'],
3708
+				);
3709
+			}
3710
+
3711
+
3712
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3713
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3714
+				: '';
3715
+		}
3716
+
3717
+		// we also need some hidden fields
3718
+		$settings_template_args['hidden_fields'] = array(
3719
+			'messenger_settings[messenger]' => array(
3720
+				'type'  => 'hidden',
3721
+				'value' => $messenger->name,
3722
+			),
3723
+			'type'                          => array(
3724
+				'type'  => 'hidden',
3725
+				'value' => 'messenger',
3726
+			),
3727
+		);
3728
+
3729
+		// make sure any active message types that are existing are included in the hidden fields
3730
+		if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3731
+			foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3732
+				$settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3733
+					'type'  => 'hidden',
3734
+					'value' => $mt,
3735
+				);
3736
+			}
3737
+		}
3738
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3739
+			$settings_template_args['hidden_fields'],
3740
+			'array'
3741
+		);
3742
+		$active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3743
+
3744
+		$settings_template_args['messenger'] = $messenger->name;
3745
+		$settings_template_args['description'] = $messenger->description;
3746
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3747
+
3748
+
3749
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3750
+			$messenger->name
3751
+		)
3752
+			? $settings_template_args['show_hide_edit_form']
3753
+			: ' hidden';
3754
+
3755
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3756
+			? ' hidden'
3757
+			: $settings_template_args['show_hide_edit_form'];
3758
+
3759
+
3760
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3761
+		$settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3762
+		$settings_template_args['on_off_status'] = $active ? true : false;
3763
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3764
+		$content = EEH_Template::display_template(
3765
+			$template,
3766
+			$settings_template_args,
3767
+			true
3768
+		);
3769
+
3770
+		return $content;
3771
+	}
3772
+
3773
+
3774
+	/**
3775
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3776
+	 *
3777
+	 * @throws DomainException
3778
+	 * @throws EE_Error
3779
+	 * @throws InvalidDataTypeException
3780
+	 * @throws InvalidInterfaceException
3781
+	 * @throws InvalidArgumentException
3782
+	 * @throws ReflectionException
3783
+	 */
3784
+	public function activate_messenger_toggle()
3785
+	{
3786
+		$success = true;
3787
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3788
+		// let's check that we have required data
3789
+		if (! isset($this->_req_data['messenger'])) {
3790
+			EE_Error::add_error(
3791
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3792
+				__FILE__,
3793
+				__FUNCTION__,
3794
+				__LINE__
3795
+			);
3796
+			$success = false;
3797
+		}
3798
+
3799
+		// do a nonce check here since we're not arriving via a normal route
3800
+		$nonce = isset($this->_req_data['activate_nonce'])
3801
+			? sanitize_text_field($this->_req_data['activate_nonce'])
3802
+			: '';
3803
+		$nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3804
+
3805
+		$this->_verify_nonce($nonce, $nonce_ref);
3806
+
3807
+
3808
+		if (! isset($this->_req_data['status'])) {
3809
+			EE_Error::add_error(
3810
+				esc_html__(
3811
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3812
+					'event_espresso'
3813
+				),
3814
+				__FILE__,
3815
+				__FUNCTION__,
3816
+				__LINE__
3817
+			);
3818
+			$success = false;
3819
+		}
3820
+
3821
+		// do check to verify we have a valid status.
3822
+		$status = $this->_req_data['status'];
3823
+
3824
+		if ($status !== 'off' && $status !== 'on') {
3825
+			EE_Error::add_error(
3826
+				sprintf(
3827
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3828
+					$this->_req_data['status']
3829
+				),
3830
+				__FILE__,
3831
+				__FUNCTION__,
3832
+				__LINE__
3833
+			);
3834
+			$success = false;
3835
+		}
3836
+
3837
+		if ($success) {
3838
+			// made it here?  Stop dawdling then!!
3839
+			$success = $status === 'off'
3840
+				? $this->_deactivate_messenger($this->_req_data['messenger'])
3841
+				: $this->_activate_messenger($this->_req_data['messenger']);
3842
+		}
3843
+
3844
+		$this->_template_args['success'] = $success;
3845
+
3846
+		// no special instructions so let's just do the json return (which should automatically do all the special stuff).
3847
+		$this->_return_json();
3848
+	}
3849
+
3850
+
3851
+	/**
3852
+	 * used by ajax from the messages settings page to activate|deactivate a message type
3853
+	 *
3854
+	 * @throws DomainException
3855
+	 * @throws EE_Error
3856
+	 * @throws ReflectionException
3857
+	 * @throws InvalidDataTypeException
3858
+	 * @throws InvalidInterfaceException
3859
+	 * @throws InvalidArgumentException
3860
+	 */
3861
+	public function activate_mt_toggle()
3862
+	{
3863
+		$success = true;
3864
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3865
+
3866
+		// let's make sure we have the necessary data
3867
+		if (! isset($this->_req_data['message_type'])) {
3868
+			EE_Error::add_error(
3869
+				esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3870
+				__FILE__,
3871
+				__FUNCTION__,
3872
+				__LINE__
3873
+			);
3874
+			$success = false;
3875
+		}
3876
+
3877
+		if (! isset($this->_req_data['messenger'])) {
3878
+			EE_Error::add_error(
3879
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3880
+				__FILE__,
3881
+				__FUNCTION__,
3882
+				__LINE__
3883
+			);
3884
+			$success = false;
3885
+		}
3886
+
3887
+		if (! isset($this->_req_data['status'])) {
3888
+			EE_Error::add_error(
3889
+				esc_html__(
3890
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3891
+					'event_espresso'
3892
+				),
3893
+				__FILE__,
3894
+				__FUNCTION__,
3895
+				__LINE__
3896
+			);
3897
+			$success = false;
3898
+		}
3899
+
3900
+
3901
+		// do check to verify we have a valid status.
3902
+		$status = $this->_req_data['status'];
3903
+
3904
+		if ($status !== 'activate' && $status !== 'deactivate') {
3905
+			EE_Error::add_error(
3906
+				sprintf(
3907
+					esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3908
+					$this->_req_data['status']
3909
+				),
3910
+				__FILE__,
3911
+				__FUNCTION__,
3912
+				__LINE__
3913
+			);
3914
+			$success = false;
3915
+		}
3916
+
3917
+
3918
+		// do a nonce check here since we're not arriving via a normal route
3919
+		$nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3920
+		$nonce_ref = $this->_req_data['message_type'] . '_nonce';
3921
+
3922
+		$this->_verify_nonce($nonce, $nonce_ref);
3923
+
3924
+		if ($success) {
3925
+			// made it here? um, what are you waiting for then?
3926
+			$success = $status === 'deactivate'
3927
+				? $this->_deactivate_message_type_for_messenger(
3928
+					$this->_req_data['messenger'],
3929
+					$this->_req_data['message_type']
3930
+				)
3931
+				: $this->_activate_message_type_for_messenger(
3932
+					$this->_req_data['messenger'],
3933
+					$this->_req_data['message_type']
3934
+				);
3935
+		}
3936
+
3937
+		$this->_template_args['success'] = $success;
3938
+		$this->_return_json();
3939
+	}
3940
+
3941
+
3942
+	/**
3943
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
3944
+	 *
3945
+	 * @param string $messenger_name The name of the messenger being activated
3946
+	 * @return bool
3947
+	 * @throws DomainException
3948
+	 * @throws EE_Error
3949
+	 * @throws InvalidArgumentException
3950
+	 * @throws ReflectionException
3951
+	 * @throws InvalidDataTypeException
3952
+	 * @throws InvalidInterfaceException
3953
+	 */
3954
+	protected function _activate_messenger($messenger_name)
3955
+	{
3956
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3957
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3958
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger
3959
+			? $active_messenger->get_default_message_types()
3960
+			: array();
3961
+
3962
+		// ensure is active
3963
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3964
+
3965
+		// set response_data for reload
3966
+		foreach ($message_types_to_activate as $message_type_name) {
3967
+			/** @var EE_message_type $message_type */
3968
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3969
+			if ($this->_message_resource_manager->is_message_type_active_for_messenger(
3970
+				$messenger_name,
3971
+				$message_type_name
3972
+			)
3973
+				&& $message_type instanceof EE_message_type
3974
+			) {
3975
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
3976
+				if ($message_type->get_admin_settings_fields()) {
3977
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
3978
+				}
3979
+			}
3980
+		}
3981
+
3982
+		// add success message for activating messenger
3983
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3984
+	}
3985
+
3986
+
3987
+	/**
3988
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
3989
+	 *
3990
+	 * @param string $messenger_name The name of the messenger being activated
3991
+	 * @return bool
3992
+	 * @throws DomainException
3993
+	 * @throws EE_Error
3994
+	 * @throws InvalidArgumentException
3995
+	 * @throws ReflectionException
3996
+	 * @throws InvalidDataTypeException
3997
+	 * @throws InvalidInterfaceException
3998
+	 */
3999
+	protected function _deactivate_messenger($messenger_name)
4000
+	{
4001
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4002
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4003
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
4004
+
4005
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4006
+	}
4007
+
4008
+
4009
+	/**
4010
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4011
+	 *
4012
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
4013
+	 * @param string $message_type_name The name of the message type being activated for the messenger
4014
+	 * @return bool
4015
+	 * @throws DomainException
4016
+	 * @throws EE_Error
4017
+	 * @throws InvalidArgumentException
4018
+	 * @throws ReflectionException
4019
+	 * @throws InvalidDataTypeException
4020
+	 * @throws InvalidInterfaceException
4021
+	 */
4022
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4023
+	{
4024
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4025
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4026
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4027
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4028
+
4029
+		// ensure is active
4030
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
4031
+
4032
+		// set response for load
4033
+		if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4034
+			$messenger_name,
4035
+			$message_type_name
4036
+		)
4037
+		) {
4038
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
4039
+			if ($message_type_to_activate->get_admin_settings_fields()) {
4040
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
4041
+			}
4042
+		}
4043
+
4044
+		return $this->_setup_response_message_for_activating_messenger_with_message_types(
4045
+			$active_messenger,
4046
+			$message_type_to_activate
4047
+		);
4048
+	}
4049
+
4050
+
4051
+	/**
4052
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4053
+	 *
4054
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4055
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
4056
+	 * @return bool
4057
+	 * @throws DomainException
4058
+	 * @throws EE_Error
4059
+	 * @throws InvalidArgumentException
4060
+	 * @throws ReflectionException
4061
+	 * @throws InvalidDataTypeException
4062
+	 * @throws InvalidInterfaceException
4063
+	 */
4064
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4065
+	{
4066
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4067
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4068
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4069
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4070
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4071
+
4072
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4073
+			$active_messenger,
4074
+			$message_type_to_deactivate
4075
+		);
4076
+	}
4077
+
4078
+
4079
+	/**
4080
+	 * This just initializes the defaults for activating messenger and message type responses.
4081
+	 */
4082
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
4083
+	{
4084
+		$this->_template_args['data']['active_mts'] = array();
4085
+		$this->_template_args['data']['mt_reload'] = array();
4086
+	}
4087
+
4088
+
4089
+	/**
4090
+	 * Setup appropriate response for activating a messenger and/or message types
4091
+	 *
4092
+	 * @param EE_messenger         $messenger
4093
+	 * @param EE_message_type|null $message_type
4094
+	 * @return bool
4095
+	 * @throws DomainException
4096
+	 * @throws EE_Error
4097
+	 * @throws InvalidArgumentException
4098
+	 * @throws ReflectionException
4099
+	 * @throws InvalidDataTypeException
4100
+	 * @throws InvalidInterfaceException
4101
+	 */
4102
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
4103
+		$messenger,
4104
+		EE_Message_Type $message_type = null
4105
+	) {
4106
+		// if $messenger isn't a valid messenger object then get out.
4107
+		if (! $messenger instanceof EE_Messenger) {
4108
+			EE_Error::add_error(
4109
+				esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4110
+				__FILE__,
4111
+				__FUNCTION__,
4112
+				__LINE__
4113
+			);
4114
+
4115
+			return false;
4116
+		}
4117
+		// activated
4118
+		if ($this->_template_args['data']['active_mts']) {
4119
+			EE_Error::overwrite_success();
4120
+			// activated a message type with the messenger
4121
+			if ($message_type instanceof EE_message_type) {
4122
+				EE_Error::add_success(
4123
+					sprintf(
4124
+						esc_html__(
4125
+							'%s message type has been successfully activated with the %s messenger',
4126
+							'event_espresso'
4127
+						),
4128
+						ucwords($message_type->label['singular']),
4129
+						ucwords($messenger->label['singular'])
4130
+					)
4131
+				);
4132
+
4133
+				// if message type was invoice then let's make sure we activate the invoice payment method.
4134
+				if ($message_type->name === 'invoice') {
4135
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
4136
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4137
+					if ($pm instanceof EE_Payment_Method) {
4138
+						EE_Error::add_attention(
4139
+							esc_html__(
4140
+								'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.',
4141
+								'event_espresso'
4142
+							)
4143
+						);
4144
+					}
4145
+				}
4146
+				// just toggles the entire messenger
4147
+			} else {
4148
+				EE_Error::add_success(
4149
+					sprintf(
4150
+						esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4151
+						ucwords($messenger->label['singular'])
4152
+					)
4153
+				);
4154
+			}
4155
+
4156
+			return true;
4157
+
4158
+			// possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4159
+			// message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4160
+			// in which case we just give a success message for the messenger being successfully activated.
4161
+		} else {
4162
+			if (! $messenger->get_default_message_types()) {
4163
+				// messenger doesn't have any default message types so still a success.
4164
+				EE_Error::add_success(
4165
+					sprintf(
4166
+						esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4167
+						ucwords($messenger->label['singular'])
4168
+					)
4169
+				);
4170
+
4171
+				return true;
4172
+			} else {
4173
+				EE_Error::add_error(
4174
+					$message_type instanceof EE_message_type
4175
+						? sprintf(
4176
+							esc_html__(
4177
+								'%s message type was not successfully activated with the %s messenger',
4178
+								'event_espresso'
4179
+							),
4180
+							ucwords($message_type->label['singular']),
4181
+							ucwords($messenger->label['singular'])
4182
+						)
4183
+						: sprintf(
4184
+							esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4185
+							ucwords($messenger->label['singular'])
4186
+						),
4187
+					__FILE__,
4188
+					__FUNCTION__,
4189
+					__LINE__
4190
+				);
4191
+
4192
+				return false;
4193
+			}
4194
+		}
4195
+	}
4196
+
4197
+
4198
+	/**
4199
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
4200
+	 *
4201
+	 * @param EE_messenger         $messenger
4202
+	 * @param EE_message_type|null $message_type
4203
+	 * @return bool
4204
+	 * @throws DomainException
4205
+	 * @throws EE_Error
4206
+	 * @throws InvalidArgumentException
4207
+	 * @throws ReflectionException
4208
+	 * @throws InvalidDataTypeException
4209
+	 * @throws InvalidInterfaceException
4210
+	 */
4211
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4212
+		$messenger,
4213
+		EE_message_type $message_type = null
4214
+	) {
4215
+		EE_Error::overwrite_success();
4216
+
4217
+		// if $messenger isn't a valid messenger object then get out.
4218
+		if (! $messenger instanceof EE_Messenger) {
4219
+			EE_Error::add_error(
4220
+				esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4221
+				__FILE__,
4222
+				__FUNCTION__,
4223
+				__LINE__
4224
+			);
4225
+
4226
+			return false;
4227
+		}
4228
+
4229
+		if ($message_type instanceof EE_message_type) {
4230
+			$message_type_name = $message_type->name;
4231
+			EE_Error::add_success(
4232
+				sprintf(
4233
+					esc_html__(
4234
+						'%s message type has been successfully deactivated for the %s messenger.',
4235
+						'event_espresso'
4236
+					),
4237
+					ucwords($message_type->label['singular']),
4238
+					ucwords($messenger->label['singular'])
4239
+				)
4240
+			);
4241
+		} else {
4242
+			$message_type_name = '';
4243
+			EE_Error::add_success(
4244
+				sprintf(
4245
+					esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4246
+					ucwords($messenger->label['singular'])
4247
+				)
4248
+			);
4249
+		}
4250
+
4251
+		// if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4252
+		if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4253
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
4254
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4255
+			if ($count_updated > 0) {
4256
+				$msg = $message_type_name === 'invoice'
4257
+					? esc_html__(
4258
+						'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.',
4259
+						'event_espresso'
4260
+					)
4261
+					: esc_html__(
4262
+						'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.',
4263
+						'event_espresso'
4264
+					);
4265
+				EE_Error::add_attention($msg);
4266
+			}
4267
+		}
4268
+
4269
+		return true;
4270
+	}
4271
+
4272
+
4273
+	/**
4274
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4275
+	 *
4276
+	 * @throws DomainException
4277
+	 */
4278
+	public function update_mt_form()
4279
+	{
4280
+		if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4281
+			EE_Error::add_error(
4282
+				esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4283
+				__FILE__,
4284
+				__FUNCTION__,
4285
+				__LINE__
4286
+			);
4287
+			$this->_return_json();
4288
+		}
4289
+
4290
+		$message_types = $this->get_installed_message_types();
4291
+
4292
+		$message_type = $message_types[ $this->_req_data['message_type'] ];
4293
+		$messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4294
+
4295
+		$content = $this->_message_type_settings_content(
4296
+			$message_type,
4297
+			$messenger,
4298
+			true
4299
+		);
4300
+		$this->_template_args['success'] = true;
4301
+		$this->_template_args['content'] = $content;
4302
+		$this->_return_json();
4303
+	}
4304
+
4305
+
4306
+	/**
4307
+	 * this handles saving the settings for a messenger or message type
4308
+	 *
4309
+	 */
4310
+	public function save_settings()
4311
+	{
4312
+		if (! isset($this->_req_data['type'])) {
4313
+			EE_Error::add_error(
4314
+				esc_html__(
4315
+					'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4316
+					'event_espresso'
4317
+				),
4318
+				__FILE__,
4319
+				__FUNCTION__,
4320
+				__LINE__
4321
+			);
4322
+			$this->_template_args['error'] = true;
4323
+			$this->_return_json();
4324
+		}
4325
+
4326
+
4327
+		if ($this->_req_data['type'] === 'messenger') {
4328
+			// this should be an array.
4329
+			$settings = $this->_req_data['messenger_settings'];
4330
+			$messenger = $settings['messenger'];
4331
+			// let's setup the settings data
4332
+			foreach ($settings as $key => $value) {
4333
+				switch ($key) {
4334
+					case 'messenger':
4335
+						unset($settings['messenger']);
4336
+						break;
4337
+					case 'message_types':
4338
+						unset($settings['message_types']);
4339
+						break;
4340
+					default:
4341
+						$settings[ $key ] = $value;
4342
+						break;
4343
+				}
4344
+			}
4345
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4346
+		} elseif ($this->_req_data['type'] === 'message_type') {
4347
+			$settings = $this->_req_data['message_type_settings'];
4348
+			$messenger = $settings['messenger'];
4349
+			$message_type = $settings['message_type'];
4350
+
4351
+			foreach ($settings as $key => $value) {
4352
+				switch ($key) {
4353
+					case 'messenger':
4354
+						unset($settings['messenger']);
4355
+						break;
4356
+					case 'message_type':
4357
+						unset($settings['message_type']);
4358
+						break;
4359
+					default:
4360
+						$settings[ $key ] = $value;
4361
+						break;
4362
+				}
4363
+			}
4364
+
4365
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4366
+		}
4367
+
4368
+		// okay we should have the data all setup.  Now we just update!
4369
+		$success = $this->_message_resource_manager->update_active_messengers_option();
4370
+
4371
+		if ($success) {
4372
+			EE_Error::add_success(__('Settings updated', 'event_espresso'));
4373
+		} else {
4374
+			EE_Error::add_error(
4375
+				esc_html__(
4376
+					'Settings did not get updated',
4377
+					'event_espresso'
4378
+				),
4379
+				__FILE__,
4380
+				__FUNCTION__,
4381
+				__LINE__
4382
+			);
4383
+		}
4384
+
4385
+		$this->_template_args['success'] = $success;
4386
+		$this->_return_json();
4387
+	}
4388
+
4389
+
4390
+
4391
+
4392
+	/**  EE MESSAGE PROCESSING ACTIONS **/
4393
+
4394
+
4395
+	/**
4396
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4397
+	 * However, this does not send immediately, it just queues for sending.
4398
+	 *
4399
+	 * @since 4.9.0
4400
+	 * @throws EE_Error
4401
+	 * @throws InvalidDataTypeException
4402
+	 * @throws InvalidInterfaceException
4403
+	 * @throws InvalidArgumentException
4404
+	 * @throws ReflectionException
4405
+	 */
4406
+	protected function _generate_now()
4407
+	{
4408
+		EED_Messages::generate_now($this->_get_msg_ids_from_request());
4409
+		$this->_redirect_after_action(false, '', '', array(), true);
4410
+	}
4411
+
4412
+
4413
+	/**
4414
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4415
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
4416
+	 *
4417
+	 * @since 4.9.0
4418
+	 * @throws EE_Error
4419
+	 * @throws InvalidDataTypeException
4420
+	 * @throws InvalidInterfaceException
4421
+	 * @throws InvalidArgumentException
4422
+	 * @throws ReflectionException
4423
+	 */
4424
+	protected function _generate_and_send_now()
4425
+	{
4426
+		EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4427
+		$this->_redirect_after_action(false, '', '', array(), true);
4428
+	}
4429
+
4430
+
4431
+	/**
4432
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4433
+	 *
4434
+	 * @since 4.9.0
4435
+	 * @throws EE_Error
4436
+	 * @throws InvalidDataTypeException
4437
+	 * @throws InvalidInterfaceException
4438
+	 * @throws InvalidArgumentException
4439
+	 * @throws ReflectionException
4440
+	 */
4441
+	protected function _queue_for_resending()
4442
+	{
4443
+		EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4444
+		$this->_redirect_after_action(false, '', '', array(), true);
4445
+	}
4446
+
4447
+
4448
+	/**
4449
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4450
+	 *
4451
+	 * @since 4.9.0
4452
+	 * @throws EE_Error
4453
+	 * @throws InvalidDataTypeException
4454
+	 * @throws InvalidInterfaceException
4455
+	 * @throws InvalidArgumentException
4456
+	 * @throws ReflectionException
4457
+	 */
4458
+	protected function _send_now()
4459
+	{
4460
+		EED_Messages::send_now($this->_get_msg_ids_from_request());
4461
+		$this->_redirect_after_action(false, '', '', array(), true);
4462
+	}
4463
+
4464
+
4465
+	/**
4466
+	 * Deletes EE_messages for IDs in the request.
4467
+	 *
4468
+	 * @since 4.9.0
4469
+	 * @throws EE_Error
4470
+	 * @throws InvalidDataTypeException
4471
+	 * @throws InvalidInterfaceException
4472
+	 * @throws InvalidArgumentException
4473
+	 */
4474
+	protected function _delete_ee_messages()
4475
+	{
4476
+		$msg_ids = $this->_get_msg_ids_from_request();
4477
+		$deleted_count = 0;
4478
+		foreach ($msg_ids as $msg_id) {
4479
+			if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4480
+				$deleted_count++;
4481
+			}
4482
+		}
4483
+		if ($deleted_count) {
4484
+			EE_Error::add_success(
4485
+				esc_html(
4486
+					_n(
4487
+						'Message successfully deleted',
4488
+						'Messages successfully deleted',
4489
+						$deleted_count,
4490
+						'event_espresso'
4491
+					)
4492
+				)
4493
+			);
4494
+			$this->_redirect_after_action(
4495
+				false,
4496
+				'',
4497
+				'',
4498
+				array(),
4499
+				true
4500
+			);
4501
+		} else {
4502
+			EE_Error::add_error(
4503
+				_n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4504
+				__FILE__,
4505
+				__FUNCTION__,
4506
+				__LINE__
4507
+			);
4508
+			$this->_redirect_after_action(false, '', '', array(), true);
4509
+		}
4510
+	}
4511
+
4512
+
4513
+	/**
4514
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4515
+	 *
4516
+	 * @since 4.9.0
4517
+	 * @return array
4518
+	 */
4519
+	protected function _get_msg_ids_from_request()
4520
+	{
4521
+		if (! isset($this->_req_data['MSG_ID'])) {
4522
+			return array();
4523
+		}
4524
+
4525
+		return is_array($this->_req_data['MSG_ID'])
4526
+			? array_keys($this->_req_data['MSG_ID'])
4527
+			: array($this->_req_data['MSG_ID']);
4528
+	}
4529 4529
 }
Please login to merge, or discard this patch.
core/helpers/EEH_MSG_Template.helper.php 2 patches
Indentation   +1227 added lines, -1227 removed lines patch added patch discarded remove patch
@@ -14,1231 +14,1231 @@
 block discarded – undo
14 14
 {
15 15
 
16 16
 
17
-    /**
18
-     * Holds a collection of EE_Message_Template_Pack objects.
19
-     * @type EE_Messages_Template_Pack_Collection
20
-     */
21
-    protected static $_template_pack_collection;
22
-
23
-
24
-
25
-
26
-    private static function _set_autoloader()
27
-    {
28
-        EED_Messages::set_autoloaders();
29
-    }
30
-
31
-
32
-    /**
33
-     * generate_new_templates
34
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will automatically create the defaults for the event.  The user would then be redirected to edit the default context for the event.
35
-     *
36
-     * @access protected
37
-     * @param  string $messenger     the messenger we are generating templates for
38
-     * @param array   $message_types array of message types that the templates are generated for.
39
-     * @param int     $GRP_ID        If a non global template is being generated then it is expected we'll have a GRP_ID to use as the base for the new generated template.
40
-     * @param bool    $global        true indicates generating templates on messenger activation. false requires GRP_ID for event specific template generation.
41
-     * @throws \EE_Error
42
-     * @return array  @see EEH_MSG_Template::_create_new_templates for the return value of each element in the array for templates
43
-     *                that are generated.  If this is an empty array then it means no templates were generated which usually
44
-     *                means there was an error.  Anything in the array with an empty value for `MTP_context` means that it
45
-     *                was not a new generated template but just reactivated (which only happens for global templates that
46
-     *                already exist in the database.
47
-     */
48
-    public static function generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
49
-    {
50
-        // make sure message_type is an array.
51
-        $message_types = (array) $message_types;
52
-        $templates = array();
53
-
54
-        if (empty($messenger)) {
55
-            throw new EE_Error(__('We need a messenger to generate templates!', 'event_espresso'));
56
-        }
57
-
58
-        // if we STILL have empty $message_types then we need to generate an error message b/c we NEED message types to do the template files.
59
-        if (empty($message_types)) {
60
-            throw new EE_Error(__('We need at least one message type to generate templates!', 'event_espresso'));
61
-        }
62
-
63
-        EEH_MSG_Template::_set_autoloader();
64
-        foreach ($message_types as $message_type) {
65
-            // if global then let's attempt to get the GRP_ID for this combo IF GRP_ID is empty.
66
-            if ($global && empty($GRP_ID)) {
67
-                $GRP_ID = EEM_Message_Template_Group::instance()->get_one(
68
-                    array(
69
-                        array(
70
-                            'MTP_messenger'    => $messenger,
71
-                            'MTP_message_type' => $message_type,
72
-                            'MTP_is_global'    => true,
73
-                        ),
74
-                    )
75
-                );
76
-                $GRP_ID = $GRP_ID instanceof EE_Message_Template_Group ? $GRP_ID->ID() : 0;
77
-            }
78
-            // if this is global template generation.
79
-            // First let's determine if we already HAVE global templates for this messenger and message_type combination.
80
-            //  If we do then NO generation!!
81
-            if ($global && EEH_MSG_Template::already_generated($messenger, $message_type, $GRP_ID)) {
82
-                $templates[] = array(
83
-                    'GRP_ID' => $GRP_ID,
84
-                    'MTP_context' => '',
85
-                );
86
-                // we already have generated templates for this so let's go to the next message type.
87
-                continue;
88
-            }
89
-            $new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
90
-
91
-            if (! $new_message_template_group) {
92
-                continue;
93
-            }
94
-            $templates[] = $new_message_template_group;
95
-        }
96
-
97
-        return $templates;
98
-    }
99
-
100
-
101
-    /**
102
-     * The purpose of this method is to determine if there are already generated templates in the database for the given variables.
103
-     * @param  string $messenger     messenger
104
-     * @param  string $message_type message type
105
-     * @param  int $GRP_ID        GRP ID ( if a custom template) (if not provided then we're just doing global template check)
106
-     * @return bool                true = generated, false = hasn't been generated.
107
-     */
108
-    public static function already_generated($messenger, $message_type, $GRP_ID = 0)
109
-    {
110
-        EEH_MSG_Template::_set_autoloader();
111
-        // what method we use depends on whether we have an GRP_ID or not
112
-        $count = empty($GRP_ID)
113
-            ? EEM_Message_Template::instance()->count(
114
-                array(
115
-                    array(
116
-                        'Message_Template_Group.MTP_messenger'    => $messenger,
117
-                        'Message_Template_Group.MTP_message_type' => $message_type,
118
-                        'Message_Template_Group.MTP_is_global'    => true
119
-                    )
120
-                )
121
-            )
122
-            : EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
123
-
124
-        return $count > 0;
125
-    }
126
-
127
-
128
-
129
-
130
-    /**
131
-     * Updates all message templates matching the incoming messengers and message types to active status.
132
-     *
133
-     * @static
134
-     * @param  array  $messenger_names     Messenger slug
135
-     * @param  array  $message_type_names  Message type slug
136
-     * @return  int                         count of updated records.
137
-     */
138
-    public static function update_to_active($messenger_names, $message_type_names)
139
-    {
140
-        $messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
141
-        $message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
142
-        return EEM_Message_Template_Group::instance()->update(
143
-            array( 'MTP_is_active' => 1 ),
144
-            array(
145
-                array(
146
-                    'MTP_messenger'     => array( 'IN', $messenger_names ),
147
-                    'MTP_message_type'  => array( 'IN', $message_type_names )
148
-                )
149
-            )
150
-        );
151
-    }
152
-
153
-
154
-
155
-    /**
156
-     * Updates all message template groups matching the incoming arguments to inactive status.
157
-     *
158
-     * @static
159
-     * @param array $messenger_names    The messenger slugs.
160
-     *                              If empty then all templates matching the message types are marked inactive.
161
-     *                              Otherwise only templates matching the messengers and message types.
162
-     * @param array $message_type_names     The message type slugs.
163
-     *                              If empty then all templates matching the messengers are marked inactive.
164
-     *                              Otherwise only templates matching the messengers and message types.
165
-     *
166
-     * @return int  count of updated records.
167
-     */
168
-    public static function update_to_inactive($messenger_names = array(), $message_type_names = array())
169
-    {
170
-        return EEM_Message_Template_Group::instance()->deactivate_message_template_groups_for(
171
-            $messenger_names,
172
-            $message_type_names
173
-        );
174
-    }
175
-
176
-
177
-    /**
178
-     * The purpose of this function is to return all installed message objects
179
-     * (messengers and message type regardless of whether they are ACTIVE or not)
180
-     *
181
-     * @deprecated 4.9.0
182
-     * @static
183
-     * @param string $type
184
-     * @return array array consisting of installed messenger objects and installed message type objects.
185
-     */
186
-    public static function get_installed_message_objects($type = 'all')
187
-    {
188
-        self::_set_autoloader();
189
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
190
-        return array(
191
-            'messenger' => $message_resource_manager->installed_messengers(),
192
-            'message_type' => $message_resource_manager->installed_message_types()
193
-        );
194
-    }
195
-
196
-
197
-    /**
198
-     * This will return an array of shortcodes => labels from the
199
-     * messenger and message_type objects associated with this
200
-     * template.
201
-     *
202
-     * @since 4.3.0
203
-     *
204
-     * @param string $message_type
205
-     * @param string $messenger
206
-     * @param array  $fields    What fields we're returning valid shortcodes for.
207
-     *                          If empty then we assume all fields are to be returned. Optional.
208
-     * @param string $context   What context we're going to return shortcodes for. Optional.
209
-     * @param bool $merged      If TRUE then we don't return shortcodes indexed by field,
210
-     *                          but instead an array of the unique shortcodes for all the given ( or all) fields.
211
-     *                          Optional.
212
-     * @throws \EE_Error
213
-     * @return mixed (array|bool) an array of shortcodes in the format
214
-     *                                              array( '[shortcode] => 'label')
215
-     *                                              OR
216
-     *                                              FALSE if no shortcodes found.
217
-     */
218
-    public static function get_shortcodes(
219
-        $message_type,
220
-        $messenger,
221
-        $fields = array(),
222
-        $context = 'admin',
223
-        $merged = false
224
-    ) {
225
-        $messenger_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger)));
226
-        $mt_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type)));
227
-        /** @var EE_Message_Resource_Manager $message_resource_manager */
228
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
229
-        // convert slug to object
230
-        $messenger = $message_resource_manager->get_messenger($messenger);
231
-
232
-        // if messenger isn't a EE_messenger resource then bail.
233
-        if (! $messenger instanceof EE_messenger) {
234
-            return array();
235
-        }
236
-
237
-        // validate class for getting our list of shortcodes
238
-        $classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
239
-        if (! class_exists($classname)) {
240
-            $msg[] = __('The Validator class was unable to load', 'event_espresso');
241
-            $msg[] = sprintf(
242
-                __('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
243
-                $classname
244
-            );
245
-            throw new EE_Error(implode('||', $msg));
246
-        }
247
-
248
-        /** @type EE_Messages_Validator $_VLD */
249
-        $_VLD = new $classname(array(), $context);
250
-        $valid_shortcodes = $_VLD->get_validators();
251
-
252
-        // let's make sure we're only getting the shortcode part of the validators
253
-        $shortcodes = array();
254
-        foreach ($valid_shortcodes as $field => $validators) {
255
-            $shortcodes[ $field ] = $validators['shortcodes'];
256
-        }
257
-        $valid_shortcodes = $shortcodes;
258
-
259
-        // if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
260
-        if (! empty($fields)) {
261
-            $specified_shortcodes = array();
262
-            foreach ($fields as $field) {
263
-                if (isset($valid_shortcodes[ $field ])) {
264
-                    $specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
265
-                }
266
-            }
267
-            $valid_shortcodes = $specified_shortcodes;
268
-        }
269
-
270
-        // if not merged then let's replace the fields with the localized fields
271
-        if (! $merged) {
272
-            // let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
273
-            $field_settings = $messenger->get_template_fields();
274
-            $localized = array();
275
-            foreach ($valid_shortcodes as $field => $shortcodes) {
276
-                // get localized field label
277
-                if (isset($field_settings[ $field ])) {
278
-                    // possible that this is used as a main field.
279
-                    if (empty($field_settings[ $field ])) {
280
-                        if (isset($field_settings['extra'][ $field ])) {
281
-                            $_field = $field_settings['extra'][ $field ]['main']['label'];
282
-                        } else {
283
-                            $_field = $field;
284
-                        }
285
-                    } else {
286
-                        $_field = $field_settings[ $field ]['label'];
287
-                    }
288
-                } elseif (isset($field_settings['extra'])) {
289
-                    // loop through extra "main fields" and see if any of their children have our field
290
-                    foreach ($field_settings['extra'] as $main_field => $fields) {
291
-                        if (isset($fields[ $field ])) {
292
-                            $_field = $fields[ $field ]['label'];
293
-                        } else {
294
-                            $_field = $field;
295
-                        }
296
-                    }
297
-                } else {
298
-                    $_field = $field;
299
-                }
300
-                if (isset($_field)) {
301
-                    $localized[ (string) $_field ] = $shortcodes;
302
-                }
303
-            }
304
-            $valid_shortcodes = $localized;
305
-        }
306
-
307
-        // if $merged then let's merge all the shortcodes into one list NOT indexed by field.
308
-        if ($merged) {
309
-            $merged_codes = array();
310
-            foreach ($valid_shortcodes as $field => $shortcode) {
311
-                foreach ($shortcode as $code => $label) {
312
-                    if (isset($merged_codes[ $code ])) {
313
-                        continue;
314
-                    } else {
315
-                        $merged_codes[ $code ] = $label;
316
-                    }
317
-                }
318
-            }
319
-            $valid_shortcodes = $merged_codes;
320
-        }
321
-
322
-        return $valid_shortcodes;
323
-    }
324
-
325
-
326
-    /**
327
-     * Get Messenger object.
328
-     *
329
-     * @since 4.3.0
330
-     * @deprecated 4.9.0
331
-     * @param string $messenger messenger slug for the messenger object we want to retrieve.
332
-     * @throws \EE_Error
333
-     * @return EE_messenger
334
-     */
335
-    public static function messenger_obj($messenger)
336
-    {
337
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
338
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
339
-        return $Message_Resource_Manager->get_messenger($messenger);
340
-    }
341
-
342
-
343
-    /**
344
-     * get Message type object
345
-     *
346
-     * @since 4.3.0
347
-     * @deprecated 4.9.0
348
-     * @param string $message_type the slug for the message type object to retrieve
349
-     * @throws \EE_Error
350
-     * @return EE_message_type
351
-     */
352
-    public static function message_type_obj($message_type)
353
-    {
354
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
355
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
356
-        return $Message_Resource_Manager->get_message_type($message_type);
357
-    }
358
-
359
-
360
-
361
-
362
-
363
-    /**
364
-     * Given a message_type slug, will return whether that message type is active in the system or not.
365
-     *
366
-     * @since    4.3.0
367
-     * @param  string   $message_type message type to check for.
368
-     * @return boolean
369
-     */
370
-    public static function is_mt_active($message_type)
371
-    {
372
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
373
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
374
-        $active_mts = $Message_Resource_Manager->list_of_active_message_types();
375
-        return in_array($message_type, $active_mts);
376
-    }
377
-
378
-
379
-
380
-    /**
381
-     * Given a messenger slug, will return whether that messenger is active in the system or not.
382
-     *
383
-     * @since    4.3.0
384
-     *
385
-     * @param  string  $messenger slug for messenger to check.
386
-     * @return boolean
387
-     */
388
-    public static function is_messenger_active($messenger)
389
-    {
390
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
391
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
392
-        $active_messenger = $Message_Resource_Manager->get_active_messenger($messenger);
393
-        return $active_messenger instanceof EE_messenger ? true : false;
394
-    }
395
-
396
-
397
-
398
-    /**
399
-     * Used to return active messengers array stored in the wp options table.
400
-     * If no value is present in the option then an empty array is returned.
401
-     *
402
-     * @deprecated 4.9
403
-     * @since 4.3.1
404
-     *
405
-     * @return array
406
-     */
407
-    public static function get_active_messengers_in_db()
408
-    {
409
-        EE_Error::doing_it_wrong(
410
-            __METHOD__,
411
-            __('Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso'),
412
-            '4.9.0'
413
-        );
414
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
415
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
416
-        return $Message_Resource_Manager->get_active_messengers_option();
417
-    }
418
-
419
-
420
-
421
-
422
-    /**
423
-     * Used to update the active messengers array stored in the wp options table.
424
-     *
425
-     * @since 4.3.1
426
-     * @deprecated 4.9.0
427
-     *
428
-     * @param array $data_to_save Incoming data to save.
429
-     *
430
-     * @return bool FALSE if not updated, TRUE if updated.
431
-     */
432
-    public static function update_active_messengers_in_db($data_to_save)
433
-    {
434
-        EE_Error::doing_it_wrong(
435
-            __METHOD__,
436
-            __('Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso'),
437
-            '4.9.0'
438
-        );
439
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
440
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
441
-        return $Message_Resource_Manager->update_active_messengers_option($data_to_save);
442
-    }
443
-
444
-
445
-    /**
446
-     * This does some validation of incoming params, determines what type of url is being prepped and returns the
447
-     * appropriate url trigger
448
-     *
449
-     * @param EE_message_type $message_type
450
-     * @param EE_Message $message
451
-     * @param EE_Registration | null $registration  The registration object must be included if this
452
-     *                                              is going to be a registration trigger url.
453
-     * @param string $sending_messenger             The (optional) sending messenger for the url.
454
-     *
455
-     * @return string
456
-     * @throws EE_Error
457
-     */
458
-    public static function get_url_trigger(
459
-        EE_message_type $message_type,
460
-        EE_Message $message,
461
-        $registration = null,
462
-        $sending_messenger = ''
463
-    ) {
464
-        // first determine if the url can be to the EE_Message object.
465
-        if (! $message_type->always_generate()) {
466
-            return EEH_MSG_Template::generate_browser_trigger($message);
467
-        }
468
-
469
-        // if $registration object is not valid then exit early because there's nothing that can be generated.
470
-        if (! $registration instanceof EE_Registration) {
471
-            throw new EE_Error(
472
-                __('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
473
-            );
474
-        }
475
-
476
-        // validate given context
477
-        $contexts = $message_type->get_contexts();
478
-        if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
479
-            throw new EE_Error(
480
-                sprintf(
481
-                    __('The context %s is not a valid context for %s.', 'event_espresso'),
482
-                    $message->context(),
483
-                    get_class($message_type)
484
-                )
485
-            );
486
-        }
487
-
488
-        // valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
489
-        if (! empty($sending_messenger)) {
490
-            $with_messengers = $message_type->with_messengers();
491
-            if (! isset($with_messengers[ $message->messenger() ])
492
-                 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ]) ) {
493
-                throw new EE_Error(
494
-                    sprintf(
495
-                        __(
496
-                            'The given sending messenger string (%1$s) does not match a valid sending messenger with the %2$s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
497
-                            'event_espresso'
498
-                        ),
499
-                        $sending_messenger,
500
-                        get_class($message_type)
501
-                    )
502
-                );
503
-            }
504
-        } else {
505
-            $sending_messenger = $message->messenger();
506
-        }
507
-        return EEH_MSG_Template::generate_url_trigger(
508
-            $sending_messenger,
509
-            $message->messenger(),
510
-            $message->context(),
511
-            $message->message_type(),
512
-            $registration,
513
-            $message->GRP_ID()
514
-        );
515
-    }
516
-
517
-
518
-    /**
519
-     * This returns the url for triggering a in browser view of a specific EE_Message object.
520
-     * @param EE_Message $message
521
-     * @return string.
522
-     */
523
-    public static function generate_browser_trigger(EE_Message $message)
524
-    {
525
-        $query_args = array(
526
-            'ee' => 'msg_browser_trigger',
527
-            'token' => $message->MSG_token()
528
-        );
529
-        return apply_filters(
530
-            'FHEE__EEH_MSG_Template__generate_browser_trigger',
531
-            add_query_arg($query_args, site_url()),
532
-            $message
533
-        );
534
-    }
535
-
536
-
537
-
538
-
539
-
540
-
541
-    /**
542
-     * This returns the url for triggering an in browser view of the error saved on the incoming message object.
543
-     * @param EE_Message $message
544
-     * @return string
545
-     */
546
-    public static function generate_error_display_trigger(EE_Message $message)
547
-    {
548
-        return apply_filters(
549
-            'FHEE__EEH_MSG_Template__generate_error_display_trigger',
550
-            add_query_arg(
551
-                array(
552
-                    'ee' => 'msg_browser_error_trigger',
553
-                    'token' => $message->MSG_token()
554
-                ),
555
-                site_url()
556
-            ),
557
-            $message
558
-        );
559
-    }
560
-
561
-
562
-
563
-
564
-
565
-
566
-    /**
567
-     * This generates a url trigger for the msg_url_trigger route using the given arguments
568
-     *
569
-     * @param string          $sending_messenger    The sending messenger slug.
570
-     * @param string          $generating_messenger The generating messenger slug.
571
-     * @param string          $context              The context for the template.
572
-     * @param string          $message_type         The message type slug
573
-     * @param EE_Registration $registration
574
-     * @param integer          $message_template_group id   The EE_Message_Template_Group ID for the template.
575
-     * @param integer          $data_id     The id to the EE_Base_Class for getting the data used by the trigger.
576
-     * @return string          The generated url.
577
-     */
578
-    public static function generate_url_trigger(
579
-        $sending_messenger,
580
-        $generating_messenger,
581
-        $context,
582
-        $message_type,
583
-        EE_Registration $registration,
584
-        $message_template_group,
585
-        $data_id = 0
586
-    ) {
587
-        $query_args = array(
588
-            'ee' => 'msg_url_trigger',
589
-            'snd_msgr' => $sending_messenger,
590
-            'gen_msgr' => $generating_messenger,
591
-            'message_type' => $message_type,
592
-            'context' => $context,
593
-            'token' => $registration->reg_url_link(),
594
-            'GRP_ID' => $message_template_group,
595
-            'id' => $data_id
596
-            );
597
-        $url = add_query_arg($query_args, get_home_url());
598
-
599
-        // made it here so now we can just get the url and filter it.  Filtered globally and by message type.
600
-        $url = apply_filters(
601
-            'FHEE__EEH_MSG_Template__generate_url_trigger',
602
-            $url,
603
-            $sending_messenger,
604
-            $generating_messenger,
605
-            $context,
606
-            $message_type,
607
-            $registration,
608
-            $message_template_group,
609
-            $data_id
610
-        );
611
-        return $url;
612
-    }
613
-
614
-
615
-
616
-
617
-    /**
618
-     * Return the specific css for the action icon given.
619
-     *
620
-     * @since 4.9.0
621
-     *
622
-     * @param string $type  What action to return.
623
-     * @return string
624
-     */
625
-    public static function get_message_action_icon($type)
626
-    {
627
-        $action_icons = self::get_message_action_icons();
628
-        return isset($action_icons[ $type ]) ? $action_icons[ $type ] : '';
629
-    }
630
-
631
-
632
-    /**
633
-     * This is used for retrieving the css classes used for the icons representing message actions.
634
-     *
635
-     * @since 4.9.0
636
-     *
637
-     * @return array
638
-     */
639
-    public static function get_message_action_icons()
640
-    {
641
-        return apply_filters(
642
-            'FHEE__EEH_MSG_Template__message_action_icons',
643
-            array(
644
-                'view' => array(
645
-                    'label' => __('View Message', 'event_espresso'),
646
-                    'css_class' => 'dashicons dashicons-welcome-view-site',
647
-                ),
648
-                'error' => array(
649
-                    'label' => __('View Error Message', 'event_espresso'),
650
-                    'css_class' => 'dashicons dashicons-info',
651
-                ),
652
-                'see_notifications_for' => array(
653
-                    'label' => __('View Related Messages', 'event_espresso'),
654
-                    'css_class' => 'dashicons dashicons-megaphone',
655
-                ),
656
-                'generate_now' => array(
657
-                    'label' => __('Generate the message now.', 'event_espresso'),
658
-                    'css_class' => 'dashicons dashicons-admin-tools',
659
-                ),
660
-                'send_now' => array(
661
-                    'label' => __('Send Immediately', 'event_espresso'),
662
-                    'css_class' => 'dashicons dashicons-controls-forward',
663
-                ),
664
-                'queue_for_resending' => array(
665
-                    'label' => __('Queue for Resending', 'event_espresso'),
666
-                    'css_class' => 'dashicons dashicons-controls-repeat',
667
-                ),
668
-                'view_transaction' => array(
669
-                    'label' => __('View related Transaction', 'event_espresso'),
670
-                    'css_class' => 'dashicons dashicons-cart',
671
-                )
672
-            )
673
-        );
674
-    }
675
-
676
-
677
-    /**
678
-     * This returns the url for a given action related to EE_Message.
679
-     *
680
-     * @since 4.9.0
681
-     *
682
-     * @param string $type  What type of action to return the url for.
683
-     * @param EE_Message $message   Required for generating the correct url for some types.
684
-     * @param array  $query_params   Any additional query params to be included with the generated url.
685
-     *
686
-     * @return string
687
-     */
688
-    public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
689
-    {
690
-        $action_urls = self::get_message_action_urls($message, $query_params);
691
-        return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
692
-    }
693
-
694
-
695
-
696
-    /**
697
-     * This returns all the current urls for EE_Message actions.
698
-     *
699
-     * @since 4.9.0
700
-     *
701
-     * @param  EE_Message   $message    The EE_Message object required to generate correct urls for some types.
702
-     * @param  array    $query_params   Any additional query_params to be included with the generated url.
703
-     *
704
-     * @return array
705
-     */
706
-    public static function get_message_action_urls(EE_Message $message = null, $query_params = array())
707
-    {
708
-        EE_Registry::instance()->load_helper('URL');
709
-        // if $message is not an instance of EE_Message then let's just do a dummy.
710
-        $message = empty($message) ? EE_Message_Factory::create() : $message;
711
-        $action_urls =  apply_filters(
712
-            'FHEE__EEH_MSG_Template__get_message_action_url',
713
-            array(
714
-                'view' => EEH_MSG_Template::generate_browser_trigger($message),
715
-                'error' => EEH_MSG_Template::generate_error_display_trigger($message),
716
-                'see_notifications_for' => EEH_URL::add_query_args_and_nonce(
717
-                    array_merge(
718
-                        array(
719
-                            'page' => 'espresso_messages',
720
-                            'action' => 'default',
721
-                            'filterby' => 1,
722
-                        ),
723
-                        $query_params
724
-                    ),
725
-                    admin_url('admin.php')
726
-                ),
727
-                'generate_now' => EEH_URL::add_query_args_and_nonce(
728
-                    array(
729
-                        'page' => 'espresso_messages',
730
-                        'action' => 'generate_now',
731
-                        'MSG_ID' => $message->ID()
732
-                    ),
733
-                    admin_url('admin.php')
734
-                ),
735
-                'send_now' => EEH_URL::add_query_args_and_nonce(
736
-                    array(
737
-                        'page' => 'espresso_messages',
738
-                        'action' => 'send_now',
739
-                        'MSG_ID' => $message->ID()
740
-                    ),
741
-                    admin_url('admin.php')
742
-                ),
743
-                'queue_for_resending' => EEH_URL::add_query_args_and_nonce(
744
-                    array(
745
-                        'page' => 'espresso_messages',
746
-                        'action' => 'queue_for_resending',
747
-                        'MSG_ID' => $message->ID()
748
-                    ),
749
-                    admin_url('admin.php')
750
-                ),
751
-            )
752
-        );
753
-        if ($message->TXN_ID() > 0
754
-            && EE_Registry::instance()->CAP->current_user_can(
755
-                'ee_read_transaction',
756
-                'espresso_transactions_default',
757
-                $message->TXN_ID()
758
-            )
759
-        ) {
760
-            $action_urls['view_transaction'] = EEH_URL::add_query_args_and_nonce(
761
-                array(
762
-                    'page' => 'espresso_transactions',
763
-                    'action' => 'view_transaction',
764
-                    'TXN_ID' => $message->TXN_ID()
765
-                ),
766
-                admin_url('admin.php')
767
-            );
768
-        } else {
769
-            $action_urls['view_transaction'] = '';
770
-        }
771
-        return $action_urls;
772
-    }
773
-
774
-
775
-    /**
776
-     * This returns a generated link html including the icon used for the action link for EE_Message actions.
777
-     *
778
-     * @since 4.9.0
779
-     *
780
-     * @param string $type What type of action the link is for (if invalid type is passed in then an
781
-     *                     empty string is returned)
782
-     * @param EE_Message|null $message  The EE_Message object (required for some actions to generate correctly)
783
-     * @param array           $query_params Any extra query params to include in the generated link.
784
-     *
785
-     * @return string
786
-     */
787
-    public static function get_message_action_link($type, EE_Message $message = null, $query_params = array())
788
-    {
789
-        $url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
790
-        $icon_css = EEH_MSG_Template::get_message_action_icon($type);
791
-        $title = isset($icon_css['label']) ? 'title="' . $icon_css['label'] . '"' : '';
792
-
793
-        if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
794
-            return '';
795
-        }
796
-
797
-        $icon_css['css_class'] .= esc_attr(
798
-            apply_filters(
799
-                'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
800
-                ' js-ee-message-action-link ee-message-action-link-' . $type,
801
-                $type,
802
-                $message,
803
-                $query_params
804
-            )
805
-        );
806
-
807
-        return '<a href="' . $url . '"' . $title . '><span class="' . esc_attr($icon_css['css_class']) . '"></span></a>';
808
-    }
809
-
810
-
811
-
812
-
813
-
814
-    /**
815
-     * This returns an array with keys as reg statuses and values as the corresponding message type slug (filtered).
816
-     *
817
-     * @since 4.9.0
818
-     * @return array
819
-     */
820
-    public static function reg_status_to_message_type_array()
821
-    {
822
-        return (array) apply_filters(
823
-            'FHEE__EEH_MSG_Template__reg_status_to_message_type_array',
824
-            array(
825
-                EEM_Registration::status_id_approved => 'registration',
826
-                EEM_Registration::status_id_pending_payment => 'pending_approval',
827
-                EEM_Registration::status_id_not_approved => 'not_approved_registration',
828
-                EEM_Registration::status_id_cancelled => 'cancelled_registration',
829
-                EEM_Registration::status_id_declined => 'declined_registration'
830
-            )
831
-        );
832
-    }
833
-
834
-
835
-
836
-
837
-    /**
838
-     * This returns the corresponding registration message type slug to the given reg status. If there isn't a
839
-     * match, then returns an empty string.
840
-     *
841
-     * @since 4.9.0
842
-     * @param $reg_status
843
-     * @return string
844
-     */
845
-    public static function convert_reg_status_to_message_type($reg_status)
846
-    {
847
-        $reg_status_array = self::reg_status_to_message_type_array();
848
-        return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
849
-    }
850
-
851
-
852
-    /**
853
-     * This returns an array with keys as payment stati and values as the corresponding message type slug (filtered).
854
-     *
855
-     * @since 4.9.0
856
-     * @return array
857
-     */
858
-    public static function payment_status_to_message_type_array()
859
-    {
860
-        return (array) apply_filters(
861
-            'FHEE__EEH_MSG_Template__payment_status_to_message_type_array',
862
-            array(
863
-                EEM_Payment::status_id_approved => 'payment',
864
-                EEM_Payment::status_id_pending => 'payment_pending',
865
-                EEM_Payment::status_id_cancelled => 'payment_cancelled',
866
-                EEM_Payment::status_id_declined => 'payment_declined',
867
-                EEM_Payment::status_id_failed => 'payment_failed'
868
-            )
869
-        );
870
-    }
871
-
872
-
873
-
874
-
875
-    /**
876
-     * This returns the corresponding payment message type slug to the given payment status. If there isn't a match then
877
-     * an empty string is returned
878
-     *
879
-     * @since 4.9.0
880
-     * @param $payment_status
881
-     * @return string
882
-     */
883
-    public static function convert_payment_status_to_message_type($payment_status)
884
-    {
885
-        $payment_status_array = self::payment_status_to_message_type_array();
886
-        return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
887
-    }
888
-
889
-
890
-    /**
891
-     * This is used to retrieve the template pack for the given name.
892
-     *
893
-     * @param string $template_pack_name  should match the set `dbref` property value on the EE_Messages_Template_Pack.
894
-     *
895
-     * @return EE_Messages_Template_Pack
896
-     */
897
-    public static function get_template_pack($template_pack_name)
898
-    {
899
-        if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
900
-            self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
901
-        }
902
-
903
-        // first see if in collection already
904
-        $template_pack = self::$_template_pack_collection->get_by_name($template_pack_name);
905
-
906
-        if ($template_pack instanceof EE_Messages_Template_Pack) {
907
-            return $template_pack;
908
-        }
909
-
910
-        // nope...let's get it.
911
-        // not set yet so let's attempt to get it.
912
-        $pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
913
-            ' ',
914
-            '_',
915
-            ucwords(
916
-                str_replace('_', ' ', $template_pack_name)
917
-            )
918
-        );
919
-        if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
920
-            return self::get_template_pack('default');
921
-        } else {
922
-            $template_pack = new $pack_class_name;
923
-            self::$_template_pack_collection->add($template_pack);
924
-            return $template_pack;
925
-        }
926
-    }
927
-
928
-
929
-
930
-
931
-    /**
932
-     * Globs template packs installed in core and returns the template pack collection with all installed template packs
933
-     * in it.
934
-     *
935
-     * @since 4.9.0
936
-     *
937
-     * @return EE_Messages_Template_Pack_Collection
938
-     */
939
-    public static function get_template_pack_collection()
940
-    {
941
-        $new_collection = false;
942
-        if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
943
-            self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
944
-            $new_collection = true;
945
-        }
946
-
947
-        // glob the defaults directory for messages
948
-        $templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
949
-        foreach ($templates as $template_path) {
950
-            // grab folder name
951
-            $template = basename($template_path);
952
-
953
-            if (! $new_collection) {
954
-                // already have it?
955
-                if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
956
-                    continue;
957
-                }
958
-            }
959
-
960
-            // setup classname.
961
-            $template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
962
-                ' ',
963
-                '_',
964
-                ucwords(
965
-                    str_replace(
966
-                        '_',
967
-                        ' ',
968
-                        $template
969
-                    )
970
-                )
971
-            );
972
-            if (! class_exists($template_pack_class_name)) {
973
-                continue;
974
-            }
975
-            self::$_template_pack_collection->add(new $template_pack_class_name);
976
-        }
977
-
978
-        /**
979
-         * Filter for plugins to add in any additional template packs
980
-         * Note the filter name here is for backward compat, this used to be found in EED_Messages.
981
-         */
982
-        $additional_template_packs = apply_filters('FHEE__EED_Messages__get_template_packs__template_packs', array());
983
-        foreach ((array) $additional_template_packs as $template_pack) {
984
-            if (self::$_template_pack_collection->get_by_name(
985
-                $template_pack->dbref
986
-            ) instanceof EE_Messages_Template_Pack
987
-            ) {
988
-                continue;
989
-            }
990
-            self::$_template_pack_collection->add($template_pack);
991
-        }
992
-        return self::$_template_pack_collection;
993
-    }
994
-
995
-
996
-
997
-    /**
998
-     * This is a wrapper for the protected _create_new_templates function
999
-     *
1000
-     * @param string $messenger_name
1001
-     * @param string $message_type_name message type that the templates are being created for
1002
-     * @param int    $GRP_ID
1003
-     * @param bool   $global
1004
-     * @return array
1005
-     * @throws \EE_Error
1006
-     */
1007
-    public static function create_new_templates($messenger_name, $message_type_name, $GRP_ID = 0, $global = false)
1008
-    {
1009
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1010
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1011
-        $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1012
-        $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1013
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1014
-            return array();
1015
-        }
1016
-        // whew made it this far!  Okay, let's go ahead and create the templates then
1017
-        return EEH_MSG_Template::_create_new_templates($messenger, $message_type, $GRP_ID, $global);
1018
-    }
1019
-
1020
-
1021
-
1022
-    /**
1023
-     * @param \EE_messenger    $messenger
1024
-     * @param \EE_message_type $message_type
1025
-     * @param                  $GRP_ID
1026
-     * @param                  $global
1027
-     * @return array|mixed
1028
-     */
1029
-    protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1030
-    {
1031
-        // if we're creating a custom template then we don't need to use the defaults class
1032
-        if (! $global) {
1033
-            return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1034
-        }
1035
-        /** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1036
-        $Message_Template_Defaults = EE_Registry::factory(
1037
-            'EE_Messages_Template_Defaults',
1038
-            array( $messenger, $message_type, $GRP_ID )
1039
-        );
1040
-        // generate templates
1041
-        $success = $Message_Template_Defaults->create_new_templates();
1042
-
1043
-        // if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1044
-        // its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1045
-        // attempts.
1046
-        if (! $success) {
1047
-            /** @var EE_Message_Resource_Manager $message_resource_manager */
1048
-            $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1049
-            $message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
1050
-        }
1051
-
1052
-        /**
1053
-         * $success is in an array in the following format
1054
-         * array(
1055
-         *    'GRP_ID' => $new_grp_id,
1056
-         *    'MTP_context' => $first_context_in_new_templates,
1057
-         * )
1058
-         */
1059
-        return $success;
1060
-    }
1061
-
1062
-
1063
-
1064
-    /**
1065
-     * This creates a custom template using the incoming GRP_ID
1066
-     *
1067
-     * @param \EE_messenger    $messenger
1068
-     * @param \EE_message_type $message_type
1069
-     * @param  int             $GRP_ID      GRP_ID for the template_group being used as the base
1070
-     * @return  array $success              This will be an array in the format:
1071
-     *                                      array(
1072
-     *                                          'GRP_ID' => $new_grp_id,
1073
-     *                                          'MTP_context' => $first_context_in_created_template
1074
-     *                                      )
1075
-     * @access private
1076
-     */
1077
-    private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1078
-    {
1079
-        // defaults
1080
-        $success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1081
-        // get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1082
-        $Message_Template_Group = empty($GRP_ID)
1083
-            ? EEM_Message_Template_Group::instance()->get_one(
1084
-                array(
1085
-                    array(
1086
-                        'MTP_messenger'    => $messenger->name,
1087
-                        'MTP_message_type' => $message_type->name,
1088
-                        'MTP_is_global'    => true
1089
-                    )
1090
-                )
1091
-            )
1092
-            : EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1093
-        // if we don't have a mtg at this point then we need to bail.
1094
-        if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1095
-            EE_Error::add_error(
1096
-                sprintf(
1097
-                    __(
1098
-                        'Something went wrong with generating the custom template from this group id: %s.  This usually happens when there is no matching message template group in the db.',
1099
-                        'event_espresso'
1100
-                    ),
1101
-                    $GRP_ID
1102
-                ),
1103
-                __FILE__,
1104
-                __FUNCTION__,
1105
-                __LINE__
1106
-            );
1107
-            return $success;
1108
-        }
1109
-        // let's get all the related message_template objects for this group.
1110
-        $message_templates = $Message_Template_Group->message_templates();
1111
-        // now we have what we need to setup the new template
1112
-        $new_mtg = clone $Message_Template_Group;
1113
-        $new_mtg->set('GRP_ID', 0);
1114
-        $new_mtg->set('MTP_is_global', false);
1115
-        $template_name = defined('DOING_AJAX') && ! empty($_POST['templateName'])
1116
-            ? $_POST['templateName']
1117
-            : __(
1118
-                'New Custom Template',
1119
-                'event_espresso'
1120
-            );
1121
-        $template_description = defined("DOING_AJAX") && ! empty($_POST['templateDescription'])
1122
-            ? $_POST['templateDescription']
1123
-            : sprintf(
1124
-                __(
1125
-                    'This is a custom template that was created for the %s messenger and %s message type.',
1126
-                    'event_espresso'
1127
-                ),
1128
-                $new_mtg->messenger_obj()->label['singular'],
1129
-                $new_mtg->message_type_obj()->label['singular']
1130
-            );
1131
-        $new_mtg->set('MTP_name', $template_name);
1132
-        $new_mtg->set('MTP_description', $template_description);
1133
-        // remove ALL relations on this template group so they don't get saved!
1134
-        $new_mtg->_remove_relations('Message_Template');
1135
-        $new_mtg->save();
1136
-        $success['GRP_ID'] = $new_mtg->ID();
1137
-        $success['template_name'] = $template_name;
1138
-        // add new message templates and add relation to.
1139
-        foreach ($message_templates as $message_template) {
1140
-            if (! $message_template instanceof EE_Message_Template) {
1141
-                continue;
1142
-            }
1143
-            $new_message_template = clone $message_template;
1144
-            $new_message_template->set('MTP_ID', 0);
1145
-            $new_message_template->set('GRP_ID', $new_mtg->ID()); // relation
1146
-            $new_message_template->save();
1147
-            if (empty($success['MTP_context'])) {
1148
-                $success['MTP_context'] = $new_message_template->get('MTP_context');
1149
-            }
1150
-        }
1151
-        return $success;
1152
-    }
1153
-
1154
-
1155
-
1156
-    /**
1157
-     * message_type_has_active_templates_for_messenger
1158
-     *
1159
-     * @param \EE_messenger    $messenger
1160
-     * @param \EE_message_type $message_type
1161
-     * @param bool             $global
1162
-     * @return bool
1163
-     */
1164
-    public static function message_type_has_active_templates_for_messenger(
1165
-        EE_messenger $messenger,
1166
-        EE_message_type $message_type,
1167
-        $global = false
1168
-    ) {
1169
-        // is given message_type valid for given messenger (if this is not a global save)
1170
-        if ($global) {
1171
-            return true;
1172
-        }
1173
-        $active_templates = EEM_Message_Template_Group::instance()->count(
1174
-            array(
1175
-                array(
1176
-                    'MTP_is_active'    => true,
1177
-                    'MTP_messenger'    => $messenger->name,
1178
-                    'MTP_message_type' => $message_type->name
1179
-                )
1180
-            )
1181
-        );
1182
-        if ($active_templates > 0) {
1183
-            return true;
1184
-        }
1185
-        EE_Error::add_error(
1186
-            sprintf(
1187
-                __(
1188
-                    'The %1$s message type is not registered with the %2$s messenger. Please visit the Messenger activation page to assign this message type first if you want to use it.',
1189
-                    'event_espresso'
1190
-                ),
1191
-                $message_type->name,
1192
-                $messenger->name
1193
-            ),
1194
-            __FILE__,
1195
-            __FUNCTION__,
1196
-            __LINE__
1197
-        );
1198
-        return false;
1199
-    }
1200
-
1201
-
1202
-
1203
-    /**
1204
-     * get_fields
1205
-     * This takes a given messenger and message type and returns all the template fields indexed by context (and with field type).
1206
-     *
1207
-     * @param  string $messenger_name    name of EE_messenger
1208
-     * @param  string $message_type_name name of EE_message_type
1209
-     * @return array
1210
-     */
1211
-    public static function get_fields($messenger_name, $message_type_name)
1212
-    {
1213
-        $template_fields = array();
1214
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1215
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1216
-        $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1217
-        $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1218
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1219
-            return array();
1220
-        }
1221
-
1222
-        $excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1223
-
1224
-        // okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1225
-        foreach ($message_type->get_contexts() as $context => $details) {
1226
-            foreach ($messenger->get_template_fields() as $field => $value) {
1227
-                if (in_array($field, $excluded_fields_for_messenger, true)) {
1228
-                    continue;
1229
-                }
1230
-                $template_fields[ $context ][ $field ] = $value;
1231
-            }
1232
-        }
1233
-        if (empty($template_fields)) {
1234
-            EE_Error::add_error(
1235
-                __('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'),
1236
-                __FILE__,
1237
-                __FUNCTION__,
1238
-                __LINE__
1239
-            );
1240
-            return array();
1241
-        }
1242
-        return $template_fields;
1243
-    }
17
+	/**
18
+	 * Holds a collection of EE_Message_Template_Pack objects.
19
+	 * @type EE_Messages_Template_Pack_Collection
20
+	 */
21
+	protected static $_template_pack_collection;
22
+
23
+
24
+
25
+
26
+	private static function _set_autoloader()
27
+	{
28
+		EED_Messages::set_autoloaders();
29
+	}
30
+
31
+
32
+	/**
33
+	 * generate_new_templates
34
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will automatically create the defaults for the event.  The user would then be redirected to edit the default context for the event.
35
+	 *
36
+	 * @access protected
37
+	 * @param  string $messenger     the messenger we are generating templates for
38
+	 * @param array   $message_types array of message types that the templates are generated for.
39
+	 * @param int     $GRP_ID        If a non global template is being generated then it is expected we'll have a GRP_ID to use as the base for the new generated template.
40
+	 * @param bool    $global        true indicates generating templates on messenger activation. false requires GRP_ID for event specific template generation.
41
+	 * @throws \EE_Error
42
+	 * @return array  @see EEH_MSG_Template::_create_new_templates for the return value of each element in the array for templates
43
+	 *                that are generated.  If this is an empty array then it means no templates were generated which usually
44
+	 *                means there was an error.  Anything in the array with an empty value for `MTP_context` means that it
45
+	 *                was not a new generated template but just reactivated (which only happens for global templates that
46
+	 *                already exist in the database.
47
+	 */
48
+	public static function generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
49
+	{
50
+		// make sure message_type is an array.
51
+		$message_types = (array) $message_types;
52
+		$templates = array();
53
+
54
+		if (empty($messenger)) {
55
+			throw new EE_Error(__('We need a messenger to generate templates!', 'event_espresso'));
56
+		}
57
+
58
+		// if we STILL have empty $message_types then we need to generate an error message b/c we NEED message types to do the template files.
59
+		if (empty($message_types)) {
60
+			throw new EE_Error(__('We need at least one message type to generate templates!', 'event_espresso'));
61
+		}
62
+
63
+		EEH_MSG_Template::_set_autoloader();
64
+		foreach ($message_types as $message_type) {
65
+			// if global then let's attempt to get the GRP_ID for this combo IF GRP_ID is empty.
66
+			if ($global && empty($GRP_ID)) {
67
+				$GRP_ID = EEM_Message_Template_Group::instance()->get_one(
68
+					array(
69
+						array(
70
+							'MTP_messenger'    => $messenger,
71
+							'MTP_message_type' => $message_type,
72
+							'MTP_is_global'    => true,
73
+						),
74
+					)
75
+				);
76
+				$GRP_ID = $GRP_ID instanceof EE_Message_Template_Group ? $GRP_ID->ID() : 0;
77
+			}
78
+			// if this is global template generation.
79
+			// First let's determine if we already HAVE global templates for this messenger and message_type combination.
80
+			//  If we do then NO generation!!
81
+			if ($global && EEH_MSG_Template::already_generated($messenger, $message_type, $GRP_ID)) {
82
+				$templates[] = array(
83
+					'GRP_ID' => $GRP_ID,
84
+					'MTP_context' => '',
85
+				);
86
+				// we already have generated templates for this so let's go to the next message type.
87
+				continue;
88
+			}
89
+			$new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
90
+
91
+			if (! $new_message_template_group) {
92
+				continue;
93
+			}
94
+			$templates[] = $new_message_template_group;
95
+		}
96
+
97
+		return $templates;
98
+	}
99
+
100
+
101
+	/**
102
+	 * The purpose of this method is to determine if there are already generated templates in the database for the given variables.
103
+	 * @param  string $messenger     messenger
104
+	 * @param  string $message_type message type
105
+	 * @param  int $GRP_ID        GRP ID ( if a custom template) (if not provided then we're just doing global template check)
106
+	 * @return bool                true = generated, false = hasn't been generated.
107
+	 */
108
+	public static function already_generated($messenger, $message_type, $GRP_ID = 0)
109
+	{
110
+		EEH_MSG_Template::_set_autoloader();
111
+		// what method we use depends on whether we have an GRP_ID or not
112
+		$count = empty($GRP_ID)
113
+			? EEM_Message_Template::instance()->count(
114
+				array(
115
+					array(
116
+						'Message_Template_Group.MTP_messenger'    => $messenger,
117
+						'Message_Template_Group.MTP_message_type' => $message_type,
118
+						'Message_Template_Group.MTP_is_global'    => true
119
+					)
120
+				)
121
+			)
122
+			: EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
123
+
124
+		return $count > 0;
125
+	}
126
+
127
+
128
+
129
+
130
+	/**
131
+	 * Updates all message templates matching the incoming messengers and message types to active status.
132
+	 *
133
+	 * @static
134
+	 * @param  array  $messenger_names     Messenger slug
135
+	 * @param  array  $message_type_names  Message type slug
136
+	 * @return  int                         count of updated records.
137
+	 */
138
+	public static function update_to_active($messenger_names, $message_type_names)
139
+	{
140
+		$messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
141
+		$message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
142
+		return EEM_Message_Template_Group::instance()->update(
143
+			array( 'MTP_is_active' => 1 ),
144
+			array(
145
+				array(
146
+					'MTP_messenger'     => array( 'IN', $messenger_names ),
147
+					'MTP_message_type'  => array( 'IN', $message_type_names )
148
+				)
149
+			)
150
+		);
151
+	}
152
+
153
+
154
+
155
+	/**
156
+	 * Updates all message template groups matching the incoming arguments to inactive status.
157
+	 *
158
+	 * @static
159
+	 * @param array $messenger_names    The messenger slugs.
160
+	 *                              If empty then all templates matching the message types are marked inactive.
161
+	 *                              Otherwise only templates matching the messengers and message types.
162
+	 * @param array $message_type_names     The message type slugs.
163
+	 *                              If empty then all templates matching the messengers are marked inactive.
164
+	 *                              Otherwise only templates matching the messengers and message types.
165
+	 *
166
+	 * @return int  count of updated records.
167
+	 */
168
+	public static function update_to_inactive($messenger_names = array(), $message_type_names = array())
169
+	{
170
+		return EEM_Message_Template_Group::instance()->deactivate_message_template_groups_for(
171
+			$messenger_names,
172
+			$message_type_names
173
+		);
174
+	}
175
+
176
+
177
+	/**
178
+	 * The purpose of this function is to return all installed message objects
179
+	 * (messengers and message type regardless of whether they are ACTIVE or not)
180
+	 *
181
+	 * @deprecated 4.9.0
182
+	 * @static
183
+	 * @param string $type
184
+	 * @return array array consisting of installed messenger objects and installed message type objects.
185
+	 */
186
+	public static function get_installed_message_objects($type = 'all')
187
+	{
188
+		self::_set_autoloader();
189
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
190
+		return array(
191
+			'messenger' => $message_resource_manager->installed_messengers(),
192
+			'message_type' => $message_resource_manager->installed_message_types()
193
+		);
194
+	}
195
+
196
+
197
+	/**
198
+	 * This will return an array of shortcodes => labels from the
199
+	 * messenger and message_type objects associated with this
200
+	 * template.
201
+	 *
202
+	 * @since 4.3.0
203
+	 *
204
+	 * @param string $message_type
205
+	 * @param string $messenger
206
+	 * @param array  $fields    What fields we're returning valid shortcodes for.
207
+	 *                          If empty then we assume all fields are to be returned. Optional.
208
+	 * @param string $context   What context we're going to return shortcodes for. Optional.
209
+	 * @param bool $merged      If TRUE then we don't return shortcodes indexed by field,
210
+	 *                          but instead an array of the unique shortcodes for all the given ( or all) fields.
211
+	 *                          Optional.
212
+	 * @throws \EE_Error
213
+	 * @return mixed (array|bool) an array of shortcodes in the format
214
+	 *                                              array( '[shortcode] => 'label')
215
+	 *                                              OR
216
+	 *                                              FALSE if no shortcodes found.
217
+	 */
218
+	public static function get_shortcodes(
219
+		$message_type,
220
+		$messenger,
221
+		$fields = array(),
222
+		$context = 'admin',
223
+		$merged = false
224
+	) {
225
+		$messenger_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger)));
226
+		$mt_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type)));
227
+		/** @var EE_Message_Resource_Manager $message_resource_manager */
228
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
229
+		// convert slug to object
230
+		$messenger = $message_resource_manager->get_messenger($messenger);
231
+
232
+		// if messenger isn't a EE_messenger resource then bail.
233
+		if (! $messenger instanceof EE_messenger) {
234
+			return array();
235
+		}
236
+
237
+		// validate class for getting our list of shortcodes
238
+		$classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
239
+		if (! class_exists($classname)) {
240
+			$msg[] = __('The Validator class was unable to load', 'event_espresso');
241
+			$msg[] = sprintf(
242
+				__('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
243
+				$classname
244
+			);
245
+			throw new EE_Error(implode('||', $msg));
246
+		}
247
+
248
+		/** @type EE_Messages_Validator $_VLD */
249
+		$_VLD = new $classname(array(), $context);
250
+		$valid_shortcodes = $_VLD->get_validators();
251
+
252
+		// let's make sure we're only getting the shortcode part of the validators
253
+		$shortcodes = array();
254
+		foreach ($valid_shortcodes as $field => $validators) {
255
+			$shortcodes[ $field ] = $validators['shortcodes'];
256
+		}
257
+		$valid_shortcodes = $shortcodes;
258
+
259
+		// if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
260
+		if (! empty($fields)) {
261
+			$specified_shortcodes = array();
262
+			foreach ($fields as $field) {
263
+				if (isset($valid_shortcodes[ $field ])) {
264
+					$specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
265
+				}
266
+			}
267
+			$valid_shortcodes = $specified_shortcodes;
268
+		}
269
+
270
+		// if not merged then let's replace the fields with the localized fields
271
+		if (! $merged) {
272
+			// let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
273
+			$field_settings = $messenger->get_template_fields();
274
+			$localized = array();
275
+			foreach ($valid_shortcodes as $field => $shortcodes) {
276
+				// get localized field label
277
+				if (isset($field_settings[ $field ])) {
278
+					// possible that this is used as a main field.
279
+					if (empty($field_settings[ $field ])) {
280
+						if (isset($field_settings['extra'][ $field ])) {
281
+							$_field = $field_settings['extra'][ $field ]['main']['label'];
282
+						} else {
283
+							$_field = $field;
284
+						}
285
+					} else {
286
+						$_field = $field_settings[ $field ]['label'];
287
+					}
288
+				} elseif (isset($field_settings['extra'])) {
289
+					// loop through extra "main fields" and see if any of their children have our field
290
+					foreach ($field_settings['extra'] as $main_field => $fields) {
291
+						if (isset($fields[ $field ])) {
292
+							$_field = $fields[ $field ]['label'];
293
+						} else {
294
+							$_field = $field;
295
+						}
296
+					}
297
+				} else {
298
+					$_field = $field;
299
+				}
300
+				if (isset($_field)) {
301
+					$localized[ (string) $_field ] = $shortcodes;
302
+				}
303
+			}
304
+			$valid_shortcodes = $localized;
305
+		}
306
+
307
+		// if $merged then let's merge all the shortcodes into one list NOT indexed by field.
308
+		if ($merged) {
309
+			$merged_codes = array();
310
+			foreach ($valid_shortcodes as $field => $shortcode) {
311
+				foreach ($shortcode as $code => $label) {
312
+					if (isset($merged_codes[ $code ])) {
313
+						continue;
314
+					} else {
315
+						$merged_codes[ $code ] = $label;
316
+					}
317
+				}
318
+			}
319
+			$valid_shortcodes = $merged_codes;
320
+		}
321
+
322
+		return $valid_shortcodes;
323
+	}
324
+
325
+
326
+	/**
327
+	 * Get Messenger object.
328
+	 *
329
+	 * @since 4.3.0
330
+	 * @deprecated 4.9.0
331
+	 * @param string $messenger messenger slug for the messenger object we want to retrieve.
332
+	 * @throws \EE_Error
333
+	 * @return EE_messenger
334
+	 */
335
+	public static function messenger_obj($messenger)
336
+	{
337
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
338
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
339
+		return $Message_Resource_Manager->get_messenger($messenger);
340
+	}
341
+
342
+
343
+	/**
344
+	 * get Message type object
345
+	 *
346
+	 * @since 4.3.0
347
+	 * @deprecated 4.9.0
348
+	 * @param string $message_type the slug for the message type object to retrieve
349
+	 * @throws \EE_Error
350
+	 * @return EE_message_type
351
+	 */
352
+	public static function message_type_obj($message_type)
353
+	{
354
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
355
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
356
+		return $Message_Resource_Manager->get_message_type($message_type);
357
+	}
358
+
359
+
360
+
361
+
362
+
363
+	/**
364
+	 * Given a message_type slug, will return whether that message type is active in the system or not.
365
+	 *
366
+	 * @since    4.3.0
367
+	 * @param  string   $message_type message type to check for.
368
+	 * @return boolean
369
+	 */
370
+	public static function is_mt_active($message_type)
371
+	{
372
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
373
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
374
+		$active_mts = $Message_Resource_Manager->list_of_active_message_types();
375
+		return in_array($message_type, $active_mts);
376
+	}
377
+
378
+
379
+
380
+	/**
381
+	 * Given a messenger slug, will return whether that messenger is active in the system or not.
382
+	 *
383
+	 * @since    4.3.0
384
+	 *
385
+	 * @param  string  $messenger slug for messenger to check.
386
+	 * @return boolean
387
+	 */
388
+	public static function is_messenger_active($messenger)
389
+	{
390
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
391
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
392
+		$active_messenger = $Message_Resource_Manager->get_active_messenger($messenger);
393
+		return $active_messenger instanceof EE_messenger ? true : false;
394
+	}
395
+
396
+
397
+
398
+	/**
399
+	 * Used to return active messengers array stored in the wp options table.
400
+	 * If no value is present in the option then an empty array is returned.
401
+	 *
402
+	 * @deprecated 4.9
403
+	 * @since 4.3.1
404
+	 *
405
+	 * @return array
406
+	 */
407
+	public static function get_active_messengers_in_db()
408
+	{
409
+		EE_Error::doing_it_wrong(
410
+			__METHOD__,
411
+			__('Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso'),
412
+			'4.9.0'
413
+		);
414
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
415
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
416
+		return $Message_Resource_Manager->get_active_messengers_option();
417
+	}
418
+
419
+
420
+
421
+
422
+	/**
423
+	 * Used to update the active messengers array stored in the wp options table.
424
+	 *
425
+	 * @since 4.3.1
426
+	 * @deprecated 4.9.0
427
+	 *
428
+	 * @param array $data_to_save Incoming data to save.
429
+	 *
430
+	 * @return bool FALSE if not updated, TRUE if updated.
431
+	 */
432
+	public static function update_active_messengers_in_db($data_to_save)
433
+	{
434
+		EE_Error::doing_it_wrong(
435
+			__METHOD__,
436
+			__('Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso'),
437
+			'4.9.0'
438
+		);
439
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
440
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
441
+		return $Message_Resource_Manager->update_active_messengers_option($data_to_save);
442
+	}
443
+
444
+
445
+	/**
446
+	 * This does some validation of incoming params, determines what type of url is being prepped and returns the
447
+	 * appropriate url trigger
448
+	 *
449
+	 * @param EE_message_type $message_type
450
+	 * @param EE_Message $message
451
+	 * @param EE_Registration | null $registration  The registration object must be included if this
452
+	 *                                              is going to be a registration trigger url.
453
+	 * @param string $sending_messenger             The (optional) sending messenger for the url.
454
+	 *
455
+	 * @return string
456
+	 * @throws EE_Error
457
+	 */
458
+	public static function get_url_trigger(
459
+		EE_message_type $message_type,
460
+		EE_Message $message,
461
+		$registration = null,
462
+		$sending_messenger = ''
463
+	) {
464
+		// first determine if the url can be to the EE_Message object.
465
+		if (! $message_type->always_generate()) {
466
+			return EEH_MSG_Template::generate_browser_trigger($message);
467
+		}
468
+
469
+		// if $registration object is not valid then exit early because there's nothing that can be generated.
470
+		if (! $registration instanceof EE_Registration) {
471
+			throw new EE_Error(
472
+				__('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
473
+			);
474
+		}
475
+
476
+		// validate given context
477
+		$contexts = $message_type->get_contexts();
478
+		if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
479
+			throw new EE_Error(
480
+				sprintf(
481
+					__('The context %s is not a valid context for %s.', 'event_espresso'),
482
+					$message->context(),
483
+					get_class($message_type)
484
+				)
485
+			);
486
+		}
487
+
488
+		// valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
489
+		if (! empty($sending_messenger)) {
490
+			$with_messengers = $message_type->with_messengers();
491
+			if (! isset($with_messengers[ $message->messenger() ])
492
+				 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ]) ) {
493
+				throw new EE_Error(
494
+					sprintf(
495
+						__(
496
+							'The given sending messenger string (%1$s) does not match a valid sending messenger with the %2$s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
497
+							'event_espresso'
498
+						),
499
+						$sending_messenger,
500
+						get_class($message_type)
501
+					)
502
+				);
503
+			}
504
+		} else {
505
+			$sending_messenger = $message->messenger();
506
+		}
507
+		return EEH_MSG_Template::generate_url_trigger(
508
+			$sending_messenger,
509
+			$message->messenger(),
510
+			$message->context(),
511
+			$message->message_type(),
512
+			$registration,
513
+			$message->GRP_ID()
514
+		);
515
+	}
516
+
517
+
518
+	/**
519
+	 * This returns the url for triggering a in browser view of a specific EE_Message object.
520
+	 * @param EE_Message $message
521
+	 * @return string.
522
+	 */
523
+	public static function generate_browser_trigger(EE_Message $message)
524
+	{
525
+		$query_args = array(
526
+			'ee' => 'msg_browser_trigger',
527
+			'token' => $message->MSG_token()
528
+		);
529
+		return apply_filters(
530
+			'FHEE__EEH_MSG_Template__generate_browser_trigger',
531
+			add_query_arg($query_args, site_url()),
532
+			$message
533
+		);
534
+	}
535
+
536
+
537
+
538
+
539
+
540
+
541
+	/**
542
+	 * This returns the url for triggering an in browser view of the error saved on the incoming message object.
543
+	 * @param EE_Message $message
544
+	 * @return string
545
+	 */
546
+	public static function generate_error_display_trigger(EE_Message $message)
547
+	{
548
+		return apply_filters(
549
+			'FHEE__EEH_MSG_Template__generate_error_display_trigger',
550
+			add_query_arg(
551
+				array(
552
+					'ee' => 'msg_browser_error_trigger',
553
+					'token' => $message->MSG_token()
554
+				),
555
+				site_url()
556
+			),
557
+			$message
558
+		);
559
+	}
560
+
561
+
562
+
563
+
564
+
565
+
566
+	/**
567
+	 * This generates a url trigger for the msg_url_trigger route using the given arguments
568
+	 *
569
+	 * @param string          $sending_messenger    The sending messenger slug.
570
+	 * @param string          $generating_messenger The generating messenger slug.
571
+	 * @param string          $context              The context for the template.
572
+	 * @param string          $message_type         The message type slug
573
+	 * @param EE_Registration $registration
574
+	 * @param integer          $message_template_group id   The EE_Message_Template_Group ID for the template.
575
+	 * @param integer          $data_id     The id to the EE_Base_Class for getting the data used by the trigger.
576
+	 * @return string          The generated url.
577
+	 */
578
+	public static function generate_url_trigger(
579
+		$sending_messenger,
580
+		$generating_messenger,
581
+		$context,
582
+		$message_type,
583
+		EE_Registration $registration,
584
+		$message_template_group,
585
+		$data_id = 0
586
+	) {
587
+		$query_args = array(
588
+			'ee' => 'msg_url_trigger',
589
+			'snd_msgr' => $sending_messenger,
590
+			'gen_msgr' => $generating_messenger,
591
+			'message_type' => $message_type,
592
+			'context' => $context,
593
+			'token' => $registration->reg_url_link(),
594
+			'GRP_ID' => $message_template_group,
595
+			'id' => $data_id
596
+			);
597
+		$url = add_query_arg($query_args, get_home_url());
598
+
599
+		// made it here so now we can just get the url and filter it.  Filtered globally and by message type.
600
+		$url = apply_filters(
601
+			'FHEE__EEH_MSG_Template__generate_url_trigger',
602
+			$url,
603
+			$sending_messenger,
604
+			$generating_messenger,
605
+			$context,
606
+			$message_type,
607
+			$registration,
608
+			$message_template_group,
609
+			$data_id
610
+		);
611
+		return $url;
612
+	}
613
+
614
+
615
+
616
+
617
+	/**
618
+	 * Return the specific css for the action icon given.
619
+	 *
620
+	 * @since 4.9.0
621
+	 *
622
+	 * @param string $type  What action to return.
623
+	 * @return string
624
+	 */
625
+	public static function get_message_action_icon($type)
626
+	{
627
+		$action_icons = self::get_message_action_icons();
628
+		return isset($action_icons[ $type ]) ? $action_icons[ $type ] : '';
629
+	}
630
+
631
+
632
+	/**
633
+	 * This is used for retrieving the css classes used for the icons representing message actions.
634
+	 *
635
+	 * @since 4.9.0
636
+	 *
637
+	 * @return array
638
+	 */
639
+	public static function get_message_action_icons()
640
+	{
641
+		return apply_filters(
642
+			'FHEE__EEH_MSG_Template__message_action_icons',
643
+			array(
644
+				'view' => array(
645
+					'label' => __('View Message', 'event_espresso'),
646
+					'css_class' => 'dashicons dashicons-welcome-view-site',
647
+				),
648
+				'error' => array(
649
+					'label' => __('View Error Message', 'event_espresso'),
650
+					'css_class' => 'dashicons dashicons-info',
651
+				),
652
+				'see_notifications_for' => array(
653
+					'label' => __('View Related Messages', 'event_espresso'),
654
+					'css_class' => 'dashicons dashicons-megaphone',
655
+				),
656
+				'generate_now' => array(
657
+					'label' => __('Generate the message now.', 'event_espresso'),
658
+					'css_class' => 'dashicons dashicons-admin-tools',
659
+				),
660
+				'send_now' => array(
661
+					'label' => __('Send Immediately', 'event_espresso'),
662
+					'css_class' => 'dashicons dashicons-controls-forward',
663
+				),
664
+				'queue_for_resending' => array(
665
+					'label' => __('Queue for Resending', 'event_espresso'),
666
+					'css_class' => 'dashicons dashicons-controls-repeat',
667
+				),
668
+				'view_transaction' => array(
669
+					'label' => __('View related Transaction', 'event_espresso'),
670
+					'css_class' => 'dashicons dashicons-cart',
671
+				)
672
+			)
673
+		);
674
+	}
675
+
676
+
677
+	/**
678
+	 * This returns the url for a given action related to EE_Message.
679
+	 *
680
+	 * @since 4.9.0
681
+	 *
682
+	 * @param string $type  What type of action to return the url for.
683
+	 * @param EE_Message $message   Required for generating the correct url for some types.
684
+	 * @param array  $query_params   Any additional query params to be included with the generated url.
685
+	 *
686
+	 * @return string
687
+	 */
688
+	public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
689
+	{
690
+		$action_urls = self::get_message_action_urls($message, $query_params);
691
+		return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
692
+	}
693
+
694
+
695
+
696
+	/**
697
+	 * This returns all the current urls for EE_Message actions.
698
+	 *
699
+	 * @since 4.9.0
700
+	 *
701
+	 * @param  EE_Message   $message    The EE_Message object required to generate correct urls for some types.
702
+	 * @param  array    $query_params   Any additional query_params to be included with the generated url.
703
+	 *
704
+	 * @return array
705
+	 */
706
+	public static function get_message_action_urls(EE_Message $message = null, $query_params = array())
707
+	{
708
+		EE_Registry::instance()->load_helper('URL');
709
+		// if $message is not an instance of EE_Message then let's just do a dummy.
710
+		$message = empty($message) ? EE_Message_Factory::create() : $message;
711
+		$action_urls =  apply_filters(
712
+			'FHEE__EEH_MSG_Template__get_message_action_url',
713
+			array(
714
+				'view' => EEH_MSG_Template::generate_browser_trigger($message),
715
+				'error' => EEH_MSG_Template::generate_error_display_trigger($message),
716
+				'see_notifications_for' => EEH_URL::add_query_args_and_nonce(
717
+					array_merge(
718
+						array(
719
+							'page' => 'espresso_messages',
720
+							'action' => 'default',
721
+							'filterby' => 1,
722
+						),
723
+						$query_params
724
+					),
725
+					admin_url('admin.php')
726
+				),
727
+				'generate_now' => EEH_URL::add_query_args_and_nonce(
728
+					array(
729
+						'page' => 'espresso_messages',
730
+						'action' => 'generate_now',
731
+						'MSG_ID' => $message->ID()
732
+					),
733
+					admin_url('admin.php')
734
+				),
735
+				'send_now' => EEH_URL::add_query_args_and_nonce(
736
+					array(
737
+						'page' => 'espresso_messages',
738
+						'action' => 'send_now',
739
+						'MSG_ID' => $message->ID()
740
+					),
741
+					admin_url('admin.php')
742
+				),
743
+				'queue_for_resending' => EEH_URL::add_query_args_and_nonce(
744
+					array(
745
+						'page' => 'espresso_messages',
746
+						'action' => 'queue_for_resending',
747
+						'MSG_ID' => $message->ID()
748
+					),
749
+					admin_url('admin.php')
750
+				),
751
+			)
752
+		);
753
+		if ($message->TXN_ID() > 0
754
+			&& EE_Registry::instance()->CAP->current_user_can(
755
+				'ee_read_transaction',
756
+				'espresso_transactions_default',
757
+				$message->TXN_ID()
758
+			)
759
+		) {
760
+			$action_urls['view_transaction'] = EEH_URL::add_query_args_and_nonce(
761
+				array(
762
+					'page' => 'espresso_transactions',
763
+					'action' => 'view_transaction',
764
+					'TXN_ID' => $message->TXN_ID()
765
+				),
766
+				admin_url('admin.php')
767
+			);
768
+		} else {
769
+			$action_urls['view_transaction'] = '';
770
+		}
771
+		return $action_urls;
772
+	}
773
+
774
+
775
+	/**
776
+	 * This returns a generated link html including the icon used for the action link for EE_Message actions.
777
+	 *
778
+	 * @since 4.9.0
779
+	 *
780
+	 * @param string $type What type of action the link is for (if invalid type is passed in then an
781
+	 *                     empty string is returned)
782
+	 * @param EE_Message|null $message  The EE_Message object (required for some actions to generate correctly)
783
+	 * @param array           $query_params Any extra query params to include in the generated link.
784
+	 *
785
+	 * @return string
786
+	 */
787
+	public static function get_message_action_link($type, EE_Message $message = null, $query_params = array())
788
+	{
789
+		$url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
790
+		$icon_css = EEH_MSG_Template::get_message_action_icon($type);
791
+		$title = isset($icon_css['label']) ? 'title="' . $icon_css['label'] . '"' : '';
792
+
793
+		if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
794
+			return '';
795
+		}
796
+
797
+		$icon_css['css_class'] .= esc_attr(
798
+			apply_filters(
799
+				'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
800
+				' js-ee-message-action-link ee-message-action-link-' . $type,
801
+				$type,
802
+				$message,
803
+				$query_params
804
+			)
805
+		);
806
+
807
+		return '<a href="' . $url . '"' . $title . '><span class="' . esc_attr($icon_css['css_class']) . '"></span></a>';
808
+	}
809
+
810
+
811
+
812
+
813
+
814
+	/**
815
+	 * This returns an array with keys as reg statuses and values as the corresponding message type slug (filtered).
816
+	 *
817
+	 * @since 4.9.0
818
+	 * @return array
819
+	 */
820
+	public static function reg_status_to_message_type_array()
821
+	{
822
+		return (array) apply_filters(
823
+			'FHEE__EEH_MSG_Template__reg_status_to_message_type_array',
824
+			array(
825
+				EEM_Registration::status_id_approved => 'registration',
826
+				EEM_Registration::status_id_pending_payment => 'pending_approval',
827
+				EEM_Registration::status_id_not_approved => 'not_approved_registration',
828
+				EEM_Registration::status_id_cancelled => 'cancelled_registration',
829
+				EEM_Registration::status_id_declined => 'declined_registration'
830
+			)
831
+		);
832
+	}
833
+
834
+
835
+
836
+
837
+	/**
838
+	 * This returns the corresponding registration message type slug to the given reg status. If there isn't a
839
+	 * match, then returns an empty string.
840
+	 *
841
+	 * @since 4.9.0
842
+	 * @param $reg_status
843
+	 * @return string
844
+	 */
845
+	public static function convert_reg_status_to_message_type($reg_status)
846
+	{
847
+		$reg_status_array = self::reg_status_to_message_type_array();
848
+		return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
849
+	}
850
+
851
+
852
+	/**
853
+	 * This returns an array with keys as payment stati and values as the corresponding message type slug (filtered).
854
+	 *
855
+	 * @since 4.9.0
856
+	 * @return array
857
+	 */
858
+	public static function payment_status_to_message_type_array()
859
+	{
860
+		return (array) apply_filters(
861
+			'FHEE__EEH_MSG_Template__payment_status_to_message_type_array',
862
+			array(
863
+				EEM_Payment::status_id_approved => 'payment',
864
+				EEM_Payment::status_id_pending => 'payment_pending',
865
+				EEM_Payment::status_id_cancelled => 'payment_cancelled',
866
+				EEM_Payment::status_id_declined => 'payment_declined',
867
+				EEM_Payment::status_id_failed => 'payment_failed'
868
+			)
869
+		);
870
+	}
871
+
872
+
873
+
874
+
875
+	/**
876
+	 * This returns the corresponding payment message type slug to the given payment status. If there isn't a match then
877
+	 * an empty string is returned
878
+	 *
879
+	 * @since 4.9.0
880
+	 * @param $payment_status
881
+	 * @return string
882
+	 */
883
+	public static function convert_payment_status_to_message_type($payment_status)
884
+	{
885
+		$payment_status_array = self::payment_status_to_message_type_array();
886
+		return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
887
+	}
888
+
889
+
890
+	/**
891
+	 * This is used to retrieve the template pack for the given name.
892
+	 *
893
+	 * @param string $template_pack_name  should match the set `dbref` property value on the EE_Messages_Template_Pack.
894
+	 *
895
+	 * @return EE_Messages_Template_Pack
896
+	 */
897
+	public static function get_template_pack($template_pack_name)
898
+	{
899
+		if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
900
+			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
901
+		}
902
+
903
+		// first see if in collection already
904
+		$template_pack = self::$_template_pack_collection->get_by_name($template_pack_name);
905
+
906
+		if ($template_pack instanceof EE_Messages_Template_Pack) {
907
+			return $template_pack;
908
+		}
909
+
910
+		// nope...let's get it.
911
+		// not set yet so let's attempt to get it.
912
+		$pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
913
+			' ',
914
+			'_',
915
+			ucwords(
916
+				str_replace('_', ' ', $template_pack_name)
917
+			)
918
+		);
919
+		if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
920
+			return self::get_template_pack('default');
921
+		} else {
922
+			$template_pack = new $pack_class_name;
923
+			self::$_template_pack_collection->add($template_pack);
924
+			return $template_pack;
925
+		}
926
+	}
927
+
928
+
929
+
930
+
931
+	/**
932
+	 * Globs template packs installed in core and returns the template pack collection with all installed template packs
933
+	 * in it.
934
+	 *
935
+	 * @since 4.9.0
936
+	 *
937
+	 * @return EE_Messages_Template_Pack_Collection
938
+	 */
939
+	public static function get_template_pack_collection()
940
+	{
941
+		$new_collection = false;
942
+		if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
943
+			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
944
+			$new_collection = true;
945
+		}
946
+
947
+		// glob the defaults directory for messages
948
+		$templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
949
+		foreach ($templates as $template_path) {
950
+			// grab folder name
951
+			$template = basename($template_path);
952
+
953
+			if (! $new_collection) {
954
+				// already have it?
955
+				if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
956
+					continue;
957
+				}
958
+			}
959
+
960
+			// setup classname.
961
+			$template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
962
+				' ',
963
+				'_',
964
+				ucwords(
965
+					str_replace(
966
+						'_',
967
+						' ',
968
+						$template
969
+					)
970
+				)
971
+			);
972
+			if (! class_exists($template_pack_class_name)) {
973
+				continue;
974
+			}
975
+			self::$_template_pack_collection->add(new $template_pack_class_name);
976
+		}
977
+
978
+		/**
979
+		 * Filter for plugins to add in any additional template packs
980
+		 * Note the filter name here is for backward compat, this used to be found in EED_Messages.
981
+		 */
982
+		$additional_template_packs = apply_filters('FHEE__EED_Messages__get_template_packs__template_packs', array());
983
+		foreach ((array) $additional_template_packs as $template_pack) {
984
+			if (self::$_template_pack_collection->get_by_name(
985
+				$template_pack->dbref
986
+			) instanceof EE_Messages_Template_Pack
987
+			) {
988
+				continue;
989
+			}
990
+			self::$_template_pack_collection->add($template_pack);
991
+		}
992
+		return self::$_template_pack_collection;
993
+	}
994
+
995
+
996
+
997
+	/**
998
+	 * This is a wrapper for the protected _create_new_templates function
999
+	 *
1000
+	 * @param string $messenger_name
1001
+	 * @param string $message_type_name message type that the templates are being created for
1002
+	 * @param int    $GRP_ID
1003
+	 * @param bool   $global
1004
+	 * @return array
1005
+	 * @throws \EE_Error
1006
+	 */
1007
+	public static function create_new_templates($messenger_name, $message_type_name, $GRP_ID = 0, $global = false)
1008
+	{
1009
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1010
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1011
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1012
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1013
+		if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1014
+			return array();
1015
+		}
1016
+		// whew made it this far!  Okay, let's go ahead and create the templates then
1017
+		return EEH_MSG_Template::_create_new_templates($messenger, $message_type, $GRP_ID, $global);
1018
+	}
1019
+
1020
+
1021
+
1022
+	/**
1023
+	 * @param \EE_messenger    $messenger
1024
+	 * @param \EE_message_type $message_type
1025
+	 * @param                  $GRP_ID
1026
+	 * @param                  $global
1027
+	 * @return array|mixed
1028
+	 */
1029
+	protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1030
+	{
1031
+		// if we're creating a custom template then we don't need to use the defaults class
1032
+		if (! $global) {
1033
+			return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1034
+		}
1035
+		/** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1036
+		$Message_Template_Defaults = EE_Registry::factory(
1037
+			'EE_Messages_Template_Defaults',
1038
+			array( $messenger, $message_type, $GRP_ID )
1039
+		);
1040
+		// generate templates
1041
+		$success = $Message_Template_Defaults->create_new_templates();
1042
+
1043
+		// if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1044
+		// its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1045
+		// attempts.
1046
+		if (! $success) {
1047
+			/** @var EE_Message_Resource_Manager $message_resource_manager */
1048
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1049
+			$message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
1050
+		}
1051
+
1052
+		/**
1053
+		 * $success is in an array in the following format
1054
+		 * array(
1055
+		 *    'GRP_ID' => $new_grp_id,
1056
+		 *    'MTP_context' => $first_context_in_new_templates,
1057
+		 * )
1058
+		 */
1059
+		return $success;
1060
+	}
1061
+
1062
+
1063
+
1064
+	/**
1065
+	 * This creates a custom template using the incoming GRP_ID
1066
+	 *
1067
+	 * @param \EE_messenger    $messenger
1068
+	 * @param \EE_message_type $message_type
1069
+	 * @param  int             $GRP_ID      GRP_ID for the template_group being used as the base
1070
+	 * @return  array $success              This will be an array in the format:
1071
+	 *                                      array(
1072
+	 *                                          'GRP_ID' => $new_grp_id,
1073
+	 *                                          'MTP_context' => $first_context_in_created_template
1074
+	 *                                      )
1075
+	 * @access private
1076
+	 */
1077
+	private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1078
+	{
1079
+		// defaults
1080
+		$success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1081
+		// get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1082
+		$Message_Template_Group = empty($GRP_ID)
1083
+			? EEM_Message_Template_Group::instance()->get_one(
1084
+				array(
1085
+					array(
1086
+						'MTP_messenger'    => $messenger->name,
1087
+						'MTP_message_type' => $message_type->name,
1088
+						'MTP_is_global'    => true
1089
+					)
1090
+				)
1091
+			)
1092
+			: EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1093
+		// if we don't have a mtg at this point then we need to bail.
1094
+		if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1095
+			EE_Error::add_error(
1096
+				sprintf(
1097
+					__(
1098
+						'Something went wrong with generating the custom template from this group id: %s.  This usually happens when there is no matching message template group in the db.',
1099
+						'event_espresso'
1100
+					),
1101
+					$GRP_ID
1102
+				),
1103
+				__FILE__,
1104
+				__FUNCTION__,
1105
+				__LINE__
1106
+			);
1107
+			return $success;
1108
+		}
1109
+		// let's get all the related message_template objects for this group.
1110
+		$message_templates = $Message_Template_Group->message_templates();
1111
+		// now we have what we need to setup the new template
1112
+		$new_mtg = clone $Message_Template_Group;
1113
+		$new_mtg->set('GRP_ID', 0);
1114
+		$new_mtg->set('MTP_is_global', false);
1115
+		$template_name = defined('DOING_AJAX') && ! empty($_POST['templateName'])
1116
+			? $_POST['templateName']
1117
+			: __(
1118
+				'New Custom Template',
1119
+				'event_espresso'
1120
+			);
1121
+		$template_description = defined("DOING_AJAX") && ! empty($_POST['templateDescription'])
1122
+			? $_POST['templateDescription']
1123
+			: sprintf(
1124
+				__(
1125
+					'This is a custom template that was created for the %s messenger and %s message type.',
1126
+					'event_espresso'
1127
+				),
1128
+				$new_mtg->messenger_obj()->label['singular'],
1129
+				$new_mtg->message_type_obj()->label['singular']
1130
+			);
1131
+		$new_mtg->set('MTP_name', $template_name);
1132
+		$new_mtg->set('MTP_description', $template_description);
1133
+		// remove ALL relations on this template group so they don't get saved!
1134
+		$new_mtg->_remove_relations('Message_Template');
1135
+		$new_mtg->save();
1136
+		$success['GRP_ID'] = $new_mtg->ID();
1137
+		$success['template_name'] = $template_name;
1138
+		// add new message templates and add relation to.
1139
+		foreach ($message_templates as $message_template) {
1140
+			if (! $message_template instanceof EE_Message_Template) {
1141
+				continue;
1142
+			}
1143
+			$new_message_template = clone $message_template;
1144
+			$new_message_template->set('MTP_ID', 0);
1145
+			$new_message_template->set('GRP_ID', $new_mtg->ID()); // relation
1146
+			$new_message_template->save();
1147
+			if (empty($success['MTP_context'])) {
1148
+				$success['MTP_context'] = $new_message_template->get('MTP_context');
1149
+			}
1150
+		}
1151
+		return $success;
1152
+	}
1153
+
1154
+
1155
+
1156
+	/**
1157
+	 * message_type_has_active_templates_for_messenger
1158
+	 *
1159
+	 * @param \EE_messenger    $messenger
1160
+	 * @param \EE_message_type $message_type
1161
+	 * @param bool             $global
1162
+	 * @return bool
1163
+	 */
1164
+	public static function message_type_has_active_templates_for_messenger(
1165
+		EE_messenger $messenger,
1166
+		EE_message_type $message_type,
1167
+		$global = false
1168
+	) {
1169
+		// is given message_type valid for given messenger (if this is not a global save)
1170
+		if ($global) {
1171
+			return true;
1172
+		}
1173
+		$active_templates = EEM_Message_Template_Group::instance()->count(
1174
+			array(
1175
+				array(
1176
+					'MTP_is_active'    => true,
1177
+					'MTP_messenger'    => $messenger->name,
1178
+					'MTP_message_type' => $message_type->name
1179
+				)
1180
+			)
1181
+		);
1182
+		if ($active_templates > 0) {
1183
+			return true;
1184
+		}
1185
+		EE_Error::add_error(
1186
+			sprintf(
1187
+				__(
1188
+					'The %1$s message type is not registered with the %2$s messenger. Please visit the Messenger activation page to assign this message type first if you want to use it.',
1189
+					'event_espresso'
1190
+				),
1191
+				$message_type->name,
1192
+				$messenger->name
1193
+			),
1194
+			__FILE__,
1195
+			__FUNCTION__,
1196
+			__LINE__
1197
+		);
1198
+		return false;
1199
+	}
1200
+
1201
+
1202
+
1203
+	/**
1204
+	 * get_fields
1205
+	 * This takes a given messenger and message type and returns all the template fields indexed by context (and with field type).
1206
+	 *
1207
+	 * @param  string $messenger_name    name of EE_messenger
1208
+	 * @param  string $message_type_name name of EE_message_type
1209
+	 * @return array
1210
+	 */
1211
+	public static function get_fields($messenger_name, $message_type_name)
1212
+	{
1213
+		$template_fields = array();
1214
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1215
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1216
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1217
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1218
+		if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1219
+			return array();
1220
+		}
1221
+
1222
+		$excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1223
+
1224
+		// okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1225
+		foreach ($message_type->get_contexts() as $context => $details) {
1226
+			foreach ($messenger->get_template_fields() as $field => $value) {
1227
+				if (in_array($field, $excluded_fields_for_messenger, true)) {
1228
+					continue;
1229
+				}
1230
+				$template_fields[ $context ][ $field ] = $value;
1231
+			}
1232
+		}
1233
+		if (empty($template_fields)) {
1234
+			EE_Error::add_error(
1235
+				__('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'),
1236
+				__FILE__,
1237
+				__FUNCTION__,
1238
+				__LINE__
1239
+			);
1240
+			return array();
1241
+		}
1242
+		return $template_fields;
1243
+	}
1244 1244
 }
Please login to merge, or discard this patch.
Spacing   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
             }
89 89
             $new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
90 90
 
91
-            if (! $new_message_template_group) {
91
+            if ( ! $new_message_template_group) {
92 92
                 continue;
93 93
             }
94 94
             $templates[] = $new_message_template_group;
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
                     )
120 120
                 )
121 121
             )
122
-            : EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
122
+            : EEM_Message_Template::instance()->count(array(array('GRP_ID' => $GRP_ID)));
123 123
 
124 124
         return $count > 0;
125 125
     }
@@ -137,14 +137,14 @@  discard block
 block discarded – undo
137 137
      */
138 138
     public static function update_to_active($messenger_names, $message_type_names)
139 139
     {
140
-        $messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
141
-        $message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
140
+        $messenger_names = is_array($messenger_names) ? $messenger_names : array($messenger_names);
141
+        $message_type_names = is_array($message_type_names) ? $message_type_names : array($message_type_names);
142 142
         return EEM_Message_Template_Group::instance()->update(
143
-            array( 'MTP_is_active' => 1 ),
143
+            array('MTP_is_active' => 1),
144 144
             array(
145 145
                 array(
146
-                    'MTP_messenger'     => array( 'IN', $messenger_names ),
147
-                    'MTP_message_type'  => array( 'IN', $message_type_names )
146
+                    'MTP_messenger'     => array('IN', $messenger_names),
147
+                    'MTP_message_type'  => array('IN', $message_type_names)
148 148
                 )
149 149
             )
150 150
         );
@@ -230,13 +230,13 @@  discard block
 block discarded – undo
230 230
         $messenger = $message_resource_manager->get_messenger($messenger);
231 231
 
232 232
         // if messenger isn't a EE_messenger resource then bail.
233
-        if (! $messenger instanceof EE_messenger) {
233
+        if ( ! $messenger instanceof EE_messenger) {
234 234
             return array();
235 235
         }
236 236
 
237 237
         // validate class for getting our list of shortcodes
238
-        $classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
239
-        if (! class_exists($classname)) {
238
+        $classname = 'EE_Messages_'.$messenger_name.'_'.$mt_name.'_Validator';
239
+        if ( ! class_exists($classname)) {
240 240
             $msg[] = __('The Validator class was unable to load', 'event_espresso');
241 241
             $msg[] = sprintf(
242 242
                 __('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
@@ -252,44 +252,44 @@  discard block
 block discarded – undo
252 252
         // let's make sure we're only getting the shortcode part of the validators
253 253
         $shortcodes = array();
254 254
         foreach ($valid_shortcodes as $field => $validators) {
255
-            $shortcodes[ $field ] = $validators['shortcodes'];
255
+            $shortcodes[$field] = $validators['shortcodes'];
256 256
         }
257 257
         $valid_shortcodes = $shortcodes;
258 258
 
259 259
         // if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
260
-        if (! empty($fields)) {
260
+        if ( ! empty($fields)) {
261 261
             $specified_shortcodes = array();
262 262
             foreach ($fields as $field) {
263
-                if (isset($valid_shortcodes[ $field ])) {
264
-                    $specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
263
+                if (isset($valid_shortcodes[$field])) {
264
+                    $specified_shortcodes[$field] = $valid_shortcodes[$field];
265 265
                 }
266 266
             }
267 267
             $valid_shortcodes = $specified_shortcodes;
268 268
         }
269 269
 
270 270
         // if not merged then let's replace the fields with the localized fields
271
-        if (! $merged) {
271
+        if ( ! $merged) {
272 272
             // let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
273 273
             $field_settings = $messenger->get_template_fields();
274 274
             $localized = array();
275 275
             foreach ($valid_shortcodes as $field => $shortcodes) {
276 276
                 // get localized field label
277
-                if (isset($field_settings[ $field ])) {
277
+                if (isset($field_settings[$field])) {
278 278
                     // possible that this is used as a main field.
279
-                    if (empty($field_settings[ $field ])) {
280
-                        if (isset($field_settings['extra'][ $field ])) {
281
-                            $_field = $field_settings['extra'][ $field ]['main']['label'];
279
+                    if (empty($field_settings[$field])) {
280
+                        if (isset($field_settings['extra'][$field])) {
281
+                            $_field = $field_settings['extra'][$field]['main']['label'];
282 282
                         } else {
283 283
                             $_field = $field;
284 284
                         }
285 285
                     } else {
286
-                        $_field = $field_settings[ $field ]['label'];
286
+                        $_field = $field_settings[$field]['label'];
287 287
                     }
288 288
                 } elseif (isset($field_settings['extra'])) {
289 289
                     // loop through extra "main fields" and see if any of their children have our field
290 290
                     foreach ($field_settings['extra'] as $main_field => $fields) {
291
-                        if (isset($fields[ $field ])) {
292
-                            $_field = $fields[ $field ]['label'];
291
+                        if (isset($fields[$field])) {
292
+                            $_field = $fields[$field]['label'];
293 293
                         } else {
294 294
                             $_field = $field;
295 295
                         }
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
                     $_field = $field;
299 299
                 }
300 300
                 if (isset($_field)) {
301
-                    $localized[ (string) $_field ] = $shortcodes;
301
+                    $localized[(string) $_field] = $shortcodes;
302 302
                 }
303 303
             }
304 304
             $valid_shortcodes = $localized;
@@ -309,10 +309,10 @@  discard block
 block discarded – undo
309 309
             $merged_codes = array();
310 310
             foreach ($valid_shortcodes as $field => $shortcode) {
311 311
                 foreach ($shortcode as $code => $label) {
312
-                    if (isset($merged_codes[ $code ])) {
312
+                    if (isset($merged_codes[$code])) {
313 313
                         continue;
314 314
                     } else {
315
-                        $merged_codes[ $code ] = $label;
315
+                        $merged_codes[$code] = $label;
316 316
                     }
317 317
                 }
318 318
             }
@@ -462,12 +462,12 @@  discard block
 block discarded – undo
462 462
         $sending_messenger = ''
463 463
     ) {
464 464
         // first determine if the url can be to the EE_Message object.
465
-        if (! $message_type->always_generate()) {
465
+        if ( ! $message_type->always_generate()) {
466 466
             return EEH_MSG_Template::generate_browser_trigger($message);
467 467
         }
468 468
 
469 469
         // if $registration object is not valid then exit early because there's nothing that can be generated.
470
-        if (! $registration instanceof EE_Registration) {
470
+        if ( ! $registration instanceof EE_Registration) {
471 471
             throw new EE_Error(
472 472
                 __('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
473 473
             );
@@ -475,7 +475,7 @@  discard block
 block discarded – undo
475 475
 
476 476
         // validate given context
477 477
         $contexts = $message_type->get_contexts();
478
-        if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
478
+        if ($message->context() !== '' && ! isset($contexts[$message->context()])) {
479 479
             throw new EE_Error(
480 480
                 sprintf(
481 481
                     __('The context %s is not a valid context for %s.', 'event_espresso'),
@@ -486,10 +486,10 @@  discard block
 block discarded – undo
486 486
         }
487 487
 
488 488
         // valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
489
-        if (! empty($sending_messenger)) {
489
+        if ( ! empty($sending_messenger)) {
490 490
             $with_messengers = $message_type->with_messengers();
491
-            if (! isset($with_messengers[ $message->messenger() ])
492
-                 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ]) ) {
491
+            if ( ! isset($with_messengers[$message->messenger()])
492
+                 || ! in_array($sending_messenger, $with_messengers[$message->messenger()])) {
493 493
                 throw new EE_Error(
494 494
                     sprintf(
495 495
                         __(
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
     public static function get_message_action_icon($type)
626 626
     {
627 627
         $action_icons = self::get_message_action_icons();
628
-        return isset($action_icons[ $type ]) ? $action_icons[ $type ] : '';
628
+        return isset($action_icons[$type]) ? $action_icons[$type] : '';
629 629
     }
630 630
 
631 631
 
@@ -688,7 +688,7 @@  discard block
 block discarded – undo
688 688
     public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
689 689
     {
690 690
         $action_urls = self::get_message_action_urls($message, $query_params);
691
-        return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
691
+        return isset($action_urls[$type]) ? $action_urls[$type] : '';
692 692
     }
693 693
 
694 694
 
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
         EE_Registry::instance()->load_helper('URL');
709 709
         // if $message is not an instance of EE_Message then let's just do a dummy.
710 710
         $message = empty($message) ? EE_Message_Factory::create() : $message;
711
-        $action_urls =  apply_filters(
711
+        $action_urls = apply_filters(
712 712
             'FHEE__EEH_MSG_Template__get_message_action_url',
713 713
             array(
714 714
                 'view' => EEH_MSG_Template::generate_browser_trigger($message),
@@ -788,7 +788,7 @@  discard block
 block discarded – undo
788 788
     {
789 789
         $url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
790 790
         $icon_css = EEH_MSG_Template::get_message_action_icon($type);
791
-        $title = isset($icon_css['label']) ? 'title="' . $icon_css['label'] . '"' : '';
791
+        $title = isset($icon_css['label']) ? 'title="'.$icon_css['label'].'"' : '';
792 792
 
793 793
         if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
794 794
             return '';
@@ -797,14 +797,14 @@  discard block
 block discarded – undo
797 797
         $icon_css['css_class'] .= esc_attr(
798 798
             apply_filters(
799 799
                 'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
800
-                ' js-ee-message-action-link ee-message-action-link-' . $type,
800
+                ' js-ee-message-action-link ee-message-action-link-'.$type,
801 801
                 $type,
802 802
                 $message,
803 803
                 $query_params
804 804
             )
805 805
         );
806 806
 
807
-        return '<a href="' . $url . '"' . $title . '><span class="' . esc_attr($icon_css['css_class']) . '"></span></a>';
807
+        return '<a href="'.$url.'"'.$title.'><span class="'.esc_attr($icon_css['css_class']).'"></span></a>';
808 808
     }
809 809
 
810 810
 
@@ -845,7 +845,7 @@  discard block
 block discarded – undo
845 845
     public static function convert_reg_status_to_message_type($reg_status)
846 846
     {
847 847
         $reg_status_array = self::reg_status_to_message_type_array();
848
-        return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
848
+        return isset($reg_status_array[$reg_status]) ? $reg_status_array[$reg_status] : '';
849 849
     }
850 850
 
851 851
 
@@ -883,7 +883,7 @@  discard block
 block discarded – undo
883 883
     public static function convert_payment_status_to_message_type($payment_status)
884 884
     {
885 885
         $payment_status_array = self::payment_status_to_message_type_array();
886
-        return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
886
+        return isset($payment_status_array[$payment_status]) ? $payment_status_array[$payment_status] : '';
887 887
     }
888 888
 
889 889
 
@@ -896,7 +896,7 @@  discard block
 block discarded – undo
896 896
      */
897 897
     public static function get_template_pack($template_pack_name)
898 898
     {
899
-        if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
899
+        if ( ! self::$_template_pack_collection instanceof EE_Object_Collection) {
900 900
             self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
901 901
         }
902 902
 
@@ -909,14 +909,14 @@  discard block
 block discarded – undo
909 909
 
910 910
         // nope...let's get it.
911 911
         // not set yet so let's attempt to get it.
912
-        $pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
912
+        $pack_class_name = 'EE_Messages_Template_Pack_'.str_replace(
913 913
             ' ',
914 914
             '_',
915 915
             ucwords(
916 916
                 str_replace('_', ' ', $template_pack_name)
917 917
             )
918 918
         );
919
-        if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
919
+        if ( ! class_exists($pack_class_name) && $template_pack_name !== 'default') {
920 920
             return self::get_template_pack('default');
921 921
         } else {
922 922
             $template_pack = new $pack_class_name;
@@ -939,18 +939,18 @@  discard block
 block discarded – undo
939 939
     public static function get_template_pack_collection()
940 940
     {
941 941
         $new_collection = false;
942
-        if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
942
+        if ( ! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
943 943
             self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
944 944
             $new_collection = true;
945 945
         }
946 946
 
947 947
         // glob the defaults directory for messages
948
-        $templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
948
+        $templates = glob(EE_LIBRARIES.'messages/defaults/*', GLOB_ONLYDIR);
949 949
         foreach ($templates as $template_path) {
950 950
             // grab folder name
951 951
             $template = basename($template_path);
952 952
 
953
-            if (! $new_collection) {
953
+            if ( ! $new_collection) {
954 954
                 // already have it?
955 955
                 if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
956 956
                     continue;
@@ -958,7 +958,7 @@  discard block
 block discarded – undo
958 958
             }
959 959
 
960 960
             // setup classname.
961
-            $template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
961
+            $template_pack_class_name = 'EE_Messages_Template_Pack_'.str_replace(
962 962
                 ' ',
963 963
                 '_',
964 964
                 ucwords(
@@ -969,7 +969,7 @@  discard block
 block discarded – undo
969 969
                     )
970 970
                 )
971 971
             );
972
-            if (! class_exists($template_pack_class_name)) {
972
+            if ( ! class_exists($template_pack_class_name)) {
973 973
                 continue;
974 974
             }
975 975
             self::$_template_pack_collection->add(new $template_pack_class_name);
@@ -1010,7 +1010,7 @@  discard block
 block discarded – undo
1010 1010
         $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1011 1011
         $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1012 1012
         $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1013
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1013
+        if ( ! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1014 1014
             return array();
1015 1015
         }
1016 1016
         // whew made it this far!  Okay, let's go ahead and create the templates then
@@ -1029,13 +1029,13 @@  discard block
 block discarded – undo
1029 1029
     protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1030 1030
     {
1031 1031
         // if we're creating a custom template then we don't need to use the defaults class
1032
-        if (! $global) {
1032
+        if ( ! $global) {
1033 1033
             return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1034 1034
         }
1035 1035
         /** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1036 1036
         $Message_Template_Defaults = EE_Registry::factory(
1037 1037
             'EE_Messages_Template_Defaults',
1038
-            array( $messenger, $message_type, $GRP_ID )
1038
+            array($messenger, $message_type, $GRP_ID)
1039 1039
         );
1040 1040
         // generate templates
1041 1041
         $success = $Message_Template_Defaults->create_new_templates();
@@ -1043,7 +1043,7 @@  discard block
 block discarded – undo
1043 1043
         // if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1044 1044
         // its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1045 1045
         // attempts.
1046
-        if (! $success) {
1046
+        if ( ! $success) {
1047 1047
             /** @var EE_Message_Resource_Manager $message_resource_manager */
1048 1048
             $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1049 1049
             $message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
@@ -1077,7 +1077,7 @@  discard block
 block discarded – undo
1077 1077
     private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1078 1078
     {
1079 1079
         // defaults
1080
-        $success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1080
+        $success = array('GRP_ID' => null, 'MTP_context' => '');
1081 1081
         // get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1082 1082
         $Message_Template_Group = empty($GRP_ID)
1083 1083
             ? EEM_Message_Template_Group::instance()->get_one(
@@ -1091,7 +1091,7 @@  discard block
 block discarded – undo
1091 1091
             )
1092 1092
             : EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1093 1093
         // if we don't have a mtg at this point then we need to bail.
1094
-        if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1094
+        if ( ! $Message_Template_Group instanceof EE_Message_Template_Group) {
1095 1095
             EE_Error::add_error(
1096 1096
                 sprintf(
1097 1097
                     __(
@@ -1137,7 +1137,7 @@  discard block
 block discarded – undo
1137 1137
         $success['template_name'] = $template_name;
1138 1138
         // add new message templates and add relation to.
1139 1139
         foreach ($message_templates as $message_template) {
1140
-            if (! $message_template instanceof EE_Message_Template) {
1140
+            if ( ! $message_template instanceof EE_Message_Template) {
1141 1141
                 continue;
1142 1142
             }
1143 1143
             $new_message_template = clone $message_template;
@@ -1215,7 +1215,7 @@  discard block
 block discarded – undo
1215 1215
         $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1216 1216
         $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1217 1217
         $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1218
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1218
+        if ( ! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1219 1219
             return array();
1220 1220
         }
1221 1221
 
@@ -1227,7 +1227,7 @@  discard block
 block discarded – undo
1227 1227
                 if (in_array($field, $excluded_fields_for_messenger, true)) {
1228 1228
                     continue;
1229 1229
                 }
1230
-                $template_fields[ $context ][ $field ] = $value;
1230
+                $template_fields[$context][$field] = $value;
1231 1231
             }
1232 1232
         }
1233 1233
         if (empty($template_fields)) {
Please login to merge, or discard this patch.
core/EE_Network_Config.core.php 2 patches
Indentation   +197 added lines, -197 removed lines patch added patch discarded remove patch
@@ -14,180 +14,180 @@  discard block
 block discarded – undo
14 14
 final class EE_Network_Config
15 15
 {
16 16
 
17
-    /**
18
-     * @var EE_Network_Config $_instance
19
-     */
20
-    private static $_instance;
21
-
22
-    /**
23
-     * addons can add their specific network_config objects to this property
24
-     *
25
-     * @var EE_Config_Base[] $addons
26
-     */
27
-    public $addons;
28
-
29
-    /**
30
-     * @var EE_Network_Core_Config $core
31
-     */
32
-    public $core;
33
-
34
-
35
-    /**
36
-     * @singleton method used to instantiate class object
37
-     * @return EE_Network_Config instance
38
-     */
39
-    public static function instance()
40
-    {
41
-        // check if class object is instantiated, and instantiated properly
42
-        if (! self::$_instance instanceof EE_Network_Config) {
43
-            self::$_instance = new self();
44
-        }
45
-        return self::$_instance;
46
-    }
47
-
48
-
49
-    /**
50
-     * class constructor
51
-     */
52
-    private function __construct()
53
-    {
54
-        do_action('AHEE__EE_Network_Config__construct__begin', $this);
55
-        // set defaults
56
-        $this->core = apply_filters('FHEE__EE_Network_Config___construct__core', new EE_Network_Core_Config());
57
-        $this->addons = array();
58
-
59
-        $this->_load_config();
60
-
61
-        // construct__end hook
62
-        do_action('AHEE__EE_Network_Config__construct__end', $this);
63
-    }
64
-
65
-
66
-    /**
67
-     * load EE Network Config options
68
-     *
69
-     * @return void
70
-     */
71
-    private function _load_config()
72
-    {
73
-        // load network config start hook
74
-        do_action('AHEE__EE_Network_Config___load_config__start', $this);
75
-        $config = $this->get_config();
76
-        foreach ($config as $config_prop => $settings) {
77
-            if ($config_prop === 'core' && ! $settings instanceof EE_Network_Core_Config) {
78
-                $core = new EE_Network_Core_Config();
79
-                foreach ($settings as $prop => $setting) {
80
-                    if (property_exists($core, $prop)) {
81
-                        $core->{$prop} = $setting;
82
-                    }
83
-                }
84
-                $settings = $core;
85
-                add_filter('FHEE__EE_Network_Config___load_config__update_network_config', '__return_true');
86
-            }
87
-            if (is_object($settings) && property_exists($this, $config_prop)) {
88
-                $this->{$config_prop} = apply_filters(
89
-                    'FHEE__EE_Network_Config___load_config__config_settings',
90
-                    $settings,
91
-                    $config_prop,
92
-                    $this
93
-                );
94
-                if (method_exists($settings, 'populate')) {
95
-                    $this->{$config_prop}->populate();
96
-                }
97
-                if (method_exists($settings, 'do_hooks')) {
98
-                    $this->{$config_prop}->do_hooks();
99
-                }
100
-            }
101
-        }
102
-        if (apply_filters('FHEE__EE_Network_Config___load_config__update_network_config', false)) {
103
-            $this->update_config();
104
-        }
105
-
106
-        // load network config end hook
107
-        do_action('AHEE__EE_Network_Config___load_config__end', $this);
108
-    }
109
-
110
-
111
-    /**
112
-     * get_config
113
-     *
114
-     * @return array of network config stuff
115
-     */
116
-    public function get_config()
117
-    {
118
-        // grab network configuration
119
-        $CFG = get_site_option('ee_network_config', array());
120
-        $CFG = apply_filters('FHEE__EE_Network_Config__get_config__CFG', $CFG);
121
-        return $CFG;
122
-    }
123
-
124
-
125
-    /**
126
-     * update_config
127
-     *
128
-     * @param bool $add_success
129
-     * @param bool $add_error
130
-     * @return bool success
131
-     */
132
-    public function update_config($add_success = false, $add_error = true)
133
-    {
134
-        do_action('AHEE__EE_Network_Config__update_config__begin', $this);
135
-
136
-        // need to bust cache for comparing original if this is a multisite install
137
-        if (is_multisite()) {
138
-            global $current_site;
139
-            $cache_key = $current_site->id . ':ee_network_config';
140
-            wp_cache_delete($cache_key, 'site-options');
141
-        }
142
-
143
-        // we have to compare existing saved config with config in memory because if there is no difference that means
144
-        // that the method executed fine but there just was no update.  WordPress doesn't distinguish between false because
145
-        // there were 0 records updated because of no change vs false because some error produced problems with the update.
146
-        $original = get_site_option('ee_network_config');
147
-
148
-        if ($original == $this) {
149
-            return true;
150
-        }
151
-        // update
152
-        $saved = update_site_option('ee_network_config', $this);
153
-
154
-        do_action('AHEE__EE_Network_Config__update_config__end', $this, $saved);
155
-        // if config remains the same or was updated successfully
156
-        if ($saved) {
157
-            if ($add_success) {
158
-                $msg = is_multisite() ? __(
159
-                    'The Event Espresso Network Configuration Settings have been successfully updated.',
160
-                    'event_espresso'
161
-                ) : __('Extra Event Espresso Configuration settings were successfully updated.', 'event_espresso');
162
-                EE_Error::add_success($msg);
163
-            }
164
-            return true;
165
-        }
166
-        if ($add_error) {
167
-            $msg = is_multisite() ? __(
168
-                'The Event Espresso Network Configuration Settings were not updated.',
169
-                'event_espresso'
170
-            ) : __('Extra Event Espresso Network Configuration settings were not updated.', 'event_espresso');
171
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
172
-        }
173
-        return false;
174
-    }
175
-
176
-
177
-    /**
178
-     * __sleep
179
-     *
180
-     * @return array
181
-     */
182
-    public function __sleep()
183
-    {
184
-        return apply_filters(
185
-            'FHEE__EE_Network_Config__sleep',
186
-            array(
187
-                'core',
188
-            )
189
-        );
190
-    }
17
+	/**
18
+	 * @var EE_Network_Config $_instance
19
+	 */
20
+	private static $_instance;
21
+
22
+	/**
23
+	 * addons can add their specific network_config objects to this property
24
+	 *
25
+	 * @var EE_Config_Base[] $addons
26
+	 */
27
+	public $addons;
28
+
29
+	/**
30
+	 * @var EE_Network_Core_Config $core
31
+	 */
32
+	public $core;
33
+
34
+
35
+	/**
36
+	 * @singleton method used to instantiate class object
37
+	 * @return EE_Network_Config instance
38
+	 */
39
+	public static function instance()
40
+	{
41
+		// check if class object is instantiated, and instantiated properly
42
+		if (! self::$_instance instanceof EE_Network_Config) {
43
+			self::$_instance = new self();
44
+		}
45
+		return self::$_instance;
46
+	}
47
+
48
+
49
+	/**
50
+	 * class constructor
51
+	 */
52
+	private function __construct()
53
+	{
54
+		do_action('AHEE__EE_Network_Config__construct__begin', $this);
55
+		// set defaults
56
+		$this->core = apply_filters('FHEE__EE_Network_Config___construct__core', new EE_Network_Core_Config());
57
+		$this->addons = array();
58
+
59
+		$this->_load_config();
60
+
61
+		// construct__end hook
62
+		do_action('AHEE__EE_Network_Config__construct__end', $this);
63
+	}
64
+
65
+
66
+	/**
67
+	 * load EE Network Config options
68
+	 *
69
+	 * @return void
70
+	 */
71
+	private function _load_config()
72
+	{
73
+		// load network config start hook
74
+		do_action('AHEE__EE_Network_Config___load_config__start', $this);
75
+		$config = $this->get_config();
76
+		foreach ($config as $config_prop => $settings) {
77
+			if ($config_prop === 'core' && ! $settings instanceof EE_Network_Core_Config) {
78
+				$core = new EE_Network_Core_Config();
79
+				foreach ($settings as $prop => $setting) {
80
+					if (property_exists($core, $prop)) {
81
+						$core->{$prop} = $setting;
82
+					}
83
+				}
84
+				$settings = $core;
85
+				add_filter('FHEE__EE_Network_Config___load_config__update_network_config', '__return_true');
86
+			}
87
+			if (is_object($settings) && property_exists($this, $config_prop)) {
88
+				$this->{$config_prop} = apply_filters(
89
+					'FHEE__EE_Network_Config___load_config__config_settings',
90
+					$settings,
91
+					$config_prop,
92
+					$this
93
+				);
94
+				if (method_exists($settings, 'populate')) {
95
+					$this->{$config_prop}->populate();
96
+				}
97
+				if (method_exists($settings, 'do_hooks')) {
98
+					$this->{$config_prop}->do_hooks();
99
+				}
100
+			}
101
+		}
102
+		if (apply_filters('FHEE__EE_Network_Config___load_config__update_network_config', false)) {
103
+			$this->update_config();
104
+		}
105
+
106
+		// load network config end hook
107
+		do_action('AHEE__EE_Network_Config___load_config__end', $this);
108
+	}
109
+
110
+
111
+	/**
112
+	 * get_config
113
+	 *
114
+	 * @return array of network config stuff
115
+	 */
116
+	public function get_config()
117
+	{
118
+		// grab network configuration
119
+		$CFG = get_site_option('ee_network_config', array());
120
+		$CFG = apply_filters('FHEE__EE_Network_Config__get_config__CFG', $CFG);
121
+		return $CFG;
122
+	}
123
+
124
+
125
+	/**
126
+	 * update_config
127
+	 *
128
+	 * @param bool $add_success
129
+	 * @param bool $add_error
130
+	 * @return bool success
131
+	 */
132
+	public function update_config($add_success = false, $add_error = true)
133
+	{
134
+		do_action('AHEE__EE_Network_Config__update_config__begin', $this);
135
+
136
+		// need to bust cache for comparing original if this is a multisite install
137
+		if (is_multisite()) {
138
+			global $current_site;
139
+			$cache_key = $current_site->id . ':ee_network_config';
140
+			wp_cache_delete($cache_key, 'site-options');
141
+		}
142
+
143
+		// we have to compare existing saved config with config in memory because if there is no difference that means
144
+		// that the method executed fine but there just was no update.  WordPress doesn't distinguish between false because
145
+		// there were 0 records updated because of no change vs false because some error produced problems with the update.
146
+		$original = get_site_option('ee_network_config');
147
+
148
+		if ($original == $this) {
149
+			return true;
150
+		}
151
+		// update
152
+		$saved = update_site_option('ee_network_config', $this);
153
+
154
+		do_action('AHEE__EE_Network_Config__update_config__end', $this, $saved);
155
+		// if config remains the same or was updated successfully
156
+		if ($saved) {
157
+			if ($add_success) {
158
+				$msg = is_multisite() ? __(
159
+					'The Event Espresso Network Configuration Settings have been successfully updated.',
160
+					'event_espresso'
161
+				) : __('Extra Event Espresso Configuration settings were successfully updated.', 'event_espresso');
162
+				EE_Error::add_success($msg);
163
+			}
164
+			return true;
165
+		}
166
+		if ($add_error) {
167
+			$msg = is_multisite() ? __(
168
+				'The Event Espresso Network Configuration Settings were not updated.',
169
+				'event_espresso'
170
+			) : __('Extra Event Espresso Network Configuration settings were not updated.', 'event_espresso');
171
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
172
+		}
173
+		return false;
174
+	}
175
+
176
+
177
+	/**
178
+	 * __sleep
179
+	 *
180
+	 * @return array
181
+	 */
182
+	public function __sleep()
183
+	{
184
+		return apply_filters(
185
+			'FHEE__EE_Network_Config__sleep',
186
+			array(
187
+				'core',
188
+			)
189
+		);
190
+	}
191 191
 }
192 192
 
193 193
 
@@ -197,27 +197,27 @@  discard block
 block discarded – undo
197 197
 class EE_Network_Core_Config extends EE_Config_Base
198 198
 {
199 199
 
200
-    /**
201
-     * PUE site license key
202
-     *
203
-     * @var string $site_license_key
204
-     */
205
-    public $site_license_key;
206
-
207
-    /**
208
-     * This indicates whether messages system processing should be done on the same request or not.
209
-     *
210
-     * @var boolean $do_messages_on_same_request
211
-     */
212
-    public $do_messages_on_same_request;
213
-
214
-
215
-    /**
216
-     * EE_Network_Core_Config constructor.
217
-     */
218
-    public function __construct()
219
-    {
220
-        $this->site_license_key = '';
221
-        $this->do_messages_on_same_request = false;
222
-    }
200
+	/**
201
+	 * PUE site license key
202
+	 *
203
+	 * @var string $site_license_key
204
+	 */
205
+	public $site_license_key;
206
+
207
+	/**
208
+	 * This indicates whether messages system processing should be done on the same request or not.
209
+	 *
210
+	 * @var boolean $do_messages_on_same_request
211
+	 */
212
+	public $do_messages_on_same_request;
213
+
214
+
215
+	/**
216
+	 * EE_Network_Core_Config constructor.
217
+	 */
218
+	public function __construct()
219
+	{
220
+		$this->site_license_key = '';
221
+		$this->do_messages_on_same_request = false;
222
+	}
223 223
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
     public static function instance()
40 40
     {
41 41
         // check if class object is instantiated, and instantiated properly
42
-        if (! self::$_instance instanceof EE_Network_Config) {
42
+        if ( ! self::$_instance instanceof EE_Network_Config) {
43 43
             self::$_instance = new self();
44 44
         }
45 45
         return self::$_instance;
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
         // need to bust cache for comparing original if this is a multisite install
137 137
         if (is_multisite()) {
138 138
             global $current_site;
139
-            $cache_key = $current_site->id . ':ee_network_config';
139
+            $cache_key = $current_site->id.':ee_network_config';
140 140
             wp_cache_delete($cache_key, 'site-options');
141 141
         }
142 142
 
Please login to merge, or discard this patch.