Completed
Branch FET-10304-welcome-to-vue (84d61b)
by
unknown
161:42 queued 151:21
created
core/helpers/EEH_Activation.helper.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -613,7 +613,7 @@  discard block
 block discarded – undo
613 613
      *
614 614
      * @since  4.6.0
615 615
      * @global WPDB $wpdb
616
-     * @return mixed null|int WP_user ID or NULL
616
+     * @return integer|null null|int WP_user ID or NULL
617 617
      */
618 618
     public static function get_default_creator_id()
619 619
     {
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
      * @static
775 775
      * @deprecated instead use TableManager::dropTable()
776 776
      * @param string $table_name
777
-     * @return bool | int
777
+     * @return integer | int
778 778
      */
779 779
     public static function delete_unused_db_table($table_name)
780 780
     {
@@ -791,7 +791,7 @@  discard block
 block discarded – undo
791 791
      * @deprecated instead use TableManager::dropIndex()
792 792
      * @param string $table_name
793 793
      * @param string $index_name
794
-     * @return bool | int
794
+     * @return integer | int
795 795
      */
796 796
     public static function drop_index($table_name, $index_name)
797 797
     {
Please login to merge, or discard this patch.
Indentation   +1694 added lines, -1694 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -14,231 +14,231 @@  discard block
 block discarded – undo
14 14
 class EEH_Activation
15 15
 {
16 16
 
17
-    /**
18
-     * constant used to indicate a cron task is no longer in use
19
-     */
20
-    const cron_task_no_longer_in_use = 'no_longer_in_use';
21
-
22
-    /**
23
-     * option name that will indicate whether or not we still
24
-     * need to create EE's folders in the uploads directory
25
-     * (because if EE was installed without file system access,
26
-     * we need to request credentials before we can create them)
27
-     */
28
-    const upload_directories_incomplete_option_name = 'ee_upload_directories_incomplete';
29
-
30
-    /**
31
-     * WP_User->ID
32
-     *
33
-     * @var int
34
-     */
35
-    private static $_default_creator_id;
36
-
37
-    /**
38
-     * indicates whether or not we've already verified core's default data during this request,
39
-     * because after migrations are done, any addons activated while in maintenance mode
40
-     * will want to setup their own default data, and they might hook into core's default data
41
-     * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
42
-     * This prevents doing that for EVERY single addon.
43
-     *
44
-     * @var boolean
45
-     */
46
-    protected static $_initialized_db_content_already_in_this_request = false;
47
-
48
-    /**
49
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
50
-     */
51
-    private static $table_analysis;
52
-
53
-    /**
54
-     * @var \EventEspresso\core\services\database\TableManager $table_manager
55
-     */
56
-    private static $table_manager;
57
-
58
-
59
-    /**
60
-     * @return \EventEspresso\core\services\database\TableAnalysis
61
-     */
62
-    public static function getTableAnalysis()
63
-    {
64
-        if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
65
-            self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
66
-        }
67
-        return self::$table_analysis;
68
-    }
69
-
70
-
71
-    /**
72
-     * @return \EventEspresso\core\services\database\TableManager
73
-     */
74
-    public static function getTableManager()
75
-    {
76
-        if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
77
-            self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
78
-        }
79
-        return self::$table_manager;
80
-    }
81
-
82
-
83
-    /**
84
-     *    _ensure_table_name_has_prefix
85
-     *
86
-     * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
87
-     * @access     public
88
-     * @static
89
-     * @param $table_name
90
-     * @return string
91
-     */
92
-    public static function ensure_table_name_has_prefix($table_name)
93
-    {
94
-        return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
95
-    }
96
-
97
-
98
-    /**
99
-     *    system_initialization
100
-     *    ensures the EE configuration settings are loaded with at least default options set
101
-     *    and that all critical EE pages have been generated with the appropriate shortcodes in place
102
-     *
103
-     * @access public
104
-     * @static
105
-     * @return void
106
-     */
107
-    public static function system_initialization()
108
-    {
109
-        EEH_Activation::reset_and_update_config();
110
-        //which is fired BEFORE activation of plugin anyways
111
-        EEH_Activation::verify_default_pages_exist();
112
-    }
113
-
114
-
115
-    /**
116
-     * Sets the database schema and creates folders. This should
117
-     * be called on plugin activation and reactivation
118
-     *
119
-     * @return boolean success, whether the database and folders are setup properly
120
-     * @throws \EE_Error
121
-     */
122
-    public static function initialize_db_and_folders()
123
-    {
124
-        $good_filesystem = EEH_Activation::create_upload_directories();
125
-        $good_db         = EEH_Activation::create_database_tables();
126
-        return $good_filesystem && $good_db;
127
-    }
128
-
129
-
130
-    /**
131
-     * assuming we have an up-to-date database schema, this will populate it
132
-     * with default and initial data. This should be called
133
-     * upon activation of a new plugin, reactivation, and at the end
134
-     * of running migration scripts
135
-     *
136
-     * @throws \EE_Error
137
-     */
138
-    public static function initialize_db_content()
139
-    {
140
-        //let's avoid doing all this logic repeatedly, especially when addons are requesting it
141
-        if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
142
-            return;
143
-        }
144
-        EEH_Activation::$_initialized_db_content_already_in_this_request = true;
145
-
146
-        EEH_Activation::initialize_system_questions();
147
-        EEH_Activation::insert_default_status_codes();
148
-        EEH_Activation::generate_default_message_templates();
149
-        EEH_Activation::create_no_ticket_prices_array();
150
-        EE_Registry::instance()->CAP->init_caps();
151
-
152
-        EEH_Activation::validate_messages_system();
153
-        EEH_Activation::insert_default_payment_methods();
154
-        //in case we've
155
-        EEH_Activation::remove_cron_tasks();
156
-        EEH_Activation::create_cron_tasks();
157
-        // remove all TXN locks since that is being done via extra meta now
158
-        delete_option('ee_locked_transactions');
159
-        //also, check for CAF default db content
160
-        do_action('AHEE__EEH_Activation__initialize_db_content');
161
-        //also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
162
-        //which users really won't care about on initial activation
163
-        EE_Error::overwrite_success();
164
-    }
165
-
166
-
167
-    /**
168
-     * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
169
-     * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
170
-     * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
171
-     * (null)
172
-     *
173
-     * @param string $which_to_include can be 'current' (ones that are currently in use),
174
-     *                                 'old' (only returns ones that should no longer be used),or 'all',
175
-     * @return array
176
-     * @throws \EE_Error
177
-     */
178
-    public static function get_cron_tasks($which_to_include)
179
-    {
180
-        $cron_tasks = apply_filters(
181
-            'FHEE__EEH_Activation__get_cron_tasks',
182
-            array(
183
-                'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
17
+	/**
18
+	 * constant used to indicate a cron task is no longer in use
19
+	 */
20
+	const cron_task_no_longer_in_use = 'no_longer_in_use';
21
+
22
+	/**
23
+	 * option name that will indicate whether or not we still
24
+	 * need to create EE's folders in the uploads directory
25
+	 * (because if EE was installed without file system access,
26
+	 * we need to request credentials before we can create them)
27
+	 */
28
+	const upload_directories_incomplete_option_name = 'ee_upload_directories_incomplete';
29
+
30
+	/**
31
+	 * WP_User->ID
32
+	 *
33
+	 * @var int
34
+	 */
35
+	private static $_default_creator_id;
36
+
37
+	/**
38
+	 * indicates whether or not we've already verified core's default data during this request,
39
+	 * because after migrations are done, any addons activated while in maintenance mode
40
+	 * will want to setup their own default data, and they might hook into core's default data
41
+	 * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
42
+	 * This prevents doing that for EVERY single addon.
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	protected static $_initialized_db_content_already_in_this_request = false;
47
+
48
+	/**
49
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
50
+	 */
51
+	private static $table_analysis;
52
+
53
+	/**
54
+	 * @var \EventEspresso\core\services\database\TableManager $table_manager
55
+	 */
56
+	private static $table_manager;
57
+
58
+
59
+	/**
60
+	 * @return \EventEspresso\core\services\database\TableAnalysis
61
+	 */
62
+	public static function getTableAnalysis()
63
+	{
64
+		if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
65
+			self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
66
+		}
67
+		return self::$table_analysis;
68
+	}
69
+
70
+
71
+	/**
72
+	 * @return \EventEspresso\core\services\database\TableManager
73
+	 */
74
+	public static function getTableManager()
75
+	{
76
+		if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
77
+			self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
78
+		}
79
+		return self::$table_manager;
80
+	}
81
+
82
+
83
+	/**
84
+	 *    _ensure_table_name_has_prefix
85
+	 *
86
+	 * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
87
+	 * @access     public
88
+	 * @static
89
+	 * @param $table_name
90
+	 * @return string
91
+	 */
92
+	public static function ensure_table_name_has_prefix($table_name)
93
+	{
94
+		return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
95
+	}
96
+
97
+
98
+	/**
99
+	 *    system_initialization
100
+	 *    ensures the EE configuration settings are loaded with at least default options set
101
+	 *    and that all critical EE pages have been generated with the appropriate shortcodes in place
102
+	 *
103
+	 * @access public
104
+	 * @static
105
+	 * @return void
106
+	 */
107
+	public static function system_initialization()
108
+	{
109
+		EEH_Activation::reset_and_update_config();
110
+		//which is fired BEFORE activation of plugin anyways
111
+		EEH_Activation::verify_default_pages_exist();
112
+	}
113
+
114
+
115
+	/**
116
+	 * Sets the database schema and creates folders. This should
117
+	 * be called on plugin activation and reactivation
118
+	 *
119
+	 * @return boolean success, whether the database and folders are setup properly
120
+	 * @throws \EE_Error
121
+	 */
122
+	public static function initialize_db_and_folders()
123
+	{
124
+		$good_filesystem = EEH_Activation::create_upload_directories();
125
+		$good_db         = EEH_Activation::create_database_tables();
126
+		return $good_filesystem && $good_db;
127
+	}
128
+
129
+
130
+	/**
131
+	 * assuming we have an up-to-date database schema, this will populate it
132
+	 * with default and initial data. This should be called
133
+	 * upon activation of a new plugin, reactivation, and at the end
134
+	 * of running migration scripts
135
+	 *
136
+	 * @throws \EE_Error
137
+	 */
138
+	public static function initialize_db_content()
139
+	{
140
+		//let's avoid doing all this logic repeatedly, especially when addons are requesting it
141
+		if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
142
+			return;
143
+		}
144
+		EEH_Activation::$_initialized_db_content_already_in_this_request = true;
145
+
146
+		EEH_Activation::initialize_system_questions();
147
+		EEH_Activation::insert_default_status_codes();
148
+		EEH_Activation::generate_default_message_templates();
149
+		EEH_Activation::create_no_ticket_prices_array();
150
+		EE_Registry::instance()->CAP->init_caps();
151
+
152
+		EEH_Activation::validate_messages_system();
153
+		EEH_Activation::insert_default_payment_methods();
154
+		//in case we've
155
+		EEH_Activation::remove_cron_tasks();
156
+		EEH_Activation::create_cron_tasks();
157
+		// remove all TXN locks since that is being done via extra meta now
158
+		delete_option('ee_locked_transactions');
159
+		//also, check for CAF default db content
160
+		do_action('AHEE__EEH_Activation__initialize_db_content');
161
+		//also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
162
+		//which users really won't care about on initial activation
163
+		EE_Error::overwrite_success();
164
+	}
165
+
166
+
167
+	/**
168
+	 * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
169
+	 * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
170
+	 * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
171
+	 * (null)
172
+	 *
173
+	 * @param string $which_to_include can be 'current' (ones that are currently in use),
174
+	 *                                 'old' (only returns ones that should no longer be used),or 'all',
175
+	 * @return array
176
+	 * @throws \EE_Error
177
+	 */
178
+	public static function get_cron_tasks($which_to_include)
179
+	{
180
+		$cron_tasks = apply_filters(
181
+			'FHEE__EEH_Activation__get_cron_tasks',
182
+			array(
183
+				'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
184 184
 //				'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
185
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
186
-                //there may have been a bug which prevented from these cron tasks from getting unscheduled, so we might want to remove these for a few updates
187
-            )
188
-        );
189
-        if ($which_to_include === 'old') {
190
-            $cron_tasks = array_filter(
191
-                $cron_tasks,
192
-                function ($value) {
193
-                    return $value === EEH_Activation::cron_task_no_longer_in_use;
194
-                }
195
-            );
196
-        } elseif ($which_to_include === 'current') {
197
-            $cron_tasks = array_filter($cron_tasks);
198
-        } elseif (WP_DEBUG && $which_to_include !== 'all') {
199
-            throw new EE_Error(
200
-                sprintf(
201
-                    __(
202
-                        'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
203
-                        'event_espresso'
204
-                    ),
205
-                    $which_to_include
206
-                )
207
-            );
208
-        }
209
-        return $cron_tasks;
210
-    }
211
-
212
-
213
-    /**
214
-     * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
215
-     *
216
-     * @throws \EE_Error
217
-     */
218
-    public static function create_cron_tasks()
219
-    {
220
-
221
-        foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
222
-            if (! wp_next_scheduled($hook_name)) {
223
-                wp_schedule_event(time(), $frequency, $hook_name);
224
-            }
225
-        }
226
-
227
-    }
228
-
229
-
230
-    /**
231
-     * Remove the currently-existing and now-removed cron tasks.
232
-     *
233
-     * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
234
-     * @throws \EE_Error
235
-     */
236
-    public static function remove_cron_tasks($remove_all = true)
237
-    {
238
-        $cron_tasks_to_remove = $remove_all ? 'all' : 'old';
239
-        $crons                = _get_cron_array();
240
-        $crons                = is_array($crons) ? $crons : array();
241
-        /* reminder of what $crons look like:
185
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
186
+				//there may have been a bug which prevented from these cron tasks from getting unscheduled, so we might want to remove these for a few updates
187
+			)
188
+		);
189
+		if ($which_to_include === 'old') {
190
+			$cron_tasks = array_filter(
191
+				$cron_tasks,
192
+				function ($value) {
193
+					return $value === EEH_Activation::cron_task_no_longer_in_use;
194
+				}
195
+			);
196
+		} elseif ($which_to_include === 'current') {
197
+			$cron_tasks = array_filter($cron_tasks);
198
+		} elseif (WP_DEBUG && $which_to_include !== 'all') {
199
+			throw new EE_Error(
200
+				sprintf(
201
+					__(
202
+						'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
203
+						'event_espresso'
204
+					),
205
+					$which_to_include
206
+				)
207
+			);
208
+		}
209
+		return $cron_tasks;
210
+	}
211
+
212
+
213
+	/**
214
+	 * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
215
+	 *
216
+	 * @throws \EE_Error
217
+	 */
218
+	public static function create_cron_tasks()
219
+	{
220
+
221
+		foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
222
+			if (! wp_next_scheduled($hook_name)) {
223
+				wp_schedule_event(time(), $frequency, $hook_name);
224
+			}
225
+		}
226
+
227
+	}
228
+
229
+
230
+	/**
231
+	 * Remove the currently-existing and now-removed cron tasks.
232
+	 *
233
+	 * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
234
+	 * @throws \EE_Error
235
+	 */
236
+	public static function remove_cron_tasks($remove_all = true)
237
+	{
238
+		$cron_tasks_to_remove = $remove_all ? 'all' : 'old';
239
+		$crons                = _get_cron_array();
240
+		$crons                = is_array($crons) ? $crons : array();
241
+		/* reminder of what $crons look like:
242 242
          * Top-level keys are timestamps, and their values are arrays.
243 243
          * The 2nd level arrays have keys with each of the cron task hook names to run at that time
244 244
          * and their values are arrays.
@@ -255,966 +255,966 @@  discard block
 block discarded – undo
255 255
          *					...
256 256
          *      ...
257 257
          */
258
-        $ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
259
-        foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
260
-            if (is_array($hooks_to_fire_at_time)) {
261
-                foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
262
-                    if (isset($ee_cron_tasks_to_remove[$hook_name])
263
-                        && is_array($ee_cron_tasks_to_remove[$hook_name])
264
-                    ) {
265
-                        unset($crons[$timestamp][$hook_name]);
266
-                    }
267
-                }
268
-                //also take care of any empty cron timestamps.
269
-                if (empty($hooks_to_fire_at_time)) {
270
-                    unset($crons[$timestamp]);
271
-                }
272
-            }
273
-        }
274
-        _set_cron_array($crons);
275
-    }
276
-
277
-
278
-    /**
279
-     *    CPT_initialization
280
-     *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
281
-     *
282
-     * @access public
283
-     * @static
284
-     * @return void
285
-     */
286
-    public static function CPT_initialization()
287
-    {
288
-        // register Custom Post Types
289
-        EE_Registry::instance()->load_core('Register_CPTs');
290
-        flush_rewrite_rules();
291
-    }
292
-
293
-
294
-
295
-    /**
296
-     *    reset_and_update_config
297
-     * The following code was moved over from EE_Config so that it will no longer run on every request.
298
-     * If there is old calendar config data saved, then it will get converted on activation.
299
-     * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
300
-     *
301
-     * @access public
302
-     * @static
303
-     * @return void
304
-     */
305
-    public static function reset_and_update_config()
306
-    {
307
-        do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
308
-        add_filter(
309
-            'FHEE__EE_Config___load_core_config__config_settings',
310
-            array('EEH_Activation', 'migrate_old_config_data'),
311
-            10,
312
-            3
313
-        );
314
-        //EE_Config::reset();
315
-        if (! EE_Config::logging_enabled()) {
316
-            delete_option(EE_Config::LOG_NAME);
317
-        }
318
-    }
319
-
320
-
321
-    /**
322
-     *    load_calendar_config
323
-     *
324
-     * @access    public
325
-     * @return    void
326
-     */
327
-    public static function load_calendar_config()
328
-    {
329
-        // grab array of all plugin folders and loop thru it
330
-        $plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
331
-        if (empty($plugins)) {
332
-            return;
333
-        }
334
-        foreach ($plugins as $plugin_path) {
335
-            // grab plugin folder name from path
336
-            $plugin = basename($plugin_path);
337
-            // drill down to Espresso plugins
338
-            // then to calendar related plugins
339
-            if (
340
-                strpos($plugin, 'espresso') !== false
341
-                || strpos($plugin, 'Espresso') !== false
342
-                || strpos($plugin, 'ee4') !== false
343
-                || strpos($plugin, 'EE4') !== false
344
-                || strpos($plugin, 'calendar') !== false
345
-            ) {
346
-                // this is what we are looking for
347
-                $calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
348
-                // does it exist in this folder ?
349
-                if (is_readable($calendar_config)) {
350
-                    // YEAH! let's load it
351
-                    require_once($calendar_config);
352
-                }
353
-            }
354
-        }
355
-    }
356
-
357
-
358
-
359
-    /**
360
-     *    _migrate_old_config_data
361
-     *
362
-     * @access    public
363
-     * @param array|stdClass $settings
364
-     * @param string         $config
365
-     * @param \EE_Config     $EE_Config
366
-     * @return \stdClass
367
-     */
368
-    public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
369
-    {
370
-        $convert_from_array = array('addons');
371
-        // in case old settings were saved as an array
372
-        if (is_array($settings) && in_array($config, $convert_from_array)) {
373
-            // convert existing settings to an object
374
-            $config_array = $settings;
375
-            $settings = new stdClass();
376
-            foreach ($config_array as $key => $value) {
377
-                if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
378
-                    $EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
379
-                } else {
380
-                    $settings->{$key} = $value;
381
-                }
382
-            }
383
-            add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
384
-        }
385
-        return $settings;
386
-    }
387
-
388
-
389
-    /**
390
-     * deactivate_event_espresso
391
-     *
392
-     * @access public
393
-     * @static
394
-     * @return void
395
-     */
396
-    public static function deactivate_event_espresso()
397
-    {
398
-        // check permissions
399
-        if (current_user_can('activate_plugins')) {
400
-            deactivate_plugins(EE_PLUGIN_BASENAME, true);
401
-        }
402
-    }
403
-
404
-
405
-
406
-
407
-
408
-    /**
409
-     * verify_default_pages_exist
410
-     *
411
-     * @access public
412
-     * @static
413
-     * @return void
414
-     */
415
-    public static function verify_default_pages_exist()
416
-    {
417
-        $critical_page_problem = false;
418
-        $critical_pages = array(
419
-            array(
420
-                'id'   => 'reg_page_id',
421
-                'name' => __('Registration Checkout', 'event_espresso'),
422
-                'post' => null,
423
-                'code' => 'ESPRESSO_CHECKOUT',
424
-            ),
425
-            array(
426
-                'id'   => 'txn_page_id',
427
-                'name' => __('Transactions', 'event_espresso'),
428
-                'post' => null,
429
-                'code' => 'ESPRESSO_TXN_PAGE',
430
-            ),
431
-            array(
432
-                'id'   => 'thank_you_page_id',
433
-                'name' => __('Thank You', 'event_espresso'),
434
-                'post' => null,
435
-                'code' => 'ESPRESSO_THANK_YOU',
436
-            ),
437
-            array(
438
-                'id'   => 'cancel_page_id',
439
-                'name' => __('Registration Cancelled', 'event_espresso'),
440
-                'post' => null,
441
-                'code' => 'ESPRESSO_CANCELLED',
442
-            ),
443
-        );
444
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
445
-        foreach ($critical_pages as $critical_page) {
446
-            // is critical page ID set in config ?
447
-            if ($EE_Core_Config->{$critical_page['id']} !== false) {
448
-                // attempt to find post by ID
449
-                $critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
450
-            }
451
-            // no dice?
452
-            if ($critical_page['post'] === null) {
453
-                // attempt to find post by title
454
-                $critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
455
-                // still nothing?
456
-                if ($critical_page['post'] === null) {
457
-                    $critical_page = EEH_Activation::create_critical_page($critical_page);
458
-                    // REALLY? Still nothing ??!?!?
459
-                    if ($critical_page['post'] === null) {
460
-                        $msg = __(
461
-                            'The Event Espresso critical page configuration settings could not be updated.',
462
-                            'event_espresso'
463
-                        );
464
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
465
-                        break;
466
-                    }
467
-                }
468
-            }
469
-            // track post_shortcodes
470
-            if ($critical_page['post']) {
471
-                EEH_Activation::_track_critical_page_post_shortcodes($critical_page);
472
-            }
473
-            // check that Post ID matches critical page ID in config
474
-            if (
475
-                isset($critical_page['post']->ID)
476
-                && $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
477
-            ) {
478
-                //update Config with post ID
479
-                $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
480
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
481
-                    $msg = __(
482
-                        'The Event Espresso critical page configuration settings could not be updated.',
483
-                        'event_espresso'
484
-                    );
485
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
486
-                }
487
-            }
488
-            $critical_page_problem =
489
-                ! isset($critical_page['post']->post_status)
490
-                || $critical_page['post']->post_status !== 'publish'
491
-                || strpos($critical_page['post']->post_content, $critical_page['code']) === false
492
-                    ? true
493
-                    : $critical_page_problem;
494
-        }
495
-        if ($critical_page_problem) {
496
-            $msg = sprintf(
497
-                __(
498
-                    'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
499
-                    'event_espresso'
500
-                ),
501
-                '<a href="'
502
-                . admin_url('admin.php?page=espresso_general_settings&action=critical_pages')
503
-                . '">'
504
-                . __('Event Espresso Critical Pages Settings', 'event_espresso')
505
-                . '</a>'
506
-            );
507
-            EE_Error::add_persistent_admin_notice('critical_page_problem', $msg);
508
-        }
509
-        if (EE_Error::has_notices()) {
510
-            EE_Error::get_notices(false, true, true);
511
-        }
512
-    }
513
-
514
-
515
-
516
-    /**
517
-     * Returns the first post which uses the specified shortcode
518
-     *
519
-     * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
520
-     *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
521
-     *                             "[ESPRESSO_THANK_YOU"
522
-     *                             (we don't search for the closing shortcode bracket because they might have added
523
-     *                             parameter to the shortcode
524
-     * @return WP_Post or NULl
525
-     */
526
-    public static function get_page_by_ee_shortcode($ee_shortcode)
527
-    {
528
-        global $wpdb;
529
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
530
-        $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
531
-        if ($post_id) {
532
-            return get_post($post_id);
533
-        } else {
534
-            return null;
535
-        }
536
-    }
537
-
538
-
539
-    /**
540
-     *    This function generates a post for critical espresso pages
541
-     *
542
-     * @access public
543
-     * @static
544
-     * @param array $critical_page
545
-     * @return array
546
-     */
547
-    public static function create_critical_page($critical_page)
548
-    {
549
-
550
-        $post_args = array(
551
-            'post_title'     => $critical_page['name'],
552
-            'post_status'    => 'publish',
553
-            'post_type'      => 'page',
554
-            'comment_status' => 'closed',
555
-            'post_content'   => '[' . $critical_page['code'] . ']',
556
-        );
557
-
558
-        $post_id = wp_insert_post($post_args);
559
-        if (! $post_id) {
560
-            $msg = sprintf(
561
-                __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
562
-                $critical_page['name']
563
-            );
564
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
565
-            return $critical_page;
566
-        }
567
-        // get newly created post's details
568
-        if (! $critical_page['post'] = get_post($post_id)) {
569
-            $msg = sprintf(
570
-                __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
571
-                $critical_page['name']
572
-            );
573
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
574
-        }
575
-
576
-        return $critical_page;
577
-
578
-    }
579
-
580
-
581
-
582
-
583
-
584
-    /**
585
-     *    This function adds a critical page's shortcode to the post_shortcodes array
586
-     *
587
-     * @access private
588
-     * @static
589
-     * @param array $critical_page
590
-     * @return void
591
-     */
592
-    private static function _track_critical_page_post_shortcodes($critical_page = array())
593
-    {
594
-        // check the goods
595
-        if ( ! $critical_page['post'] instanceof WP_Post) {
596
-            $msg = sprintf(
597
-                __(
598
-                    'The Event Espresso critical page shortcode for the page %s can not be tracked because it is not a WP_Post object.',
599
-                    'event_espresso'
600
-                ),
601
-                $critical_page['name']
602
-            );
603
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
604
-            return;
605
-        }
606
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
607
-        // map shortcode to post
608
-        $EE_Core_Config->post_shortcodes[$critical_page['post']->post_name][$critical_page['code']] = $critical_page['post']->ID;
609
-        // and make sure it's NOT added to the WP "Posts Page"
610
-        // name of the WP Posts Page
611
-        $posts_page = EE_Config::get_page_for_posts();
612
-        if (isset($EE_Core_Config->post_shortcodes[$posts_page])) {
613
-            unset($EE_Core_Config->post_shortcodes[$posts_page][$critical_page['code']]);
614
-        }
615
-        if ($posts_page !== 'posts' && isset($EE_Core_Config->post_shortcodes['posts'])) {
616
-            unset($EE_Core_Config->post_shortcodes['posts'][$critical_page['code']]);
617
-        }
618
-        // update post_shortcode CFG
619
-        if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
620
-            $msg = sprintf(
621
-                __(
622
-                    'The Event Espresso critical page shortcode for the %s page could not be configured properly.',
623
-                    'event_espresso'
624
-                ),
625
-                $critical_page['name']
626
-            );
627
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
628
-        }
629
-    }
630
-
631
-
632
-
633
-    /**
634
-     * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
635
-     * The role being used to check is filterable.
636
-     *
637
-     * @since  4.6.0
638
-     * @global WPDB $wpdb
639
-     * @return mixed null|int WP_user ID or NULL
640
-     */
641
-    public static function get_default_creator_id()
642
-    {
643
-        global $wpdb;
644
-        if ( ! empty(self::$_default_creator_id)) {
645
-            return self::$_default_creator_id;
646
-        }/**/
647
-        $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
648
-        //let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
649
-        $pre_filtered_id = apply_filters(
650
-            'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
651
-            false,
652
-            $role_to_check
653
-        );
654
-        if ($pre_filtered_id !== false) {
655
-            return (int)$pre_filtered_id;
656
-        }
657
-        $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
658
-        $query = $wpdb->prepare(
659
-            "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
660
-            '%' . $role_to_check . '%'
661
-        );
662
-        $user_id = $wpdb->get_var($query);
663
-        $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
664
-        if ($user_id && (int)$user_id) {
665
-            self::$_default_creator_id = (int)$user_id;
666
-            return self::$_default_creator_id;
667
-        } else {
668
-            return null;
669
-        }
670
-    }
671
-
672
-
673
-
674
-    /**
675
-     * used by EE and EE addons during plugin activation to create tables.
676
-     * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
677
-     * but includes extra logic regarding activations.
678
-     *
679
-     * @access public
680
-     * @static
681
-     * @param string  $table_name              without the $wpdb->prefix
682
-     * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
683
-     *                                         table query)
684
-     * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
685
-     * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
686
-     *                                         and new once this function is done (ie, you really do want to CREATE a
687
-     *                                         table, and expect it to be empty once you're done) leave as FALSE when
688
-     *                                         you just want to verify the table exists and matches this definition
689
-     *                                         (and if it HAS data in it you want to leave it be)
690
-     * @return void
691
-     * @throws EE_Error if there are database errors
692
-     */
693
-    public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
694
-    {
695
-        if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
696
-            return;
697
-        }
698
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
699
-        if ( ! function_exists('dbDelta')) {
700
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
701
-        }
702
-        $tableAnalysis = \EEH_Activation::getTableAnalysis();
703
-        $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
704
-        // do we need to first delete an existing version of this table ?
705
-        if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
706
-            // ok, delete the table... but ONLY if it's empty
707
-            $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
708
-            // table is NOT empty, are you SURE you want to delete this table ???
709
-            if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
710
-                \EEH_Activation::getTableManager()->dropTable($wp_table_name);
711
-            } else if ( ! $deleted_safely) {
712
-                // so we should be more cautious rather than just dropping tables so easily
713
-                error_log(
714
-                    sprintf(
715
-                        __(
716
-                            'It appears that database table "%1$s" exists when it shouldn\'t, and therefore may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend: %2$s 1. create a new COMPLETE backup of your database, %2$s 2. delete ALL tables from your database, %2$s 3. restore to your previous backup. %2$s If, however, you have not restored to a backup, then somehow your "%3$s" WordPress option could not be read. You can probably ignore this message, but should investigate why that option is being removed.',
717
-                            'event_espresso'
718
-                        ),
719
-                        $wp_table_name,
720
-                        '<br/>',
721
-                        'espresso_db_update'
722
-                    )
723
-                );
724
-            }
725
-        }
726
-        $engine = str_replace('ENGINE=', '', $engine);
727
-        \EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
728
-    }
729
-
730
-
731
-
732
-    /**
733
-     *    add_column_if_it_doesn't_exist
734
-     *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
735
-     *
736
-     * @access     public
737
-     * @static
738
-     * @deprecated instead use TableManager::addColumn()
739
-     * @param string $table_name  (without "wp_", eg "esp_attendee"
740
-     * @param string $column_name
741
-     * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
742
-     *                            'VARCHAR(10)'
743
-     * @return bool|int
744
-     */
745
-    public static function add_column_if_it_doesnt_exist(
746
-        $table_name,
747
-        $column_name,
748
-        $column_info = 'INT UNSIGNED NOT NULL'
749
-    ) {
750
-        return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
751
-    }
752
-
753
-
754
-    /**
755
-     * get_fields_on_table
756
-     * Gets all the fields on the database table.
757
-     *
758
-     * @access     public
759
-     * @deprecated instead use TableManager::getTableColumns()
760
-     * @static
761
-     * @param string $table_name , without prefixed $wpdb->prefix
762
-     * @return array of database column names
763
-     */
764
-    public static function get_fields_on_table($table_name = null)
765
-    {
766
-        return \EEH_Activation::getTableManager()->getTableColumns($table_name);
767
-    }
768
-
769
-
770
-    /**
771
-     * db_table_is_empty
772
-     *
773
-     * @access     public\
774
-     * @deprecated instead use TableAnalysis::tableIsEmpty()
775
-     * @static
776
-     * @param string $table_name
777
-     * @return bool
778
-     */
779
-    public static function db_table_is_empty($table_name)
780
-    {
781
-        return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
782
-    }
783
-
784
-
785
-    /**
786
-     * delete_db_table_if_empty
787
-     *
788
-     * @access public
789
-     * @static
790
-     * @param string $table_name
791
-     * @return bool | int
792
-     */
793
-    public static function delete_db_table_if_empty($table_name)
794
-    {
795
-        if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
796
-            return \EEH_Activation::getTableManager()->dropTable($table_name);
797
-        }
798
-        return false;
799
-    }
800
-
801
-
802
-    /**
803
-     * delete_unused_db_table
804
-     *
805
-     * @access     public
806
-     * @static
807
-     * @deprecated instead use TableManager::dropTable()
808
-     * @param string $table_name
809
-     * @return bool | int
810
-     */
811
-    public static function delete_unused_db_table($table_name)
812
-    {
813
-        return \EEH_Activation::getTableManager()->dropTable($table_name);
814
-    }
815
-
816
-
817
-    /**
818
-     * drop_index
819
-     *
820
-     * @access     public
821
-     * @static
822
-     * @deprecated instead use TableManager::dropIndex()
823
-     * @param string $table_name
824
-     * @param string $index_name
825
-     * @return bool | int
826
-     */
827
-    public static function drop_index($table_name, $index_name)
828
-    {
829
-        return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
830
-    }
831
-
832
-
833
-
834
-    /**
835
-     * create_database_tables
836
-     *
837
-     * @access public
838
-     * @static
839
-     * @throws EE_Error
840
-     * @return boolean success (whether database is setup properly or not)
841
-     */
842
-    public static function create_database_tables()
843
-    {
844
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
845
-        //find the migration script that sets the database to be compatible with the code
846
-        $dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
847
-        if ($dms_name) {
848
-            $current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
849
-            $current_data_migration_script->set_migrating(false);
850
-            $current_data_migration_script->schema_changes_before_migration();
851
-            $current_data_migration_script->schema_changes_after_migration();
852
-            if ($current_data_migration_script->get_errors()) {
853
-                if (WP_DEBUG) {
854
-                    foreach ($current_data_migration_script->get_errors() as $error) {
855
-                        EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
856
-                    }
857
-                } else {
858
-                    EE_Error::add_error(
859
-                        __(
860
-                            'There were errors creating the Event Espresso database tables and Event Espresso has been 
258
+		$ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
259
+		foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
260
+			if (is_array($hooks_to_fire_at_time)) {
261
+				foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
262
+					if (isset($ee_cron_tasks_to_remove[$hook_name])
263
+						&& is_array($ee_cron_tasks_to_remove[$hook_name])
264
+					) {
265
+						unset($crons[$timestamp][$hook_name]);
266
+					}
267
+				}
268
+				//also take care of any empty cron timestamps.
269
+				if (empty($hooks_to_fire_at_time)) {
270
+					unset($crons[$timestamp]);
271
+				}
272
+			}
273
+		}
274
+		_set_cron_array($crons);
275
+	}
276
+
277
+
278
+	/**
279
+	 *    CPT_initialization
280
+	 *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
281
+	 *
282
+	 * @access public
283
+	 * @static
284
+	 * @return void
285
+	 */
286
+	public static function CPT_initialization()
287
+	{
288
+		// register Custom Post Types
289
+		EE_Registry::instance()->load_core('Register_CPTs');
290
+		flush_rewrite_rules();
291
+	}
292
+
293
+
294
+
295
+	/**
296
+	 *    reset_and_update_config
297
+	 * The following code was moved over from EE_Config so that it will no longer run on every request.
298
+	 * If there is old calendar config data saved, then it will get converted on activation.
299
+	 * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
300
+	 *
301
+	 * @access public
302
+	 * @static
303
+	 * @return void
304
+	 */
305
+	public static function reset_and_update_config()
306
+	{
307
+		do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
308
+		add_filter(
309
+			'FHEE__EE_Config___load_core_config__config_settings',
310
+			array('EEH_Activation', 'migrate_old_config_data'),
311
+			10,
312
+			3
313
+		);
314
+		//EE_Config::reset();
315
+		if (! EE_Config::logging_enabled()) {
316
+			delete_option(EE_Config::LOG_NAME);
317
+		}
318
+	}
319
+
320
+
321
+	/**
322
+	 *    load_calendar_config
323
+	 *
324
+	 * @access    public
325
+	 * @return    void
326
+	 */
327
+	public static function load_calendar_config()
328
+	{
329
+		// grab array of all plugin folders and loop thru it
330
+		$plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
331
+		if (empty($plugins)) {
332
+			return;
333
+		}
334
+		foreach ($plugins as $plugin_path) {
335
+			// grab plugin folder name from path
336
+			$plugin = basename($plugin_path);
337
+			// drill down to Espresso plugins
338
+			// then to calendar related plugins
339
+			if (
340
+				strpos($plugin, 'espresso') !== false
341
+				|| strpos($plugin, 'Espresso') !== false
342
+				|| strpos($plugin, 'ee4') !== false
343
+				|| strpos($plugin, 'EE4') !== false
344
+				|| strpos($plugin, 'calendar') !== false
345
+			) {
346
+				// this is what we are looking for
347
+				$calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
348
+				// does it exist in this folder ?
349
+				if (is_readable($calendar_config)) {
350
+					// YEAH! let's load it
351
+					require_once($calendar_config);
352
+				}
353
+			}
354
+		}
355
+	}
356
+
357
+
358
+
359
+	/**
360
+	 *    _migrate_old_config_data
361
+	 *
362
+	 * @access    public
363
+	 * @param array|stdClass $settings
364
+	 * @param string         $config
365
+	 * @param \EE_Config     $EE_Config
366
+	 * @return \stdClass
367
+	 */
368
+	public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
369
+	{
370
+		$convert_from_array = array('addons');
371
+		// in case old settings were saved as an array
372
+		if (is_array($settings) && in_array($config, $convert_from_array)) {
373
+			// convert existing settings to an object
374
+			$config_array = $settings;
375
+			$settings = new stdClass();
376
+			foreach ($config_array as $key => $value) {
377
+				if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
378
+					$EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
379
+				} else {
380
+					$settings->{$key} = $value;
381
+				}
382
+			}
383
+			add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
384
+		}
385
+		return $settings;
386
+	}
387
+
388
+
389
+	/**
390
+	 * deactivate_event_espresso
391
+	 *
392
+	 * @access public
393
+	 * @static
394
+	 * @return void
395
+	 */
396
+	public static function deactivate_event_espresso()
397
+	{
398
+		// check permissions
399
+		if (current_user_can('activate_plugins')) {
400
+			deactivate_plugins(EE_PLUGIN_BASENAME, true);
401
+		}
402
+	}
403
+
404
+
405
+
406
+
407
+
408
+	/**
409
+	 * verify_default_pages_exist
410
+	 *
411
+	 * @access public
412
+	 * @static
413
+	 * @return void
414
+	 */
415
+	public static function verify_default_pages_exist()
416
+	{
417
+		$critical_page_problem = false;
418
+		$critical_pages = array(
419
+			array(
420
+				'id'   => 'reg_page_id',
421
+				'name' => __('Registration Checkout', 'event_espresso'),
422
+				'post' => null,
423
+				'code' => 'ESPRESSO_CHECKOUT',
424
+			),
425
+			array(
426
+				'id'   => 'txn_page_id',
427
+				'name' => __('Transactions', 'event_espresso'),
428
+				'post' => null,
429
+				'code' => 'ESPRESSO_TXN_PAGE',
430
+			),
431
+			array(
432
+				'id'   => 'thank_you_page_id',
433
+				'name' => __('Thank You', 'event_espresso'),
434
+				'post' => null,
435
+				'code' => 'ESPRESSO_THANK_YOU',
436
+			),
437
+			array(
438
+				'id'   => 'cancel_page_id',
439
+				'name' => __('Registration Cancelled', 'event_espresso'),
440
+				'post' => null,
441
+				'code' => 'ESPRESSO_CANCELLED',
442
+			),
443
+		);
444
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
445
+		foreach ($critical_pages as $critical_page) {
446
+			// is critical page ID set in config ?
447
+			if ($EE_Core_Config->{$critical_page['id']} !== false) {
448
+				// attempt to find post by ID
449
+				$critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
450
+			}
451
+			// no dice?
452
+			if ($critical_page['post'] === null) {
453
+				// attempt to find post by title
454
+				$critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
455
+				// still nothing?
456
+				if ($critical_page['post'] === null) {
457
+					$critical_page = EEH_Activation::create_critical_page($critical_page);
458
+					// REALLY? Still nothing ??!?!?
459
+					if ($critical_page['post'] === null) {
460
+						$msg = __(
461
+							'The Event Espresso critical page configuration settings could not be updated.',
462
+							'event_espresso'
463
+						);
464
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
465
+						break;
466
+					}
467
+				}
468
+			}
469
+			// track post_shortcodes
470
+			if ($critical_page['post']) {
471
+				EEH_Activation::_track_critical_page_post_shortcodes($critical_page);
472
+			}
473
+			// check that Post ID matches critical page ID in config
474
+			if (
475
+				isset($critical_page['post']->ID)
476
+				&& $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
477
+			) {
478
+				//update Config with post ID
479
+				$EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
480
+				if (! EE_Config::instance()->update_espresso_config(false, false)) {
481
+					$msg = __(
482
+						'The Event Espresso critical page configuration settings could not be updated.',
483
+						'event_espresso'
484
+					);
485
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
486
+				}
487
+			}
488
+			$critical_page_problem =
489
+				! isset($critical_page['post']->post_status)
490
+				|| $critical_page['post']->post_status !== 'publish'
491
+				|| strpos($critical_page['post']->post_content, $critical_page['code']) === false
492
+					? true
493
+					: $critical_page_problem;
494
+		}
495
+		if ($critical_page_problem) {
496
+			$msg = sprintf(
497
+				__(
498
+					'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
499
+					'event_espresso'
500
+				),
501
+				'<a href="'
502
+				. admin_url('admin.php?page=espresso_general_settings&action=critical_pages')
503
+				. '">'
504
+				. __('Event Espresso Critical Pages Settings', 'event_espresso')
505
+				. '</a>'
506
+			);
507
+			EE_Error::add_persistent_admin_notice('critical_page_problem', $msg);
508
+		}
509
+		if (EE_Error::has_notices()) {
510
+			EE_Error::get_notices(false, true, true);
511
+		}
512
+	}
513
+
514
+
515
+
516
+	/**
517
+	 * Returns the first post which uses the specified shortcode
518
+	 *
519
+	 * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
520
+	 *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
521
+	 *                             "[ESPRESSO_THANK_YOU"
522
+	 *                             (we don't search for the closing shortcode bracket because they might have added
523
+	 *                             parameter to the shortcode
524
+	 * @return WP_Post or NULl
525
+	 */
526
+	public static function get_page_by_ee_shortcode($ee_shortcode)
527
+	{
528
+		global $wpdb;
529
+		$shortcode_and_opening_bracket = '[' . $ee_shortcode;
530
+		$post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
531
+		if ($post_id) {
532
+			return get_post($post_id);
533
+		} else {
534
+			return null;
535
+		}
536
+	}
537
+
538
+
539
+	/**
540
+	 *    This function generates a post for critical espresso pages
541
+	 *
542
+	 * @access public
543
+	 * @static
544
+	 * @param array $critical_page
545
+	 * @return array
546
+	 */
547
+	public static function create_critical_page($critical_page)
548
+	{
549
+
550
+		$post_args = array(
551
+			'post_title'     => $critical_page['name'],
552
+			'post_status'    => 'publish',
553
+			'post_type'      => 'page',
554
+			'comment_status' => 'closed',
555
+			'post_content'   => '[' . $critical_page['code'] . ']',
556
+		);
557
+
558
+		$post_id = wp_insert_post($post_args);
559
+		if (! $post_id) {
560
+			$msg = sprintf(
561
+				__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
562
+				$critical_page['name']
563
+			);
564
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
565
+			return $critical_page;
566
+		}
567
+		// get newly created post's details
568
+		if (! $critical_page['post'] = get_post($post_id)) {
569
+			$msg = sprintf(
570
+				__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
571
+				$critical_page['name']
572
+			);
573
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
574
+		}
575
+
576
+		return $critical_page;
577
+
578
+	}
579
+
580
+
581
+
582
+
583
+
584
+	/**
585
+	 *    This function adds a critical page's shortcode to the post_shortcodes array
586
+	 *
587
+	 * @access private
588
+	 * @static
589
+	 * @param array $critical_page
590
+	 * @return void
591
+	 */
592
+	private static function _track_critical_page_post_shortcodes($critical_page = array())
593
+	{
594
+		// check the goods
595
+		if ( ! $critical_page['post'] instanceof WP_Post) {
596
+			$msg = sprintf(
597
+				__(
598
+					'The Event Espresso critical page shortcode for the page %s can not be tracked because it is not a WP_Post object.',
599
+					'event_espresso'
600
+				),
601
+				$critical_page['name']
602
+			);
603
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
604
+			return;
605
+		}
606
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
607
+		// map shortcode to post
608
+		$EE_Core_Config->post_shortcodes[$critical_page['post']->post_name][$critical_page['code']] = $critical_page['post']->ID;
609
+		// and make sure it's NOT added to the WP "Posts Page"
610
+		// name of the WP Posts Page
611
+		$posts_page = EE_Config::get_page_for_posts();
612
+		if (isset($EE_Core_Config->post_shortcodes[$posts_page])) {
613
+			unset($EE_Core_Config->post_shortcodes[$posts_page][$critical_page['code']]);
614
+		}
615
+		if ($posts_page !== 'posts' && isset($EE_Core_Config->post_shortcodes['posts'])) {
616
+			unset($EE_Core_Config->post_shortcodes['posts'][$critical_page['code']]);
617
+		}
618
+		// update post_shortcode CFG
619
+		if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
620
+			$msg = sprintf(
621
+				__(
622
+					'The Event Espresso critical page shortcode for the %s page could not be configured properly.',
623
+					'event_espresso'
624
+				),
625
+				$critical_page['name']
626
+			);
627
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
628
+		}
629
+	}
630
+
631
+
632
+
633
+	/**
634
+	 * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
635
+	 * The role being used to check is filterable.
636
+	 *
637
+	 * @since  4.6.0
638
+	 * @global WPDB $wpdb
639
+	 * @return mixed null|int WP_user ID or NULL
640
+	 */
641
+	public static function get_default_creator_id()
642
+	{
643
+		global $wpdb;
644
+		if ( ! empty(self::$_default_creator_id)) {
645
+			return self::$_default_creator_id;
646
+		}/**/
647
+		$role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
648
+		//let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
649
+		$pre_filtered_id = apply_filters(
650
+			'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
651
+			false,
652
+			$role_to_check
653
+		);
654
+		if ($pre_filtered_id !== false) {
655
+			return (int)$pre_filtered_id;
656
+		}
657
+		$capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
658
+		$query = $wpdb->prepare(
659
+			"SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
660
+			'%' . $role_to_check . '%'
661
+		);
662
+		$user_id = $wpdb->get_var($query);
663
+		$user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
664
+		if ($user_id && (int)$user_id) {
665
+			self::$_default_creator_id = (int)$user_id;
666
+			return self::$_default_creator_id;
667
+		} else {
668
+			return null;
669
+		}
670
+	}
671
+
672
+
673
+
674
+	/**
675
+	 * used by EE and EE addons during plugin activation to create tables.
676
+	 * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
677
+	 * but includes extra logic regarding activations.
678
+	 *
679
+	 * @access public
680
+	 * @static
681
+	 * @param string  $table_name              without the $wpdb->prefix
682
+	 * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
683
+	 *                                         table query)
684
+	 * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
685
+	 * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
686
+	 *                                         and new once this function is done (ie, you really do want to CREATE a
687
+	 *                                         table, and expect it to be empty once you're done) leave as FALSE when
688
+	 *                                         you just want to verify the table exists and matches this definition
689
+	 *                                         (and if it HAS data in it you want to leave it be)
690
+	 * @return void
691
+	 * @throws EE_Error if there are database errors
692
+	 */
693
+	public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
694
+	{
695
+		if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
696
+			return;
697
+		}
698
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
699
+		if ( ! function_exists('dbDelta')) {
700
+			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
701
+		}
702
+		$tableAnalysis = \EEH_Activation::getTableAnalysis();
703
+		$wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
704
+		// do we need to first delete an existing version of this table ?
705
+		if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
706
+			// ok, delete the table... but ONLY if it's empty
707
+			$deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
708
+			// table is NOT empty, are you SURE you want to delete this table ???
709
+			if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
710
+				\EEH_Activation::getTableManager()->dropTable($wp_table_name);
711
+			} else if ( ! $deleted_safely) {
712
+				// so we should be more cautious rather than just dropping tables so easily
713
+				error_log(
714
+					sprintf(
715
+						__(
716
+							'It appears that database table "%1$s" exists when it shouldn\'t, and therefore may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend: %2$s 1. create a new COMPLETE backup of your database, %2$s 2. delete ALL tables from your database, %2$s 3. restore to your previous backup. %2$s If, however, you have not restored to a backup, then somehow your "%3$s" WordPress option could not be read. You can probably ignore this message, but should investigate why that option is being removed.',
717
+							'event_espresso'
718
+						),
719
+						$wp_table_name,
720
+						'<br/>',
721
+						'espresso_db_update'
722
+					)
723
+				);
724
+			}
725
+		}
726
+		$engine = str_replace('ENGINE=', '', $engine);
727
+		\EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
728
+	}
729
+
730
+
731
+
732
+	/**
733
+	 *    add_column_if_it_doesn't_exist
734
+	 *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
735
+	 *
736
+	 * @access     public
737
+	 * @static
738
+	 * @deprecated instead use TableManager::addColumn()
739
+	 * @param string $table_name  (without "wp_", eg "esp_attendee"
740
+	 * @param string $column_name
741
+	 * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
742
+	 *                            'VARCHAR(10)'
743
+	 * @return bool|int
744
+	 */
745
+	public static function add_column_if_it_doesnt_exist(
746
+		$table_name,
747
+		$column_name,
748
+		$column_info = 'INT UNSIGNED NOT NULL'
749
+	) {
750
+		return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
751
+	}
752
+
753
+
754
+	/**
755
+	 * get_fields_on_table
756
+	 * Gets all the fields on the database table.
757
+	 *
758
+	 * @access     public
759
+	 * @deprecated instead use TableManager::getTableColumns()
760
+	 * @static
761
+	 * @param string $table_name , without prefixed $wpdb->prefix
762
+	 * @return array of database column names
763
+	 */
764
+	public static function get_fields_on_table($table_name = null)
765
+	{
766
+		return \EEH_Activation::getTableManager()->getTableColumns($table_name);
767
+	}
768
+
769
+
770
+	/**
771
+	 * db_table_is_empty
772
+	 *
773
+	 * @access     public\
774
+	 * @deprecated instead use TableAnalysis::tableIsEmpty()
775
+	 * @static
776
+	 * @param string $table_name
777
+	 * @return bool
778
+	 */
779
+	public static function db_table_is_empty($table_name)
780
+	{
781
+		return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
782
+	}
783
+
784
+
785
+	/**
786
+	 * delete_db_table_if_empty
787
+	 *
788
+	 * @access public
789
+	 * @static
790
+	 * @param string $table_name
791
+	 * @return bool | int
792
+	 */
793
+	public static function delete_db_table_if_empty($table_name)
794
+	{
795
+		if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
796
+			return \EEH_Activation::getTableManager()->dropTable($table_name);
797
+		}
798
+		return false;
799
+	}
800
+
801
+
802
+	/**
803
+	 * delete_unused_db_table
804
+	 *
805
+	 * @access     public
806
+	 * @static
807
+	 * @deprecated instead use TableManager::dropTable()
808
+	 * @param string $table_name
809
+	 * @return bool | int
810
+	 */
811
+	public static function delete_unused_db_table($table_name)
812
+	{
813
+		return \EEH_Activation::getTableManager()->dropTable($table_name);
814
+	}
815
+
816
+
817
+	/**
818
+	 * drop_index
819
+	 *
820
+	 * @access     public
821
+	 * @static
822
+	 * @deprecated instead use TableManager::dropIndex()
823
+	 * @param string $table_name
824
+	 * @param string $index_name
825
+	 * @return bool | int
826
+	 */
827
+	public static function drop_index($table_name, $index_name)
828
+	{
829
+		return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
830
+	}
831
+
832
+
833
+
834
+	/**
835
+	 * create_database_tables
836
+	 *
837
+	 * @access public
838
+	 * @static
839
+	 * @throws EE_Error
840
+	 * @return boolean success (whether database is setup properly or not)
841
+	 */
842
+	public static function create_database_tables()
843
+	{
844
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
845
+		//find the migration script that sets the database to be compatible with the code
846
+		$dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
847
+		if ($dms_name) {
848
+			$current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
849
+			$current_data_migration_script->set_migrating(false);
850
+			$current_data_migration_script->schema_changes_before_migration();
851
+			$current_data_migration_script->schema_changes_after_migration();
852
+			if ($current_data_migration_script->get_errors()) {
853
+				if (WP_DEBUG) {
854
+					foreach ($current_data_migration_script->get_errors() as $error) {
855
+						EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
856
+					}
857
+				} else {
858
+					EE_Error::add_error(
859
+						__(
860
+							'There were errors creating the Event Espresso database tables and Event Espresso has been 
861 861
                             deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.',
862
-                            'event_espresso'
863
-                        )
864
-                    );
865
-                }
866
-                return false;
867
-            }
868
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to();
869
-        } else {
870
-            EE_Error::add_error(
871
-                __(
872
-                    'Could not determine most up-to-date data migration script from which to pull database schema
862
+							'event_espresso'
863
+						)
864
+					);
865
+				}
866
+				return false;
867
+			}
868
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to();
869
+		} else {
870
+			EE_Error::add_error(
871
+				__(
872
+					'Could not determine most up-to-date data migration script from which to pull database schema
873 873
                      structure. So database is probably not setup properly',
874
-                    'event_espresso'
875
-                ),
876
-                __FILE__,
877
-                __FUNCTION__,
878
-                __LINE__
879
-            );
880
-            return false;
881
-        }
882
-        return true;
883
-    }
884
-
885
-
886
-
887
-    /**
888
-     * initialize_system_questions
889
-     *
890
-     * @access public
891
-     * @static
892
-     * @return void
893
-     */
894
-    public static function initialize_system_questions()
895
-    {
896
-        // QUESTION GROUPS
897
-        global $wpdb;
898
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
899
-        $SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
900
-        // what we have
901
-        $question_groups = $wpdb->get_col($SQL);
902
-        // check the response
903
-        $question_groups = is_array($question_groups) ? $question_groups : array();
904
-        // what we should have
905
-        $QSG_systems = array(1, 2);
906
-        // loop thru what we should have and compare to what we have
907
-        foreach ($QSG_systems as $QSG_system) {
908
-            // reset values array
909
-            $QSG_values = array();
910
-            // if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
911
-            if (! in_array("$QSG_system", $question_groups)) {
912
-                // add it
913
-                switch ($QSG_system) {
914
-                    case 1:
915
-                        $QSG_values = array(
916
-                            'QSG_name'            => __('Personal Information', 'event_espresso'),
917
-                            'QSG_identifier'      => 'personal-information-' . time(),
918
-                            'QSG_desc'            => '',
919
-                            'QSG_order'           => 1,
920
-                            'QSG_show_group_name' => 1,
921
-                            'QSG_show_group_desc' => 1,
922
-                            'QSG_system'          => EEM_Question_Group::system_personal,
923
-                            'QSG_deleted'         => 0,
924
-                        );
925
-                        break;
926
-                    case 2:
927
-                        $QSG_values = array(
928
-                            'QSG_name'            => __('Address Information', 'event_espresso'),
929
-                            'QSG_identifier'      => 'address-information-' . time(),
930
-                            'QSG_desc'            => '',
931
-                            'QSG_order'           => 2,
932
-                            'QSG_show_group_name' => 1,
933
-                            'QSG_show_group_desc' => 1,
934
-                            'QSG_system'          => EEM_Question_Group::system_address,
935
-                            'QSG_deleted'         => 0,
936
-                        );
937
-                        break;
938
-                }
939
-                // make sure we have some values before inserting them
940
-                if (! empty($QSG_values)) {
941
-                    // insert system question
942
-                    $wpdb->insert(
943
-                        $table_name,
944
-                        $QSG_values,
945
-                        array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
946
-                    );
947
-                    $QSG_IDs[$QSG_system] = $wpdb->insert_id;
948
-                }
949
-            }
950
-        }
951
-        // QUESTIONS
952
-        global $wpdb;
953
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
954
-        $SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
955
-        // what we have
956
-        $questions = $wpdb->get_col($SQL);
957
-        // what we should have
958
-        $QST_systems = array(
959
-            'fname',
960
-            'lname',
961
-            'email',
962
-            'address',
963
-            'address2',
964
-            'city',
965
-            'country',
966
-            'state',
967
-            'zip',
968
-            'phone',
969
-        );
970
-        $order_for_group_1 = 1;
971
-        $order_for_group_2 = 1;
972
-        // loop thru what we should have and compare to what we have
973
-        foreach ($QST_systems as $QST_system) {
974
-            // reset values array
975
-            $QST_values = array();
976
-            // if we don't have what we should have
977
-            if (! in_array($QST_system, $questions)) {
978
-                // add it
979
-                switch ($QST_system) {
980
-                    case 'fname':
981
-                        $QST_values = array(
982
-                            'QST_display_text'  => __('First Name', 'event_espresso'),
983
-                            'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
984
-                            'QST_system'        => 'fname',
985
-                            'QST_type'          => 'TEXT',
986
-                            'QST_required'      => 1,
987
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
988
-                            'QST_order'         => 1,
989
-                            'QST_admin_only'    => 0,
990
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
991
-                            'QST_wp_user'       => self::get_default_creator_id(),
992
-                            'QST_deleted'       => 0,
993
-                        );
994
-                        break;
995
-                    case 'lname':
996
-                        $QST_values = array(
997
-                            'QST_display_text'  => __('Last Name', 'event_espresso'),
998
-                            'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
999
-                            'QST_system'        => 'lname',
1000
-                            'QST_type'          => 'TEXT',
1001
-                            'QST_required'      => 1,
1002
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1003
-                            'QST_order'         => 2,
1004
-                            'QST_admin_only'    => 0,
1005
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1006
-                            'QST_wp_user'       => self::get_default_creator_id(),
1007
-                            'QST_deleted'       => 0,
1008
-                        );
1009
-                        break;
1010
-                    case 'email':
1011
-                        $QST_values = array(
1012
-                            'QST_display_text'  => __('Email Address', 'event_espresso'),
1013
-                            'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
1014
-                            'QST_system'        => 'email',
1015
-                            'QST_type'          => 'EMAIL',
1016
-                            'QST_required'      => 1,
1017
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1018
-                            'QST_order'         => 3,
1019
-                            'QST_admin_only'    => 0,
1020
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1021
-                            'QST_wp_user'       => self::get_default_creator_id(),
1022
-                            'QST_deleted'       => 0,
1023
-                        );
1024
-                        break;
1025
-                    case 'address':
1026
-                        $QST_values = array(
1027
-                            'QST_display_text'  => __('Address', 'event_espresso'),
1028
-                            'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
1029
-                            'QST_system'        => 'address',
1030
-                            'QST_type'          => 'TEXT',
1031
-                            'QST_required'      => 0,
1032
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1033
-                            'QST_order'         => 4,
1034
-                            'QST_admin_only'    => 0,
1035
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1036
-                            'QST_wp_user'       => self::get_default_creator_id(),
1037
-                            'QST_deleted'       => 0,
1038
-                        );
1039
-                        break;
1040
-                    case 'address2':
1041
-                        $QST_values = array(
1042
-                            'QST_display_text'  => __('Address2', 'event_espresso'),
1043
-                            'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1044
-                            'QST_system'        => 'address2',
1045
-                            'QST_type'          => 'TEXT',
1046
-                            'QST_required'      => 0,
1047
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1048
-                            'QST_order'         => 5,
1049
-                            'QST_admin_only'    => 0,
1050
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1051
-                            'QST_wp_user'       => self::get_default_creator_id(),
1052
-                            'QST_deleted'       => 0,
1053
-                        );
1054
-                        break;
1055
-                    case 'city':
1056
-                        $QST_values = array(
1057
-                            'QST_display_text'  => __('City', 'event_espresso'),
1058
-                            'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1059
-                            'QST_system'        => 'city',
1060
-                            'QST_type'          => 'TEXT',
1061
-                            'QST_required'      => 0,
1062
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1063
-                            'QST_order'         => 6,
1064
-                            'QST_admin_only'    => 0,
1065
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1066
-                            'QST_wp_user'       => self::get_default_creator_id(),
1067
-                            'QST_deleted'       => 0,
1068
-                        );
1069
-                        break;
1070
-                    case 'country':
1071
-                        $QST_values = array(
1072
-                            'QST_display_text'  => __('Country', 'event_espresso'),
1073
-                            'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1074
-                            'QST_system'        => 'country',
1075
-                            'QST_type'          => 'COUNTRY',
1076
-                            'QST_required'      => 0,
1077
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1078
-                            'QST_order'         => 7,
1079
-                            'QST_admin_only'    => 0,
1080
-                            'QST_wp_user'       => self::get_default_creator_id(),
1081
-                            'QST_deleted'       => 0,
1082
-                        );
1083
-                        break;
1084
-                    case 'state':
1085
-                        $QST_values = array(
1086
-                            'QST_display_text'  => __('State/Province', 'event_espresso'),
1087
-                            'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1088
-                            'QST_system'        => 'state',
1089
-                            'QST_type'          => 'STATE',
1090
-                            'QST_required'      => 0,
1091
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1092
-                            'QST_order'         => 8,
1093
-                            'QST_admin_only'    => 0,
1094
-                            'QST_wp_user'       => self::get_default_creator_id(),
1095
-                            'QST_deleted'       => 0,
1096
-                        );
1097
-                        break;
1098
-                    case 'zip':
1099
-                        $QST_values = array(
1100
-                            'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1101
-                            'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1102
-                            'QST_system'        => 'zip',
1103
-                            'QST_type'          => 'TEXT',
1104
-                            'QST_required'      => 0,
1105
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1106
-                            'QST_order'         => 9,
1107
-                            'QST_admin_only'    => 0,
1108
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1109
-                            'QST_wp_user'       => self::get_default_creator_id(),
1110
-                            'QST_deleted'       => 0,
1111
-                        );
1112
-                        break;
1113
-                    case 'phone':
1114
-                        $QST_values = array(
1115
-                            'QST_display_text'  => __('Phone Number', 'event_espresso'),
1116
-                            'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1117
-                            'QST_system'        => 'phone',
1118
-                            'QST_type'          => 'TEXT',
1119
-                            'QST_required'      => 0,
1120
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1121
-                            'QST_order'         => 10,
1122
-                            'QST_admin_only'    => 0,
1123
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1124
-                            'QST_wp_user'       => self::get_default_creator_id(),
1125
-                            'QST_deleted'       => 0,
1126
-                        );
1127
-                        break;
1128
-                }
1129
-                if (! empty($QST_values)) {
1130
-                    // insert system question
1131
-                    $wpdb->insert(
1132
-                        $table_name,
1133
-                        $QST_values,
1134
-                        array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1135
-                    );
1136
-                    $QST_ID = $wpdb->insert_id;
1137
-                    // QUESTION GROUP QUESTIONS
1138
-                    if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1139
-                        $system_question_we_want = EEM_Question_Group::system_personal;
1140
-                    } else {
1141
-                        $system_question_we_want = EEM_Question_Group::system_address;
1142
-                    }
1143
-                    if (isset($QSG_IDs[$system_question_we_want])) {
1144
-                        $QSG_ID = $QSG_IDs[$system_question_we_want];
1145
-                    } else {
1146
-                        $id_col = EEM_Question_Group::instance()
1147
-                                                    ->get_col(array(array('QSG_system' => $system_question_we_want)));
1148
-                        if (is_array($id_col)) {
1149
-                            $QSG_ID = reset($id_col);
1150
-                        } else {
1151
-                            //ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1152
-                            EE_Log::instance()->log(
1153
-                                __FILE__,
1154
-                                __FUNCTION__,
1155
-                                sprintf(
1156
-                                    __(
1157
-                                        'Could not associate question %1$s to a question group because no system question
874
+					'event_espresso'
875
+				),
876
+				__FILE__,
877
+				__FUNCTION__,
878
+				__LINE__
879
+			);
880
+			return false;
881
+		}
882
+		return true;
883
+	}
884
+
885
+
886
+
887
+	/**
888
+	 * initialize_system_questions
889
+	 *
890
+	 * @access public
891
+	 * @static
892
+	 * @return void
893
+	 */
894
+	public static function initialize_system_questions()
895
+	{
896
+		// QUESTION GROUPS
897
+		global $wpdb;
898
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
899
+		$SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
900
+		// what we have
901
+		$question_groups = $wpdb->get_col($SQL);
902
+		// check the response
903
+		$question_groups = is_array($question_groups) ? $question_groups : array();
904
+		// what we should have
905
+		$QSG_systems = array(1, 2);
906
+		// loop thru what we should have and compare to what we have
907
+		foreach ($QSG_systems as $QSG_system) {
908
+			// reset values array
909
+			$QSG_values = array();
910
+			// if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
911
+			if (! in_array("$QSG_system", $question_groups)) {
912
+				// add it
913
+				switch ($QSG_system) {
914
+					case 1:
915
+						$QSG_values = array(
916
+							'QSG_name'            => __('Personal Information', 'event_espresso'),
917
+							'QSG_identifier'      => 'personal-information-' . time(),
918
+							'QSG_desc'            => '',
919
+							'QSG_order'           => 1,
920
+							'QSG_show_group_name' => 1,
921
+							'QSG_show_group_desc' => 1,
922
+							'QSG_system'          => EEM_Question_Group::system_personal,
923
+							'QSG_deleted'         => 0,
924
+						);
925
+						break;
926
+					case 2:
927
+						$QSG_values = array(
928
+							'QSG_name'            => __('Address Information', 'event_espresso'),
929
+							'QSG_identifier'      => 'address-information-' . time(),
930
+							'QSG_desc'            => '',
931
+							'QSG_order'           => 2,
932
+							'QSG_show_group_name' => 1,
933
+							'QSG_show_group_desc' => 1,
934
+							'QSG_system'          => EEM_Question_Group::system_address,
935
+							'QSG_deleted'         => 0,
936
+						);
937
+						break;
938
+				}
939
+				// make sure we have some values before inserting them
940
+				if (! empty($QSG_values)) {
941
+					// insert system question
942
+					$wpdb->insert(
943
+						$table_name,
944
+						$QSG_values,
945
+						array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
946
+					);
947
+					$QSG_IDs[$QSG_system] = $wpdb->insert_id;
948
+				}
949
+			}
950
+		}
951
+		// QUESTIONS
952
+		global $wpdb;
953
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
954
+		$SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
955
+		// what we have
956
+		$questions = $wpdb->get_col($SQL);
957
+		// what we should have
958
+		$QST_systems = array(
959
+			'fname',
960
+			'lname',
961
+			'email',
962
+			'address',
963
+			'address2',
964
+			'city',
965
+			'country',
966
+			'state',
967
+			'zip',
968
+			'phone',
969
+		);
970
+		$order_for_group_1 = 1;
971
+		$order_for_group_2 = 1;
972
+		// loop thru what we should have and compare to what we have
973
+		foreach ($QST_systems as $QST_system) {
974
+			// reset values array
975
+			$QST_values = array();
976
+			// if we don't have what we should have
977
+			if (! in_array($QST_system, $questions)) {
978
+				// add it
979
+				switch ($QST_system) {
980
+					case 'fname':
981
+						$QST_values = array(
982
+							'QST_display_text'  => __('First Name', 'event_espresso'),
983
+							'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
984
+							'QST_system'        => 'fname',
985
+							'QST_type'          => 'TEXT',
986
+							'QST_required'      => 1,
987
+							'QST_required_text' => __('This field is required', 'event_espresso'),
988
+							'QST_order'         => 1,
989
+							'QST_admin_only'    => 0,
990
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
991
+							'QST_wp_user'       => self::get_default_creator_id(),
992
+							'QST_deleted'       => 0,
993
+						);
994
+						break;
995
+					case 'lname':
996
+						$QST_values = array(
997
+							'QST_display_text'  => __('Last Name', 'event_espresso'),
998
+							'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
999
+							'QST_system'        => 'lname',
1000
+							'QST_type'          => 'TEXT',
1001
+							'QST_required'      => 1,
1002
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1003
+							'QST_order'         => 2,
1004
+							'QST_admin_only'    => 0,
1005
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1006
+							'QST_wp_user'       => self::get_default_creator_id(),
1007
+							'QST_deleted'       => 0,
1008
+						);
1009
+						break;
1010
+					case 'email':
1011
+						$QST_values = array(
1012
+							'QST_display_text'  => __('Email Address', 'event_espresso'),
1013
+							'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
1014
+							'QST_system'        => 'email',
1015
+							'QST_type'          => 'EMAIL',
1016
+							'QST_required'      => 1,
1017
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1018
+							'QST_order'         => 3,
1019
+							'QST_admin_only'    => 0,
1020
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1021
+							'QST_wp_user'       => self::get_default_creator_id(),
1022
+							'QST_deleted'       => 0,
1023
+						);
1024
+						break;
1025
+					case 'address':
1026
+						$QST_values = array(
1027
+							'QST_display_text'  => __('Address', 'event_espresso'),
1028
+							'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
1029
+							'QST_system'        => 'address',
1030
+							'QST_type'          => 'TEXT',
1031
+							'QST_required'      => 0,
1032
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1033
+							'QST_order'         => 4,
1034
+							'QST_admin_only'    => 0,
1035
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1036
+							'QST_wp_user'       => self::get_default_creator_id(),
1037
+							'QST_deleted'       => 0,
1038
+						);
1039
+						break;
1040
+					case 'address2':
1041
+						$QST_values = array(
1042
+							'QST_display_text'  => __('Address2', 'event_espresso'),
1043
+							'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1044
+							'QST_system'        => 'address2',
1045
+							'QST_type'          => 'TEXT',
1046
+							'QST_required'      => 0,
1047
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1048
+							'QST_order'         => 5,
1049
+							'QST_admin_only'    => 0,
1050
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1051
+							'QST_wp_user'       => self::get_default_creator_id(),
1052
+							'QST_deleted'       => 0,
1053
+						);
1054
+						break;
1055
+					case 'city':
1056
+						$QST_values = array(
1057
+							'QST_display_text'  => __('City', 'event_espresso'),
1058
+							'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1059
+							'QST_system'        => 'city',
1060
+							'QST_type'          => 'TEXT',
1061
+							'QST_required'      => 0,
1062
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1063
+							'QST_order'         => 6,
1064
+							'QST_admin_only'    => 0,
1065
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1066
+							'QST_wp_user'       => self::get_default_creator_id(),
1067
+							'QST_deleted'       => 0,
1068
+						);
1069
+						break;
1070
+					case 'country':
1071
+						$QST_values = array(
1072
+							'QST_display_text'  => __('Country', 'event_espresso'),
1073
+							'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1074
+							'QST_system'        => 'country',
1075
+							'QST_type'          => 'COUNTRY',
1076
+							'QST_required'      => 0,
1077
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1078
+							'QST_order'         => 7,
1079
+							'QST_admin_only'    => 0,
1080
+							'QST_wp_user'       => self::get_default_creator_id(),
1081
+							'QST_deleted'       => 0,
1082
+						);
1083
+						break;
1084
+					case 'state':
1085
+						$QST_values = array(
1086
+							'QST_display_text'  => __('State/Province', 'event_espresso'),
1087
+							'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1088
+							'QST_system'        => 'state',
1089
+							'QST_type'          => 'STATE',
1090
+							'QST_required'      => 0,
1091
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1092
+							'QST_order'         => 8,
1093
+							'QST_admin_only'    => 0,
1094
+							'QST_wp_user'       => self::get_default_creator_id(),
1095
+							'QST_deleted'       => 0,
1096
+						);
1097
+						break;
1098
+					case 'zip':
1099
+						$QST_values = array(
1100
+							'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1101
+							'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1102
+							'QST_system'        => 'zip',
1103
+							'QST_type'          => 'TEXT',
1104
+							'QST_required'      => 0,
1105
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1106
+							'QST_order'         => 9,
1107
+							'QST_admin_only'    => 0,
1108
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1109
+							'QST_wp_user'       => self::get_default_creator_id(),
1110
+							'QST_deleted'       => 0,
1111
+						);
1112
+						break;
1113
+					case 'phone':
1114
+						$QST_values = array(
1115
+							'QST_display_text'  => __('Phone Number', 'event_espresso'),
1116
+							'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1117
+							'QST_system'        => 'phone',
1118
+							'QST_type'          => 'TEXT',
1119
+							'QST_required'      => 0,
1120
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1121
+							'QST_order'         => 10,
1122
+							'QST_admin_only'    => 0,
1123
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1124
+							'QST_wp_user'       => self::get_default_creator_id(),
1125
+							'QST_deleted'       => 0,
1126
+						);
1127
+						break;
1128
+				}
1129
+				if (! empty($QST_values)) {
1130
+					// insert system question
1131
+					$wpdb->insert(
1132
+						$table_name,
1133
+						$QST_values,
1134
+						array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1135
+					);
1136
+					$QST_ID = $wpdb->insert_id;
1137
+					// QUESTION GROUP QUESTIONS
1138
+					if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1139
+						$system_question_we_want = EEM_Question_Group::system_personal;
1140
+					} else {
1141
+						$system_question_we_want = EEM_Question_Group::system_address;
1142
+					}
1143
+					if (isset($QSG_IDs[$system_question_we_want])) {
1144
+						$QSG_ID = $QSG_IDs[$system_question_we_want];
1145
+					} else {
1146
+						$id_col = EEM_Question_Group::instance()
1147
+													->get_col(array(array('QSG_system' => $system_question_we_want)));
1148
+						if (is_array($id_col)) {
1149
+							$QSG_ID = reset($id_col);
1150
+						} else {
1151
+							//ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1152
+							EE_Log::instance()->log(
1153
+								__FILE__,
1154
+								__FUNCTION__,
1155
+								sprintf(
1156
+									__(
1157
+										'Could not associate question %1$s to a question group because no system question
1158 1158
                                          group existed',
1159
-                                        'event_espresso'
1160
-                                    ),
1161
-                                    $QST_ID),
1162
-                                'error');
1163
-                            continue;
1164
-                        }
1165
-                    }
1166
-                    // add system questions to groups
1167
-                    $wpdb->insert(
1168
-                        \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1169
-                        array(
1170
-                            'QSG_ID'    => $QSG_ID,
1171
-                            'QST_ID'    => $QST_ID,
1172
-                            'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1173
-                        ),
1174
-                        array('%d', '%d', '%d')
1175
-                    );
1176
-                }
1177
-            }
1178
-        }
1179
-    }
1180
-
1181
-
1182
-    /**
1183
-     * Makes sure the default payment method (Invoice) is active.
1184
-     * This used to be done automatically as part of constructing the old gateways config
1185
-     *
1186
-     * @throws \EE_Error
1187
-     */
1188
-    public static function insert_default_payment_methods()
1189
-    {
1190
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1191
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
1192
-            EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1193
-        } else {
1194
-            EEM_Payment_Method::instance()->verify_button_urls();
1195
-        }
1196
-    }
1197
-
1198
-    /**
1199
-     * insert_default_status_codes
1200
-     *
1201
-     * @access public
1202
-     * @static
1203
-     * @return void
1204
-     */
1205
-    public static function insert_default_status_codes()
1206
-    {
1207
-
1208
-        global $wpdb;
1209
-
1210
-        if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1211
-
1212
-            $table_name = EEM_Status::instance()->table();
1213
-
1214
-            $SQL = "DELETE FROM $table_name WHERE STS_ID IN ( 'ACT', 'NAC', 'NOP', 'OPN', 'CLS', 'PND', 'ONG', 'SEC', 'DRF', 'DEL', 'DEN', 'EXP', 'RPP', 'RCN', 'RDC', 'RAP', 'RNA', 'RWL', 'TAB', 'TIN', 'TFL', 'TCM', 'TOP', 'PAP', 'PCN', 'PFL', 'PDC', 'EDR', 'ESN', 'PPN', 'RIC', 'MSN', 'MFL', 'MID', 'MRS', 'MIC', 'MDO', 'MEX' );";
1215
-            $wpdb->query($SQL);
1216
-
1217
-            $SQL = "INSERT INTO $table_name
1159
+										'event_espresso'
1160
+									),
1161
+									$QST_ID),
1162
+								'error');
1163
+							continue;
1164
+						}
1165
+					}
1166
+					// add system questions to groups
1167
+					$wpdb->insert(
1168
+						\EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1169
+						array(
1170
+							'QSG_ID'    => $QSG_ID,
1171
+							'QST_ID'    => $QST_ID,
1172
+							'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1173
+						),
1174
+						array('%d', '%d', '%d')
1175
+					);
1176
+				}
1177
+			}
1178
+		}
1179
+	}
1180
+
1181
+
1182
+	/**
1183
+	 * Makes sure the default payment method (Invoice) is active.
1184
+	 * This used to be done automatically as part of constructing the old gateways config
1185
+	 *
1186
+	 * @throws \EE_Error
1187
+	 */
1188
+	public static function insert_default_payment_methods()
1189
+	{
1190
+		if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1191
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
1192
+			EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1193
+		} else {
1194
+			EEM_Payment_Method::instance()->verify_button_urls();
1195
+		}
1196
+	}
1197
+
1198
+	/**
1199
+	 * insert_default_status_codes
1200
+	 *
1201
+	 * @access public
1202
+	 * @static
1203
+	 * @return void
1204
+	 */
1205
+	public static function insert_default_status_codes()
1206
+	{
1207
+
1208
+		global $wpdb;
1209
+
1210
+		if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1211
+
1212
+			$table_name = EEM_Status::instance()->table();
1213
+
1214
+			$SQL = "DELETE FROM $table_name WHERE STS_ID IN ( 'ACT', 'NAC', 'NOP', 'OPN', 'CLS', 'PND', 'ONG', 'SEC', 'DRF', 'DEL', 'DEN', 'EXP', 'RPP', 'RCN', 'RDC', 'RAP', 'RNA', 'RWL', 'TAB', 'TIN', 'TFL', 'TCM', 'TOP', 'PAP', 'PCN', 'PFL', 'PDC', 'EDR', 'ESN', 'PPN', 'RIC', 'MSN', 'MFL', 'MID', 'MRS', 'MIC', 'MDO', 'MEX' );";
1215
+			$wpdb->query($SQL);
1216
+
1217
+			$SQL = "INSERT INTO $table_name
1218 1218
 					(STS_ID, STS_code, STS_type, STS_can_edit, STS_desc, STS_open) VALUES
1219 1219
 					('ACT', 'ACTIVE', 'event', 0, NULL, 1),
1220 1220
 					('NAC', 'NOT_ACTIVE', 'event', 0, NULL, 0),
@@ -1254,521 +1254,521 @@  discard block
 block discarded – undo
1254 1254
 					('MID', 'IDLE', 'message', 0, NULL, 1),
1255 1255
 					('MRS', 'RESEND', 'message', 0, NULL, 1),
1256 1256
 					('MIC', 'INCOMPLETE', 'message', 0, NULL, 0);";
1257
-            $wpdb->query($SQL);
1258
-
1259
-        }
1260
-
1261
-    }
1262
-
1263
-
1264
-    /**
1265
-     * create_upload_directories
1266
-     * Creates folders in the uploads directory to facilitate addons and templates
1267
-     *
1268
-     * @access public
1269
-     * @static
1270
-     * @return boolean success of verifying upload directories exist
1271
-     */
1272
-    public static function create_upload_directories()
1273
-    {
1274
-        // Create the required folders
1275
-        $folders = array(
1276
-            EVENT_ESPRESSO_TEMPLATE_DIR,
1277
-            EVENT_ESPRESSO_GATEWAY_DIR,
1278
-            EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1279
-            EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1280
-            EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/',
1281
-        );
1282
-        foreach ($folders as $folder) {
1283
-            try {
1284
-                EEH_File::ensure_folder_exists_and_is_writable($folder);
1285
-                @ chmod($folder, 0755);
1286
-            } catch (EE_Error $e) {
1287
-                EE_Error::add_error(
1288
-                    sprintf(
1289
-                        __('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1290
-                        $folder,
1291
-                        '<br />' . $e->getMessage()
1292
-                    ),
1293
-                    __FILE__, __FUNCTION__, __LINE__
1294
-                );
1295
-                //indicate we'll need to fix this later
1296
-                update_option(EEH_Activation::upload_directories_incomplete_option_name, true);
1297
-                return false;
1298
-            }
1299
-        }
1300
-        //just add the .htaccess file to the logs directory to begin with. Even if logging
1301
-        //is disabled, there might be activation errors recorded in there
1302
-        EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs/');
1303
-        //remember EE's folders are all good
1304
-        delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1305
-        return true;
1306
-    }
1307
-
1308
-    /**
1309
-     * Whether the upload directories need to be fixed or not.
1310
-     * If EE is installed but filesystem access isn't initially available,
1311
-     * we need to get the user's filesystem credentials and THEN create them,
1312
-     * so there might be period of time when EE is installed but its
1313
-     * upload directories aren't available. This indicates such a state
1314
-     *
1315
-     * @return boolean
1316
-     */
1317
-    public static function upload_directories_incomplete()
1318
-    {
1319
-        return get_option(EEH_Activation::upload_directories_incomplete_option_name, false);
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * generate_default_message_templates
1325
-     *
1326
-     * @static
1327
-     * @throws EE_Error
1328
-     * @return bool     true means new templates were created.
1329
-     *                  false means no templates were created.
1330
-     *                  This is NOT an error flag. To check for errors you will want
1331
-     *                  to use either EE_Error or a try catch for an EE_Error exception.
1332
-     */
1333
-    public static function generate_default_message_templates()
1334
-    {
1335
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1336
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1337
-        /*
1257
+			$wpdb->query($SQL);
1258
+
1259
+		}
1260
+
1261
+	}
1262
+
1263
+
1264
+	/**
1265
+	 * create_upload_directories
1266
+	 * Creates folders in the uploads directory to facilitate addons and templates
1267
+	 *
1268
+	 * @access public
1269
+	 * @static
1270
+	 * @return boolean success of verifying upload directories exist
1271
+	 */
1272
+	public static function create_upload_directories()
1273
+	{
1274
+		// Create the required folders
1275
+		$folders = array(
1276
+			EVENT_ESPRESSO_TEMPLATE_DIR,
1277
+			EVENT_ESPRESSO_GATEWAY_DIR,
1278
+			EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1279
+			EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1280
+			EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/',
1281
+		);
1282
+		foreach ($folders as $folder) {
1283
+			try {
1284
+				EEH_File::ensure_folder_exists_and_is_writable($folder);
1285
+				@ chmod($folder, 0755);
1286
+			} catch (EE_Error $e) {
1287
+				EE_Error::add_error(
1288
+					sprintf(
1289
+						__('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1290
+						$folder,
1291
+						'<br />' . $e->getMessage()
1292
+					),
1293
+					__FILE__, __FUNCTION__, __LINE__
1294
+				);
1295
+				//indicate we'll need to fix this later
1296
+				update_option(EEH_Activation::upload_directories_incomplete_option_name, true);
1297
+				return false;
1298
+			}
1299
+		}
1300
+		//just add the .htaccess file to the logs directory to begin with. Even if logging
1301
+		//is disabled, there might be activation errors recorded in there
1302
+		EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs/');
1303
+		//remember EE's folders are all good
1304
+		delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1305
+		return true;
1306
+	}
1307
+
1308
+	/**
1309
+	 * Whether the upload directories need to be fixed or not.
1310
+	 * If EE is installed but filesystem access isn't initially available,
1311
+	 * we need to get the user's filesystem credentials and THEN create them,
1312
+	 * so there might be period of time when EE is installed but its
1313
+	 * upload directories aren't available. This indicates such a state
1314
+	 *
1315
+	 * @return boolean
1316
+	 */
1317
+	public static function upload_directories_incomplete()
1318
+	{
1319
+		return get_option(EEH_Activation::upload_directories_incomplete_option_name, false);
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * generate_default_message_templates
1325
+	 *
1326
+	 * @static
1327
+	 * @throws EE_Error
1328
+	 * @return bool     true means new templates were created.
1329
+	 *                  false means no templates were created.
1330
+	 *                  This is NOT an error flag. To check for errors you will want
1331
+	 *                  to use either EE_Error or a try catch for an EE_Error exception.
1332
+	 */
1333
+	public static function generate_default_message_templates()
1334
+	{
1335
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1336
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1337
+		/*
1338 1338
          * This first method is taking care of ensuring any default messengers
1339 1339
          * that should be made active and have templates generated are done.
1340 1340
          */
1341
-        $new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1342
-            $message_resource_manager
1343
-        );
1344
-        /**
1345
-         * This method is verifying there are no NEW default message types
1346
-         * for ACTIVE messengers that need activated (and corresponding templates setup).
1347
-         */
1348
-        $new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1349
-            $message_resource_manager
1350
-        );
1351
-        //after all is done, let's persist these changes to the db.
1352
-        $message_resource_manager->update_has_activated_messengers_option();
1353
-        $message_resource_manager->update_active_messengers_option();
1354
-        // will return true if either of these are true.  Otherwise will return false.
1355
-        return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1356
-    }
1357
-
1358
-
1359
-
1360
-    /**
1361
-     * @param \EE_Message_Resource_Manager $message_resource_manager
1362
-     * @return array|bool
1363
-     * @throws \EE_Error
1364
-     */
1365
-    protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1366
-        EE_Message_Resource_Manager $message_resource_manager
1367
-    ) {
1368
-        /** @type EE_messenger[] $active_messengers */
1369
-        $active_messengers = $message_resource_manager->active_messengers();
1370
-        $installed_message_types = $message_resource_manager->installed_message_types();
1371
-        $templates_created = false;
1372
-        foreach ($active_messengers as $active_messenger) {
1373
-            $default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1374
-            $default_message_type_names_to_activate = array();
1375
-            // looping through each default message type reported by the messenger
1376
-            // and setup the actual message types to activate.
1377
-            foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1378
-                // if already active or has already been activated before we skip
1379
-                // (otherwise we might reactivate something user's intentionally deactivated.)
1380
-                // we also skip if the message type is not installed.
1381
-                if (
1382
-                    $message_resource_manager->has_message_type_been_activated_for_messenger(
1383
-                        $default_message_type_name_for_messenger,
1384
-                        $active_messenger->name
1385
-                    )
1386
-                    || $message_resource_manager->is_message_type_active_for_messenger(
1387
-                        $active_messenger->name,
1388
-                        $default_message_type_name_for_messenger
1389
-                    )
1390
-                    || ! isset($installed_message_types[$default_message_type_name_for_messenger])
1391
-                ) {
1392
-                    continue;
1393
-                }
1394
-                $default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1395
-            }
1396
-            //let's activate!
1397
-            $message_resource_manager->ensure_message_types_are_active(
1398
-                $default_message_type_names_to_activate,
1399
-                $active_messenger->name,
1400
-                false
1401
-            );
1402
-            //activate the templates for these message types
1403
-            if ( ! empty($default_message_type_names_to_activate)) {
1404
-                $templates_created = EEH_MSG_Template::generate_new_templates(
1405
-                    $active_messenger->name,
1406
-                    $default_message_type_names_for_messenger,
1407
-                    '',
1408
-                    true
1409
-                );
1410
-            }
1411
-        }
1412
-        return $templates_created;
1413
-    }
1414
-
1415
-
1416
-
1417
-    /**
1418
-     * This will activate and generate default messengers and default message types for those messengers.
1419
-     *
1420
-     * @param EE_message_Resource_Manager $message_resource_manager
1421
-     * @return array|bool  True means there were default messengers and message type templates generated.
1422
-     *                     False means that there were no templates generated
1423
-     *                     (which could simply mean there are no default message types for a messenger).
1424
-     * @throws EE_Error
1425
-     */
1426
-    protected static function _activate_and_generate_default_messengers_and_message_templates(
1427
-        EE_Message_Resource_Manager $message_resource_manager
1428
-    ) {
1429
-        /** @type EE_messenger[] $messengers_to_generate */
1430
-        $messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1431
-        $installed_message_types = $message_resource_manager->installed_message_types();
1432
-        $templates_generated = false;
1433
-        foreach ($messengers_to_generate as $messenger_to_generate) {
1434
-            $default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1435
-            //verify the default message types match an installed message type.
1436
-            foreach ($default_message_type_names_for_messenger as $key => $name) {
1437
-                if (
1438
-                    ! isset($installed_message_types[$name])
1439
-                    || $message_resource_manager->has_message_type_been_activated_for_messenger(
1440
-                        $name,
1441
-                        $messenger_to_generate->name
1442
-                    )
1443
-                ) {
1444
-                    unset($default_message_type_names_for_messenger[$key]);
1445
-                }
1446
-            }
1447
-            // in previous iterations, the active_messengers option in the db
1448
-            // needed updated before calling create templates. however with the changes this may not be necessary.
1449
-            // This comment is left here just in case we discover that we _do_ need to update before
1450
-            // passing off to create templates (after the refactor is done).
1451
-            // @todo remove this comment when determined not necessary.
1452
-            $message_resource_manager->activate_messenger(
1453
-                $messenger_to_generate->name,
1454
-                $default_message_type_names_for_messenger,
1455
-                false
1456
-            );
1457
-            //create any templates needing created (or will reactivate templates already generated as necessary).
1458
-            if ( ! empty($default_message_type_names_for_messenger)) {
1459
-                $templates_generated = EEH_MSG_Template::generate_new_templates(
1460
-                    $messenger_to_generate->name,
1461
-                    $default_message_type_names_for_messenger,
1462
-                    '',
1463
-                    true
1464
-                );
1465
-            }
1466
-        }
1467
-        return $templates_generated;
1468
-    }
1469
-
1470
-
1471
-    /**
1472
-     * This returns the default messengers to generate templates for on activation of EE.
1473
-     * It considers:
1474
-     * - whether a messenger is already active in the db.
1475
-     * - whether a messenger has been made active at any time in the past.
1476
-     *
1477
-     * @static
1478
-     * @param  EE_Message_Resource_Manager $message_resource_manager
1479
-     * @return EE_messenger[]
1480
-     */
1481
-    protected static function _get_default_messengers_to_generate_on_activation(
1482
-        EE_Message_Resource_Manager $message_resource_manager
1483
-    ) {
1484
-        $active_messengers    = $message_resource_manager->active_messengers();
1485
-        $installed_messengers = $message_resource_manager->installed_messengers();
1486
-        $has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1487
-
1488
-        $messengers_to_generate = array();
1489
-        foreach ($installed_messengers as $installed_messenger) {
1490
-            //if installed messenger is a messenger that should be activated on install
1491
-            //and is not already active
1492
-            //and has never been activated
1493
-            if (
1494
-                ! $installed_messenger->activate_on_install
1495
-                || isset($active_messengers[$installed_messenger->name])
1496
-                || isset($has_activated[$installed_messenger->name])
1497
-            ) {
1498
-                continue;
1499
-            }
1500
-            $messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1501
-        }
1502
-        return $messengers_to_generate;
1503
-    }
1504
-
1505
-
1506
-    /**
1507
-     * This simply validates active message types to ensure they actually match installed
1508
-     * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1509
-     * rows are set inactive.
1510
-     * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1511
-     * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1512
-     * are still handled in here.
1513
-     *
1514
-     * @since 4.3.1
1515
-     * @return void
1516
-     */
1517
-    public static function validate_messages_system()
1518
-    {
1519
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1520
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1521
-        $message_resource_manager->validate_active_message_types_are_installed();
1522
-        do_action('AHEE__EEH_Activation__validate_messages_system');
1523
-    }
1524
-
1525
-
1526
-    /**
1527
-     * create_no_ticket_prices_array
1528
-     *
1529
-     * @access public
1530
-     * @static
1531
-     * @return void
1532
-     */
1533
-    public static function create_no_ticket_prices_array()
1534
-    {
1535
-        // this creates an array for tracking events that have no active ticket prices created
1536
-        // this allows us to warn admins of the situation so that it can be corrected
1537
-        $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1538
-        if (! $espresso_no_ticket_prices) {
1539
-            add_option('ee_no_ticket_prices', array(), '', false);
1540
-        }
1541
-    }
1542
-
1543
-
1544
-    /**
1545
-     * plugin_deactivation
1546
-     *
1547
-     * @access public
1548
-     * @static
1549
-     * @return void
1550
-     */
1551
-    public static function plugin_deactivation()
1552
-    {
1553
-    }
1554
-
1555
-
1556
-    /**
1557
-     * Finds all our EE4 custom post types, and deletes them and their associated data
1558
-     * (like post meta or term relations)
1559
-     *
1560
-     * @global wpdb $wpdb
1561
-     * @throws \EE_Error
1562
-     */
1563
-    public static function delete_all_espresso_cpt_data()
1564
-    {
1565
-        global $wpdb;
1566
-        //get all the CPT post_types
1567
-        $ee_post_types = array();
1568
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1569
-            if (method_exists($model_name, 'instance')) {
1570
-                $model_obj = call_user_func(array($model_name, 'instance'));
1571
-                if ($model_obj instanceof EEM_CPT_Base) {
1572
-                    $ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1573
-                }
1574
-            }
1575
-        }
1576
-        //get all our CPTs
1577
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1578
-        $cpt_ids = $wpdb->get_col($query);
1579
-        //delete each post meta and term relations too
1580
-        foreach ($cpt_ids as $post_id) {
1581
-            wp_delete_post($post_id, true);
1582
-        }
1583
-    }
1584
-
1585
-    /**
1586
-     * Deletes all EE custom tables
1587
-     *
1588
-     * @return array
1589
-     */
1590
-    public static function drop_espresso_tables()
1591
-    {
1592
-        $tables = array();
1593
-        // load registry
1594
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1595
-            if (method_exists($model_name, 'instance')) {
1596
-                $model_obj = call_user_func(array($model_name, 'instance'));
1597
-                if ($model_obj instanceof EEM_Base) {
1598
-                    foreach ($model_obj->get_tables() as $table) {
1599
-                        if (strpos($table->get_table_name(), 'esp_')
1600
-                            &&
1601
-                            (
1602
-                                is_main_site()//main site? nuke them all
1603
-                                || ! $table->is_global()//not main site,but not global either. nuke it
1604
-                            )
1605
-                        ) {
1606
-                            $tables[] = $table->get_table_name();
1607
-                        }
1608
-                    }
1609
-                }
1610
-            }
1611
-        }
1612
-
1613
-        //there are some tables whose models were removed.
1614
-        //they should be removed when removing all EE core's data
1615
-        $tables_without_models = array(
1616
-            'esp_promotion',
1617
-            'esp_promotion_applied',
1618
-            'esp_promotion_object',
1619
-            'esp_promotion_rule',
1620
-            'esp_rule',
1621
-        );
1622
-        foreach ($tables_without_models as $table) {
1623
-            $tables[] = $table;
1624
-        }
1625
-        return \EEH_Activation::getTableManager()->dropTables($tables);
1626
-    }
1627
-
1628
-
1629
-
1630
-    /**
1631
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
1632
-     * each table name provided has a wpdb prefix attached, and that it exists.
1633
-     * Returns the list actually deleted
1634
-     *
1635
-     * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1636
-     * @global WPDB $wpdb
1637
-     * @param array $table_names
1638
-     * @return array of table names which we deleted
1639
-     */
1640
-    public static function drop_tables($table_names)
1641
-    {
1642
-        return \EEH_Activation::getTableManager()->dropTables($table_names);
1643
-    }
1644
-
1645
-
1646
-
1647
-    /**
1648
-     * plugin_uninstall
1649
-     *
1650
-     * @access public
1651
-     * @static
1652
-     * @param bool $remove_all
1653
-     * @return void
1654
-     */
1655
-    public static function delete_all_espresso_tables_and_data($remove_all = true)
1656
-    {
1657
-        global $wpdb;
1658
-        self::drop_espresso_tables();
1659
-        $wp_options_to_delete = array(
1660
-            'ee_no_ticket_prices'                => true,
1661
-            'ee_active_messengers'               => true,
1662
-            'ee_has_activated_messenger'         => true,
1663
-            'ee_flush_rewrite_rules'             => true,
1664
-            'ee_config'                          => false,
1665
-            'ee_data_migration_current_db_state' => true,
1666
-            'ee_data_migration_mapping_'         => false,
1667
-            'ee_data_migration_script_'          => false,
1668
-            'ee_data_migrations'                 => true,
1669
-            'ee_dms_map'                         => false,
1670
-            'ee_notices'                         => true,
1671
-            'lang_file_check_'                   => false,
1672
-            'ee_maintenance_mode'                => true,
1673
-            'ee_ueip_optin'                      => true,
1674
-            'ee_ueip_has_notified'               => true,
1675
-            'ee_plugin_activation_errors'        => true,
1676
-            'ee_id_mapping_from'                 => false,
1677
-            'espresso_persistent_admin_notices'  => true,
1678
-            'ee_encryption_key'                  => true,
1679
-            'pue_force_upgrade_'                 => false,
1680
-            'pue_json_error_'                    => false,
1681
-            'pue_install_key_'                   => false,
1682
-            'pue_verification_error_'            => false,
1683
-            'pu_dismissed_upgrade_'              => false,
1684
-            'external_updates-'                  => false,
1685
-            'ee_extra_data'                      => true,
1686
-            'ee_ssn_'                            => false,
1687
-            'ee_rss_'                            => false,
1688
-            'ee_rte_n_tx_'                       => false,
1689
-            'ee_pers_admin_notices'              => true,
1690
-            'ee_job_parameters_'                 => false,
1691
-            'ee_upload_directories_incomplete'   => true,
1692
-            'ee_verified_db_collations'          => true,
1693
-        );
1694
-        if (is_main_site()) {
1695
-            $wp_options_to_delete['ee_network_config'] = true;
1696
-        }
1697
-        $undeleted_options = array();
1698
-        foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1699
-            if ($no_wildcard) {
1700
-                if ( ! delete_option($option_name)) {
1701
-                    $undeleted_options[] = $option_name;
1702
-                }
1703
-            } else {
1704
-                $option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1705
-                foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1706
-                    if ( ! delete_option($option_name_from_wildcard)) {
1707
-                        $undeleted_options[] = $option_name_from_wildcard;
1708
-                    }
1709
-                }
1710
-            }
1711
-        }
1712
-        //also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1713
-        remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1714
-        if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1715
-            $db_update_sans_ee4 = array();
1716
-            foreach ($espresso_db_update as $version => $times_activated) {
1717
-                if ((string)$version[0] === '3') {//if its NON EE4
1718
-                    $db_update_sans_ee4[$version] = $times_activated;
1719
-                }
1720
-            }
1721
-            update_option('espresso_db_update', $db_update_sans_ee4);
1722
-        }
1723
-        $errors = '';
1724
-        if ( ! empty($undeleted_options)) {
1725
-            $errors .= sprintf(
1726
-                __('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1727
-                '<br/>',
1728
-                implode(',<br/>', $undeleted_options)
1729
-            );
1730
-        }
1731
-        if ( ! empty($errors)) {
1732
-            EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1733
-        }
1734
-    }
1735
-
1736
-    /**
1737
-     * Gets the mysql error code from the last used query by wpdb
1738
-     *
1739
-     * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1740
-     */
1741
-    public static function last_wpdb_error_code()
1742
-    {
1743
-        global $wpdb;
1744
-        if ($wpdb->use_mysqli) {
1745
-            return mysqli_errno($wpdb->dbh);
1746
-        } else {
1747
-            return mysql_errno($wpdb->dbh);
1748
-        }
1749
-    }
1750
-
1751
-    /**
1752
-     * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1753
-     *
1754
-     * @global wpdb  $wpdb
1755
-     * @deprecated instead use TableAnalysis::tableExists()
1756
-     * @param string $table_name with or without $wpdb->prefix
1757
-     * @return boolean
1758
-     */
1759
-    public static function table_exists($table_name)
1760
-    {
1761
-        return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1762
-    }
1763
-
1764
-    /**
1765
-     * Resets the cache on EEH_Activation
1766
-     */
1767
-    public static function reset()
1768
-    {
1769
-        self::$_default_creator_id                             = null;
1770
-        self::$_initialized_db_content_already_in_this_request = false;
1771
-    }
1341
+		$new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1342
+			$message_resource_manager
1343
+		);
1344
+		/**
1345
+		 * This method is verifying there are no NEW default message types
1346
+		 * for ACTIVE messengers that need activated (and corresponding templates setup).
1347
+		 */
1348
+		$new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1349
+			$message_resource_manager
1350
+		);
1351
+		//after all is done, let's persist these changes to the db.
1352
+		$message_resource_manager->update_has_activated_messengers_option();
1353
+		$message_resource_manager->update_active_messengers_option();
1354
+		// will return true if either of these are true.  Otherwise will return false.
1355
+		return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1356
+	}
1357
+
1358
+
1359
+
1360
+	/**
1361
+	 * @param \EE_Message_Resource_Manager $message_resource_manager
1362
+	 * @return array|bool
1363
+	 * @throws \EE_Error
1364
+	 */
1365
+	protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1366
+		EE_Message_Resource_Manager $message_resource_manager
1367
+	) {
1368
+		/** @type EE_messenger[] $active_messengers */
1369
+		$active_messengers = $message_resource_manager->active_messengers();
1370
+		$installed_message_types = $message_resource_manager->installed_message_types();
1371
+		$templates_created = false;
1372
+		foreach ($active_messengers as $active_messenger) {
1373
+			$default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1374
+			$default_message_type_names_to_activate = array();
1375
+			// looping through each default message type reported by the messenger
1376
+			// and setup the actual message types to activate.
1377
+			foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1378
+				// if already active or has already been activated before we skip
1379
+				// (otherwise we might reactivate something user's intentionally deactivated.)
1380
+				// we also skip if the message type is not installed.
1381
+				if (
1382
+					$message_resource_manager->has_message_type_been_activated_for_messenger(
1383
+						$default_message_type_name_for_messenger,
1384
+						$active_messenger->name
1385
+					)
1386
+					|| $message_resource_manager->is_message_type_active_for_messenger(
1387
+						$active_messenger->name,
1388
+						$default_message_type_name_for_messenger
1389
+					)
1390
+					|| ! isset($installed_message_types[$default_message_type_name_for_messenger])
1391
+				) {
1392
+					continue;
1393
+				}
1394
+				$default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1395
+			}
1396
+			//let's activate!
1397
+			$message_resource_manager->ensure_message_types_are_active(
1398
+				$default_message_type_names_to_activate,
1399
+				$active_messenger->name,
1400
+				false
1401
+			);
1402
+			//activate the templates for these message types
1403
+			if ( ! empty($default_message_type_names_to_activate)) {
1404
+				$templates_created = EEH_MSG_Template::generate_new_templates(
1405
+					$active_messenger->name,
1406
+					$default_message_type_names_for_messenger,
1407
+					'',
1408
+					true
1409
+				);
1410
+			}
1411
+		}
1412
+		return $templates_created;
1413
+	}
1414
+
1415
+
1416
+
1417
+	/**
1418
+	 * This will activate and generate default messengers and default message types for those messengers.
1419
+	 *
1420
+	 * @param EE_message_Resource_Manager $message_resource_manager
1421
+	 * @return array|bool  True means there were default messengers and message type templates generated.
1422
+	 *                     False means that there were no templates generated
1423
+	 *                     (which could simply mean there are no default message types for a messenger).
1424
+	 * @throws EE_Error
1425
+	 */
1426
+	protected static function _activate_and_generate_default_messengers_and_message_templates(
1427
+		EE_Message_Resource_Manager $message_resource_manager
1428
+	) {
1429
+		/** @type EE_messenger[] $messengers_to_generate */
1430
+		$messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1431
+		$installed_message_types = $message_resource_manager->installed_message_types();
1432
+		$templates_generated = false;
1433
+		foreach ($messengers_to_generate as $messenger_to_generate) {
1434
+			$default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1435
+			//verify the default message types match an installed message type.
1436
+			foreach ($default_message_type_names_for_messenger as $key => $name) {
1437
+				if (
1438
+					! isset($installed_message_types[$name])
1439
+					|| $message_resource_manager->has_message_type_been_activated_for_messenger(
1440
+						$name,
1441
+						$messenger_to_generate->name
1442
+					)
1443
+				) {
1444
+					unset($default_message_type_names_for_messenger[$key]);
1445
+				}
1446
+			}
1447
+			// in previous iterations, the active_messengers option in the db
1448
+			// needed updated before calling create templates. however with the changes this may not be necessary.
1449
+			// This comment is left here just in case we discover that we _do_ need to update before
1450
+			// passing off to create templates (after the refactor is done).
1451
+			// @todo remove this comment when determined not necessary.
1452
+			$message_resource_manager->activate_messenger(
1453
+				$messenger_to_generate->name,
1454
+				$default_message_type_names_for_messenger,
1455
+				false
1456
+			);
1457
+			//create any templates needing created (or will reactivate templates already generated as necessary).
1458
+			if ( ! empty($default_message_type_names_for_messenger)) {
1459
+				$templates_generated = EEH_MSG_Template::generate_new_templates(
1460
+					$messenger_to_generate->name,
1461
+					$default_message_type_names_for_messenger,
1462
+					'',
1463
+					true
1464
+				);
1465
+			}
1466
+		}
1467
+		return $templates_generated;
1468
+	}
1469
+
1470
+
1471
+	/**
1472
+	 * This returns the default messengers to generate templates for on activation of EE.
1473
+	 * It considers:
1474
+	 * - whether a messenger is already active in the db.
1475
+	 * - whether a messenger has been made active at any time in the past.
1476
+	 *
1477
+	 * @static
1478
+	 * @param  EE_Message_Resource_Manager $message_resource_manager
1479
+	 * @return EE_messenger[]
1480
+	 */
1481
+	protected static function _get_default_messengers_to_generate_on_activation(
1482
+		EE_Message_Resource_Manager $message_resource_manager
1483
+	) {
1484
+		$active_messengers    = $message_resource_manager->active_messengers();
1485
+		$installed_messengers = $message_resource_manager->installed_messengers();
1486
+		$has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1487
+
1488
+		$messengers_to_generate = array();
1489
+		foreach ($installed_messengers as $installed_messenger) {
1490
+			//if installed messenger is a messenger that should be activated on install
1491
+			//and is not already active
1492
+			//and has never been activated
1493
+			if (
1494
+				! $installed_messenger->activate_on_install
1495
+				|| isset($active_messengers[$installed_messenger->name])
1496
+				|| isset($has_activated[$installed_messenger->name])
1497
+			) {
1498
+				continue;
1499
+			}
1500
+			$messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1501
+		}
1502
+		return $messengers_to_generate;
1503
+	}
1504
+
1505
+
1506
+	/**
1507
+	 * This simply validates active message types to ensure they actually match installed
1508
+	 * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1509
+	 * rows are set inactive.
1510
+	 * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1511
+	 * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1512
+	 * are still handled in here.
1513
+	 *
1514
+	 * @since 4.3.1
1515
+	 * @return void
1516
+	 */
1517
+	public static function validate_messages_system()
1518
+	{
1519
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1520
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1521
+		$message_resource_manager->validate_active_message_types_are_installed();
1522
+		do_action('AHEE__EEH_Activation__validate_messages_system');
1523
+	}
1524
+
1525
+
1526
+	/**
1527
+	 * create_no_ticket_prices_array
1528
+	 *
1529
+	 * @access public
1530
+	 * @static
1531
+	 * @return void
1532
+	 */
1533
+	public static function create_no_ticket_prices_array()
1534
+	{
1535
+		// this creates an array for tracking events that have no active ticket prices created
1536
+		// this allows us to warn admins of the situation so that it can be corrected
1537
+		$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1538
+		if (! $espresso_no_ticket_prices) {
1539
+			add_option('ee_no_ticket_prices', array(), '', false);
1540
+		}
1541
+	}
1542
+
1543
+
1544
+	/**
1545
+	 * plugin_deactivation
1546
+	 *
1547
+	 * @access public
1548
+	 * @static
1549
+	 * @return void
1550
+	 */
1551
+	public static function plugin_deactivation()
1552
+	{
1553
+	}
1554
+
1555
+
1556
+	/**
1557
+	 * Finds all our EE4 custom post types, and deletes them and their associated data
1558
+	 * (like post meta or term relations)
1559
+	 *
1560
+	 * @global wpdb $wpdb
1561
+	 * @throws \EE_Error
1562
+	 */
1563
+	public static function delete_all_espresso_cpt_data()
1564
+	{
1565
+		global $wpdb;
1566
+		//get all the CPT post_types
1567
+		$ee_post_types = array();
1568
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1569
+			if (method_exists($model_name, 'instance')) {
1570
+				$model_obj = call_user_func(array($model_name, 'instance'));
1571
+				if ($model_obj instanceof EEM_CPT_Base) {
1572
+					$ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1573
+				}
1574
+			}
1575
+		}
1576
+		//get all our CPTs
1577
+		$query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1578
+		$cpt_ids = $wpdb->get_col($query);
1579
+		//delete each post meta and term relations too
1580
+		foreach ($cpt_ids as $post_id) {
1581
+			wp_delete_post($post_id, true);
1582
+		}
1583
+	}
1584
+
1585
+	/**
1586
+	 * Deletes all EE custom tables
1587
+	 *
1588
+	 * @return array
1589
+	 */
1590
+	public static function drop_espresso_tables()
1591
+	{
1592
+		$tables = array();
1593
+		// load registry
1594
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1595
+			if (method_exists($model_name, 'instance')) {
1596
+				$model_obj = call_user_func(array($model_name, 'instance'));
1597
+				if ($model_obj instanceof EEM_Base) {
1598
+					foreach ($model_obj->get_tables() as $table) {
1599
+						if (strpos($table->get_table_name(), 'esp_')
1600
+							&&
1601
+							(
1602
+								is_main_site()//main site? nuke them all
1603
+								|| ! $table->is_global()//not main site,but not global either. nuke it
1604
+							)
1605
+						) {
1606
+							$tables[] = $table->get_table_name();
1607
+						}
1608
+					}
1609
+				}
1610
+			}
1611
+		}
1612
+
1613
+		//there are some tables whose models were removed.
1614
+		//they should be removed when removing all EE core's data
1615
+		$tables_without_models = array(
1616
+			'esp_promotion',
1617
+			'esp_promotion_applied',
1618
+			'esp_promotion_object',
1619
+			'esp_promotion_rule',
1620
+			'esp_rule',
1621
+		);
1622
+		foreach ($tables_without_models as $table) {
1623
+			$tables[] = $table;
1624
+		}
1625
+		return \EEH_Activation::getTableManager()->dropTables($tables);
1626
+	}
1627
+
1628
+
1629
+
1630
+	/**
1631
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
1632
+	 * each table name provided has a wpdb prefix attached, and that it exists.
1633
+	 * Returns the list actually deleted
1634
+	 *
1635
+	 * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1636
+	 * @global WPDB $wpdb
1637
+	 * @param array $table_names
1638
+	 * @return array of table names which we deleted
1639
+	 */
1640
+	public static function drop_tables($table_names)
1641
+	{
1642
+		return \EEH_Activation::getTableManager()->dropTables($table_names);
1643
+	}
1644
+
1645
+
1646
+
1647
+	/**
1648
+	 * plugin_uninstall
1649
+	 *
1650
+	 * @access public
1651
+	 * @static
1652
+	 * @param bool $remove_all
1653
+	 * @return void
1654
+	 */
1655
+	public static function delete_all_espresso_tables_and_data($remove_all = true)
1656
+	{
1657
+		global $wpdb;
1658
+		self::drop_espresso_tables();
1659
+		$wp_options_to_delete = array(
1660
+			'ee_no_ticket_prices'                => true,
1661
+			'ee_active_messengers'               => true,
1662
+			'ee_has_activated_messenger'         => true,
1663
+			'ee_flush_rewrite_rules'             => true,
1664
+			'ee_config'                          => false,
1665
+			'ee_data_migration_current_db_state' => true,
1666
+			'ee_data_migration_mapping_'         => false,
1667
+			'ee_data_migration_script_'          => false,
1668
+			'ee_data_migrations'                 => true,
1669
+			'ee_dms_map'                         => false,
1670
+			'ee_notices'                         => true,
1671
+			'lang_file_check_'                   => false,
1672
+			'ee_maintenance_mode'                => true,
1673
+			'ee_ueip_optin'                      => true,
1674
+			'ee_ueip_has_notified'               => true,
1675
+			'ee_plugin_activation_errors'        => true,
1676
+			'ee_id_mapping_from'                 => false,
1677
+			'espresso_persistent_admin_notices'  => true,
1678
+			'ee_encryption_key'                  => true,
1679
+			'pue_force_upgrade_'                 => false,
1680
+			'pue_json_error_'                    => false,
1681
+			'pue_install_key_'                   => false,
1682
+			'pue_verification_error_'            => false,
1683
+			'pu_dismissed_upgrade_'              => false,
1684
+			'external_updates-'                  => false,
1685
+			'ee_extra_data'                      => true,
1686
+			'ee_ssn_'                            => false,
1687
+			'ee_rss_'                            => false,
1688
+			'ee_rte_n_tx_'                       => false,
1689
+			'ee_pers_admin_notices'              => true,
1690
+			'ee_job_parameters_'                 => false,
1691
+			'ee_upload_directories_incomplete'   => true,
1692
+			'ee_verified_db_collations'          => true,
1693
+		);
1694
+		if (is_main_site()) {
1695
+			$wp_options_to_delete['ee_network_config'] = true;
1696
+		}
1697
+		$undeleted_options = array();
1698
+		foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1699
+			if ($no_wildcard) {
1700
+				if ( ! delete_option($option_name)) {
1701
+					$undeleted_options[] = $option_name;
1702
+				}
1703
+			} else {
1704
+				$option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1705
+				foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1706
+					if ( ! delete_option($option_name_from_wildcard)) {
1707
+						$undeleted_options[] = $option_name_from_wildcard;
1708
+					}
1709
+				}
1710
+			}
1711
+		}
1712
+		//also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1713
+		remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1714
+		if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1715
+			$db_update_sans_ee4 = array();
1716
+			foreach ($espresso_db_update as $version => $times_activated) {
1717
+				if ((string)$version[0] === '3') {//if its NON EE4
1718
+					$db_update_sans_ee4[$version] = $times_activated;
1719
+				}
1720
+			}
1721
+			update_option('espresso_db_update', $db_update_sans_ee4);
1722
+		}
1723
+		$errors = '';
1724
+		if ( ! empty($undeleted_options)) {
1725
+			$errors .= sprintf(
1726
+				__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1727
+				'<br/>',
1728
+				implode(',<br/>', $undeleted_options)
1729
+			);
1730
+		}
1731
+		if ( ! empty($errors)) {
1732
+			EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1733
+		}
1734
+	}
1735
+
1736
+	/**
1737
+	 * Gets the mysql error code from the last used query by wpdb
1738
+	 *
1739
+	 * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1740
+	 */
1741
+	public static function last_wpdb_error_code()
1742
+	{
1743
+		global $wpdb;
1744
+		if ($wpdb->use_mysqli) {
1745
+			return mysqli_errno($wpdb->dbh);
1746
+		} else {
1747
+			return mysql_errno($wpdb->dbh);
1748
+		}
1749
+	}
1750
+
1751
+	/**
1752
+	 * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1753
+	 *
1754
+	 * @global wpdb  $wpdb
1755
+	 * @deprecated instead use TableAnalysis::tableExists()
1756
+	 * @param string $table_name with or without $wpdb->prefix
1757
+	 * @return boolean
1758
+	 */
1759
+	public static function table_exists($table_name)
1760
+	{
1761
+		return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1762
+	}
1763
+
1764
+	/**
1765
+	 * Resets the cache on EEH_Activation
1766
+	 */
1767
+	public static function reset()
1768
+	{
1769
+		self::$_default_creator_id                             = null;
1770
+		self::$_initialized_db_content_already_in_this_request = false;
1771
+	}
1772 1772
 }
1773 1773
 // End of file EEH_Activation.helper.php
1774 1774
 // Location: /helpers/EEH_Activation.core.php
Please login to merge, or discard this patch.
Spacing   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
      */
62 62
     public static function getTableAnalysis()
63 63
     {
64
-        if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
64
+        if ( ! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
65 65
             self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
66 66
         }
67 67
         return self::$table_analysis;
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
      */
74 74
     public static function getTableManager()
75 75
     {
76
-        if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
76
+        if ( ! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
77 77
             self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
78 78
         }
79 79
         return self::$table_manager;
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
         if ($which_to_include === 'old') {
190 190
             $cron_tasks = array_filter(
191 191
                 $cron_tasks,
192
-                function ($value) {
192
+                function($value) {
193 193
                     return $value === EEH_Activation::cron_task_no_longer_in_use;
194 194
                 }
195 195
             );
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
     {
220 220
 
221 221
         foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
222
-            if (! wp_next_scheduled($hook_name)) {
222
+            if ( ! wp_next_scheduled($hook_name)) {
223 223
                 wp_schedule_event(time(), $frequency, $hook_name);
224 224
             }
225 225
         }
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
             3
313 313
         );
314 314
         //EE_Config::reset();
315
-        if (! EE_Config::logging_enabled()) {
315
+        if ( ! EE_Config::logging_enabled()) {
316 316
             delete_option(EE_Config::LOG_NAME);
317 317
         }
318 318
     }
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
     public static function load_calendar_config()
328 328
     {
329 329
         // grab array of all plugin folders and loop thru it
330
-        $plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
330
+        $plugins = glob(WP_PLUGIN_DIR.DS.'*', GLOB_ONLYDIR);
331 331
         if (empty($plugins)) {
332 332
             return;
333 333
         }
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
                 || strpos($plugin, 'calendar') !== false
345 345
             ) {
346 346
                 // this is what we are looking for
347
-                $calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
347
+                $calendar_config = $plugin_path.DS.'EE_Calendar_Config.php';
348 348
                 // does it exist in this folder ?
349 349
                 if (is_readable($calendar_config)) {
350 350
                     // YEAH! let's load it
@@ -477,7 +477,7 @@  discard block
 block discarded – undo
477 477
             ) {
478 478
                 //update Config with post ID
479 479
                 $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
480
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
480
+                if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
481 481
                     $msg = __(
482 482
                         'The Event Espresso critical page configuration settings could not be updated.',
483 483
                         'event_espresso'
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
     public static function get_page_by_ee_shortcode($ee_shortcode)
527 527
     {
528 528
         global $wpdb;
529
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
529
+        $shortcode_and_opening_bracket = '['.$ee_shortcode;
530 530
         $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
531 531
         if ($post_id) {
532 532
             return get_post($post_id);
@@ -552,11 +552,11 @@  discard block
 block discarded – undo
552 552
             'post_status'    => 'publish',
553 553
             'post_type'      => 'page',
554 554
             'comment_status' => 'closed',
555
-            'post_content'   => '[' . $critical_page['code'] . ']',
555
+            'post_content'   => '['.$critical_page['code'].']',
556 556
         );
557 557
 
558 558
         $post_id = wp_insert_post($post_args);
559
-        if (! $post_id) {
559
+        if ( ! $post_id) {
560 560
             $msg = sprintf(
561 561
                 __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
562 562
                 $critical_page['name']
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
             return $critical_page;
566 566
         }
567 567
         // get newly created post's details
568
-        if (! $critical_page['post'] = get_post($post_id)) {
568
+        if ( ! $critical_page['post'] = get_post($post_id)) {
569 569
             $msg = sprintf(
570 570
                 __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
571 571
                 $critical_page['name']
@@ -652,17 +652,17 @@  discard block
 block discarded – undo
652 652
             $role_to_check
653 653
         );
654 654
         if ($pre_filtered_id !== false) {
655
-            return (int)$pre_filtered_id;
655
+            return (int) $pre_filtered_id;
656 656
         }
657 657
         $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
658 658
         $query = $wpdb->prepare(
659 659
             "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
660
-            '%' . $role_to_check . '%'
660
+            '%'.$role_to_check.'%'
661 661
         );
662 662
         $user_id = $wpdb->get_var($query);
663 663
         $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
664
-        if ($user_id && (int)$user_id) {
665
-            self::$_default_creator_id = (int)$user_id;
664
+        if ($user_id && (int) $user_id) {
665
+            self::$_default_creator_id = (int) $user_id;
666 666
             return self::$_default_creator_id;
667 667
         } else {
668 668
             return null;
@@ -697,7 +697,7 @@  discard block
 block discarded – undo
697 697
         }
698 698
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
699 699
         if ( ! function_exists('dbDelta')) {
700
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
700
+            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
701 701
         }
702 702
         $tableAnalysis = \EEH_Activation::getTableAnalysis();
703 703
         $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
@@ -908,13 +908,13 @@  discard block
 block discarded – undo
908 908
             // reset values array
909 909
             $QSG_values = array();
910 910
             // if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
911
-            if (! in_array("$QSG_system", $question_groups)) {
911
+            if ( ! in_array("$QSG_system", $question_groups)) {
912 912
                 // add it
913 913
                 switch ($QSG_system) {
914 914
                     case 1:
915 915
                         $QSG_values = array(
916 916
                             'QSG_name'            => __('Personal Information', 'event_espresso'),
917
-                            'QSG_identifier'      => 'personal-information-' . time(),
917
+                            'QSG_identifier'      => 'personal-information-'.time(),
918 918
                             'QSG_desc'            => '',
919 919
                             'QSG_order'           => 1,
920 920
                             'QSG_show_group_name' => 1,
@@ -926,7 +926,7 @@  discard block
 block discarded – undo
926 926
                     case 2:
927 927
                         $QSG_values = array(
928 928
                             'QSG_name'            => __('Address Information', 'event_espresso'),
929
-                            'QSG_identifier'      => 'address-information-' . time(),
929
+                            'QSG_identifier'      => 'address-information-'.time(),
930 930
                             'QSG_desc'            => '',
931 931
                             'QSG_order'           => 2,
932 932
                             'QSG_show_group_name' => 1,
@@ -937,7 +937,7 @@  discard block
 block discarded – undo
937 937
                         break;
938 938
                 }
939 939
                 // make sure we have some values before inserting them
940
-                if (! empty($QSG_values)) {
940
+                if ( ! empty($QSG_values)) {
941 941
                     // insert system question
942 942
                     $wpdb->insert(
943 943
                         $table_name,
@@ -974,7 +974,7 @@  discard block
 block discarded – undo
974 974
             // reset values array
975 975
             $QST_values = array();
976 976
             // if we don't have what we should have
977
-            if (! in_array($QST_system, $questions)) {
977
+            if ( ! in_array($QST_system, $questions)) {
978 978
                 // add it
979 979
                 switch ($QST_system) {
980 980
                     case 'fname':
@@ -1126,7 +1126,7 @@  discard block
 block discarded – undo
1126 1126
                         );
1127 1127
                         break;
1128 1128
                 }
1129
-                if (! empty($QST_values)) {
1129
+                if ( ! empty($QST_values)) {
1130 1130
                     // insert system question
1131 1131
                     $wpdb->insert(
1132 1132
                         $table_name,
@@ -1187,7 +1187,7 @@  discard block
 block discarded – undo
1187 1187
      */
1188 1188
     public static function insert_default_payment_methods()
1189 1189
     {
1190
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1190
+        if ( ! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1191 1191
             EE_Registry::instance()->load_lib('Payment_Method_Manager');
1192 1192
             EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1193 1193
         } else {
@@ -1275,9 +1275,9 @@  discard block
 block discarded – undo
1275 1275
         $folders = array(
1276 1276
             EVENT_ESPRESSO_TEMPLATE_DIR,
1277 1277
             EVENT_ESPRESSO_GATEWAY_DIR,
1278
-            EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1279
-            EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1280
-            EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/',
1278
+            EVENT_ESPRESSO_UPLOAD_DIR.'logs/',
1279
+            EVENT_ESPRESSO_UPLOAD_DIR.'css/',
1280
+            EVENT_ESPRESSO_UPLOAD_DIR.'tickets/',
1281 1281
         );
1282 1282
         foreach ($folders as $folder) {
1283 1283
             try {
@@ -1288,7 +1288,7 @@  discard block
 block discarded – undo
1288 1288
                     sprintf(
1289 1289
                         __('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1290 1290
                         $folder,
1291
-                        '<br />' . $e->getMessage()
1291
+                        '<br />'.$e->getMessage()
1292 1292
                     ),
1293 1293
                     __FILE__, __FUNCTION__, __LINE__
1294 1294
                 );
@@ -1299,7 +1299,7 @@  discard block
 block discarded – undo
1299 1299
         }
1300 1300
         //just add the .htaccess file to the logs directory to begin with. Even if logging
1301 1301
         //is disabled, there might be activation errors recorded in there
1302
-        EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs/');
1302
+        EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR.'logs/');
1303 1303
         //remember EE's folders are all good
1304 1304
         delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1305 1305
         return true;
@@ -1535,7 +1535,7 @@  discard block
 block discarded – undo
1535 1535
         // this creates an array for tracking events that have no active ticket prices created
1536 1536
         // this allows us to warn admins of the situation so that it can be corrected
1537 1537
         $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1538
-        if (! $espresso_no_ticket_prices) {
1538
+        if ( ! $espresso_no_ticket_prices) {
1539 1539
             add_option('ee_no_ticket_prices', array(), '', false);
1540 1540
         }
1541 1541
     }
@@ -1574,7 +1574,7 @@  discard block
 block discarded – undo
1574 1574
             }
1575 1575
         }
1576 1576
         //get all our CPTs
1577
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1577
+        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (".implode(",", $ee_post_types).")";
1578 1578
         $cpt_ids = $wpdb->get_col($query);
1579 1579
         //delete each post meta and term relations too
1580 1580
         foreach ($cpt_ids as $post_id) {
@@ -1714,7 +1714,7 @@  discard block
 block discarded – undo
1714 1714
         if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1715 1715
             $db_update_sans_ee4 = array();
1716 1716
             foreach ($espresso_db_update as $version => $times_activated) {
1717
-                if ((string)$version[0] === '3') {//if its NON EE4
1717
+                if ((string) $version[0] === '3') {//if its NON EE4
1718 1718
                     $db_update_sans_ee4[$version] = $times_activated;
1719 1719
                 }
1720 1720
             }
Please login to merge, or discard this patch.
admin_pages/messages/Messages_Admin_Page.core.php 2 patches
Indentation   +3614 added lines, -3614 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('NO direct script access allowed');
2
+	exit('NO direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -17,2213 +17,2213 @@  discard block
 block discarded – undo
17 17
 class Messages_Admin_Page extends EE_Admin_Page
18 18
 {
19 19
     
20
-    /**
21
-     * @type EE_Message_Resource_Manager $_message_resource_manager
22
-     */
23
-    protected $_message_resource_manager;
24
-    
25
-    /**
26
-     * @type string $_active_message_type_name
27
-     */
28
-    protected $_active_message_type_name = '';
29
-    
30
-    /**
31
-     * @type EE_messenger $_active_messenger
32
-     */
33
-    protected $_active_messenger;
34
-    protected $_activate_state;
35
-    protected $_activate_meta_box_type;
36
-    protected $_current_message_meta_box;
37
-    protected $_current_message_meta_box_object;
38
-    protected $_context_switcher;
39
-    protected $_shortcodes = array();
40
-    protected $_active_messengers = array();
41
-    protected $_active_message_types = array();
42
-    
43
-    /**
44
-     * @var EE_Message_Template_Group $_message_template_group
45
-     */
46
-    protected $_message_template_group;
47
-    protected $_m_mt_settings = array();
48
-    
49
-    
50
-    /**
51
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
52
-     * IF there is no group then it gets automatically set to the Default template pack.
53
-     *
54
-     * @since 4.5.0
55
-     *
56
-     * @var EE_Messages_Template_Pack
57
-     */
58
-    protected $_template_pack;
59
-    
60
-    
61
-    /**
62
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
63
-     * group is.  If there is no group then it automatically gets set to default.
64
-     *
65
-     * @since 4.5.0
66
-     *
67
-     * @var string
68
-     */
69
-    protected $_variation;
70
-    
71
-    
72
-    /**
73
-     * @param bool $routing
74
-     */
75
-    public function __construct($routing = true)
76
-    {
77
-        //make sure messages autoloader is running
78
-        EED_Messages::set_autoloaders();
79
-        parent::__construct($routing);
80
-    }
81
-    
82
-    
83
-    protected function _init_page_props()
84
-    {
85
-        $this->page_slug        = EE_MSG_PG_SLUG;
86
-        $this->page_label       = __('Messages Settings', 'event_espresso');
87
-        $this->_admin_base_url  = EE_MSG_ADMIN_URL;
88
-        $this->_admin_base_path = EE_MSG_ADMIN;
89
-        
90
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
91
-        
92
-        $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
93
-        $this->_load_message_resource_manager();
94
-    }
95
-    
96
-    
97
-    /**
98
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
99
-     *
100
-     *
101
-     * @throws EE_Error
102
-     */
103
-    protected function _load_message_resource_manager()
104
-    {
105
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
106
-    }
107
-    
108
-    
109
-    /**
110
-     * @deprecated 4.9.9.rc.014
111
-     * @return array
112
-     */
113
-    public function get_messengers_for_list_table()
114
-    {
115
-        EE_Error::doing_it_wrong(
116
-            __METHOD__,
117
-            __('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
20
+	/**
21
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
22
+	 */
23
+	protected $_message_resource_manager;
24
+    
25
+	/**
26
+	 * @type string $_active_message_type_name
27
+	 */
28
+	protected $_active_message_type_name = '';
29
+    
30
+	/**
31
+	 * @type EE_messenger $_active_messenger
32
+	 */
33
+	protected $_active_messenger;
34
+	protected $_activate_state;
35
+	protected $_activate_meta_box_type;
36
+	protected $_current_message_meta_box;
37
+	protected $_current_message_meta_box_object;
38
+	protected $_context_switcher;
39
+	protected $_shortcodes = array();
40
+	protected $_active_messengers = array();
41
+	protected $_active_message_types = array();
42
+    
43
+	/**
44
+	 * @var EE_Message_Template_Group $_message_template_group
45
+	 */
46
+	protected $_message_template_group;
47
+	protected $_m_mt_settings = array();
48
+    
49
+    
50
+	/**
51
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
52
+	 * IF there is no group then it gets automatically set to the Default template pack.
53
+	 *
54
+	 * @since 4.5.0
55
+	 *
56
+	 * @var EE_Messages_Template_Pack
57
+	 */
58
+	protected $_template_pack;
59
+    
60
+    
61
+	/**
62
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
63
+	 * group is.  If there is no group then it automatically gets set to default.
64
+	 *
65
+	 * @since 4.5.0
66
+	 *
67
+	 * @var string
68
+	 */
69
+	protected $_variation;
70
+    
71
+    
72
+	/**
73
+	 * @param bool $routing
74
+	 */
75
+	public function __construct($routing = true)
76
+	{
77
+		//make sure messages autoloader is running
78
+		EED_Messages::set_autoloaders();
79
+		parent::__construct($routing);
80
+	}
81
+    
82
+    
83
+	protected function _init_page_props()
84
+	{
85
+		$this->page_slug        = EE_MSG_PG_SLUG;
86
+		$this->page_label       = __('Messages Settings', 'event_espresso');
87
+		$this->_admin_base_url  = EE_MSG_ADMIN_URL;
88
+		$this->_admin_base_path = EE_MSG_ADMIN;
89
+        
90
+		$this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
91
+        
92
+		$this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
93
+		$this->_load_message_resource_manager();
94
+	}
95
+    
96
+    
97
+	/**
98
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
99
+	 *
100
+	 *
101
+	 * @throws EE_Error
102
+	 */
103
+	protected function _load_message_resource_manager()
104
+	{
105
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
106
+	}
107
+    
108
+    
109
+	/**
110
+	 * @deprecated 4.9.9.rc.014
111
+	 * @return array
112
+	 */
113
+	public function get_messengers_for_list_table()
114
+	{
115
+		EE_Error::doing_it_wrong(
116
+			__METHOD__,
117
+			__('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
118 118
 			values for use in creating a messenger filter dropdown which is now generated differently via
119 119
 			 Messages_Admin_Page::get_messengers_select_input', 'event_espresso'),
120
-            '4.9.9.rc.014'
121
-        );
122
-        
123
-        $m_values          = array();
124
-        $active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
125
-        //setup messengers for selects
126
-        $i = 1;
127
-        foreach ($active_messengers as $active_messenger) {
128
-            if ($active_messenger instanceof EE_Message) {
129
-                $m_values[$i]['id']   = $active_messenger->messenger();
130
-                $m_values[$i]['text'] = ucwords($active_messenger->messenger_label());
131
-                $i++;
132
-            }
133
-        }
134
-        
135
-        return $m_values;
136
-    }
137
-    
138
-    
139
-    /**
140
-     * @deprecated 4.9.9.rc.014
141
-     * @return array
142
-     */
143
-    public function get_message_types_for_list_table()
144
-    {
145
-        EE_Error::doing_it_wrong(
146
-            __METHOD__,
147
-            __('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
120
+			'4.9.9.rc.014'
121
+		);
122
+        
123
+		$m_values          = array();
124
+		$active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
125
+		//setup messengers for selects
126
+		$i = 1;
127
+		foreach ($active_messengers as $active_messenger) {
128
+			if ($active_messenger instanceof EE_Message) {
129
+				$m_values[$i]['id']   = $active_messenger->messenger();
130
+				$m_values[$i]['text'] = ucwords($active_messenger->messenger_label());
131
+				$i++;
132
+			}
133
+		}
134
+        
135
+		return $m_values;
136
+	}
137
+    
138
+    
139
+	/**
140
+	 * @deprecated 4.9.9.rc.014
141
+	 * @return array
142
+	 */
143
+	public function get_message_types_for_list_table()
144
+	{
145
+		EE_Error::doing_it_wrong(
146
+			__METHOD__,
147
+			__('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
148 148
 			values for use in creating a message type filter dropdown which is now generated differently via
149 149
 			 Messages_Admin_Page::get_message_types_select_input', 'event_espresso'),
150
-            '4.9.9.rc.014'
151
-        );
152
-        
153
-        $mt_values       = array();
154
-        $active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
155
-        $i               = 1;
156
-        foreach ($active_messages as $active_message) {
157
-            if ($active_message instanceof EE_Message) {
158
-                $mt_values[$i]['id']   = $active_message->message_type();
159
-                $mt_values[$i]['text'] = ucwords($active_message->message_type_label());
160
-                $i++;
161
-            }
162
-        }
163
-        
164
-        return $mt_values;
165
-    }
166
-    
167
-    
168
-    /**
169
-     * @deprecated 4.9.9.rc.014
170
-     * @return array
171
-     */
172
-    public function get_contexts_for_message_types_for_list_table()
173
-    {
174
-        EE_Error::doing_it_wrong(
175
-            __METHOD__,
176
-            __('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
150
+			'4.9.9.rc.014'
151
+		);
152
+        
153
+		$mt_values       = array();
154
+		$active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
155
+		$i               = 1;
156
+		foreach ($active_messages as $active_message) {
157
+			if ($active_message instanceof EE_Message) {
158
+				$mt_values[$i]['id']   = $active_message->message_type();
159
+				$mt_values[$i]['text'] = ucwords($active_message->message_type_label());
160
+				$i++;
161
+			}
162
+		}
163
+        
164
+		return $mt_values;
165
+	}
166
+    
167
+    
168
+	/**
169
+	 * @deprecated 4.9.9.rc.014
170
+	 * @return array
171
+	 */
172
+	public function get_contexts_for_message_types_for_list_table()
173
+	{
174
+		EE_Error::doing_it_wrong(
175
+			__METHOD__,
176
+			__('This method is no longer in use.  There is no replacement for it. The method was used to generate a set of
177 177
 			values for use in creating a message type context filter dropdown which is now generated differently via
178 178
 			 Messages_Admin_Page::get_contexts_for_message_types_select_input', 'event_espresso'),
179
-            '4.9.9.rc.014'
180
-        );
181
-        
182
-        $contexts                = array();
183
-        $active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
184
-        foreach ($active_message_contexts as $active_message) {
185
-            if ($active_message instanceof EE_Message) {
186
-                $message_type = $active_message->message_type_object();
187
-                if ($message_type instanceof EE_message_type) {
188
-                    $message_type_contexts = $message_type->get_contexts();
189
-                    foreach ($message_type_contexts as $context => $context_details) {
190
-                        $contexts[$context] = $context_details['label'];
191
-                    }
192
-                }
193
-            }
194
-        }
195
-        
196
-        return $contexts;
197
-    }
198
-    
199
-    
200
-    /**
201
-     * Generate select input with provided messenger options array.
202
-     *
203
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
204
-     *                                 labels.
205
-     *
206
-     * @return string
207
-     */
208
-    public function get_messengers_select_input($messenger_options)
209
-    {
210
-        //if empty or just one value then just return an empty string
211
-        if (empty($messenger_options)
212
-            || ! is_array($messenger_options)
213
-            || count($messenger_options) === 1
214
-        ) {
215
-            return '';
216
-        }
217
-        //merge in default
218
-        $messenger_options = array_merge(
219
-            array('none_selected' => __('Show All Messengers', 'event_espresso')),
220
-            $messenger_options
221
-        );
222
-        $input             = new EE_Select_Input(
223
-            $messenger_options,
224
-            array(
225
-                'html_name'  => 'ee_messenger_filter_by',
226
-                'html_id'    => 'ee_messenger_filter_by',
227
-                'html_class' => 'wide',
228
-                'default'    => isset($this->_req_data['ee_messenger_filter_by'])
229
-                    ? sanitize_title($this->_req_data['ee_messenger_filter_by'])
230
-                    : 'none_selected'
231
-            )
232
-        );
233
-        
234
-        return $input->get_html_for_input();
235
-    }
236
-    
237
-    
238
-    /**
239
-     * Generate select input with provided message type options array.
240
-     *
241
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
242
-     *                                    message type labels
243
-     *
244
-     * @return string
245
-     */
246
-    public function get_message_types_select_input($message_type_options)
247
-    {
248
-        //if empty or count of options is 1 then just return an empty string
249
-        if (empty($message_type_options)
250
-            || ! is_array($message_type_options)
251
-            || count($message_type_options) === 1
252
-        ) {
253
-            return '';
254
-        }
255
-        //merge in default
256
-        $message_type_options = array_merge(
257
-            array('none_selected' => __('Show All Message Types', 'event_espresso')),
258
-            $message_type_options
259
-        );
260
-        $input                = new EE_Select_Input(
261
-            $message_type_options,
262
-            array(
263
-                'html_name'  => 'ee_message_type_filter_by',
264
-                'html_id'    => 'ee_message_type_filter_by',
265
-                'html_class' => 'wide',
266
-                'default'    => isset($this->_req_data['ee_message_type_filter_by'])
267
-                    ? sanitize_title($this->_req_data['ee_message_type_filter_by'])
268
-                    : 'none_selected',
269
-            )
270
-        );
271
-        
272
-        return $input->get_html_for_input();
273
-    }
274
-    
275
-    
276
-    /**
277
-     * Generate select input with provide message type contexts array.
278
-     *
279
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
280
-     *                               context label.
281
-     *
282
-     * @return string
283
-     */
284
-    public function get_contexts_for_message_types_select_input($context_options)
285
-    {
286
-        //if empty or count of options is one then just return empty string
287
-        if (empty($context_options)
288
-            || ! is_array($context_options)
289
-            || count($context_options) === 1
290
-        ) {
291
-            return '';
292
-        }
293
-        //merge in default
294
-        $context_options = array_merge(
295
-            array('none_selected' => __('Show all Contexts', 'event_espresso')),
296
-            $context_options
297
-        );
298
-        $input           = new EE_Select_Input(
299
-            $context_options,
300
-            array(
301
-                'html_name'  => 'ee_context_filter_by',
302
-                'html_id'    => 'ee_context_filter_by',
303
-                'html_class' => 'wide',
304
-                'default'    => isset($this->_req_data['ee_context_filter_by'])
305
-                    ? sanitize_title($this->_req_data['ee_context_filter_by'])
306
-                    : 'none_selected',
307
-            )
308
-        );
309
-        
310
-        return $input->get_html_for_input();
311
-    }
312
-    
313
-    
314
-    protected function _ajax_hooks()
315
-    {
316
-        add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
317
-        add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
318
-        add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
319
-        add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
320
-        add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
321
-    }
322
-    
323
-    
324
-    protected function _define_page_props()
325
-    {
326
-        $this->_admin_page_title = $this->page_label;
327
-        $this->_labels           = array(
328
-            'buttons'    => array(
329
-                'add'    => __('Add New Message Template', 'event_espresso'),
330
-                'edit'   => __('Edit Message Template', 'event_espresso'),
331
-                'delete' => __('Delete Message Template', 'event_espresso')
332
-            ),
333
-            'publishbox' => __('Update Actions', 'event_espresso')
334
-        );
335
-    }
336
-    
337
-    
338
-    /**
339
-     *        an array for storing key => value pairs of request actions and their corresponding methods
340
-     * @access protected
341
-     * @return void
342
-     */
343
-    protected function _set_page_routes()
344
-    {
345
-        $grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
346
-            ? $this->_req_data['GRP_ID']
347
-            : 0;
348
-        $grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
349
-            ? $this->_req_data['id']
350
-            : $grp_id;
351
-        $msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
352
-            ? $this->_req_data['MSG_ID']
353
-            : 0;
354
-        
355
-        $this->_page_routes = array(
356
-            'default'                          => array(
357
-                'func'       => '_message_queue_list_table',
358
-                'capability' => 'ee_read_global_messages'
359
-            ),
360
-            'global_mtps'                      => array(
361
-                'func'       => '_ee_default_messages_overview_list_table',
362
-                'capability' => 'ee_read_global_messages'
363
-            ),
364
-            'custom_mtps'                      => array(
365
-                'func'       => '_custom_mtps_preview',
366
-                'capability' => 'ee_read_messages'
367
-            ),
368
-            'add_new_message_template'         => array(
369
-                'func'       => '_add_message_template',
370
-                'capability' => 'ee_edit_messages',
371
-                'noheader'   => true
372
-            ),
373
-            'edit_message_template'            => array(
374
-                'func'       => '_edit_message_template',
375
-                'capability' => 'ee_edit_message',
376
-                'obj_id'     => $grp_id
377
-            ),
378
-            'preview_message'                  => array(
379
-                'func'               => '_preview_message',
380
-                'capability'         => 'ee_read_message',
381
-                'obj_id'             => $grp_id,
382
-                'noheader'           => true,
383
-                'headers_sent_route' => 'display_preview_message'
384
-            ),
385
-            'display_preview_message'          => array(
386
-                'func'       => '_display_preview_message',
387
-                'capability' => 'ee_read_message',
388
-                'obj_id'     => $grp_id
389
-            ),
390
-            'insert_message_template'          => array(
391
-                'func'       => '_insert_or_update_message_template',
392
-                'capability' => 'ee_edit_messages',
393
-                'args'       => array('new_template' => true),
394
-                'noheader'   => true
395
-            ),
396
-            'update_message_template'          => array(
397
-                'func'       => '_insert_or_update_message_template',
398
-                'capability' => 'ee_edit_message',
399
-                'obj_id'     => $grp_id,
400
-                'args'       => array('new_template' => false),
401
-                'noheader'   => true
402
-            ),
403
-            'trash_message_template'           => array(
404
-                'func'       => '_trash_or_restore_message_template',
405
-                'capability' => 'ee_delete_message',
406
-                'obj_id'     => $grp_id,
407
-                'args'       => array('trash' => true, 'all' => true),
408
-                'noheader'   => true
409
-            ),
410
-            'trash_message_template_context'   => array(
411
-                'func'       => '_trash_or_restore_message_template',
412
-                'capability' => 'ee_delete_message',
413
-                'obj_id'     => $grp_id,
414
-                'args'       => array('trash' => true),
415
-                'noheader'   => true
416
-            ),
417
-            'restore_message_template'         => array(
418
-                'func'       => '_trash_or_restore_message_template',
419
-                'capability' => 'ee_delete_message',
420
-                'obj_id'     => $grp_id,
421
-                'args'       => array('trash' => false, 'all' => true),
422
-                'noheader'   => true
423
-            ),
424
-            'restore_message_template_context' => array(
425
-                'func'       => '_trash_or_restore_message_template',
426
-                'capability' => 'ee_delete_message',
427
-                'obj_id'     => $grp_id,
428
-                'args'       => array('trash' => false),
429
-                'noheader'   => true
430
-            ),
431
-            'delete_message_template'          => array(
432
-                'func'       => '_delete_message_template',
433
-                'capability' => 'ee_delete_message',
434
-                'obj_id'     => $grp_id,
435
-                'noheader'   => true
436
-            ),
437
-            'reset_to_default'                 => array(
438
-                'func'       => '_reset_to_default_template',
439
-                'capability' => 'ee_edit_message',
440
-                'obj_id'     => $grp_id,
441
-                'noheader'   => true
442
-            ),
443
-            'settings'                         => array(
444
-                'func'       => '_settings',
445
-                'capability' => 'manage_options'
446
-            ),
447
-            'update_global_settings'           => array(
448
-                'func'       => '_update_global_settings',
449
-                'capability' => 'manage_options',
450
-                'noheader'   => true
451
-            ),
452
-            'generate_now'                     => array(
453
-                'func'       => '_generate_now',
454
-                'capability' => 'ee_send_message',
455
-                'noheader'   => true
456
-            ),
457
-            'generate_and_send_now'            => array(
458
-                'func'       => '_generate_and_send_now',
459
-                'capability' => 'ee_send_message',
460
-                'noheader'   => true
461
-            ),
462
-            'queue_for_resending'              => array(
463
-                'func'       => '_queue_for_resending',
464
-                'capability' => 'ee_send_message',
465
-                'noheader'   => true
466
-            ),
467
-            'send_now'                         => array(
468
-                'func'       => '_send_now',
469
-                'capability' => 'ee_send_message',
470
-                'noheader'   => true
471
-            ),
472
-            'delete_ee_message'                => array(
473
-                'func'       => '_delete_ee_messages',
474
-                'capability' => 'ee_delete_message',
475
-                'noheader'   => true
476
-            ),
477
-            'delete_ee_messages'               => array(
478
-                'func'       => '_delete_ee_messages',
479
-                'capability' => 'ee_delete_messages',
480
-                'noheader'   => true,
481
-                'obj_id'     => $msg_id
482
-            )
483
-        );
484
-    }
485
-    
486
-    
487
-    protected function _set_page_config()
488
-    {
489
-        $this->_page_config = array(
490
-            'default'                  => array(
491
-                'nav'           => array(
492
-                    'label' => __('Message Activity', 'event_espresso'),
493
-                    'order' => 10
494
-                ),
495
-                'list_table'    => 'EE_Message_List_Table',
496
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
497
-                'require_nonce' => false
498
-            ),
499
-            'global_mtps'              => array(
500
-                'nav'           => array(
501
-                    'label' => __('Default Message Templates', 'event_espresso'),
502
-                    'order' => 20
503
-                ),
504
-                'list_table'    => 'Messages_Template_List_Table',
505
-                'help_tabs'     => array(
506
-                    'messages_overview_help_tab'                                => array(
507
-                        'title'    => __('Messages Overview', 'event_espresso'),
508
-                        'filename' => 'messages_overview'
509
-                    ),
510
-                    'messages_overview_messages_table_column_headings_help_tab' => array(
511
-                        'title'    => __('Messages Table Column Headings', 'event_espresso'),
512
-                        'filename' => 'messages_overview_table_column_headings'
513
-                    ),
514
-                    'messages_overview_messages_filters_help_tab'               => array(
515
-                        'title'    => __('Message Filters', 'event_espresso'),
516
-                        'filename' => 'messages_overview_filters'
517
-                    ),
518
-                    'messages_overview_messages_views_help_tab'                 => array(
519
-                        'title'    => __('Message Views', 'event_espresso'),
520
-                        'filename' => 'messages_overview_views'
521
-                    ),
522
-                    'message_overview_message_types_help_tab'                   => array(
523
-                        'title'    => __('Message Types', 'event_espresso'),
524
-                        'filename' => 'messages_overview_types'
525
-                    ),
526
-                    'messages_overview_messengers_help_tab'                     => array(
527
-                        'title'    => __('Messengers', 'event_espresso'),
528
-                        'filename' => 'messages_overview_messengers',
529
-                    ),
530
-                    'messages_overview_other_help_tab'                          => array(
531
-                        'title'    => __('Messages Other', 'event_espresso'),
532
-                        'filename' => 'messages_overview_other',
533
-                    ),
534
-                ),
535
-                'help_tour'     => array('Messages_Overview_Help_Tour'),
536
-                'require_nonce' => false
537
-            ),
538
-            'custom_mtps'              => array(
539
-                'nav'           => array(
540
-                    'label' => __('Custom Message Templates', 'event_espresso'),
541
-                    'order' => 30
542
-                ),
543
-                'help_tabs'     => array(),
544
-                'help_tour'     => array(),
545
-                'require_nonce' => false
546
-            ),
547
-            'add_new_message_template' => array(
548
-                'nav'           => array(
549
-                    'label'      => __('Add New Message Templates', 'event_espresso'),
550
-                    'order'      => 5,
551
-                    'persistent' => false
552
-                ),
553
-                'require_nonce' => false
554
-            ),
555
-            'edit_message_template'    => array(
556
-                'labels'        => array(
557
-                    'buttons'    => array(
558
-                        'reset' => __('Reset Templates'),
559
-                    ),
560
-                    'publishbox' => __('Update Actions', 'event_espresso')
561
-                ),
562
-                'nav'           => array(
563
-                    'label'      => __('Edit Message Templates', 'event_espresso'),
564
-                    'order'      => 5,
565
-                    'persistent' => false,
566
-                    'url'        => ''
567
-                ),
568
-                'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
569
-                'has_metaboxes' => true,
570
-                'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
571
-                'help_tabs'     => array(
572
-                    'edit_message_template'       => array(
573
-                        'title'    => __('Message Template Editor', 'event_espresso'),
574
-                        'callback' => 'edit_message_template_help_tab'
575
-                    ),
576
-                    'message_templates_help_tab'  => array(
577
-                        'title'    => __('Message Templates', 'event_espresso'),
578
-                        'filename' => 'messages_templates'
579
-                    ),
580
-                    'message_template_shortcodes' => array(
581
-                        'title'    => __('Message Shortcodes', 'event_espresso'),
582
-                        'callback' => 'message_template_shortcodes_help_tab'
583
-                    ),
584
-                    'message_preview_help_tab'    => array(
585
-                        'title'    => __('Message Preview', 'event_espresso'),
586
-                        'filename' => 'messages_preview'
587
-                    ),
588
-                ),
589
-                'require_nonce' => false
590
-            ),
591
-            'display_preview_message'  => array(
592
-                'nav'           => array(
593
-                    'label'      => __('Message Preview', 'event_espresso'),
594
-                    'order'      => 5,
595
-                    'url'        => '',
596
-                    'persistent' => false
597
-                ),
598
-                'help_tabs'     => array(
599
-                    'preview_message' => array(
600
-                        'title'    => __('About Previews', 'event_espresso'),
601
-                        'callback' => 'preview_message_help_tab'
602
-                    )
603
-                ),
604
-                'require_nonce' => false
605
-            ),
606
-            'settings'                 => array(
607
-                'nav'           => array(
608
-                    'label' => __('Settings', 'event_espresso'),
609
-                    'order' => 40
610
-                ),
611
-                'metaboxes'     => array('_messages_settings_metaboxes'),
612
-                'help_tabs'     => array(
613
-                    'messages_settings_help_tab'               => array(
614
-                        'title'    => __('Messages Settings', 'event_espresso'),
615
-                        'filename' => 'messages_settings'
616
-                    ),
617
-                    'messages_settings_message_types_help_tab' => array(
618
-                        'title'    => __('Activating / Deactivating Message Types', 'event_espresso'),
619
-                        'filename' => 'messages_settings_message_types'
620
-                    ),
621
-                    'messages_settings_messengers_help_tab'    => array(
622
-                        'title'    => __('Activating / Deactivating Messengers', 'event_espresso'),
623
-                        'filename' => 'messages_settings_messengers'
624
-                    ),
625
-                ),
626
-                'help_tour'     => array('Messages_Settings_Help_Tour'),
627
-                'require_nonce' => false
628
-            )
629
-        );
630
-    }
631
-    
632
-    
633
-    protected function _add_screen_options()
634
-    {
635
-        //todo
636
-    }
637
-    
638
-    
639
-    protected function _add_screen_options_global_mtps()
640
-    {
641
-        /**
642
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
643
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
644
-         */
645
-        $page_title              = $this->_admin_page_title;
646
-        $this->_admin_page_title = __('Global Message Templates', 'event_espresso');
647
-        $this->_per_page_screen_option();
648
-        $this->_admin_page_title = $page_title;
649
-    }
650
-    
651
-    
652
-    protected function _add_screen_options_default()
653
-    {
654
-        $this->_admin_page_title = __('Message Activity', 'event_espresso');
655
-        $this->_per_page_screen_option();
656
-    }
657
-    
658
-    
659
-    //none of the below group are currently used for Messages
660
-    protected function _add_feature_pointers()
661
-    {
662
-    }
663
-    
664
-    public function admin_init()
665
-    {
666
-    }
667
-    
668
-    public function admin_notices()
669
-    {
670
-    }
671
-    
672
-    public function admin_footer_scripts()
673
-    {
674
-    }
675
-    
676
-    
677
-    public function messages_help_tab()
678
-    {
679
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
680
-    }
681
-    
682
-    
683
-    public function messengers_help_tab()
684
-    {
685
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
686
-    }
687
-    
688
-    
689
-    public function message_types_help_tab()
690
-    {
691
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
692
-    }
693
-    
694
-    
695
-    public function messages_overview_help_tab()
696
-    {
697
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
698
-    }
699
-    
700
-    
701
-    public function message_templates_help_tab()
702
-    {
703
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
704
-    }
705
-    
706
-    
707
-    public function edit_message_template_help_tab()
708
-    {
709
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="' . esc_attr__('Editor Title',
710
-                'event_espresso') . '" />';
711
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="' . esc_attr__('Context Switcher and Preview',
712
-                'event_espresso') . '" />';
713
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="' . esc_attr__('Message Template Form Fields',
714
-                'event_espresso') . '" />';
715
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="' . esc_attr__('Shortcodes Metabox',
716
-                'event_espresso') . '" />';
717
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="' . esc_attr__('Publish Metabox',
718
-                'event_espresso') . '" />';
719
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
720
-            $args);
721
-    }
722
-    
723
-    
724
-    public function message_template_shortcodes_help_tab()
725
-    {
726
-        $this->_set_shortcodes();
727
-        $args['shortcodes'] = $this->_shortcodes;
728
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
729
-            $args);
730
-    }
179
+			'4.9.9.rc.014'
180
+		);
181
+        
182
+		$contexts                = array();
183
+		$active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
184
+		foreach ($active_message_contexts as $active_message) {
185
+			if ($active_message instanceof EE_Message) {
186
+				$message_type = $active_message->message_type_object();
187
+				if ($message_type instanceof EE_message_type) {
188
+					$message_type_contexts = $message_type->get_contexts();
189
+					foreach ($message_type_contexts as $context => $context_details) {
190
+						$contexts[$context] = $context_details['label'];
191
+					}
192
+				}
193
+			}
194
+		}
195
+        
196
+		return $contexts;
197
+	}
198
+    
199
+    
200
+	/**
201
+	 * Generate select input with provided messenger options array.
202
+	 *
203
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
204
+	 *                                 labels.
205
+	 *
206
+	 * @return string
207
+	 */
208
+	public function get_messengers_select_input($messenger_options)
209
+	{
210
+		//if empty or just one value then just return an empty string
211
+		if (empty($messenger_options)
212
+			|| ! is_array($messenger_options)
213
+			|| count($messenger_options) === 1
214
+		) {
215
+			return '';
216
+		}
217
+		//merge in default
218
+		$messenger_options = array_merge(
219
+			array('none_selected' => __('Show All Messengers', 'event_espresso')),
220
+			$messenger_options
221
+		);
222
+		$input             = new EE_Select_Input(
223
+			$messenger_options,
224
+			array(
225
+				'html_name'  => 'ee_messenger_filter_by',
226
+				'html_id'    => 'ee_messenger_filter_by',
227
+				'html_class' => 'wide',
228
+				'default'    => isset($this->_req_data['ee_messenger_filter_by'])
229
+					? sanitize_title($this->_req_data['ee_messenger_filter_by'])
230
+					: 'none_selected'
231
+			)
232
+		);
233
+        
234
+		return $input->get_html_for_input();
235
+	}
236
+    
237
+    
238
+	/**
239
+	 * Generate select input with provided message type options array.
240
+	 *
241
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
242
+	 *                                    message type labels
243
+	 *
244
+	 * @return string
245
+	 */
246
+	public function get_message_types_select_input($message_type_options)
247
+	{
248
+		//if empty or count of options is 1 then just return an empty string
249
+		if (empty($message_type_options)
250
+			|| ! is_array($message_type_options)
251
+			|| count($message_type_options) === 1
252
+		) {
253
+			return '';
254
+		}
255
+		//merge in default
256
+		$message_type_options = array_merge(
257
+			array('none_selected' => __('Show All Message Types', 'event_espresso')),
258
+			$message_type_options
259
+		);
260
+		$input                = new EE_Select_Input(
261
+			$message_type_options,
262
+			array(
263
+				'html_name'  => 'ee_message_type_filter_by',
264
+				'html_id'    => 'ee_message_type_filter_by',
265
+				'html_class' => 'wide',
266
+				'default'    => isset($this->_req_data['ee_message_type_filter_by'])
267
+					? sanitize_title($this->_req_data['ee_message_type_filter_by'])
268
+					: 'none_selected',
269
+			)
270
+		);
271
+        
272
+		return $input->get_html_for_input();
273
+	}
274
+    
275
+    
276
+	/**
277
+	 * Generate select input with provide message type contexts array.
278
+	 *
279
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
280
+	 *                               context label.
281
+	 *
282
+	 * @return string
283
+	 */
284
+	public function get_contexts_for_message_types_select_input($context_options)
285
+	{
286
+		//if empty or count of options is one then just return empty string
287
+		if (empty($context_options)
288
+			|| ! is_array($context_options)
289
+			|| count($context_options) === 1
290
+		) {
291
+			return '';
292
+		}
293
+		//merge in default
294
+		$context_options = array_merge(
295
+			array('none_selected' => __('Show all Contexts', 'event_espresso')),
296
+			$context_options
297
+		);
298
+		$input           = new EE_Select_Input(
299
+			$context_options,
300
+			array(
301
+				'html_name'  => 'ee_context_filter_by',
302
+				'html_id'    => 'ee_context_filter_by',
303
+				'html_class' => 'wide',
304
+				'default'    => isset($this->_req_data['ee_context_filter_by'])
305
+					? sanitize_title($this->_req_data['ee_context_filter_by'])
306
+					: 'none_selected',
307
+			)
308
+		);
309
+        
310
+		return $input->get_html_for_input();
311
+	}
312
+    
313
+    
314
+	protected function _ajax_hooks()
315
+	{
316
+		add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
317
+		add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
318
+		add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
319
+		add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
320
+		add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
321
+	}
322
+    
323
+    
324
+	protected function _define_page_props()
325
+	{
326
+		$this->_admin_page_title = $this->page_label;
327
+		$this->_labels           = array(
328
+			'buttons'    => array(
329
+				'add'    => __('Add New Message Template', 'event_espresso'),
330
+				'edit'   => __('Edit Message Template', 'event_espresso'),
331
+				'delete' => __('Delete Message Template', 'event_espresso')
332
+			),
333
+			'publishbox' => __('Update Actions', 'event_espresso')
334
+		);
335
+	}
336
+    
337
+    
338
+	/**
339
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
340
+	 * @access protected
341
+	 * @return void
342
+	 */
343
+	protected function _set_page_routes()
344
+	{
345
+		$grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
346
+			? $this->_req_data['GRP_ID']
347
+			: 0;
348
+		$grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
349
+			? $this->_req_data['id']
350
+			: $grp_id;
351
+		$msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
352
+			? $this->_req_data['MSG_ID']
353
+			: 0;
354
+        
355
+		$this->_page_routes = array(
356
+			'default'                          => array(
357
+				'func'       => '_message_queue_list_table',
358
+				'capability' => 'ee_read_global_messages'
359
+			),
360
+			'global_mtps'                      => array(
361
+				'func'       => '_ee_default_messages_overview_list_table',
362
+				'capability' => 'ee_read_global_messages'
363
+			),
364
+			'custom_mtps'                      => array(
365
+				'func'       => '_custom_mtps_preview',
366
+				'capability' => 'ee_read_messages'
367
+			),
368
+			'add_new_message_template'         => array(
369
+				'func'       => '_add_message_template',
370
+				'capability' => 'ee_edit_messages',
371
+				'noheader'   => true
372
+			),
373
+			'edit_message_template'            => array(
374
+				'func'       => '_edit_message_template',
375
+				'capability' => 'ee_edit_message',
376
+				'obj_id'     => $grp_id
377
+			),
378
+			'preview_message'                  => array(
379
+				'func'               => '_preview_message',
380
+				'capability'         => 'ee_read_message',
381
+				'obj_id'             => $grp_id,
382
+				'noheader'           => true,
383
+				'headers_sent_route' => 'display_preview_message'
384
+			),
385
+			'display_preview_message'          => array(
386
+				'func'       => '_display_preview_message',
387
+				'capability' => 'ee_read_message',
388
+				'obj_id'     => $grp_id
389
+			),
390
+			'insert_message_template'          => array(
391
+				'func'       => '_insert_or_update_message_template',
392
+				'capability' => 'ee_edit_messages',
393
+				'args'       => array('new_template' => true),
394
+				'noheader'   => true
395
+			),
396
+			'update_message_template'          => array(
397
+				'func'       => '_insert_or_update_message_template',
398
+				'capability' => 'ee_edit_message',
399
+				'obj_id'     => $grp_id,
400
+				'args'       => array('new_template' => false),
401
+				'noheader'   => true
402
+			),
403
+			'trash_message_template'           => array(
404
+				'func'       => '_trash_or_restore_message_template',
405
+				'capability' => 'ee_delete_message',
406
+				'obj_id'     => $grp_id,
407
+				'args'       => array('trash' => true, 'all' => true),
408
+				'noheader'   => true
409
+			),
410
+			'trash_message_template_context'   => array(
411
+				'func'       => '_trash_or_restore_message_template',
412
+				'capability' => 'ee_delete_message',
413
+				'obj_id'     => $grp_id,
414
+				'args'       => array('trash' => true),
415
+				'noheader'   => true
416
+			),
417
+			'restore_message_template'         => array(
418
+				'func'       => '_trash_or_restore_message_template',
419
+				'capability' => 'ee_delete_message',
420
+				'obj_id'     => $grp_id,
421
+				'args'       => array('trash' => false, 'all' => true),
422
+				'noheader'   => true
423
+			),
424
+			'restore_message_template_context' => array(
425
+				'func'       => '_trash_or_restore_message_template',
426
+				'capability' => 'ee_delete_message',
427
+				'obj_id'     => $grp_id,
428
+				'args'       => array('trash' => false),
429
+				'noheader'   => true
430
+			),
431
+			'delete_message_template'          => array(
432
+				'func'       => '_delete_message_template',
433
+				'capability' => 'ee_delete_message',
434
+				'obj_id'     => $grp_id,
435
+				'noheader'   => true
436
+			),
437
+			'reset_to_default'                 => array(
438
+				'func'       => '_reset_to_default_template',
439
+				'capability' => 'ee_edit_message',
440
+				'obj_id'     => $grp_id,
441
+				'noheader'   => true
442
+			),
443
+			'settings'                         => array(
444
+				'func'       => '_settings',
445
+				'capability' => 'manage_options'
446
+			),
447
+			'update_global_settings'           => array(
448
+				'func'       => '_update_global_settings',
449
+				'capability' => 'manage_options',
450
+				'noheader'   => true
451
+			),
452
+			'generate_now'                     => array(
453
+				'func'       => '_generate_now',
454
+				'capability' => 'ee_send_message',
455
+				'noheader'   => true
456
+			),
457
+			'generate_and_send_now'            => array(
458
+				'func'       => '_generate_and_send_now',
459
+				'capability' => 'ee_send_message',
460
+				'noheader'   => true
461
+			),
462
+			'queue_for_resending'              => array(
463
+				'func'       => '_queue_for_resending',
464
+				'capability' => 'ee_send_message',
465
+				'noheader'   => true
466
+			),
467
+			'send_now'                         => array(
468
+				'func'       => '_send_now',
469
+				'capability' => 'ee_send_message',
470
+				'noheader'   => true
471
+			),
472
+			'delete_ee_message'                => array(
473
+				'func'       => '_delete_ee_messages',
474
+				'capability' => 'ee_delete_message',
475
+				'noheader'   => true
476
+			),
477
+			'delete_ee_messages'               => array(
478
+				'func'       => '_delete_ee_messages',
479
+				'capability' => 'ee_delete_messages',
480
+				'noheader'   => true,
481
+				'obj_id'     => $msg_id
482
+			)
483
+		);
484
+	}
485
+    
486
+    
487
+	protected function _set_page_config()
488
+	{
489
+		$this->_page_config = array(
490
+			'default'                  => array(
491
+				'nav'           => array(
492
+					'label' => __('Message Activity', 'event_espresso'),
493
+					'order' => 10
494
+				),
495
+				'list_table'    => 'EE_Message_List_Table',
496
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
497
+				'require_nonce' => false
498
+			),
499
+			'global_mtps'              => array(
500
+				'nav'           => array(
501
+					'label' => __('Default Message Templates', 'event_espresso'),
502
+					'order' => 20
503
+				),
504
+				'list_table'    => 'Messages_Template_List_Table',
505
+				'help_tabs'     => array(
506
+					'messages_overview_help_tab'                                => array(
507
+						'title'    => __('Messages Overview', 'event_espresso'),
508
+						'filename' => 'messages_overview'
509
+					),
510
+					'messages_overview_messages_table_column_headings_help_tab' => array(
511
+						'title'    => __('Messages Table Column Headings', 'event_espresso'),
512
+						'filename' => 'messages_overview_table_column_headings'
513
+					),
514
+					'messages_overview_messages_filters_help_tab'               => array(
515
+						'title'    => __('Message Filters', 'event_espresso'),
516
+						'filename' => 'messages_overview_filters'
517
+					),
518
+					'messages_overview_messages_views_help_tab'                 => array(
519
+						'title'    => __('Message Views', 'event_espresso'),
520
+						'filename' => 'messages_overview_views'
521
+					),
522
+					'message_overview_message_types_help_tab'                   => array(
523
+						'title'    => __('Message Types', 'event_espresso'),
524
+						'filename' => 'messages_overview_types'
525
+					),
526
+					'messages_overview_messengers_help_tab'                     => array(
527
+						'title'    => __('Messengers', 'event_espresso'),
528
+						'filename' => 'messages_overview_messengers',
529
+					),
530
+					'messages_overview_other_help_tab'                          => array(
531
+						'title'    => __('Messages Other', 'event_espresso'),
532
+						'filename' => 'messages_overview_other',
533
+					),
534
+				),
535
+				'help_tour'     => array('Messages_Overview_Help_Tour'),
536
+				'require_nonce' => false
537
+			),
538
+			'custom_mtps'              => array(
539
+				'nav'           => array(
540
+					'label' => __('Custom Message Templates', 'event_espresso'),
541
+					'order' => 30
542
+				),
543
+				'help_tabs'     => array(),
544
+				'help_tour'     => array(),
545
+				'require_nonce' => false
546
+			),
547
+			'add_new_message_template' => array(
548
+				'nav'           => array(
549
+					'label'      => __('Add New Message Templates', 'event_espresso'),
550
+					'order'      => 5,
551
+					'persistent' => false
552
+				),
553
+				'require_nonce' => false
554
+			),
555
+			'edit_message_template'    => array(
556
+				'labels'        => array(
557
+					'buttons'    => array(
558
+						'reset' => __('Reset Templates'),
559
+					),
560
+					'publishbox' => __('Update Actions', 'event_espresso')
561
+				),
562
+				'nav'           => array(
563
+					'label'      => __('Edit Message Templates', 'event_espresso'),
564
+					'order'      => 5,
565
+					'persistent' => false,
566
+					'url'        => ''
567
+				),
568
+				'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
569
+				'has_metaboxes' => true,
570
+				'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
571
+				'help_tabs'     => array(
572
+					'edit_message_template'       => array(
573
+						'title'    => __('Message Template Editor', 'event_espresso'),
574
+						'callback' => 'edit_message_template_help_tab'
575
+					),
576
+					'message_templates_help_tab'  => array(
577
+						'title'    => __('Message Templates', 'event_espresso'),
578
+						'filename' => 'messages_templates'
579
+					),
580
+					'message_template_shortcodes' => array(
581
+						'title'    => __('Message Shortcodes', 'event_espresso'),
582
+						'callback' => 'message_template_shortcodes_help_tab'
583
+					),
584
+					'message_preview_help_tab'    => array(
585
+						'title'    => __('Message Preview', 'event_espresso'),
586
+						'filename' => 'messages_preview'
587
+					),
588
+				),
589
+				'require_nonce' => false
590
+			),
591
+			'display_preview_message'  => array(
592
+				'nav'           => array(
593
+					'label'      => __('Message Preview', 'event_espresso'),
594
+					'order'      => 5,
595
+					'url'        => '',
596
+					'persistent' => false
597
+				),
598
+				'help_tabs'     => array(
599
+					'preview_message' => array(
600
+						'title'    => __('About Previews', 'event_espresso'),
601
+						'callback' => 'preview_message_help_tab'
602
+					)
603
+				),
604
+				'require_nonce' => false
605
+			),
606
+			'settings'                 => array(
607
+				'nav'           => array(
608
+					'label' => __('Settings', 'event_espresso'),
609
+					'order' => 40
610
+				),
611
+				'metaboxes'     => array('_messages_settings_metaboxes'),
612
+				'help_tabs'     => array(
613
+					'messages_settings_help_tab'               => array(
614
+						'title'    => __('Messages Settings', 'event_espresso'),
615
+						'filename' => 'messages_settings'
616
+					),
617
+					'messages_settings_message_types_help_tab' => array(
618
+						'title'    => __('Activating / Deactivating Message Types', 'event_espresso'),
619
+						'filename' => 'messages_settings_message_types'
620
+					),
621
+					'messages_settings_messengers_help_tab'    => array(
622
+						'title'    => __('Activating / Deactivating Messengers', 'event_espresso'),
623
+						'filename' => 'messages_settings_messengers'
624
+					),
625
+				),
626
+				'help_tour'     => array('Messages_Settings_Help_Tour'),
627
+				'require_nonce' => false
628
+			)
629
+		);
630
+	}
631
+    
632
+    
633
+	protected function _add_screen_options()
634
+	{
635
+		//todo
636
+	}
637
+    
638
+    
639
+	protected function _add_screen_options_global_mtps()
640
+	{
641
+		/**
642
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
643
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
644
+		 */
645
+		$page_title              = $this->_admin_page_title;
646
+		$this->_admin_page_title = __('Global Message Templates', 'event_espresso');
647
+		$this->_per_page_screen_option();
648
+		$this->_admin_page_title = $page_title;
649
+	}
650
+    
651
+    
652
+	protected function _add_screen_options_default()
653
+	{
654
+		$this->_admin_page_title = __('Message Activity', 'event_espresso');
655
+		$this->_per_page_screen_option();
656
+	}
657
+    
658
+    
659
+	//none of the below group are currently used for Messages
660
+	protected function _add_feature_pointers()
661
+	{
662
+	}
663
+    
664
+	public function admin_init()
665
+	{
666
+	}
667
+    
668
+	public function admin_notices()
669
+	{
670
+	}
671
+    
672
+	public function admin_footer_scripts()
673
+	{
674
+	}
675
+    
676
+    
677
+	public function messages_help_tab()
678
+	{
679
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
680
+	}
681
+    
682
+    
683
+	public function messengers_help_tab()
684
+	{
685
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
686
+	}
687
+    
688
+    
689
+	public function message_types_help_tab()
690
+	{
691
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
692
+	}
693
+    
694
+    
695
+	public function messages_overview_help_tab()
696
+	{
697
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
698
+	}
699
+    
700
+    
701
+	public function message_templates_help_tab()
702
+	{
703
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
704
+	}
705
+    
706
+    
707
+	public function edit_message_template_help_tab()
708
+	{
709
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="' . esc_attr__('Editor Title',
710
+				'event_espresso') . '" />';
711
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="' . esc_attr__('Context Switcher and Preview',
712
+				'event_espresso') . '" />';
713
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="' . esc_attr__('Message Template Form Fields',
714
+				'event_espresso') . '" />';
715
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="' . esc_attr__('Shortcodes Metabox',
716
+				'event_espresso') . '" />';
717
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="' . esc_attr__('Publish Metabox',
718
+				'event_espresso') . '" />';
719
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
720
+			$args);
721
+	}
722
+    
723
+    
724
+	public function message_template_shortcodes_help_tab()
725
+	{
726
+		$this->_set_shortcodes();
727
+		$args['shortcodes'] = $this->_shortcodes;
728
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
729
+			$args);
730
+	}
731 731
     
732 732
     
733
-    public function preview_message_help_tab()
734
-    {
735
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
736
-    }
733
+	public function preview_message_help_tab()
734
+	{
735
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
736
+	}
737 737
     
738
-    
739
-    public function settings_help_tab()
740
-    {
741
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png' . '" alt="' . esc_attr__('Active Email Tab',
742
-                'event_espresso') . '" />';
743
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png' . '" alt="' . esc_attr__('Inactive Email Tab',
744
-                'event_espresso') . '" />';
745
-        $args['img3'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox" checked="checked"><label for="ee-on-off-toggle-on"></label>';
746
-        $args['img4'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox"><label for="ee-on-off-toggle-on"></label>';
747
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
748
-    }
738
+    
739
+	public function settings_help_tab()
740
+	{
741
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png' . '" alt="' . esc_attr__('Active Email Tab',
742
+				'event_espresso') . '" />';
743
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png' . '" alt="' . esc_attr__('Inactive Email Tab',
744
+				'event_espresso') . '" />';
745
+		$args['img3'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox" checked="checked"><label for="ee-on-off-toggle-on"></label>';
746
+		$args['img4'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox"><label for="ee-on-off-toggle-on"></label>';
747
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
748
+	}
749 749
     
750 750
     
751
-    public function load_scripts_styles()
752
-    {
753
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
754
-        wp_enqueue_style('espresso_ee_msg');
751
+	public function load_scripts_styles()
752
+	{
753
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
754
+		wp_enqueue_style('espresso_ee_msg');
755 755
         
756
-        wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
757
-            array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
758
-        wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
759
-            array('ee-dialog'), EVENT_ESPRESSO_VERSION);
760
-    }
756
+		wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
757
+			array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
758
+		wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
759
+			array('ee-dialog'), EVENT_ESPRESSO_VERSION);
760
+	}
761 761
     
762 762
     
763
-    public function load_scripts_styles_default()
764
-    {
765
-        wp_enqueue_script('ee-msg-list-table-js');
766
-    }
763
+	public function load_scripts_styles_default()
764
+	{
765
+		wp_enqueue_script('ee-msg-list-table-js');
766
+	}
767 767
     
768 768
     
769
-    public function wp_editor_css($mce_css)
770
-    {
771
-        //if we're on the edit_message_template route
772
-        if ($this->_req_action == 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
773
-            $message_type_name = $this->_active_message_type_name;
769
+	public function wp_editor_css($mce_css)
770
+	{
771
+		//if we're on the edit_message_template route
772
+		if ($this->_req_action == 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
773
+			$message_type_name = $this->_active_message_type_name;
774 774
             
775
-            //we're going to REPLACE the existing mce css
776
-            //we need to get the css file location from the active messenger
777
-            $mce_css = $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true,
778
-                'wpeditor', $this->_variation);
779
-        }
775
+			//we're going to REPLACE the existing mce css
776
+			//we need to get the css file location from the active messenger
777
+			$mce_css = $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true,
778
+				'wpeditor', $this->_variation);
779
+		}
780 780
         
781
-        return $mce_css;
782
-    }
783
-    
784
-    
785
-    public function load_scripts_styles_edit_message_template()
786
-    {
787
-        
788
-        $this->_set_shortcodes();
781
+		return $mce_css;
782
+	}
783
+    
784
+    
785
+	public function load_scripts_styles_edit_message_template()
786
+	{
787
+        
788
+		$this->_set_shortcodes();
789 789
         
790
-        EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
791
-            __('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.',
792
-                'event_espresso'),
793
-            $this->_message_template_group->messenger_obj()->label['singular'],
794
-            $this->_message_template_group->message_type_obj()->label['singular']
795
-        );
796
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = __('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?',
797
-            'event_espresso');
798
-        
799
-        wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL . 'ee_message_editor.js', array('jquery'),
800
-            EVENT_ESPRESSO_VERSION);
801
-        
802
-        wp_enqueue_script('ee_admin_js');
803
-        wp_enqueue_script('ee_msgs_edit_js');
804
-        
805
-        //add in special css for tiny_mce
806
-        add_filter('mce_css', array($this, 'wp_editor_css'));
807
-    }
808
-    
809
-    
810
-    public function load_scripts_styles_display_preview_message()
811
-    {
812
-        
813
-        $this->_set_message_template_group();
814
-        
815
-        if (isset($this->_req_data['messenger'])) {
816
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
817
-        }
818
-        
819
-        $message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
820
-        
821
-        
822
-        wp_enqueue_style('espresso_preview_css',
823
-            $this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true, 'preview',
824
-                $this->_variation));
825
-    }
826
-    
827
-    
828
-    public function load_scripts_styles_settings()
829
-    {
830
-        wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL . 'ee_message_settings.css', array(),
831
-            EVENT_ESPRESSO_VERSION);
832
-        wp_enqueue_style('ee-text-links');
833
-        wp_enqueue_style('ee-message-settings');
834
-        
835
-        wp_enqueue_script('ee-messages-settings');
836
-    }
837
-    
838
-    
839
-    /**
840
-     * set views array for List Table
841
-     */
842
-    public function _set_list_table_views_global_mtps()
843
-    {
844
-        $this->_views = array(
845
-            'in_use' => array(
846
-                'slug'        => 'in_use',
847
-                'label'       => __('In Use', 'event_espresso'),
848
-                'count'       => 0,
849
-                'bulk_action' => array(
850
-                    'trash_message_template' => __('Move to Trash', 'event_espresso')
851
-                )
852
-            )
853
-        );
854
-    }
855
-    
856
-    
857
-    /**
858
-     * set views array for message queue list table
859
-     */
860
-    public function _set_list_table_views_default()
861
-    {
862
-        EE_Registry::instance()->load_helper('Template');
863
-        
864
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can('ee_send_message',
865
-            'message_list_table_bulk_actions')
866
-            ? array(
867
-                'generate_now'          => __('Generate Now', 'event_espresso'),
868
-                'generate_and_send_now' => __('Generate and Send Now', 'event_espresso'),
869
-                'queue_for_resending'   => __('Queue for Resending', 'event_espresso'),
870
-                'send_now'              => __('Send Now', 'event_espresso')
871
-            )
872
-            : array();
873
-        
874
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can('ee_delete_messages',
875
-            'message_list_table_bulk_actions')
876
-            ? array('delete_ee_messages' => __('Delete Messages', 'event_espresso'))
877
-            : array();
878
-        
879
-        
880
-        $this->_views = array(
881
-            'all' => array(
882
-                'slug'        => 'all',
883
-                'label'       => __('All', 'event_espresso'),
884
-                'count'       => 0,
885
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action)
886
-            )
887
-        );
888
-        
889
-        
890
-        foreach (EEM_Message::instance()->all_statuses() as $status) {
891
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
892
-                continue;
893
-            }
894
-            $status_bulk_actions = $common_bulk_actions;
895
-            //unset bulk actions not applying to status
896
-            if (! empty($status_bulk_actions)) {
897
-                switch ($status) {
898
-                    case EEM_Message::status_idle:
899
-                    case EEM_Message::status_resend:
900
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
901
-                        break;
790
+		EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
791
+			__('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.',
792
+				'event_espresso'),
793
+			$this->_message_template_group->messenger_obj()->label['singular'],
794
+			$this->_message_template_group->message_type_obj()->label['singular']
795
+		);
796
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = __('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?',
797
+			'event_espresso');
798
+        
799
+		wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL . 'ee_message_editor.js', array('jquery'),
800
+			EVENT_ESPRESSO_VERSION);
801
+        
802
+		wp_enqueue_script('ee_admin_js');
803
+		wp_enqueue_script('ee_msgs_edit_js');
804
+        
805
+		//add in special css for tiny_mce
806
+		add_filter('mce_css', array($this, 'wp_editor_css'));
807
+	}
808
+    
809
+    
810
+	public function load_scripts_styles_display_preview_message()
811
+	{
812
+        
813
+		$this->_set_message_template_group();
814
+        
815
+		if (isset($this->_req_data['messenger'])) {
816
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
817
+		}
818
+        
819
+		$message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
820
+        
821
+        
822
+		wp_enqueue_style('espresso_preview_css',
823
+			$this->_active_messenger->get_variation($this->_template_pack, $message_type_name, true, 'preview',
824
+				$this->_variation));
825
+	}
826
+    
827
+    
828
+	public function load_scripts_styles_settings()
829
+	{
830
+		wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL . 'ee_message_settings.css', array(),
831
+			EVENT_ESPRESSO_VERSION);
832
+		wp_enqueue_style('ee-text-links');
833
+		wp_enqueue_style('ee-message-settings');
834
+        
835
+		wp_enqueue_script('ee-messages-settings');
836
+	}
837
+    
838
+    
839
+	/**
840
+	 * set views array for List Table
841
+	 */
842
+	public function _set_list_table_views_global_mtps()
843
+	{
844
+		$this->_views = array(
845
+			'in_use' => array(
846
+				'slug'        => 'in_use',
847
+				'label'       => __('In Use', 'event_espresso'),
848
+				'count'       => 0,
849
+				'bulk_action' => array(
850
+					'trash_message_template' => __('Move to Trash', 'event_espresso')
851
+				)
852
+			)
853
+		);
854
+	}
855
+    
856
+    
857
+	/**
858
+	 * set views array for message queue list table
859
+	 */
860
+	public function _set_list_table_views_default()
861
+	{
862
+		EE_Registry::instance()->load_helper('Template');
863
+        
864
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can('ee_send_message',
865
+			'message_list_table_bulk_actions')
866
+			? array(
867
+				'generate_now'          => __('Generate Now', 'event_espresso'),
868
+				'generate_and_send_now' => __('Generate and Send Now', 'event_espresso'),
869
+				'queue_for_resending'   => __('Queue for Resending', 'event_espresso'),
870
+				'send_now'              => __('Send Now', 'event_espresso')
871
+			)
872
+			: array();
873
+        
874
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can('ee_delete_messages',
875
+			'message_list_table_bulk_actions')
876
+			? array('delete_ee_messages' => __('Delete Messages', 'event_espresso'))
877
+			: array();
878
+        
879
+        
880
+		$this->_views = array(
881
+			'all' => array(
882
+				'slug'        => 'all',
883
+				'label'       => __('All', 'event_espresso'),
884
+				'count'       => 0,
885
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action)
886
+			)
887
+		);
888
+        
889
+        
890
+		foreach (EEM_Message::instance()->all_statuses() as $status) {
891
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
892
+				continue;
893
+			}
894
+			$status_bulk_actions = $common_bulk_actions;
895
+			//unset bulk actions not applying to status
896
+			if (! empty($status_bulk_actions)) {
897
+				switch ($status) {
898
+					case EEM_Message::status_idle:
899
+					case EEM_Message::status_resend:
900
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
901
+						break;
902 902
                     
903
-                    case EEM_Message::status_failed:
904
-                    case EEM_Message::status_debug_only:
905
-                    case EEM_Message::status_messenger_executing:
906
-                        $status_bulk_actions = array();
907
-                        break;
903
+					case EEM_Message::status_failed:
904
+					case EEM_Message::status_debug_only:
905
+					case EEM_Message::status_messenger_executing:
906
+						$status_bulk_actions = array();
907
+						break;
908 908
                     
909
-                    case EEM_Message::status_incomplete:
910
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
911
-                        break;
909
+					case EEM_Message::status_incomplete:
910
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
911
+						break;
912 912
                     
913
-                    case EEM_Message::status_retry:
914
-                    case EEM_Message::status_sent:
915
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
916
-                        break;
917
-                }
918
-            }
913
+					case EEM_Message::status_retry:
914
+					case EEM_Message::status_sent:
915
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
916
+						break;
917
+				}
918
+			}
919 919
 
920
-            //skip adding messenger executing status to views because it will be included with the Failed view.
921
-            if ( $status === EEM_Message::status_messenger_executing ) {
922
-                continue;
923
-            }
920
+			//skip adding messenger executing status to views because it will be included with the Failed view.
921
+			if ( $status === EEM_Message::status_messenger_executing ) {
922
+				continue;
923
+			}
924 924
             
925
-            $this->_views[strtolower($status)] = array(
926
-                'slug'        => strtolower($status),
927
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
928
-                'count'       => 0,
929
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action)
930
-            );
931
-        }
932
-    }
933
-    
934
-    
935
-    protected function _ee_default_messages_overview_list_table()
936
-    {
937
-        $this->_admin_page_title = __('Default Message Templates', 'event_espresso');
938
-        $this->display_admin_list_table_page_with_no_sidebar();
939
-    }
940
-    
941
-    
942
-    protected function _message_queue_list_table()
943
-    {
944
-        $this->_search_btn_label                   = __('Message Activity', 'event_espresso');
945
-        $this->_template_args['per_column']        = 6;
946
-        $this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
947
-        $this->_template_args['before_list_table'] = '<h3>' . EEM_Message::instance()->get_pretty_label_for_results() . '</h3>';
948
-        $this->display_admin_list_table_page_with_no_sidebar();
949
-    }
950
-    
951
-    
952
-    protected function _message_legend_items()
953
-    {
954
-        
955
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
956
-        $action_items       = array();
957
-        
958
-        foreach ($action_css_classes as $action_item => $action_details) {
959
-            if ($action_item === 'see_notifications_for') {
960
-                continue;
961
-            }
962
-            $action_items[$action_item] = array(
963
-                'class' => $action_details['css_class'],
964
-                'desc'  => $action_details['label']
965
-            );
966
-        }
967
-        
968
-        /** @type array $status_items status legend setup */
969
-        $status_items = array(
970
-            'sent_status'       => array(
971
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
972
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
973
-            ),
974
-            'idle_status'       => array(
975
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
976
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
977
-            ),
978
-            'failed_status'     => array(
979
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
980
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
981
-            ),
982
-            'messenger_executing_status' => array(
983
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
984
-                'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
985
-            ),
986
-            'resend_status'     => array(
987
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
988
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
989
-            ),
990
-            'incomplete_status' => array(
991
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
992
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
993
-            ),
994
-            'retry_status'      => array(
995
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
996
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
997
-            )
998
-        );
999
-        if (EEM_Message::debug()) {
1000
-            $status_items['debug_only_status'] = array(
1001
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1002
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1003
-            );
1004
-        }
1005
-        
1006
-        return array_merge($action_items, $status_items);
1007
-    }
1008
-    
1009
-    
1010
-    protected function _custom_mtps_preview()
1011
-    {
1012
-        $this->_admin_page_title              = __('Custom Message Templates (Preview)', 'event_espresso');
1013
-        $this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png" alt="' . esc_attr__('Preview Custom Message Templates screenshot',
1014
-                'event_espresso') . '" />';
1015
-        $this->_template_args['preview_text'] = '<strong>' . __('Custom Message Templates is a feature that is only available in the caffeinated version of Event Espresso.  With the Custom Message Templates feature, you are able to create custom templates and set them per event.',
1016
-                'event_espresso') . '</strong>';
1017
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1018
-    }
1019
-    
1020
-    
1021
-    /**
1022
-     * get_message_templates
1023
-     * This gets all the message templates for listing on the overview list.
1024
-     *
1025
-     * @access public
1026
-     *
1027
-     * @param int    $perpage the amount of templates groups to show per page
1028
-     * @param string $type    the current _view we're getting templates for
1029
-     * @param bool   $count   return count?
1030
-     * @param bool   $all     disregard any paging info (get all data);
1031
-     * @param bool   $global  whether to return just global (true) or custom templates (false)
1032
-     *
1033
-     * @return array
1034
-     */
1035
-    public function get_message_templates($perpage = 10, $type = 'in_use', $count = false, $all = false, $global = true)
1036
-    {
1037
-        
1038
-        $MTP = EEM_Message_Template_Group::instance();
1039
-        
1040
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1041
-        $orderby                    = $this->_req_data['orderby'];
1042
-        
1043
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'ASC';
1044
-        
1045
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
1046
-        $per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $perpage;
1047
-        
1048
-        $offset = ($current_page - 1) * $per_page;
1049
-        $limit  = $all ? null : array($offset, $per_page);
1050
-        
1051
-        
1052
-        //options will match what is in the _views array property
1053
-        switch ($type) {
925
+			$this->_views[strtolower($status)] = array(
926
+				'slug'        => strtolower($status),
927
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
928
+				'count'       => 0,
929
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action)
930
+			);
931
+		}
932
+	}
933
+    
934
+    
935
+	protected function _ee_default_messages_overview_list_table()
936
+	{
937
+		$this->_admin_page_title = __('Default Message Templates', 'event_espresso');
938
+		$this->display_admin_list_table_page_with_no_sidebar();
939
+	}
940
+    
941
+    
942
+	protected function _message_queue_list_table()
943
+	{
944
+		$this->_search_btn_label                   = __('Message Activity', 'event_espresso');
945
+		$this->_template_args['per_column']        = 6;
946
+		$this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
947
+		$this->_template_args['before_list_table'] = '<h3>' . EEM_Message::instance()->get_pretty_label_for_results() . '</h3>';
948
+		$this->display_admin_list_table_page_with_no_sidebar();
949
+	}
950
+    
951
+    
952
+	protected function _message_legend_items()
953
+	{
954
+        
955
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
956
+		$action_items       = array();
957
+        
958
+		foreach ($action_css_classes as $action_item => $action_details) {
959
+			if ($action_item === 'see_notifications_for') {
960
+				continue;
961
+			}
962
+			$action_items[$action_item] = array(
963
+				'class' => $action_details['css_class'],
964
+				'desc'  => $action_details['label']
965
+			);
966
+		}
967
+        
968
+		/** @type array $status_items status legend setup */
969
+		$status_items = array(
970
+			'sent_status'       => array(
971
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
972
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
973
+			),
974
+			'idle_status'       => array(
975
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
976
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
977
+			),
978
+			'failed_status'     => array(
979
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
980
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
981
+			),
982
+			'messenger_executing_status' => array(
983
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
984
+				'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
985
+			),
986
+			'resend_status'     => array(
987
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
988
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
989
+			),
990
+			'incomplete_status' => array(
991
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
992
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
993
+			),
994
+			'retry_status'      => array(
995
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
996
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
997
+			)
998
+		);
999
+		if (EEM_Message::debug()) {
1000
+			$status_items['debug_only_status'] = array(
1001
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1002
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1003
+			);
1004
+		}
1005
+        
1006
+		return array_merge($action_items, $status_items);
1007
+	}
1008
+    
1009
+    
1010
+	protected function _custom_mtps_preview()
1011
+	{
1012
+		$this->_admin_page_title              = __('Custom Message Templates (Preview)', 'event_espresso');
1013
+		$this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png" alt="' . esc_attr__('Preview Custom Message Templates screenshot',
1014
+				'event_espresso') . '" />';
1015
+		$this->_template_args['preview_text'] = '<strong>' . __('Custom Message Templates is a feature that is only available in the caffeinated version of Event Espresso.  With the Custom Message Templates feature, you are able to create custom templates and set them per event.',
1016
+				'event_espresso') . '</strong>';
1017
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1018
+	}
1019
+    
1020
+    
1021
+	/**
1022
+	 * get_message_templates
1023
+	 * This gets all the message templates for listing on the overview list.
1024
+	 *
1025
+	 * @access public
1026
+	 *
1027
+	 * @param int    $perpage the amount of templates groups to show per page
1028
+	 * @param string $type    the current _view we're getting templates for
1029
+	 * @param bool   $count   return count?
1030
+	 * @param bool   $all     disregard any paging info (get all data);
1031
+	 * @param bool   $global  whether to return just global (true) or custom templates (false)
1032
+	 *
1033
+	 * @return array
1034
+	 */
1035
+	public function get_message_templates($perpage = 10, $type = 'in_use', $count = false, $all = false, $global = true)
1036
+	{
1037
+        
1038
+		$MTP = EEM_Message_Template_Group::instance();
1039
+        
1040
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1041
+		$orderby                    = $this->_req_data['orderby'];
1042
+        
1043
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'ASC';
1044
+        
1045
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
1046
+		$per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $perpage;
1047
+        
1048
+		$offset = ($current_page - 1) * $per_page;
1049
+		$limit  = $all ? null : array($offset, $per_page);
1050
+        
1051
+        
1052
+		//options will match what is in the _views array property
1053
+		switch ($type) {
1054 1054
             
1055
-            case 'in_use':
1056
-                $templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1057
-                break;
1055
+			case 'in_use':
1056
+				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1057
+				break;
1058 1058
             
1059
-            default:
1060
-                $templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1059
+			default:
1060
+				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1061 1061
             
1062
-        }
1063
-        
1064
-        return $templates;
1065
-    }
1066
-    
1067
-    
1068
-    /**
1069
-     * filters etc might need a list of installed message_types
1070
-     * @return array an array of message type objects
1071
-     */
1072
-    public function get_installed_message_types()
1073
-    {
1074
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1075
-        $installed               = array();
1076
-        
1077
-        foreach ($installed_message_types as $message_type) {
1078
-            $installed[$message_type->name] = $message_type;
1079
-        }
1080
-        
1081
-        return $installed;
1082
-    }
1083
-    
1084
-    
1085
-    /**
1086
-     * _add_message_template
1087
-     *
1088
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1089
-     *
1090
-     * @param string $message_type
1091
-     * @param string $messenger
1092
-     * @param string $GRP_ID
1093
-     *
1094
-     * @throws EE_error
1095
-     */
1096
-    protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1097
-    {
1098
-        //set values override any request data
1099
-        $message_type = ! empty($message_type) ? $message_type : '';
1100
-        $message_type = empty($message_type) && ! empty($this->_req_data['message_type']) ? $this->_req_data['message_type'] : $message_type;
1101
-        
1102
-        $messenger = ! empty($messenger) ? $messenger : '';
1103
-        $messenger = empty($messenger) && ! empty($this->_req_data['messenger']) ? $this->_req_data['messenger'] : $messenger;
1104
-        
1105
-        $GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1106
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1107
-        
1108
-        //we need messenger and message type.  They should be coming from the event editor. If not here then return error
1109
-        if (empty($message_type) || empty($messenger)) {
1110
-            throw new EE_error(__('Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1111
-                'event_espresso'));
1112
-        }
1113
-        
1114
-        //we need the GRP_ID for the template being used as the base for the new template
1115
-        if (empty($GRP_ID)) {
1116
-            throw new EE_Error(__('In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1117
-                'event_espresso'));
1118
-        }
1119
-        
1120
-        //let's just make sure the template gets generated!
1121
-        
1122
-        //we need to reassign some variables for what the insert is expecting
1123
-        $this->_req_data['MTP_messenger']    = $messenger;
1124
-        $this->_req_data['MTP_message_type'] = $message_type;
1125
-        $this->_req_data['GRP_ID']           = $GRP_ID;
1126
-        $this->_insert_or_update_message_template(true);
1127
-    }
1128
-    
1129
-    
1130
-    /**
1131
-     * public wrapper for the _add_message_template method
1132
-     *
1133
-     * @param string $message_type     message type slug
1134
-     * @param string $messenger        messenger slug
1135
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1136
-     *                                 off of.
1137
-     */
1138
-    public function add_message_template($message_type, $messenger, $GRP_ID)
1139
-    {
1140
-        $this->_add_message_template($message_type, $messenger, $GRP_ID);
1141
-    }
1142
-    
1143
-    
1144
-    /**
1145
-     * _edit_message_template
1146
-     *
1147
-     * @access protected
1148
-     * @return void
1149
-     */
1150
-    protected function _edit_message_template()
1151
-    {
1152
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1153
-        $template_fields = '';
1154
-        $sidebar_fields  = '';
1155
-        //we filter the tinyMCE settings to remove the validation since message templates by their nature will not have valid html in the templates.
1156
-        add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1157
-        
1158
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1159
-            ? absint($this->_req_data['id'])
1160
-            : false;
1161
-        
1162
-        $this->_set_shortcodes(); //this also sets the _message_template property.
1163
-        $message_template_group = $this->_message_template_group;
1164
-        $c_label                = $message_template_group->context_label();
1165
-        $c_config               = $message_template_group->contexts_config();
1166
-        
1167
-        reset($c_config);
1168
-        $context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1169
-            ? strtolower($this->_req_data['context'])
1170
-            : key($c_config);
1171
-        
1172
-        
1173
-        if (empty($GRP_ID)) {
1174
-            $action = 'insert_message_template';
1175
-            //$button_both = false;
1176
-            //$button_text = array( __( 'Save','event_espresso') );
1177
-            //$button_actions = array('something_different');
1178
-            //$referrer = false;
1179
-            $edit_message_template_form_url = add_query_arg(
1180
-                array('action' => $action, 'noheader' => true),
1181
-                EE_MSG_ADMIN_URL
1182
-            );
1183
-        } else {
1184
-            $action = 'update_message_template';
1185
-            //$button_both = true;
1186
-            //$button_text = array();
1187
-            //$button_actions = array();
1188
-            //$referrer = $this->_admin_base_url;
1189
-            $edit_message_template_form_url = add_query_arg(
1190
-                array('action' => $action, 'noheader' => true),
1191
-                EE_MSG_ADMIN_URL
1192
-            );
1193
-        }
1194
-        
1195
-        //set active messenger for this view
1196
-        $this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1197
-            $message_template_group->messenger()
1198
-        );
1199
-        $this->_active_message_type_name = $message_template_group->message_type();
1200
-        
1201
-        
1202
-        //Do we have any validation errors?
1203
-        $validators = $this->_get_transient();
1204
-        $v_fields   = ! empty($validators) ? array_keys($validators) : array();
1205
-        
1206
-        
1207
-        //we need to assemble the title from Various details
1208
-        $context_label = sprintf(
1209
-            __('(%s %s)', 'event_espresso'),
1210
-            $c_config[$context]['label'],
1211
-            ucwords($c_label['label'])
1212
-        );
1213
-        
1214
-        $title = sprintf(
1215
-            __(' %s %s Template %s', 'event_espresso'),
1216
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1217
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1218
-            $context_label
1219
-        );
1220
-        
1221
-        $this->_template_args['GRP_ID']           = $GRP_ID;
1222
-        $this->_template_args['message_template'] = $message_template_group;
1223
-        $this->_template_args['is_extra_fields']  = false;
1224
-        
1225
-        
1226
-        //let's get EEH_MSG_Template so we can get template form fields
1227
-        $template_field_structure = EEH_MSG_Template::get_fields(
1228
-            $message_template_group->messenger(),
1229
-            $message_template_group->message_type()
1230
-        );
1231
-        
1232
-        if ( ! $template_field_structure) {
1233
-            $template_field_structure = false;
1234
-            $template_fields          = __('There was an error in assembling the fields for this display (you should see an error message)',
1235
-                'event_espresso');
1236
-        }
1237
-        
1238
-        
1239
-        $message_templates = $message_template_group->context_templates();
1240
-        
1241
-        
1242
-        //if we have the extra key.. then we need to remove the content index from the template_field_structure as it will get handled in the "extra" array.
1243
-        if (is_array($template_field_structure[$context]) && isset($template_field_structure[$context]['extra'])) {
1244
-            foreach ($template_field_structure[$context]['extra'] as $reference_field => $new_fields) {
1245
-                unset($template_field_structure[$context][$reference_field]);
1246
-            }
1247
-        }
1248
-        
1249
-        //let's loop through the template_field_structure and actually assemble the input fields!
1250
-        if ( ! empty($template_field_structure)) {
1251
-            foreach ($template_field_structure[$context] as $template_field => $field_setup_array) {
1252
-                //if this is an 'extra' template field then we need to remove any existing fields that are keyed up in the extra array and reset them.
1253
-                if ($template_field == 'extra') {
1254
-                    $this->_template_args['is_extra_fields'] = true;
1255
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1256
-                        $message_template = $message_templates[$context][$reference_field];
1257
-                        $content          = $message_template instanceof EE_Message_Template
1258
-                            ? $message_template->get('MTP_content')
1259
-                            : '';
1260
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1261
-                            //let's verify if we need this extra field via the shortcodes parameter.
1262
-                            $continue = false;
1263
-                            if (isset($extra_array['shortcodes_required'])) {
1264
-                                foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1265
-                                    if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1266
-                                        $continue = true;
1267
-                                    }
1268
-                                }
1269
-                                if ($continue) {
1270
-                                    continue;
1271
-                                }
1272
-                            }
1062
+		}
1063
+        
1064
+		return $templates;
1065
+	}
1066
+    
1067
+    
1068
+	/**
1069
+	 * filters etc might need a list of installed message_types
1070
+	 * @return array an array of message type objects
1071
+	 */
1072
+	public function get_installed_message_types()
1073
+	{
1074
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1075
+		$installed               = array();
1076
+        
1077
+		foreach ($installed_message_types as $message_type) {
1078
+			$installed[$message_type->name] = $message_type;
1079
+		}
1080
+        
1081
+		return $installed;
1082
+	}
1083
+    
1084
+    
1085
+	/**
1086
+	 * _add_message_template
1087
+	 *
1088
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1089
+	 *
1090
+	 * @param string $message_type
1091
+	 * @param string $messenger
1092
+	 * @param string $GRP_ID
1093
+	 *
1094
+	 * @throws EE_error
1095
+	 */
1096
+	protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1097
+	{
1098
+		//set values override any request data
1099
+		$message_type = ! empty($message_type) ? $message_type : '';
1100
+		$message_type = empty($message_type) && ! empty($this->_req_data['message_type']) ? $this->_req_data['message_type'] : $message_type;
1101
+        
1102
+		$messenger = ! empty($messenger) ? $messenger : '';
1103
+		$messenger = empty($messenger) && ! empty($this->_req_data['messenger']) ? $this->_req_data['messenger'] : $messenger;
1104
+        
1105
+		$GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1106
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1107
+        
1108
+		//we need messenger and message type.  They should be coming from the event editor. If not here then return error
1109
+		if (empty($message_type) || empty($messenger)) {
1110
+			throw new EE_error(__('Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1111
+				'event_espresso'));
1112
+		}
1113
+        
1114
+		//we need the GRP_ID for the template being used as the base for the new template
1115
+		if (empty($GRP_ID)) {
1116
+			throw new EE_Error(__('In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1117
+				'event_espresso'));
1118
+		}
1119
+        
1120
+		//let's just make sure the template gets generated!
1121
+        
1122
+		//we need to reassign some variables for what the insert is expecting
1123
+		$this->_req_data['MTP_messenger']    = $messenger;
1124
+		$this->_req_data['MTP_message_type'] = $message_type;
1125
+		$this->_req_data['GRP_ID']           = $GRP_ID;
1126
+		$this->_insert_or_update_message_template(true);
1127
+	}
1128
+    
1129
+    
1130
+	/**
1131
+	 * public wrapper for the _add_message_template method
1132
+	 *
1133
+	 * @param string $message_type     message type slug
1134
+	 * @param string $messenger        messenger slug
1135
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1136
+	 *                                 off of.
1137
+	 */
1138
+	public function add_message_template($message_type, $messenger, $GRP_ID)
1139
+	{
1140
+		$this->_add_message_template($message_type, $messenger, $GRP_ID);
1141
+	}
1142
+    
1143
+    
1144
+	/**
1145
+	 * _edit_message_template
1146
+	 *
1147
+	 * @access protected
1148
+	 * @return void
1149
+	 */
1150
+	protected function _edit_message_template()
1151
+	{
1152
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1153
+		$template_fields = '';
1154
+		$sidebar_fields  = '';
1155
+		//we filter the tinyMCE settings to remove the validation since message templates by their nature will not have valid html in the templates.
1156
+		add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1157
+        
1158
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1159
+			? absint($this->_req_data['id'])
1160
+			: false;
1161
+        
1162
+		$this->_set_shortcodes(); //this also sets the _message_template property.
1163
+		$message_template_group = $this->_message_template_group;
1164
+		$c_label                = $message_template_group->context_label();
1165
+		$c_config               = $message_template_group->contexts_config();
1166
+        
1167
+		reset($c_config);
1168
+		$context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1169
+			? strtolower($this->_req_data['context'])
1170
+			: key($c_config);
1171
+        
1172
+        
1173
+		if (empty($GRP_ID)) {
1174
+			$action = 'insert_message_template';
1175
+			//$button_both = false;
1176
+			//$button_text = array( __( 'Save','event_espresso') );
1177
+			//$button_actions = array('something_different');
1178
+			//$referrer = false;
1179
+			$edit_message_template_form_url = add_query_arg(
1180
+				array('action' => $action, 'noheader' => true),
1181
+				EE_MSG_ADMIN_URL
1182
+			);
1183
+		} else {
1184
+			$action = 'update_message_template';
1185
+			//$button_both = true;
1186
+			//$button_text = array();
1187
+			//$button_actions = array();
1188
+			//$referrer = $this->_admin_base_url;
1189
+			$edit_message_template_form_url = add_query_arg(
1190
+				array('action' => $action, 'noheader' => true),
1191
+				EE_MSG_ADMIN_URL
1192
+			);
1193
+		}
1194
+        
1195
+		//set active messenger for this view
1196
+		$this->_active_messenger         = $this->_message_resource_manager->get_active_messenger(
1197
+			$message_template_group->messenger()
1198
+		);
1199
+		$this->_active_message_type_name = $message_template_group->message_type();
1200
+        
1201
+        
1202
+		//Do we have any validation errors?
1203
+		$validators = $this->_get_transient();
1204
+		$v_fields   = ! empty($validators) ? array_keys($validators) : array();
1205
+        
1206
+        
1207
+		//we need to assemble the title from Various details
1208
+		$context_label = sprintf(
1209
+			__('(%s %s)', 'event_espresso'),
1210
+			$c_config[$context]['label'],
1211
+			ucwords($c_label['label'])
1212
+		);
1213
+        
1214
+		$title = sprintf(
1215
+			__(' %s %s Template %s', 'event_espresso'),
1216
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1217
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1218
+			$context_label
1219
+		);
1220
+        
1221
+		$this->_template_args['GRP_ID']           = $GRP_ID;
1222
+		$this->_template_args['message_template'] = $message_template_group;
1223
+		$this->_template_args['is_extra_fields']  = false;
1224
+        
1225
+        
1226
+		//let's get EEH_MSG_Template so we can get template form fields
1227
+		$template_field_structure = EEH_MSG_Template::get_fields(
1228
+			$message_template_group->messenger(),
1229
+			$message_template_group->message_type()
1230
+		);
1231
+        
1232
+		if ( ! $template_field_structure) {
1233
+			$template_field_structure = false;
1234
+			$template_fields          = __('There was an error in assembling the fields for this display (you should see an error message)',
1235
+				'event_espresso');
1236
+		}
1237
+        
1238
+        
1239
+		$message_templates = $message_template_group->context_templates();
1240
+        
1241
+        
1242
+		//if we have the extra key.. then we need to remove the content index from the template_field_structure as it will get handled in the "extra" array.
1243
+		if (is_array($template_field_structure[$context]) && isset($template_field_structure[$context]['extra'])) {
1244
+			foreach ($template_field_structure[$context]['extra'] as $reference_field => $new_fields) {
1245
+				unset($template_field_structure[$context][$reference_field]);
1246
+			}
1247
+		}
1248
+        
1249
+		//let's loop through the template_field_structure and actually assemble the input fields!
1250
+		if ( ! empty($template_field_structure)) {
1251
+			foreach ($template_field_structure[$context] as $template_field => $field_setup_array) {
1252
+				//if this is an 'extra' template field then we need to remove any existing fields that are keyed up in the extra array and reset them.
1253
+				if ($template_field == 'extra') {
1254
+					$this->_template_args['is_extra_fields'] = true;
1255
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1256
+						$message_template = $message_templates[$context][$reference_field];
1257
+						$content          = $message_template instanceof EE_Message_Template
1258
+							? $message_template->get('MTP_content')
1259
+							: '';
1260
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1261
+							//let's verify if we need this extra field via the shortcodes parameter.
1262
+							$continue = false;
1263
+							if (isset($extra_array['shortcodes_required'])) {
1264
+								foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1265
+									if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1266
+										$continue = true;
1267
+									}
1268
+								}
1269
+								if ($continue) {
1270
+									continue;
1271
+								}
1272
+							}
1273 1273
                             
1274
-                            $field_id                                = $reference_field . '-' . $extra_field . '-content';
1275
-                            $template_form_fields[$field_id]         = $extra_array;
1276
-                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields[' . $reference_field . '][content][' . $extra_field . ']';
1277
-                            $css_class                               = isset($extra_array['css_class']) ? $extra_array['css_class'] : '';
1274
+							$field_id                                = $reference_field . '-' . $extra_field . '-content';
1275
+							$template_form_fields[$field_id]         = $extra_array;
1276
+							$template_form_fields[$field_id]['name'] = 'MTP_template_fields[' . $reference_field . '][content][' . $extra_field . ']';
1277
+							$css_class                               = isset($extra_array['css_class']) ? $extra_array['css_class'] : '';
1278 1278
                             
1279
-                            $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1280
-                                                                            && in_array($extra_field, $v_fields)
1281
-                                                                            &&
1282
-                                                                            (
1283
-                                                                                is_array($validators[$extra_field])
1284
-                                                                                && isset($validators[$extra_field]['msg'])
1285
-                                                                            )
1286
-                                ? 'validate-error ' . $css_class
1287
-                                : $css_class;
1279
+							$template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1280
+																			&& in_array($extra_field, $v_fields)
1281
+																			&&
1282
+																			(
1283
+																				is_array($validators[$extra_field])
1284
+																				&& isset($validators[$extra_field]['msg'])
1285
+																			)
1286
+								? 'validate-error ' . $css_class
1287
+								: $css_class;
1288 1288
                             
1289
-                            $template_form_fields[$field_id]['value'] = ! empty($message_templates) && isset($content[$extra_field])
1290
-                                ? stripslashes(html_entity_decode($content[$extra_field], ENT_QUOTES, "UTF-8"))
1291
-                                : '';
1289
+							$template_form_fields[$field_id]['value'] = ! empty($message_templates) && isset($content[$extra_field])
1290
+								? stripslashes(html_entity_decode($content[$extra_field], ENT_QUOTES, "UTF-8"))
1291
+								: '';
1292 1292
                             
1293
-                            //do we have a validation error?  if we do then let's use that value instead
1294
-                            $template_form_fields[$field_id]['value'] = isset($validators[$extra_field]) ? $validators[$extra_field]['value'] : $template_form_fields[$field_id]['value'];
1293
+							//do we have a validation error?  if we do then let's use that value instead
1294
+							$template_form_fields[$field_id]['value'] = isset($validators[$extra_field]) ? $validators[$extra_field]['value'] : $template_form_fields[$field_id]['value'];
1295 1295
                             
1296 1296
                             
1297
-                            $template_form_fields[$field_id]['db-col'] = 'MTP_content';
1297
+							$template_form_fields[$field_id]['db-col'] = 'MTP_content';
1298 1298
                             
1299
-                            //shortcode selector
1300
-                            $field_name_to_use                                 = $extra_field == 'main' ? 'content' : $extra_field;
1301
-                            $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1302
-                                $field_name_to_use,
1303
-                                $field_id
1304
-                            );
1299
+							//shortcode selector
1300
+							$field_name_to_use                                 = $extra_field == 'main' ? 'content' : $extra_field;
1301
+							$template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1302
+								$field_name_to_use,
1303
+								$field_id
1304
+							);
1305 1305
                             
1306
-                            if (isset($extra_array['input']) && $extra_array['input'] == 'wp_editor') {
1307
-                                //we want to decode the entities
1308
-                                $template_form_fields[$field_id]['value'] = stripslashes(
1309
-                                    html_entity_decode($template_form_fields[$field_id]['value'], ENT_QUOTES, "UTF-8")
1310
-                                );
1306
+							if (isset($extra_array['input']) && $extra_array['input'] == 'wp_editor') {
1307
+								//we want to decode the entities
1308
+								$template_form_fields[$field_id]['value'] = stripslashes(
1309
+									html_entity_decode($template_form_fields[$field_id]['value'], ENT_QUOTES, "UTF-8")
1310
+								);
1311 1311
                                 
1312
-                            }/**/
1313
-                        }
1314
-                        $templatefield_MTP_id          = $reference_field . '-MTP_ID';
1315
-                        $templatefield_templatename_id = $reference_field . '-name';
1312
+							}/**/
1313
+						}
1314
+						$templatefield_MTP_id          = $reference_field . '-MTP_ID';
1315
+						$templatefield_templatename_id = $reference_field . '-name';
1316 1316
                         
1317
-                        $template_form_fields[$templatefield_MTP_id] = array(
1318
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1319
-                            'label'      => null,
1320
-                            'input'      => 'hidden',
1321
-                            'type'       => 'int',
1322
-                            'required'   => false,
1323
-                            'validation' => false,
1324
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1325
-                            'css_class'  => '',
1326
-                            'format'     => '%d',
1327
-                            'db-col'     => 'MTP_ID'
1328
-                        );
1317
+						$template_form_fields[$templatefield_MTP_id] = array(
1318
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1319
+							'label'      => null,
1320
+							'input'      => 'hidden',
1321
+							'type'       => 'int',
1322
+							'required'   => false,
1323
+							'validation' => false,
1324
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1325
+							'css_class'  => '',
1326
+							'format'     => '%d',
1327
+							'db-col'     => 'MTP_ID'
1328
+						);
1329 1329
                         
1330
-                        $template_form_fields[$templatefield_templatename_id] = array(
1331
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1332
-                            'label'      => null,
1333
-                            'input'      => 'hidden',
1334
-                            'type'       => 'string',
1335
-                            'required'   => false,
1336
-                            'validation' => true,
1337
-                            'value'      => $reference_field,
1338
-                            'css_class'  => '',
1339
-                            'format'     => '%s',
1340
-                            'db-col'     => 'MTP_template_field'
1341
-                        );
1342
-                    }
1343
-                    continue; //skip the next stuff, we got the necessary fields here for this dataset.
1344
-                } else {
1345
-                    $field_id                                 = $template_field . '-content';
1346
-                    $template_form_fields[$field_id]          = $field_setup_array;
1347
-                    $template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1348
-                    $message_template                         = isset($message_templates[$context][$template_field])
1349
-                        ? $message_templates[$context][$template_field]
1350
-                        : null;
1351
-                    $template_form_fields[$field_id]['value'] = ! empty($message_templates)
1352
-                                                                && is_array($message_templates[$context])
1353
-                                                                && $message_template instanceof EE_Message_Template
1354
-                        ? $message_template->get('MTP_content')
1355
-                        : '';
1330
+						$template_form_fields[$templatefield_templatename_id] = array(
1331
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1332
+							'label'      => null,
1333
+							'input'      => 'hidden',
1334
+							'type'       => 'string',
1335
+							'required'   => false,
1336
+							'validation' => true,
1337
+							'value'      => $reference_field,
1338
+							'css_class'  => '',
1339
+							'format'     => '%s',
1340
+							'db-col'     => 'MTP_template_field'
1341
+						);
1342
+					}
1343
+					continue; //skip the next stuff, we got the necessary fields here for this dataset.
1344
+				} else {
1345
+					$field_id                                 = $template_field . '-content';
1346
+					$template_form_fields[$field_id]          = $field_setup_array;
1347
+					$template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1348
+					$message_template                         = isset($message_templates[$context][$template_field])
1349
+						? $message_templates[$context][$template_field]
1350
+						: null;
1351
+					$template_form_fields[$field_id]['value'] = ! empty($message_templates)
1352
+																&& is_array($message_templates[$context])
1353
+																&& $message_template instanceof EE_Message_Template
1354
+						? $message_template->get('MTP_content')
1355
+						: '';
1356 1356
                     
1357
-                    //do we have a validator error for this field?  if we do then we'll use that value instead
1358
-                    $template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1359
-                        ? $validators[$template_field]['value']
1360
-                        : $template_form_fields[$field_id]['value'];
1357
+					//do we have a validator error for this field?  if we do then we'll use that value instead
1358
+					$template_form_fields[$field_id]['value'] = isset($validators[$template_field])
1359
+						? $validators[$template_field]['value']
1360
+						: $template_form_fields[$field_id]['value'];
1361 1361
                     
1362 1362
                     
1363
-                    $template_form_fields[$field_id]['db-col']    = 'MTP_content';
1364
-                    $css_class                                    = isset($field_setup_array['css_class']) ? $field_setup_array['css_class'] : '';
1365
-                    $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1366
-                                                                    && in_array($template_field, $v_fields)
1367
-                                                                    && isset($validators[$template_field]['msg'])
1368
-                        ? 'validate-error ' . $css_class
1369
-                        : $css_class;
1363
+					$template_form_fields[$field_id]['db-col']    = 'MTP_content';
1364
+					$css_class                                    = isset($field_setup_array['css_class']) ? $field_setup_array['css_class'] : '';
1365
+					$template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1366
+																	&& in_array($template_field, $v_fields)
1367
+																	&& isset($validators[$template_field]['msg'])
1368
+						? 'validate-error ' . $css_class
1369
+						: $css_class;
1370 1370
                     
1371
-                    //shortcode selector
1372
-                    $template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1373
-                        $template_field, $field_id
1374
-                    );
1375
-                }
1371
+					//shortcode selector
1372
+					$template_form_fields[$field_id]['append_content'] = $this->_get_shortcode_selector(
1373
+						$template_field, $field_id
1374
+					);
1375
+				}
1376 1376
                 
1377
-                //k took care of content field(s) now let's take care of others.
1377
+				//k took care of content field(s) now let's take care of others.
1378 1378
                 
1379
-                $templatefield_MTP_id                = $template_field . '-MTP_ID';
1380
-                $templatefield_field_templatename_id = $template_field . '-name';
1379
+				$templatefield_MTP_id                = $template_field . '-MTP_ID';
1380
+				$templatefield_field_templatename_id = $template_field . '-name';
1381 1381
                 
1382
-                //foreach template field there are actually two form fields created
1383
-                $template_form_fields[$templatefield_MTP_id] = array(
1384
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1385
-                    'label'      => null,
1386
-                    'input'      => 'hidden',
1387
-                    'type'       => 'int',
1388
-                    'required'   => false,
1389
-                    'validation' => true,
1390
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1391
-                    'css_class'  => '',
1392
-                    'format'     => '%d',
1393
-                    'db-col'     => 'MTP_ID'
1394
-                );
1382
+				//foreach template field there are actually two form fields created
1383
+				$template_form_fields[$templatefield_MTP_id] = array(
1384
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1385
+					'label'      => null,
1386
+					'input'      => 'hidden',
1387
+					'type'       => 'int',
1388
+					'required'   => false,
1389
+					'validation' => true,
1390
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1391
+					'css_class'  => '',
1392
+					'format'     => '%d',
1393
+					'db-col'     => 'MTP_ID'
1394
+				);
1395 1395
                 
1396
-                $template_form_fields[$templatefield_field_templatename_id] = array(
1397
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1398
-                    'label'      => null,
1399
-                    'input'      => 'hidden',
1400
-                    'type'       => 'string',
1401
-                    'required'   => false,
1402
-                    'validation' => true,
1403
-                    'value'      => $template_field,
1404
-                    'css_class'  => '',
1405
-                    'format'     => '%s',
1406
-                    'db-col'     => 'MTP_template_field'
1407
-                );
1396
+				$template_form_fields[$templatefield_field_templatename_id] = array(
1397
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1398
+					'label'      => null,
1399
+					'input'      => 'hidden',
1400
+					'type'       => 'string',
1401
+					'required'   => false,
1402
+					'validation' => true,
1403
+					'value'      => $template_field,
1404
+					'css_class'  => '',
1405
+					'format'     => '%s',
1406
+					'db-col'     => 'MTP_template_field'
1407
+				);
1408 1408
                 
1409
-            }
1409
+			}
1410 1410
             
1411
-            //add other fields
1412
-            $template_form_fields['ee-msg-current-context'] = array(
1413
-                'name'       => 'MTP_context',
1414
-                'label'      => null,
1415
-                'input'      => 'hidden',
1416
-                'type'       => 'string',
1417
-                'required'   => false,
1418
-                'validation' => true,
1419
-                'value'      => $context,
1420
-                'css_class'  => '',
1421
-                'format'     => '%s',
1422
-                'db-col'     => 'MTP_context'
1423
-            );
1411
+			//add other fields
1412
+			$template_form_fields['ee-msg-current-context'] = array(
1413
+				'name'       => 'MTP_context',
1414
+				'label'      => null,
1415
+				'input'      => 'hidden',
1416
+				'type'       => 'string',
1417
+				'required'   => false,
1418
+				'validation' => true,
1419
+				'value'      => $context,
1420
+				'css_class'  => '',
1421
+				'format'     => '%s',
1422
+				'db-col'     => 'MTP_context'
1423
+			);
1424 1424
             
1425
-            $template_form_fields['ee-msg-grp-id'] = array(
1426
-                'name'       => 'GRP_ID',
1427
-                'label'      => null,
1428
-                'input'      => 'hidden',
1429
-                'type'       => 'int',
1430
-                'required'   => false,
1431
-                'validation' => true,
1432
-                'value'      => $GRP_ID,
1433
-                'css_class'  => '',
1434
-                'format'     => '%d',
1435
-                'db-col'     => 'GRP_ID'
1436
-            );
1425
+			$template_form_fields['ee-msg-grp-id'] = array(
1426
+				'name'       => 'GRP_ID',
1427
+				'label'      => null,
1428
+				'input'      => 'hidden',
1429
+				'type'       => 'int',
1430
+				'required'   => false,
1431
+				'validation' => true,
1432
+				'value'      => $GRP_ID,
1433
+				'css_class'  => '',
1434
+				'format'     => '%d',
1435
+				'db-col'     => 'GRP_ID'
1436
+			);
1437 1437
             
1438
-            $template_form_fields['ee-msg-messenger'] = array(
1439
-                'name'       => 'MTP_messenger',
1440
-                'label'      => null,
1441
-                'input'      => 'hidden',
1442
-                'type'       => 'string',
1443
-                'required'   => false,
1444
-                'validation' => true,
1445
-                'value'      => $message_template_group->messenger(),
1446
-                'css_class'  => '',
1447
-                'format'     => '%s',
1448
-                'db-col'     => 'MTP_messenger'
1449
-            );
1438
+			$template_form_fields['ee-msg-messenger'] = array(
1439
+				'name'       => 'MTP_messenger',
1440
+				'label'      => null,
1441
+				'input'      => 'hidden',
1442
+				'type'       => 'string',
1443
+				'required'   => false,
1444
+				'validation' => true,
1445
+				'value'      => $message_template_group->messenger(),
1446
+				'css_class'  => '',
1447
+				'format'     => '%s',
1448
+				'db-col'     => 'MTP_messenger'
1449
+			);
1450 1450
             
1451
-            $template_form_fields['ee-msg-message-type'] = array(
1452
-                'name'       => 'MTP_message_type',
1453
-                'label'      => null,
1454
-                'input'      => 'hidden',
1455
-                'type'       => 'string',
1456
-                'required'   => false,
1457
-                'validation' => true,
1458
-                'value'      => $message_template_group->message_type(),
1459
-                'css_class'  => '',
1460
-                'format'     => '%s',
1461
-                'db-col'     => 'MTP_message_type'
1462
-            );
1451
+			$template_form_fields['ee-msg-message-type'] = array(
1452
+				'name'       => 'MTP_message_type',
1453
+				'label'      => null,
1454
+				'input'      => 'hidden',
1455
+				'type'       => 'string',
1456
+				'required'   => false,
1457
+				'validation' => true,
1458
+				'value'      => $message_template_group->message_type(),
1459
+				'css_class'  => '',
1460
+				'format'     => '%s',
1461
+				'db-col'     => 'MTP_message_type'
1462
+			);
1463 1463
             
1464
-            $sidebar_form_fields['ee-msg-is-global'] = array(
1465
-                'name'       => 'MTP_is_global',
1466
-                'label'      => __('Global Template', 'event_espresso'),
1467
-                'input'      => 'hidden',
1468
-                'type'       => 'int',
1469
-                'required'   => false,
1470
-                'validation' => true,
1471
-                'value'      => $message_template_group->get('MTP_is_global'),
1472
-                'css_class'  => '',
1473
-                'format'     => '%d',
1474
-                'db-col'     => 'MTP_is_global'
1475
-            );
1464
+			$sidebar_form_fields['ee-msg-is-global'] = array(
1465
+				'name'       => 'MTP_is_global',
1466
+				'label'      => __('Global Template', 'event_espresso'),
1467
+				'input'      => 'hidden',
1468
+				'type'       => 'int',
1469
+				'required'   => false,
1470
+				'validation' => true,
1471
+				'value'      => $message_template_group->get('MTP_is_global'),
1472
+				'css_class'  => '',
1473
+				'format'     => '%d',
1474
+				'db-col'     => 'MTP_is_global'
1475
+			);
1476 1476
             
1477
-            $sidebar_form_fields['ee-msg-is-override'] = array(
1478
-                'name'       => 'MTP_is_override',
1479
-                'label'      => __('Override all custom', 'event_espresso'),
1480
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1481
-                'type'       => 'int',
1482
-                'required'   => false,
1483
-                'validation' => true,
1484
-                'value'      => $message_template_group->get('MTP_is_override'),
1485
-                'css_class'  => '',
1486
-                'format'     => '%d',
1487
-                'db-col'     => 'MTP_is_override'
1488
-            );
1477
+			$sidebar_form_fields['ee-msg-is-override'] = array(
1478
+				'name'       => 'MTP_is_override',
1479
+				'label'      => __('Override all custom', 'event_espresso'),
1480
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1481
+				'type'       => 'int',
1482
+				'required'   => false,
1483
+				'validation' => true,
1484
+				'value'      => $message_template_group->get('MTP_is_override'),
1485
+				'css_class'  => '',
1486
+				'format'     => '%d',
1487
+				'db-col'     => 'MTP_is_override'
1488
+			);
1489 1489
             
1490
-            $sidebar_form_fields['ee-msg-is-active'] = array(
1491
-                'name'       => 'MTP_is_active',
1492
-                'label'      => __('Active Template', 'event_espresso'),
1493
-                'input'      => 'hidden',
1494
-                'type'       => 'int',
1495
-                'required'   => false,
1496
-                'validation' => true,
1497
-                'value'      => $message_template_group->is_active(),
1498
-                'css_class'  => '',
1499
-                'format'     => '%d',
1500
-                'db-col'     => 'MTP_is_active'
1501
-            );
1490
+			$sidebar_form_fields['ee-msg-is-active'] = array(
1491
+				'name'       => 'MTP_is_active',
1492
+				'label'      => __('Active Template', 'event_espresso'),
1493
+				'input'      => 'hidden',
1494
+				'type'       => 'int',
1495
+				'required'   => false,
1496
+				'validation' => true,
1497
+				'value'      => $message_template_group->is_active(),
1498
+				'css_class'  => '',
1499
+				'format'     => '%d',
1500
+				'db-col'     => 'MTP_is_active'
1501
+			);
1502 1502
             
1503
-            $sidebar_form_fields['ee-msg-deleted'] = array(
1504
-                'name'       => 'MTP_deleted',
1505
-                'label'      => null,
1506
-                'input'      => 'hidden',
1507
-                'type'       => 'int',
1508
-                'required'   => false,
1509
-                'validation' => true,
1510
-                'value'      => $message_template_group->get('MTP_deleted'),
1511
-                'css_class'  => '',
1512
-                'format'     => '%d',
1513
-                'db-col'     => 'MTP_deleted'
1514
-            );
1515
-            $sidebar_form_fields['ee-msg-author']  = array(
1516
-                'name'       => 'MTP_user_id',
1517
-                'label'      => __('Author', 'event_espresso'),
1518
-                'input'      => 'hidden',
1519
-                'type'       => 'int',
1520
-                'required'   => false,
1521
-                'validation' => false,
1522
-                'value'      => $message_template_group->user(),
1523
-                'format'     => '%d',
1524
-                'db-col'     => 'MTP_user_id'
1525
-            );
1503
+			$sidebar_form_fields['ee-msg-deleted'] = array(
1504
+				'name'       => 'MTP_deleted',
1505
+				'label'      => null,
1506
+				'input'      => 'hidden',
1507
+				'type'       => 'int',
1508
+				'required'   => false,
1509
+				'validation' => true,
1510
+				'value'      => $message_template_group->get('MTP_deleted'),
1511
+				'css_class'  => '',
1512
+				'format'     => '%d',
1513
+				'db-col'     => 'MTP_deleted'
1514
+			);
1515
+			$sidebar_form_fields['ee-msg-author']  = array(
1516
+				'name'       => 'MTP_user_id',
1517
+				'label'      => __('Author', 'event_espresso'),
1518
+				'input'      => 'hidden',
1519
+				'type'       => 'int',
1520
+				'required'   => false,
1521
+				'validation' => false,
1522
+				'value'      => $message_template_group->user(),
1523
+				'format'     => '%d',
1524
+				'db-col'     => 'MTP_user_id'
1525
+			);
1526 1526
             
1527
-            $sidebar_form_fields['ee-msg-route'] = array(
1528
-                'name'  => 'action',
1529
-                'input' => 'hidden',
1530
-                'type'  => 'string',
1531
-                'value' => $action
1532
-            );
1527
+			$sidebar_form_fields['ee-msg-route'] = array(
1528
+				'name'  => 'action',
1529
+				'input' => 'hidden',
1530
+				'type'  => 'string',
1531
+				'value' => $action
1532
+			);
1533 1533
             
1534
-            $sidebar_form_fields['ee-msg-id']        = array(
1535
-                'name'  => 'id',
1536
-                'input' => 'hidden',
1537
-                'type'  => 'int',
1538
-                'value' => $GRP_ID
1539
-            );
1540
-            $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1541
-                'name'  => $action . '_nonce',
1542
-                'input' => 'hidden',
1543
-                'type'  => 'string',
1544
-                'value' => wp_create_nonce($action . '_nonce')
1545
-            );
1534
+			$sidebar_form_fields['ee-msg-id']        = array(
1535
+				'name'  => 'id',
1536
+				'input' => 'hidden',
1537
+				'type'  => 'int',
1538
+				'value' => $GRP_ID
1539
+			);
1540
+			$sidebar_form_fields['ee-msg-evt-nonce'] = array(
1541
+				'name'  => $action . '_nonce',
1542
+				'input' => 'hidden',
1543
+				'type'  => 'string',
1544
+				'value' => wp_create_nonce($action . '_nonce')
1545
+			);
1546 1546
             
1547
-            if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1548
-                $sidebar_form_fields['ee-msg-template-switch'] = array(
1549
-                    'name'  => 'template_switch',
1550
-                    'input' => 'hidden',
1551
-                    'type'  => 'int',
1552
-                    'value' => 1
1553
-                );
1554
-            }
1547
+			if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1548
+				$sidebar_form_fields['ee-msg-template-switch'] = array(
1549
+					'name'  => 'template_switch',
1550
+					'input' => 'hidden',
1551
+					'type'  => 'int',
1552
+					'value' => 1
1553
+				);
1554
+			}
1555 1555
             
1556 1556
             
1557
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1558
-            $sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1557
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1558
+			$sidebar_fields  = $this->_generate_admin_form_fields($sidebar_form_fields);
1559 1559
             
1560 1560
             
1561
-        } //end if ( !empty($template_field_structure) )
1561
+		} //end if ( !empty($template_field_structure) )
1562 1562
         
1563
-        //set extra content for publish box
1564
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1565
-        $this->_set_publish_post_box_vars(
1566
-            'id',
1567
-            $GRP_ID,
1568
-            false,
1569
-            add_query_arg(
1570
-                array('action' => 'global_mtps'),
1571
-                $this->_admin_base_url
1572
-            )
1573
-        );
1574
-        
1575
-        //add preview button
1576
-        $preview_url    = parent::add_query_args_and_nonce(
1577
-            array(
1578
-                'message_type' => $message_template_group->message_type(),
1579
-                'messenger'    => $message_template_group->messenger(),
1580
-                'context'      => $context,
1581
-                'GRP_ID'       => $GRP_ID,
1582
-                'action'       => 'preview_message'
1583
-            ),
1584
-            $this->_admin_base_url
1585
-        );
1586
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">' . __('Preview',
1587
-                'event_espresso') . '</a>';
1588
-        
1589
-        
1590
-        //setup context switcher
1591
-        $context_switcher_args = array(
1592
-            'page'    => 'espresso_messages',
1593
-            'action'  => 'edit_message_template',
1594
-            'id'      => $GRP_ID,
1595
-            'context' => $context,
1596
-            'extra'   => $preview_button
1597
-        );
1598
-        $this->_set_context_switcher($message_template_group, $context_switcher_args);
1599
-        
1600
-        
1601
-        //main box
1602
-        $this->_template_args['template_fields']                         = $template_fields;
1603
-        $this->_template_args['sidebar_box_id']                          = 'details';
1604
-        $this->_template_args['action']                                  = $action;
1605
-        $this->_template_args['context']                                 = $context;
1606
-        $this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1607
-        $this->_template_args['learn_more_about_message_templates_link'] = $this->_learn_more_about_message_templates_link();
1608
-        
1609
-        
1610
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1611
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1612
-        $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1613
-        
1614
-        $this->_template_path = $this->_template_args['GRP_ID']
1615
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1616
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1617
-        
1618
-        //send along EE_Message_Template_Group object for further template use.
1619
-        $this->_template_args['MTP'] = $message_template_group;
1620
-        
1621
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
1622
-            $this->_template_args, true);
1623
-        
1624
-        
1625
-        //finally, let's set the admin_page title
1626
-        $this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1627
-        
1628
-        
1629
-        //we need to take care of setting the shortcodes property for use elsewhere.
1630
-        $this->_set_shortcodes();
1631
-        
1632
-        
1633
-        //final template wrapper
1634
-        $this->display_admin_page_with_sidebar();
1635
-    }
1636
-    
1637
-    
1638
-    public function filter_tinymce_init($mceInit, $editor_id)
1639
-    {
1640
-        return $mceInit;
1641
-    }
1642
-    
1643
-    
1644
-    public function add_context_switcher()
1645
-    {
1646
-        return $this->_context_switcher;
1647
-    }
1648
-    
1649
-    public function _add_form_element_before()
1650
-    {
1651
-        return '<form method="post" action="' . $this->_template_args["edit_message_template_form_url"] . '" id="ee-msg-edit-frm">';
1652
-    }
1653
-    
1654
-    public function _add_form_element_after()
1655
-    {
1656
-        return '</form>';
1657
-    }
1658
-    
1659
-    
1660
-    /**
1661
-     * This executes switching the template pack for a message template.
1662
-     *
1663
-     * @since 4.5.0
1664
-     *
1665
-     */
1666
-    public function switch_template_pack()
1667
-    {
1668
-        $GRP_ID        = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1669
-        $template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1670
-        
1671
-        //verify we have needed values.
1672
-        if (empty($GRP_ID) || empty($template_pack)) {
1673
-            $this->_template_args['error'] = true;
1674
-            EE_Error::add_error(__('The required date for switching templates is not available.', 'event_espresso'),
1675
-                __FILE__, __FUNCTION__, __LINE__);
1676
-        } else {
1677
-            //get template, set the new template_pack and then reset to default
1678
-            /** @type EE_Message_Template_Group $message_template_group */
1679
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1563
+		//set extra content for publish box
1564
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1565
+		$this->_set_publish_post_box_vars(
1566
+			'id',
1567
+			$GRP_ID,
1568
+			false,
1569
+			add_query_arg(
1570
+				array('action' => 'global_mtps'),
1571
+				$this->_admin_base_url
1572
+			)
1573
+		);
1574
+        
1575
+		//add preview button
1576
+		$preview_url    = parent::add_query_args_and_nonce(
1577
+			array(
1578
+				'message_type' => $message_template_group->message_type(),
1579
+				'messenger'    => $message_template_group->messenger(),
1580
+				'context'      => $context,
1581
+				'GRP_ID'       => $GRP_ID,
1582
+				'action'       => 'preview_message'
1583
+			),
1584
+			$this->_admin_base_url
1585
+		);
1586
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">' . __('Preview',
1587
+				'event_espresso') . '</a>';
1588
+        
1589
+        
1590
+		//setup context switcher
1591
+		$context_switcher_args = array(
1592
+			'page'    => 'espresso_messages',
1593
+			'action'  => 'edit_message_template',
1594
+			'id'      => $GRP_ID,
1595
+			'context' => $context,
1596
+			'extra'   => $preview_button
1597
+		);
1598
+		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1599
+        
1600
+        
1601
+		//main box
1602
+		$this->_template_args['template_fields']                         = $template_fields;
1603
+		$this->_template_args['sidebar_box_id']                          = 'details';
1604
+		$this->_template_args['action']                                  = $action;
1605
+		$this->_template_args['context']                                 = $context;
1606
+		$this->_template_args['edit_message_template_form_url']          = $edit_message_template_form_url;
1607
+		$this->_template_args['learn_more_about_message_templates_link'] = $this->_learn_more_about_message_templates_link();
1608
+        
1609
+        
1610
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1611
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1612
+		$this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1613
+        
1614
+		$this->_template_path = $this->_template_args['GRP_ID']
1615
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1616
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1617
+        
1618
+		//send along EE_Message_Template_Group object for further template use.
1619
+		$this->_template_args['MTP'] = $message_template_group;
1620
+        
1621
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
1622
+			$this->_template_args, true);
1623
+        
1624
+        
1625
+		//finally, let's set the admin_page title
1626
+		$this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1627
+        
1628
+        
1629
+		//we need to take care of setting the shortcodes property for use elsewhere.
1630
+		$this->_set_shortcodes();
1631
+        
1632
+        
1633
+		//final template wrapper
1634
+		$this->display_admin_page_with_sidebar();
1635
+	}
1636
+    
1637
+    
1638
+	public function filter_tinymce_init($mceInit, $editor_id)
1639
+	{
1640
+		return $mceInit;
1641
+	}
1642
+    
1643
+    
1644
+	public function add_context_switcher()
1645
+	{
1646
+		return $this->_context_switcher;
1647
+	}
1648
+    
1649
+	public function _add_form_element_before()
1650
+	{
1651
+		return '<form method="post" action="' . $this->_template_args["edit_message_template_form_url"] . '" id="ee-msg-edit-frm">';
1652
+	}
1653
+    
1654
+	public function _add_form_element_after()
1655
+	{
1656
+		return '</form>';
1657
+	}
1658
+    
1659
+    
1660
+	/**
1661
+	 * This executes switching the template pack for a message template.
1662
+	 *
1663
+	 * @since 4.5.0
1664
+	 *
1665
+	 */
1666
+	public function switch_template_pack()
1667
+	{
1668
+		$GRP_ID        = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1669
+		$template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1670
+        
1671
+		//verify we have needed values.
1672
+		if (empty($GRP_ID) || empty($template_pack)) {
1673
+			$this->_template_args['error'] = true;
1674
+			EE_Error::add_error(__('The required date for switching templates is not available.', 'event_espresso'),
1675
+				__FILE__, __FUNCTION__, __LINE__);
1676
+		} else {
1677
+			//get template, set the new template_pack and then reset to default
1678
+			/** @type EE_Message_Template_Group $message_template_group */
1679
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1680 1680
             
1681
-            $message_template_group->set_template_pack_name($template_pack);
1682
-            $this->_req_data['msgr'] = $message_template_group->messenger();
1683
-            $this->_req_data['mt']   = $message_template_group->message_type();
1681
+			$message_template_group->set_template_pack_name($template_pack);
1682
+			$this->_req_data['msgr'] = $message_template_group->messenger();
1683
+			$this->_req_data['mt']   = $message_template_group->message_type();
1684 1684
             
1685
-            $query_args = $this->_reset_to_default_template();
1685
+			$query_args = $this->_reset_to_default_template();
1686 1686
             
1687
-            if (empty($query_args['id'])) {
1688
-                EE_Error::add_error(
1689
-                    __(
1690
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
1691
-                        'event_espresso'
1692
-                    ),
1693
-                    __FILE__, __FUNCTION__, __LINE__
1694
-                );
1695
-                $this->_template_args['error'] = true;
1696
-            } else {
1697
-                $template_label       = $message_template_group->get_template_pack()->label;
1698
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1699
-                EE_Error::add_success(
1700
-                    sprintf(
1701
-                        __(
1702
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1703
-                            'event_espresso'
1704
-                        ),
1705
-                        $template_label,
1706
-                        $template_pack_labels->template_pack
1707
-                    )
1708
-                );
1709
-                //generate the redirect url for js.
1710
-                $url                                          = self::add_query_args_and_nonce($query_args,
1711
-                    $this->_admin_base_url);
1712
-                $this->_template_args['data']['redirect_url'] = $url;
1713
-                $this->_template_args['success']              = true;
1714
-            }
1687
+			if (empty($query_args['id'])) {
1688
+				EE_Error::add_error(
1689
+					__(
1690
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
1691
+						'event_espresso'
1692
+					),
1693
+					__FILE__, __FUNCTION__, __LINE__
1694
+				);
1695
+				$this->_template_args['error'] = true;
1696
+			} else {
1697
+				$template_label       = $message_template_group->get_template_pack()->label;
1698
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1699
+				EE_Error::add_success(
1700
+					sprintf(
1701
+						__(
1702
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
1703
+							'event_espresso'
1704
+						),
1705
+						$template_label,
1706
+						$template_pack_labels->template_pack
1707
+					)
1708
+				);
1709
+				//generate the redirect url for js.
1710
+				$url                                          = self::add_query_args_and_nonce($query_args,
1711
+					$this->_admin_base_url);
1712
+				$this->_template_args['data']['redirect_url'] = $url;
1713
+				$this->_template_args['success']              = true;
1714
+			}
1715 1715
             
1716
-            $this->_return_json();
1716
+			$this->_return_json();
1717 1717
             
1718
-        }
1719
-    }
1720
-    
1721
-    
1722
-    /**
1723
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
1724
-     * they want.
1725
-     *
1726
-     * @access protected
1727
-     * @return array|null
1728
-     */
1729
-    protected function _reset_to_default_template()
1730
-    {
1731
-        
1732
-        $templates = array();
1733
-        $GRP_ID    = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1734
-        //we need to make sure we've got the info we need.
1735
-        if ( ! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
1736
-            EE_Error::add_error(
1737
-                __(
1738
-                    '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.',
1739
-                    'event_espresso'
1740
-                ),
1741
-                __FILE__, __FUNCTION__, __LINE__
1742
-            );
1743
-        }
1744
-        
1745
-        // all templates will be reset to whatever the defaults are
1746
-        // for the global template matching the messenger and message type.
1747
-        $success = ! empty($GRP_ID) ? true : false;
1748
-        
1749
-        if ($success) {
1718
+		}
1719
+	}
1720
+    
1721
+    
1722
+	/**
1723
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
1724
+	 * they want.
1725
+	 *
1726
+	 * @access protected
1727
+	 * @return array|null
1728
+	 */
1729
+	protected function _reset_to_default_template()
1730
+	{
1731
+        
1732
+		$templates = array();
1733
+		$GRP_ID    = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1734
+		//we need to make sure we've got the info we need.
1735
+		if ( ! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
1736
+			EE_Error::add_error(
1737
+				__(
1738
+					'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.',
1739
+					'event_espresso'
1740
+				),
1741
+				__FILE__, __FUNCTION__, __LINE__
1742
+			);
1743
+		}
1744
+        
1745
+		// all templates will be reset to whatever the defaults are
1746
+		// for the global template matching the messenger and message type.
1747
+		$success = ! empty($GRP_ID) ? true : false;
1748
+        
1749
+		if ($success) {
1750 1750
             
1751
-            //let's first determine if the incoming template is a global template,
1752
-            // if it isn't then we need to get the global template matching messenger and message type.
1753
-            //$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
1751
+			//let's first determine if the incoming template is a global template,
1752
+			// if it isn't then we need to get the global template matching messenger and message type.
1753
+			//$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
1754 1754
             
1755 1755
             
1756
-            //note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
1757
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
1756
+			//note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
1757
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
1758 1758
             
1759
-            if ($success) {
1760
-                // if successfully deleted, lets generate the new ones.
1761
-                // Note. We set GLOBAL to true, because resets on ANY template
1762
-                // will use the related global template defaults for regeneration.
1763
-                // This means that if a custom template is reset it resets to whatever the related global template is.
1764
-                // HOWEVER, we DO keep the template pack and template variation set
1765
-                // for the current custom template when resetting.
1766
-                $templates = $this->_generate_new_templates(
1767
-                    $this->_req_data['msgr'],
1768
-                    $this->_req_data['mt'],
1769
-                    $GRP_ID,
1770
-                    true
1771
-                );
1772
-            }
1759
+			if ($success) {
1760
+				// if successfully deleted, lets generate the new ones.
1761
+				// Note. We set GLOBAL to true, because resets on ANY template
1762
+				// will use the related global template defaults for regeneration.
1763
+				// This means that if a custom template is reset it resets to whatever the related global template is.
1764
+				// HOWEVER, we DO keep the template pack and template variation set
1765
+				// for the current custom template when resetting.
1766
+				$templates = $this->_generate_new_templates(
1767
+					$this->_req_data['msgr'],
1768
+					$this->_req_data['mt'],
1769
+					$GRP_ID,
1770
+					true
1771
+				);
1772
+			}
1773 1773
             
1774
-        }
1775
-        
1776
-        //any error messages?
1777
-        if ( ! $success) {
1778
-            EE_Error::add_error(
1779
-                __('Something went wrong with deleting existing templates. Unable to reset to default',
1780
-                    'event_espresso'),
1781
-                __FILE__, __FUNCTION__, __LINE__
1782
-            );
1783
-        }
1784
-        
1785
-        //all good, let's add a success message!
1786
-        if ($success && ! empty($templates)) {
1787
-            $templates = $templates[0]; //the info for the template we generated is the first element in the returned array.
1788
-            EE_Error::overwrite_success();
1789
-            EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
1790
-        }
1791
-        
1792
-        
1793
-        $query_args = array(
1794
-            'id'      => isset($templates['GRP_ID']) ? $templates['GRP_ID'] : null,
1795
-            'context' => isset($templates['MTP_context']) ? $templates['MTP_context'] : null,
1796
-            'action'  => isset($templates['GRP_ID']) ? 'edit_message_template' : 'global_mtps'
1797
-        );
1798
-        
1799
-        //if called via ajax then we return query args otherwise redirect
1800
-        if (defined('DOING_AJAX') && DOING_AJAX) {
1801
-            return $query_args;
1802
-        } else {
1803
-            $this->_redirect_after_action(false, '', '', $query_args, true);
1774
+		}
1775
+        
1776
+		//any error messages?
1777
+		if ( ! $success) {
1778
+			EE_Error::add_error(
1779
+				__('Something went wrong with deleting existing templates. Unable to reset to default',
1780
+					'event_espresso'),
1781
+				__FILE__, __FUNCTION__, __LINE__
1782
+			);
1783
+		}
1784
+        
1785
+		//all good, let's add a success message!
1786
+		if ($success && ! empty($templates)) {
1787
+			$templates = $templates[0]; //the info for the template we generated is the first element in the returned array.
1788
+			EE_Error::overwrite_success();
1789
+			EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
1790
+		}
1791
+        
1792
+        
1793
+		$query_args = array(
1794
+			'id'      => isset($templates['GRP_ID']) ? $templates['GRP_ID'] : null,
1795
+			'context' => isset($templates['MTP_context']) ? $templates['MTP_context'] : null,
1796
+			'action'  => isset($templates['GRP_ID']) ? 'edit_message_template' : 'global_mtps'
1797
+		);
1798
+        
1799
+		//if called via ajax then we return query args otherwise redirect
1800
+		if (defined('DOING_AJAX') && DOING_AJAX) {
1801
+			return $query_args;
1802
+		} else {
1803
+			$this->_redirect_after_action(false, '', '', $query_args, true);
1804 1804
             
1805
-            return null;
1806
-        }
1807
-    }
1808
-    
1809
-    
1810
-    /**
1811
-     * Retrieve and set the message preview for display.
1812
-     *
1813
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
1814
-     *
1815
-     * @return string
1816
-     */
1817
-    public function _preview_message($send = false)
1818
-    {
1819
-        //first make sure we've got the necessary parameters
1820
-        if (
1821
-        ! isset(
1822
-            $this->_req_data['message_type'],
1823
-            $this->_req_data['messenger'],
1824
-            $this->_req_data['messenger'],
1825
-            $this->_req_data['GRP_ID']
1826
-        )
1827
-        ) {
1828
-            EE_Error::add_error(
1829
-                __('Missing necessary parameters for displaying preview', 'event_espresso'),
1830
-                __FILE__, __FUNCTION__, __LINE__
1831
-            );
1832
-        }
1833
-        
1834
-        EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
1835
-        
1836
-        
1837
-        //get the preview!
1838
-        $preview = EED_Messages::preview_message($this->_req_data['message_type'], $this->_req_data['context'],
1839
-            $this->_req_data['messenger'], $send);
1840
-        
1841
-        if ($send) {
1842
-            return $preview;
1843
-        }
1844
-        
1845
-        //let's add a button to go back to the edit view
1846
-        $query_args             = array(
1847
-            'id'      => $this->_req_data['GRP_ID'],
1848
-            'context' => $this->_req_data['context'],
1849
-            'action'  => 'edit_message_template'
1850
-        );
1851
-        $go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1852
-        $preview_button         = '<a href="' . $go_back_url . '" class="button-secondary messages-preview-go-back-button">' . __('Go Back to Edit',
1853
-                'event_espresso') . '</a>';
1854
-        $message_types          = $this->get_installed_message_types();
1855
-        $active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
1856
-        $active_messenger_label = $active_messenger instanceof EE_messenger
1857
-            ? ucwords($active_messenger->label['singular'])
1858
-            : esc_html__('Unknown Messenger', 'event_espresso');
1859
-        //let's provide a helpful title for context
1860
-        $preview_title = sprintf(
1861
-            __('Viewing Preview for %s %s Message Template', 'event_espresso'),
1862
-            $active_messenger_label,
1863
-            ucwords($message_types[$this->_req_data['message_type']]->label['singular'])
1864
-        );
1865
-        //setup display of preview.
1866
-        $this->_admin_page_title                    = $preview_title;
1867
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . stripslashes($preview);
1868
-        $this->_template_args['data']['force_json'] = true;
1869
-        
1870
-        return '';
1871
-    }
1872
-    
1873
-    
1874
-    /**
1875
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
1876
-     * gets called automatically.
1877
-     *
1878
-     * @since 4.5.0
1879
-     *
1880
-     * @return string
1881
-     */
1882
-    protected function _display_preview_message()
1883
-    {
1884
-        $this->display_admin_page_with_no_sidebar();
1885
-    }
1886
-    
1887
-    
1888
-    /**
1889
-     * registers metaboxes that should show up on the "edit_message_template" page
1890
-     *
1891
-     * @access protected
1892
-     * @return void
1893
-     */
1894
-    protected function _register_edit_meta_boxes()
1895
-    {
1896
-        add_meta_box('mtp_valid_shortcodes', __('Valid Shortcodes', 'event_espresso'),
1897
-            array($this, 'shortcode_meta_box'), $this->_current_screen->id, 'side', 'default');
1898
-        add_meta_box('mtp_extra_actions', __('Extra Actions', 'event_espresso'), array($this, 'extra_actions_meta_box'),
1899
-            $this->_current_screen->id, 'side', 'high');
1900
-        add_meta_box('mtp_templates', __('Template Styles', 'event_espresso'), array($this, 'template_pack_meta_box'),
1901
-            $this->_current_screen->id, 'side', 'high');
1902
-    }
1903
-    
1904
-    
1905
-    /**
1906
-     * metabox content for all template pack and variation selection.
1907
-     *
1908
-     * @since 4.5.0
1909
-     *
1910
-     * @return string
1911
-     */
1912
-    public function template_pack_meta_box()
1913
-    {
1914
-        $this->_set_message_template_group();
1915
-        
1916
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
1917
-        
1918
-        $tp_select_values = array();
1919
-        
1920
-        foreach ($tp_collection as $tp) {
1921
-            //only include template packs that support this messenger and message type!
1922
-            $supports = $tp->get_supports();
1923
-            if (
1924
-                ! isset($supports[$this->_message_template_group->messenger()])
1925
-                || ! in_array(
1926
-                    $this->_message_template_group->message_type(),
1927
-                    $supports[$this->_message_template_group->messenger()]
1928
-                )
1929
-            ) {
1930
-                //not supported
1931
-                continue;
1932
-            }
1805
+			return null;
1806
+		}
1807
+	}
1808
+    
1809
+    
1810
+	/**
1811
+	 * Retrieve and set the message preview for display.
1812
+	 *
1813
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
1814
+	 *
1815
+	 * @return string
1816
+	 */
1817
+	public function _preview_message($send = false)
1818
+	{
1819
+		//first make sure we've got the necessary parameters
1820
+		if (
1821
+		! isset(
1822
+			$this->_req_data['message_type'],
1823
+			$this->_req_data['messenger'],
1824
+			$this->_req_data['messenger'],
1825
+			$this->_req_data['GRP_ID']
1826
+		)
1827
+		) {
1828
+			EE_Error::add_error(
1829
+				__('Missing necessary parameters for displaying preview', 'event_espresso'),
1830
+				__FILE__, __FUNCTION__, __LINE__
1831
+			);
1832
+		}
1833
+        
1834
+		EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
1835
+        
1836
+        
1837
+		//get the preview!
1838
+		$preview = EED_Messages::preview_message($this->_req_data['message_type'], $this->_req_data['context'],
1839
+			$this->_req_data['messenger'], $send);
1840
+        
1841
+		if ($send) {
1842
+			return $preview;
1843
+		}
1844
+        
1845
+		//let's add a button to go back to the edit view
1846
+		$query_args             = array(
1847
+			'id'      => $this->_req_data['GRP_ID'],
1848
+			'context' => $this->_req_data['context'],
1849
+			'action'  => 'edit_message_template'
1850
+		);
1851
+		$go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1852
+		$preview_button         = '<a href="' . $go_back_url . '" class="button-secondary messages-preview-go-back-button">' . __('Go Back to Edit',
1853
+				'event_espresso') . '</a>';
1854
+		$message_types          = $this->get_installed_message_types();
1855
+		$active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
1856
+		$active_messenger_label = $active_messenger instanceof EE_messenger
1857
+			? ucwords($active_messenger->label['singular'])
1858
+			: esc_html__('Unknown Messenger', 'event_espresso');
1859
+		//let's provide a helpful title for context
1860
+		$preview_title = sprintf(
1861
+			__('Viewing Preview for %s %s Message Template', 'event_espresso'),
1862
+			$active_messenger_label,
1863
+			ucwords($message_types[$this->_req_data['message_type']]->label['singular'])
1864
+		);
1865
+		//setup display of preview.
1866
+		$this->_admin_page_title                    = $preview_title;
1867
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . stripslashes($preview);
1868
+		$this->_template_args['data']['force_json'] = true;
1869
+        
1870
+		return '';
1871
+	}
1872
+    
1873
+    
1874
+	/**
1875
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
1876
+	 * gets called automatically.
1877
+	 *
1878
+	 * @since 4.5.0
1879
+	 *
1880
+	 * @return string
1881
+	 */
1882
+	protected function _display_preview_message()
1883
+	{
1884
+		$this->display_admin_page_with_no_sidebar();
1885
+	}
1886
+    
1887
+    
1888
+	/**
1889
+	 * registers metaboxes that should show up on the "edit_message_template" page
1890
+	 *
1891
+	 * @access protected
1892
+	 * @return void
1893
+	 */
1894
+	protected function _register_edit_meta_boxes()
1895
+	{
1896
+		add_meta_box('mtp_valid_shortcodes', __('Valid Shortcodes', 'event_espresso'),
1897
+			array($this, 'shortcode_meta_box'), $this->_current_screen->id, 'side', 'default');
1898
+		add_meta_box('mtp_extra_actions', __('Extra Actions', 'event_espresso'), array($this, 'extra_actions_meta_box'),
1899
+			$this->_current_screen->id, 'side', 'high');
1900
+		add_meta_box('mtp_templates', __('Template Styles', 'event_espresso'), array($this, 'template_pack_meta_box'),
1901
+			$this->_current_screen->id, 'side', 'high');
1902
+	}
1903
+    
1904
+    
1905
+	/**
1906
+	 * metabox content for all template pack and variation selection.
1907
+	 *
1908
+	 * @since 4.5.0
1909
+	 *
1910
+	 * @return string
1911
+	 */
1912
+	public function template_pack_meta_box()
1913
+	{
1914
+		$this->_set_message_template_group();
1915
+        
1916
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
1917
+        
1918
+		$tp_select_values = array();
1919
+        
1920
+		foreach ($tp_collection as $tp) {
1921
+			//only include template packs that support this messenger and message type!
1922
+			$supports = $tp->get_supports();
1923
+			if (
1924
+				! isset($supports[$this->_message_template_group->messenger()])
1925
+				|| ! in_array(
1926
+					$this->_message_template_group->message_type(),
1927
+					$supports[$this->_message_template_group->messenger()]
1928
+				)
1929
+			) {
1930
+				//not supported
1931
+				continue;
1932
+			}
1933 1933
             
1934
-            $tp_select_values[] = array(
1935
-                'text' => $tp->label,
1936
-                'id'   => $tp->dbref
1937
-            );
1938
-        }
1939
-        
1940
-        //if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by the default template pack.  This still allows for the odd template pack to override.
1941
-        if (empty($tp_select_values)) {
1942
-            $tp_select_values[] = array(
1943
-                'text' => __('Default', 'event_espresso'),
1944
-                'id'   => 'default'
1945
-            );
1946
-        }
1947
-        
1948
-        //setup variation select values for the currently selected template.
1949
-        $variations               = $this->_message_template_group->get_template_pack()->get_variations(
1950
-            $this->_message_template_group->messenger(),
1951
-            $this->_message_template_group->message_type()
1952
-        );
1953
-        $variations_select_values = array();
1954
-        foreach ($variations as $variation => $label) {
1955
-            $variations_select_values[] = array(
1956
-                'text' => $label,
1957
-                'id'   => $variation
1958
-            );
1959
-        }
1960
-        
1961
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
1962
-        
1963
-        $template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
1964
-            'MTP_template_pack',
1965
-            $tp_select_values,
1966
-            $this->_message_template_group->get_template_pack_name()
1967
-        );
1968
-        $template_args['variations_selector']            = EEH_Form_Fields::select_input(
1969
-            'MTP_template_variation',
1970
-            $variations_select_values,
1971
-            $this->_message_template_group->get_template_pack_variation()
1972
-        );
1973
-        $template_args['template_pack_label']            = $template_pack_labels->template_pack;
1974
-        $template_args['template_variation_label']       = $template_pack_labels->template_variation;
1975
-        $template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
1976
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
1977
-        
1978
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
1979
-        
1980
-        EEH_Template::display_template($template, $template_args);
1981
-    }
1982
-    
1983
-    
1984
-    /**
1985
-     * This meta box holds any extra actions related to Message Templates
1986
-     * For now, this includes Resetting templates to defaults and sending a test email.
1987
-     *
1988
-     * @access  public
1989
-     * @return void
1990
-     * @throws \EE_Error
1991
-     */
1992
-    public function extra_actions_meta_box()
1993
-    {
1994
-        $template_form_fields = array();
1995
-        
1996
-        $extra_args = array(
1997
-            'msgr'   => $this->_message_template_group->messenger(),
1998
-            'mt'     => $this->_message_template_group->message_type(),
1999
-            'GRP_ID' => $this->_message_template_group->GRP_ID()
2000
-        );
2001
-        //first we need to see if there are any fields
2002
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2003
-        
2004
-        if ( ! empty($fields)) {
2005
-            //yup there be fields
2006
-            foreach ($fields as $field => $config) {
2007
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2008
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2009
-                $default  = isset($config['default']) ? $config['default'] : '';
2010
-                $default  = isset($config['value']) ? $config['value'] : $default;
1934
+			$tp_select_values[] = array(
1935
+				'text' => $tp->label,
1936
+				'id'   => $tp->dbref
1937
+			);
1938
+		}
1939
+        
1940
+		//if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by the default template pack.  This still allows for the odd template pack to override.
1941
+		if (empty($tp_select_values)) {
1942
+			$tp_select_values[] = array(
1943
+				'text' => __('Default', 'event_espresso'),
1944
+				'id'   => 'default'
1945
+			);
1946
+		}
1947
+        
1948
+		//setup variation select values for the currently selected template.
1949
+		$variations               = $this->_message_template_group->get_template_pack()->get_variations(
1950
+			$this->_message_template_group->messenger(),
1951
+			$this->_message_template_group->message_type()
1952
+		);
1953
+		$variations_select_values = array();
1954
+		foreach ($variations as $variation => $label) {
1955
+			$variations_select_values[] = array(
1956
+				'text' => $label,
1957
+				'id'   => $variation
1958
+			);
1959
+		}
1960
+        
1961
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
1962
+        
1963
+		$template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
1964
+			'MTP_template_pack',
1965
+			$tp_select_values,
1966
+			$this->_message_template_group->get_template_pack_name()
1967
+		);
1968
+		$template_args['variations_selector']            = EEH_Form_Fields::select_input(
1969
+			'MTP_template_variation',
1970
+			$variations_select_values,
1971
+			$this->_message_template_group->get_template_pack_variation()
1972
+		);
1973
+		$template_args['template_pack_label']            = $template_pack_labels->template_pack;
1974
+		$template_args['template_variation_label']       = $template_pack_labels->template_variation;
1975
+		$template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
1976
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
1977
+        
1978
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
1979
+        
1980
+		EEH_Template::display_template($template, $template_args);
1981
+	}
1982
+    
1983
+    
1984
+	/**
1985
+	 * This meta box holds any extra actions related to Message Templates
1986
+	 * For now, this includes Resetting templates to defaults and sending a test email.
1987
+	 *
1988
+	 * @access  public
1989
+	 * @return void
1990
+	 * @throws \EE_Error
1991
+	 */
1992
+	public function extra_actions_meta_box()
1993
+	{
1994
+		$template_form_fields = array();
1995
+        
1996
+		$extra_args = array(
1997
+			'msgr'   => $this->_message_template_group->messenger(),
1998
+			'mt'     => $this->_message_template_group->message_type(),
1999
+			'GRP_ID' => $this->_message_template_group->GRP_ID()
2000
+		);
2001
+		//first we need to see if there are any fields
2002
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2003
+        
2004
+		if ( ! empty($fields)) {
2005
+			//yup there be fields
2006
+			foreach ($fields as $field => $config) {
2007
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2008
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2009
+				$default  = isset($config['default']) ? $config['default'] : '';
2010
+				$default  = isset($config['value']) ? $config['value'] : $default;
2011 2011
                 
2012
-                // if type is hidden and the value is empty
2013
-                // something may have gone wrong so let's correct with the defaults
2014
-                $fix              = $config['input'] === 'hidden' && isset($existing[$field]) && empty($existing[$field])
2015
-                    ? $default
2016
-                    : '';
2017
-                $existing[$field] = isset($existing[$field]) && empty($fix)
2018
-                    ? $existing[$field]
2019
-                    : $fix;
2012
+				// if type is hidden and the value is empty
2013
+				// something may have gone wrong so let's correct with the defaults
2014
+				$fix              = $config['input'] === 'hidden' && isset($existing[$field]) && empty($existing[$field])
2015
+					? $default
2016
+					: '';
2017
+				$existing[$field] = isset($existing[$field]) && empty($fix)
2018
+					? $existing[$field]
2019
+					: $fix;
2020 2020
                 
2021
-                $template_form_fields[$field_id] = array(
2022
-                    'name'       => 'test_settings_fld[' . $field . ']',
2023
-                    'label'      => $config['label'],
2024
-                    'input'      => $config['input'],
2025
-                    'type'       => $config['type'],
2026
-                    'required'   => $config['required'],
2027
-                    'validation' => $config['validation'],
2028
-                    'value'      => isset($existing[$field]) ? $existing[$field] : $default,
2029
-                    'css_class'  => $config['css_class'],
2030
-                    'options'    => isset($config['options']) ? $config['options'] : array(),
2031
-                    'default'    => $default,
2032
-                    'format'     => $config['format']
2033
-                );
2034
-            }
2035
-        }
2036
-        
2037
-        $test_settings_fields = ! empty($template_form_fields)
2038
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2039
-            : '';
2040
-        
2041
-        $test_settings_html = '';
2042
-        //print out $test_settings_fields
2043
-        if ( ! empty($test_settings_fields)) {
2044
-            echo $test_settings_fields;
2045
-            $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2046
-            $test_settings_html .= 'name="test_button" value="';
2047
-            $test_settings_html .= __('Test Send', 'event_espresso');
2048
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2049
-        }
2050
-        
2051
-        //and button
2052
-        $test_settings_html .= '<p>' . __('Need to reset this message type and start over?', 'event_espresso') . '</p>';
2053
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2054
-        $test_settings_html .= $this->get_action_link_or_button(
2055
-            'reset_to_default',
2056
-            'reset',
2057
-            $extra_args,
2058
-            'button-primary reset-default-button'
2059
-        );
2060
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2061
-        echo $test_settings_html;
2062
-    }
2063
-    
2064
-    
2065
-    /**
2066
-     * This returns the shortcode selector skeleton for a given context and field.
2067
-     *
2068
-     * @since 4.9.rc.000
2069
-     *
2070
-     * @param string $field           The name of the field retrieving shortcodes for.
2071
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2072
-     *
2073
-     * @return string
2074
-     */
2075
-    protected function _get_shortcode_selector($field, $linked_input_id)
2076
-    {
2077
-        $template_args = array(
2078
-            'shortcodes'      => $this->_get_shortcodes(array($field), true),
2079
-            'fieldname'       => $field,
2080
-            'linked_input_id' => $linked_input_id
2081
-        );
2082
-        
2083
-        return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2084
-            $template_args, true);
2085
-    }
2086
-    
2087
-    
2088
-    /**
2089
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2090
-     * page)
2091
-     *
2092
-     * @access public
2093
-     * @return void
2094
-     */
2095
-    public function shortcode_meta_box()
2096
-    {
2097
-        $shortcodes = $this->_get_shortcodes(array(), false); //just make sure shortcodes property is set
2098
-        //$messenger = $this->_message_template_group->messenger_obj();
2099
-        //now let's set the content depending on the status of the shortcodes array
2100
-        if (empty($shortcodes)) {
2101
-            $content = '<p>' . __('There are no valid shortcodes available', 'event_espresso') . '</p>';
2102
-            echo $content;
2103
-        } else {
2104
-            //$alt = 0;
2105
-            ?>
2021
+				$template_form_fields[$field_id] = array(
2022
+					'name'       => 'test_settings_fld[' . $field . ']',
2023
+					'label'      => $config['label'],
2024
+					'input'      => $config['input'],
2025
+					'type'       => $config['type'],
2026
+					'required'   => $config['required'],
2027
+					'validation' => $config['validation'],
2028
+					'value'      => isset($existing[$field]) ? $existing[$field] : $default,
2029
+					'css_class'  => $config['css_class'],
2030
+					'options'    => isset($config['options']) ? $config['options'] : array(),
2031
+					'default'    => $default,
2032
+					'format'     => $config['format']
2033
+				);
2034
+			}
2035
+		}
2036
+        
2037
+		$test_settings_fields = ! empty($template_form_fields)
2038
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2039
+			: '';
2040
+        
2041
+		$test_settings_html = '';
2042
+		//print out $test_settings_fields
2043
+		if ( ! empty($test_settings_fields)) {
2044
+			echo $test_settings_fields;
2045
+			$test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2046
+			$test_settings_html .= 'name="test_button" value="';
2047
+			$test_settings_html .= __('Test Send', 'event_espresso');
2048
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2049
+		}
2050
+        
2051
+		//and button
2052
+		$test_settings_html .= '<p>' . __('Need to reset this message type and start over?', 'event_espresso') . '</p>';
2053
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2054
+		$test_settings_html .= $this->get_action_link_or_button(
2055
+			'reset_to_default',
2056
+			'reset',
2057
+			$extra_args,
2058
+			'button-primary reset-default-button'
2059
+		);
2060
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2061
+		echo $test_settings_html;
2062
+	}
2063
+    
2064
+    
2065
+	/**
2066
+	 * This returns the shortcode selector skeleton for a given context and field.
2067
+	 *
2068
+	 * @since 4.9.rc.000
2069
+	 *
2070
+	 * @param string $field           The name of the field retrieving shortcodes for.
2071
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2072
+	 *
2073
+	 * @return string
2074
+	 */
2075
+	protected function _get_shortcode_selector($field, $linked_input_id)
2076
+	{
2077
+		$template_args = array(
2078
+			'shortcodes'      => $this->_get_shortcodes(array($field), true),
2079
+			'fieldname'       => $field,
2080
+			'linked_input_id' => $linked_input_id
2081
+		);
2082
+        
2083
+		return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2084
+			$template_args, true);
2085
+	}
2086
+    
2087
+    
2088
+	/**
2089
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2090
+	 * page)
2091
+	 *
2092
+	 * @access public
2093
+	 * @return void
2094
+	 */
2095
+	public function shortcode_meta_box()
2096
+	{
2097
+		$shortcodes = $this->_get_shortcodes(array(), false); //just make sure shortcodes property is set
2098
+		//$messenger = $this->_message_template_group->messenger_obj();
2099
+		//now let's set the content depending on the status of the shortcodes array
2100
+		if (empty($shortcodes)) {
2101
+			$content = '<p>' . __('There are no valid shortcodes available', 'event_espresso') . '</p>';
2102
+			echo $content;
2103
+		} else {
2104
+			//$alt = 0;
2105
+			?>
2106 2106
             <div
2107 2107
                 style="float:right; margin-top:10px"><?php echo $this->_get_help_tab_link('message_template_shortcodes'); ?></div>
2108 2108
             <p class="small-text"><?php printf(__('You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2109
-                    'event_espresso'), '<span class="dashicons dashicons-menu"></span>'); ?></p>
2109
+					'event_espresso'), '<span class="dashicons dashicons-menu"></span>'); ?></p>
2110 2110
             <?php
2111
-        }
2112
-        
2113
-        
2114
-    }
2115
-    
2116
-    
2117
-    /**
2118
-     * used to set the $_shortcodes property for when its needed elsewhere.
2119
-     *
2120
-     * @access protected
2121
-     * @return void
2122
-     */
2123
-    protected function _set_shortcodes()
2124
-    {
2125
-        
2126
-        //no need to run this if the property is already set
2127
-        if ( ! empty($this->_shortcodes)) {
2128
-            return;
2129
-        }
2130
-        
2131
-        $this->_shortcodes = $this->_get_shortcodes();
2132
-    }
2133
-    
2134
-    
2135
-    /**
2136
-     * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2137
-     * property)
2138
-     *
2139
-     * @access  protected
2140
-     *
2141
-     * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2142
-     *                         for. Defaults to all (for the given context)
2143
-     * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2144
-     *
2145
-     * @return array          Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2146
-     *                        true just an array of shortcode/label pairs.
2147
-     */
2148
-    protected function _get_shortcodes($fields = array(), $merged = true)
2149
-    {
2150
-        $this->_set_message_template_group();
2151
-        
2152
-        //we need the messenger and message template to retrieve the valid shortcodes array.
2153
-        $GRP_ID  = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id']) : false;
2154
-        $context = isset($this->_req_data['context']) ? $this->_req_data['context'] : key($this->_message_template_group->contexts_config());
2155
-        
2156
-        return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2157
-    }
2158
-    
2159
-    
2160
-    /**
2161
-     * This sets the _message_template property (containing the called message_template object)
2162
-     *
2163
-     * @access protected
2164
-     * @return  void
2165
-     */
2166
-    protected function _set_message_template_group()
2167
-    {
2168
-        
2169
-        if ( ! empty($this->_message_template_group)) {
2170
-            return;
2171
-        } //get out if this is already set.
2172
-        
2173
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2174
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2175
-        
2176
-        //let's get the message templates
2177
-        $MTP = EEM_Message_Template_Group::instance();
2178
-        
2179
-        if (empty($GRP_ID)) {
2180
-            $this->_message_template_group = $MTP->create_default_object();
2181
-        } else {
2182
-            $this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2183
-        }
2184
-        
2185
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2186
-        $this->_variation     = $this->_message_template_group->get_template_pack_variation();
2187
-        
2188
-    }
2189
-    
2190
-    
2191
-    /**
2192
-     * sets up a context switcher for edit forms
2193
-     *
2194
-     * @access  protected
2195
-     *
2196
-     * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2197
-     * @param array                      $args                  various things the context switcher needs.
2198
-     *
2199
-     */
2200
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2201
-    {
2202
-        $context_details = $template_group_object->contexts_config();
2203
-        $context_label   = $template_group_object->context_label();
2204
-        ob_start();
2205
-        ?>
2111
+		}
2112
+        
2113
+        
2114
+	}
2115
+    
2116
+    
2117
+	/**
2118
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2119
+	 *
2120
+	 * @access protected
2121
+	 * @return void
2122
+	 */
2123
+	protected function _set_shortcodes()
2124
+	{
2125
+        
2126
+		//no need to run this if the property is already set
2127
+		if ( ! empty($this->_shortcodes)) {
2128
+			return;
2129
+		}
2130
+        
2131
+		$this->_shortcodes = $this->_get_shortcodes();
2132
+	}
2133
+    
2134
+    
2135
+	/**
2136
+	 * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2137
+	 * property)
2138
+	 *
2139
+	 * @access  protected
2140
+	 *
2141
+	 * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2142
+	 *                         for. Defaults to all (for the given context)
2143
+	 * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2144
+	 *
2145
+	 * @return array          Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2146
+	 *                        true just an array of shortcode/label pairs.
2147
+	 */
2148
+	protected function _get_shortcodes($fields = array(), $merged = true)
2149
+	{
2150
+		$this->_set_message_template_group();
2151
+        
2152
+		//we need the messenger and message template to retrieve the valid shortcodes array.
2153
+		$GRP_ID  = isset($this->_req_data['id']) && ! empty($this->_req_data['id']) ? absint($this->_req_data['id']) : false;
2154
+		$context = isset($this->_req_data['context']) ? $this->_req_data['context'] : key($this->_message_template_group->contexts_config());
2155
+        
2156
+		return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2157
+	}
2158
+    
2159
+    
2160
+	/**
2161
+	 * This sets the _message_template property (containing the called message_template object)
2162
+	 *
2163
+	 * @access protected
2164
+	 * @return  void
2165
+	 */
2166
+	protected function _set_message_template_group()
2167
+	{
2168
+        
2169
+		if ( ! empty($this->_message_template_group)) {
2170
+			return;
2171
+		} //get out if this is already set.
2172
+        
2173
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2174
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2175
+        
2176
+		//let's get the message templates
2177
+		$MTP = EEM_Message_Template_Group::instance();
2178
+        
2179
+		if (empty($GRP_ID)) {
2180
+			$this->_message_template_group = $MTP->create_default_object();
2181
+		} else {
2182
+			$this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2183
+		}
2184
+        
2185
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2186
+		$this->_variation     = $this->_message_template_group->get_template_pack_variation();
2187
+        
2188
+	}
2189
+    
2190
+    
2191
+	/**
2192
+	 * sets up a context switcher for edit forms
2193
+	 *
2194
+	 * @access  protected
2195
+	 *
2196
+	 * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2197
+	 * @param array                      $args                  various things the context switcher needs.
2198
+	 *
2199
+	 */
2200
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2201
+	{
2202
+		$context_details = $template_group_object->contexts_config();
2203
+		$context_label   = $template_group_object->context_label();
2204
+		ob_start();
2205
+		?>
2206 2206
         <div class="ee-msg-switcher-container">
2207 2207
             <form method="get" action="<?php echo EE_MSG_ADMIN_URL; ?>" id="ee-msg-context-switcher-frm">
2208 2208
                 <?php
2209
-                foreach ($args as $name => $value) {
2210
-                    if ($name == 'context' || empty($value) || $name == 'extra') {
2211
-                        continue;
2212
-                    }
2213
-                    ?>
2209
+				foreach ($args as $name => $value) {
2210
+					if ($name == 'context' || empty($value) || $name == 'extra') {
2211
+						continue;
2212
+					}
2213
+					?>
2214 2214
                     <input type="hidden" name="<?php echo $name; ?>" value="<?php echo $value; ?>"/>
2215 2215
                     <?php
2216
-                }
2217
-                //setup nonce_url
2218
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2219
-                ?>
2216
+				}
2217
+				//setup nonce_url
2218
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2219
+				?>
2220 2220
                 <select name="context">
2221 2221
                     <?php
2222
-                    $context_templates = $template_group_object->context_templates();
2223
-                    if (is_array($context_templates)) :
2224
-                        foreach ($context_templates as $context => $template_fields) :
2225
-                            $checked = ($context == $args['context']) ? 'selected="selected"' : '';
2226
-                            ?>
2222
+					$context_templates = $template_group_object->context_templates();
2223
+					if (is_array($context_templates)) :
2224
+						foreach ($context_templates as $context => $template_fields) :
2225
+							$checked = ($context == $args['context']) ? 'selected="selected"' : '';
2226
+							?>
2227 2227
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2228 2228
                                 <?php echo $context_details[$context]['label']; ?>
2229 2229
                             </option>
@@ -2236,1554 +2236,1554 @@  discard block
 block discarded – undo
2236 2236
             <?php echo $args['extra']; ?>
2237 2237
         </div> <!-- end .ee-msg-switcher-container -->
2238 2238
         <?php
2239
-        $output = ob_get_contents();
2240
-        ob_clean();
2241
-        $this->_context_switcher = $output;
2242
-    }
2243
-    
2244
-    
2245
-    /**
2246
-     * utility for sanitizing new values coming in.
2247
-     * Note: this is only used when updating a context.
2248
-     *
2249
-     * @access protected
2250
-     *
2251
-     * @param int $index This helps us know which template field to select from the request array.
2252
-     *
2253
-     * @return array
2254
-     */
2255
-    protected function _set_message_template_column_values($index)
2256
-    {
2257
-        if (is_array($this->_req_data['MTP_template_fields'][$index]['content'])) {
2258
-            foreach ($this->_req_data['MTP_template_fields'][$index]['content'] as $field => $value) {
2259
-                $this->_req_data['MTP_template_fields'][$index]['content'][$field] = $value;
2260
-            }
2261
-        } /*else {
2239
+		$output = ob_get_contents();
2240
+		ob_clean();
2241
+		$this->_context_switcher = $output;
2242
+	}
2243
+    
2244
+    
2245
+	/**
2246
+	 * utility for sanitizing new values coming in.
2247
+	 * Note: this is only used when updating a context.
2248
+	 *
2249
+	 * @access protected
2250
+	 *
2251
+	 * @param int $index This helps us know which template field to select from the request array.
2252
+	 *
2253
+	 * @return array
2254
+	 */
2255
+	protected function _set_message_template_column_values($index)
2256
+	{
2257
+		if (is_array($this->_req_data['MTP_template_fields'][$index]['content'])) {
2258
+			foreach ($this->_req_data['MTP_template_fields'][$index]['content'] as $field => $value) {
2259
+				$this->_req_data['MTP_template_fields'][$index]['content'][$field] = $value;
2260
+			}
2261
+		} /*else {
2262 2262
 			$this->_req_data['MTP_template_fields'][$index]['content'] = $this->_req_data['MTP_template_fields'][$index]['content'];
2263 2263
 		}*/
2264 2264
         
2265 2265
         
2266
-        $set_column_values = array(
2267
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][$index]['MTP_ID']),
2268
-            'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2269
-            'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2270
-            'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2271
-            'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2272
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][$index]['name']),
2273
-            'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2274
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][$index]['content'],
2275
-            'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2276
-                ? absint($this->_req_data['MTP_is_global'])
2277
-                : 0,
2278
-            'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2279
-                ? absint($this->_req_data['MTP_is_override'])
2280
-                : 0,
2281
-            'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2282
-            'MTP_is_active'      => absint($this->_req_data['MTP_is_active'])
2283
-        );
2284
-        
2285
-        
2286
-        return $set_column_values;
2287
-    }
2288
-    
2289
-    
2290
-    protected function _insert_or_update_message_template($new = false)
2291
-    {
2292
-        
2293
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2294
-        $success  = 0;
2295
-        $override = false;
2296
-        
2297
-        //setup notices description
2298
-        $messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2299
-        
2300
-        //need the message type and messenger objects to be able to use the labels for the notices
2301
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2302
-        $messenger_label  = $messenger_object instanceof EE_messenger ? ucwords($messenger_object->label['singular']) : '';
2303
-        
2304
-        $message_type_slug   = ! empty($this->_req_data['MTP_message_type']) ? $this->_req_data['MTP_message_type'] : '';
2305
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2306
-        
2307
-        $message_type_label = $message_type_object instanceof EE_message_type
2308
-            ? ucwords($message_type_object->label['singular'])
2309
-            : '';
2310
-        
2311
-        $context_slug = ! empty($this->_req_data['MTP_context'])
2312
-            ? $this->_req_data['MTP_context']
2313
-            : '';
2314
-        $context      = ucwords(str_replace('_', ' ', $context_slug));
2315
-        
2316
-        $item_desc = $messenger_label && $message_type_label ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' ' : '';
2317
-        $item_desc .= 'Message Template';
2318
-        $query_args  = array();
2319
-        $edit_array  = array();
2320
-        $action_desc = '';
2321
-        
2322
-        //if this is "new" then we need to generate the default contexts for the selected messenger/message_type for user to edit.
2323
-        if ($new) {
2324
-            $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2325
-            if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2326
-                if (empty($edit_array)) {
2327
-                    $success = 0;
2328
-                } else {
2329
-                    $success    = 1;
2330
-                    $edit_array = $edit_array[0];
2331
-                    $query_args = array(
2332
-                        'id'      => $edit_array['GRP_ID'],
2333
-                        'context' => $edit_array['MTP_context'],
2334
-                        'action'  => 'edit_message_template'
2335
-                    );
2336
-                }
2337
-            }
2338
-            $action_desc = 'created';
2339
-        } else {
2340
-            $MTPG = EEM_Message_Template_Group::instance();
2341
-            $MTP  = EEM_Message_Template::instance();
2266
+		$set_column_values = array(
2267
+			'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][$index]['MTP_ID']),
2268
+			'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2269
+			'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2270
+			'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2271
+			'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2272
+			'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][$index]['name']),
2273
+			'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2274
+			'MTP_content'        => $this->_req_data['MTP_template_fields'][$index]['content'],
2275
+			'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2276
+				? absint($this->_req_data['MTP_is_global'])
2277
+				: 0,
2278
+			'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2279
+				? absint($this->_req_data['MTP_is_override'])
2280
+				: 0,
2281
+			'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2282
+			'MTP_is_active'      => absint($this->_req_data['MTP_is_active'])
2283
+		);
2284
+        
2285
+        
2286
+		return $set_column_values;
2287
+	}
2288
+    
2289
+    
2290
+	protected function _insert_or_update_message_template($new = false)
2291
+	{
2292
+        
2293
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2294
+		$success  = 0;
2295
+		$override = false;
2296
+        
2297
+		//setup notices description
2298
+		$messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2299
+        
2300
+		//need the message type and messenger objects to be able to use the labels for the notices
2301
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2302
+		$messenger_label  = $messenger_object instanceof EE_messenger ? ucwords($messenger_object->label['singular']) : '';
2303
+        
2304
+		$message_type_slug   = ! empty($this->_req_data['MTP_message_type']) ? $this->_req_data['MTP_message_type'] : '';
2305
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2306
+        
2307
+		$message_type_label = $message_type_object instanceof EE_message_type
2308
+			? ucwords($message_type_object->label['singular'])
2309
+			: '';
2310
+        
2311
+		$context_slug = ! empty($this->_req_data['MTP_context'])
2312
+			? $this->_req_data['MTP_context']
2313
+			: '';
2314
+		$context      = ucwords(str_replace('_', ' ', $context_slug));
2315
+        
2316
+		$item_desc = $messenger_label && $message_type_label ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' ' : '';
2317
+		$item_desc .= 'Message Template';
2318
+		$query_args  = array();
2319
+		$edit_array  = array();
2320
+		$action_desc = '';
2321
+        
2322
+		//if this is "new" then we need to generate the default contexts for the selected messenger/message_type for user to edit.
2323
+		if ($new) {
2324
+			$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2325
+			if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2326
+				if (empty($edit_array)) {
2327
+					$success = 0;
2328
+				} else {
2329
+					$success    = 1;
2330
+					$edit_array = $edit_array[0];
2331
+					$query_args = array(
2332
+						'id'      => $edit_array['GRP_ID'],
2333
+						'context' => $edit_array['MTP_context'],
2334
+						'action'  => 'edit_message_template'
2335
+					);
2336
+				}
2337
+			}
2338
+			$action_desc = 'created';
2339
+		} else {
2340
+			$MTPG = EEM_Message_Template_Group::instance();
2341
+			$MTP  = EEM_Message_Template::instance();
2342 2342
             
2343 2343
             
2344
-            //run update for each template field in displayed context
2345
-            if ( ! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2346
-                EE_Error::add_error(
2347
-                    __('There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2348
-                        'event_espresso'),
2349
-                    __FILE__, __FUNCTION__, __LINE__
2350
-                );
2351
-                $success = 0;
2344
+			//run update for each template field in displayed context
2345
+			if ( ! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2346
+				EE_Error::add_error(
2347
+					__('There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2348
+						'event_espresso'),
2349
+					__FILE__, __FUNCTION__, __LINE__
2350
+				);
2351
+				$success = 0;
2352 2352
                 
2353
-            } else {
2354
-                //first validate all fields!
2355
-                $validates = $MTPG->validate($this->_req_data['MTP_template_fields'], $context_slug, $messenger_slug,
2356
-                    $message_type_slug);
2353
+			} else {
2354
+				//first validate all fields!
2355
+				$validates = $MTPG->validate($this->_req_data['MTP_template_fields'], $context_slug, $messenger_slug,
2356
+					$message_type_slug);
2357 2357
                 
2358
-                //if $validate returned error messages (i.e. is_array()) then we need to process them and setup an appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.  WE need to make sure there is no actual error messages in validates.
2359
-                if (is_array($validates) && ! empty($validates)) {
2360
-                    //add the transient so when the form loads we know which fields to highlight
2361
-                    $this->_add_transient('edit_message_template', $validates);
2358
+				//if $validate returned error messages (i.e. is_array()) then we need to process them and setup an appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.  WE need to make sure there is no actual error messages in validates.
2359
+				if (is_array($validates) && ! empty($validates)) {
2360
+					//add the transient so when the form loads we know which fields to highlight
2361
+					$this->_add_transient('edit_message_template', $validates);
2362 2362
                     
2363
-                    $success = 0;
2363
+					$success = 0;
2364 2364
                     
2365
-                    //setup notices
2366
-                    foreach ($validates as $field => $error) {
2367
-                        if (isset($error['msg'])) {
2368
-                            EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2369
-                        }
2370
-                    }
2365
+					//setup notices
2366
+					foreach ($validates as $field => $error) {
2367
+						if (isset($error['msg'])) {
2368
+							EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2369
+						}
2370
+					}
2371 2371
                     
2372
-                } else {
2373
-                    $set_column_values = array();
2374
-                    foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2375
-                        $set_column_values = $this->_set_message_template_column_values($template_field);
2372
+				} else {
2373
+					$set_column_values = array();
2374
+					foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2375
+						$set_column_values = $this->_set_message_template_column_values($template_field);
2376 2376
                         
2377
-                        $where_cols_n_values = array(
2378
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID']
2379
-                        );
2377
+						$where_cols_n_values = array(
2378
+							'MTP_ID' => $this->_req_data['MTP_template_fields'][$template_field]['MTP_ID']
2379
+						);
2380 2380
                         
2381
-                        $message_template_fields = array(
2382
-                            'GRP_ID'             => $set_column_values['GRP_ID'],
2383
-                            'MTP_template_field' => $set_column_values['MTP_template_field'],
2384
-                            'MTP_context'        => $set_column_values['MTP_context'],
2385
-                            'MTP_content'        => $set_column_values['MTP_content']
2386
-                        );
2387
-                        if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2388
-                            if ($updated === false) {
2389
-                                EE_Error::add_error(
2390
-                                    sprintf(
2391
-                                        __('%s field was NOT updated for some reason', 'event_espresso'),
2392
-                                        $template_field
2393
-                                    ),
2394
-                                    __FILE__, __FUNCTION__, __LINE__
2395
-                                );
2396
-                            } else {
2397
-                                $success = 1;
2398
-                            }
2399
-                        }
2400
-                        $action_desc = 'updated';
2401
-                    }
2381
+						$message_template_fields = array(
2382
+							'GRP_ID'             => $set_column_values['GRP_ID'],
2383
+							'MTP_template_field' => $set_column_values['MTP_template_field'],
2384
+							'MTP_context'        => $set_column_values['MTP_context'],
2385
+							'MTP_content'        => $set_column_values['MTP_content']
2386
+						);
2387
+						if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2388
+							if ($updated === false) {
2389
+								EE_Error::add_error(
2390
+									sprintf(
2391
+										__('%s field was NOT updated for some reason', 'event_espresso'),
2392
+										$template_field
2393
+									),
2394
+									__FILE__, __FUNCTION__, __LINE__
2395
+								);
2396
+							} else {
2397
+								$success = 1;
2398
+							}
2399
+						}
2400
+						$action_desc = 'updated';
2401
+					}
2402 2402
                     
2403
-                    //we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2404
-                    $mtpg_fields = array(
2405
-                        'MTP_user_id'      => $set_column_values['MTP_user_id'],
2406
-                        'MTP_messenger'    => $set_column_values['MTP_messenger'],
2407
-                        'MTP_message_type' => $set_column_values['MTP_message_type'],
2408
-                        'MTP_is_global'    => $set_column_values['MTP_is_global'],
2409
-                        'MTP_is_override'  => $set_column_values['MTP_is_override'],
2410
-                        'MTP_deleted'      => $set_column_values['MTP_deleted'],
2411
-                        'MTP_is_active'    => $set_column_values['MTP_is_active'],
2412
-                        'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2413
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2414
-                            : '',
2415
-                        'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2416
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2417
-                            : ''
2418
-                    );
2403
+					//we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2404
+					$mtpg_fields = array(
2405
+						'MTP_user_id'      => $set_column_values['MTP_user_id'],
2406
+						'MTP_messenger'    => $set_column_values['MTP_messenger'],
2407
+						'MTP_message_type' => $set_column_values['MTP_message_type'],
2408
+						'MTP_is_global'    => $set_column_values['MTP_is_global'],
2409
+						'MTP_is_override'  => $set_column_values['MTP_is_override'],
2410
+						'MTP_deleted'      => $set_column_values['MTP_deleted'],
2411
+						'MTP_is_active'    => $set_column_values['MTP_is_active'],
2412
+						'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2413
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2414
+							: '',
2415
+						'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2416
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2417
+							: ''
2418
+					);
2419 2419
                     
2420
-                    $mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2421
-                    $updated    = $MTPG->update($mtpg_fields, array($mtpg_where));
2420
+					$mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2421
+					$updated    = $MTPG->update($mtpg_fields, array($mtpg_where));
2422 2422
                     
2423
-                    if ($updated === false) {
2424
-                        EE_Error::add_error(
2425
-                            sprintf(
2426
-                                __('The Message Template Group (%d) was NOT updated for some reason', 'event_espresso'),
2427
-                                $set_column_values['GRP_ID']
2428
-                            ),
2429
-                            __FILE__, __FUNCTION__, __LINE__
2430
-                        );
2431
-                    } else {
2432
-                        //k now we need to ensure the template_pack and template_variation fields are set.
2433
-                        $template_pack = ! empty($this->_req_data['MTP_template_pack'])
2434
-                            ? $this->_req_data['MTP_template_pack']
2435
-                            : 'default';
2423
+					if ($updated === false) {
2424
+						EE_Error::add_error(
2425
+							sprintf(
2426
+								__('The Message Template Group (%d) was NOT updated for some reason', 'event_espresso'),
2427
+								$set_column_values['GRP_ID']
2428
+							),
2429
+							__FILE__, __FUNCTION__, __LINE__
2430
+						);
2431
+					} else {
2432
+						//k now we need to ensure the template_pack and template_variation fields are set.
2433
+						$template_pack = ! empty($this->_req_data['MTP_template_pack'])
2434
+							? $this->_req_data['MTP_template_pack']
2435
+							: 'default';
2436 2436
                         
2437
-                        $template_variation = ! empty($this->_req_data['MTP_template_variation'])
2438
-                            ? $this->_req_data['MTP_template_variation']
2439
-                            : 'default';
2437
+						$template_variation = ! empty($this->_req_data['MTP_template_variation'])
2438
+							? $this->_req_data['MTP_template_variation']
2439
+							: 'default';
2440 2440
                         
2441
-                        $mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2442
-                        if ($mtpg_obj instanceof EE_Message_Template_Group) {
2443
-                            $mtpg_obj->set_template_pack_name($template_pack);
2444
-                            $mtpg_obj->set_template_pack_variation($template_variation);
2445
-                        }
2446
-                        $success = 1;
2447
-                    }
2448
-                }
2449
-            }
2441
+						$mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2442
+						if ($mtpg_obj instanceof EE_Message_Template_Group) {
2443
+							$mtpg_obj->set_template_pack_name($template_pack);
2444
+							$mtpg_obj->set_template_pack_variation($template_variation);
2445
+						}
2446
+						$success = 1;
2447
+					}
2448
+				}
2449
+			}
2450 2450
             
2451
-        }
2452
-        
2453
-        //we return things differently if doing ajax
2454
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2455
-            $this->_template_args['success'] = $success;
2456
-            $this->_template_args['error']   = ! $success ? true : false;
2457
-            $this->_template_args['content'] = '';
2458
-            $this->_template_args['data']    = array(
2459
-                'grpID'        => $edit_array['GRP_ID'],
2460
-                'templateName' => $edit_array['template_name']
2461
-            );
2462
-            if ($success) {
2463
-                EE_Error::overwrite_success();
2464
-                EE_Error::add_success(__('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.',
2465
-                    'event_espresso'));
2466
-            }
2451
+		}
2452
+        
2453
+		//we return things differently if doing ajax
2454
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2455
+			$this->_template_args['success'] = $success;
2456
+			$this->_template_args['error']   = ! $success ? true : false;
2457
+			$this->_template_args['content'] = '';
2458
+			$this->_template_args['data']    = array(
2459
+				'grpID'        => $edit_array['GRP_ID'],
2460
+				'templateName' => $edit_array['template_name']
2461
+			);
2462
+			if ($success) {
2463
+				EE_Error::overwrite_success();
2464
+				EE_Error::add_success(__('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.',
2465
+					'event_espresso'));
2466
+			}
2467 2467
             
2468
-            $this->_return_json();
2469
-        }
2470
-        
2471
-        
2472
-        //was a test send triggered?
2473
-        if (isset($this->_req_data['test_button'])) {
2474
-            EE_Error::overwrite_success();
2475
-            $this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2476
-            $override = true;
2477
-        }
2478
-        
2479
-        if (empty($query_args)) {
2480
-            $query_args = array(
2481
-                'id'      => $this->_req_data['GRP_ID'],
2482
-                'context' => $context_slug,
2483
-                'action'  => 'edit_message_template'
2484
-            );
2485
-        }
2486
-        
2487
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2488
-    }
2489
-    
2490
-    
2491
-    /**
2492
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
2493
-     *
2494
-     * @param  string $context      what context being tested
2495
-     * @param  string $messenger    messenger being tested
2496
-     * @param  string $message_type message type being tested
2497
-     *
2498
-     */
2499
-    protected function _do_test_send($context, $messenger, $message_type)
2500
-    {
2501
-        //set things up for preview
2502
-        $this->_req_data['messenger']    = $messenger;
2503
-        $this->_req_data['message_type'] = $message_type;
2504
-        $this->_req_data['context']      = $context;
2505
-        $this->_req_data['GRP_ID']       = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2506
-        $active_messenger                = $this->_message_resource_manager->get_active_messenger($messenger);
2507
-        
2508
-        //let's save any existing fields that might be required by the messenger
2509
-        if (
2510
-            isset($this->_req_data['test_settings_fld'])
2511
-            && $active_messenger instanceof EE_messenger
2512
-        ) {
2513
-            $active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2514
-        }
2515
-        
2516
-        $success = $this->_preview_message(true);
2517
-        
2518
-        if ($success) {
2519
-            EE_Error::add_success(__('Test message sent', 'event_espresso'));
2520
-        } else {
2521
-            EE_Error::add_error(__('The test message was not sent', 'event_espresso'), __FILE__, __FUNCTION__,
2522
-                __LINE__);
2523
-        }
2524
-    }
2525
-    
2526
-    
2527
-    /**
2528
-     * _generate_new_templates
2529
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
2530
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
2531
-     * for the event.
2532
-     *
2533
-     *
2534
-     * @param  string $messenger     the messenger we are generating templates for
2535
-     * @param array   $message_types array of message types that the templates are generated for.
2536
-     * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
2537
-     *                               indicate the message_template_group being used as the base.
2538
-     *
2539
-     * @param bool    $global
2540
-     *
2541
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
2542
-     *                               encountering problems.
2543
-     * @throws \EE_Error
2544
-     */
2545
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
2546
-    {
2547
-        
2548
-        //if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we just don't generate any templates.
2549
-        if (empty($message_types)) {
2550
-            return true;
2551
-        }
2552
-        
2553
-        return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
2554
-    }
2555
-    
2556
-    
2557
-    /**
2558
-     * [_trash_or_restore_message_template]
2559
-     *
2560
-     * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
2561
-     * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
2562
-     *                        an individual context (FALSE).
2563
-     *
2564
-     * @return void
2565
-     */
2566
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
2567
-    {
2568
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2569
-        $MTP = EEM_Message_Template_Group::instance();
2570
-        
2571
-        $success = 1;
2572
-        
2573
-        //incoming GRP_IDs
2574
-        if ($all) {
2575
-            //Checkboxes
2576
-            if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2577
-                //if array has more than one element then success message should be plural.
2578
-                //todo: what about nonce?
2579
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2468
+			$this->_return_json();
2469
+		}
2470
+        
2471
+        
2472
+		//was a test send triggered?
2473
+		if (isset($this->_req_data['test_button'])) {
2474
+			EE_Error::overwrite_success();
2475
+			$this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2476
+			$override = true;
2477
+		}
2478
+        
2479
+		if (empty($query_args)) {
2480
+			$query_args = array(
2481
+				'id'      => $this->_req_data['GRP_ID'],
2482
+				'context' => $context_slug,
2483
+				'action'  => 'edit_message_template'
2484
+			);
2485
+		}
2486
+        
2487
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
2488
+	}
2489
+    
2490
+    
2491
+	/**
2492
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
2493
+	 *
2494
+	 * @param  string $context      what context being tested
2495
+	 * @param  string $messenger    messenger being tested
2496
+	 * @param  string $message_type message type being tested
2497
+	 *
2498
+	 */
2499
+	protected function _do_test_send($context, $messenger, $message_type)
2500
+	{
2501
+		//set things up for preview
2502
+		$this->_req_data['messenger']    = $messenger;
2503
+		$this->_req_data['message_type'] = $message_type;
2504
+		$this->_req_data['context']      = $context;
2505
+		$this->_req_data['GRP_ID']       = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
2506
+		$active_messenger                = $this->_message_resource_manager->get_active_messenger($messenger);
2507
+        
2508
+		//let's save any existing fields that might be required by the messenger
2509
+		if (
2510
+			isset($this->_req_data['test_settings_fld'])
2511
+			&& $active_messenger instanceof EE_messenger
2512
+		) {
2513
+			$active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
2514
+		}
2515
+        
2516
+		$success = $this->_preview_message(true);
2517
+        
2518
+		if ($success) {
2519
+			EE_Error::add_success(__('Test message sent', 'event_espresso'));
2520
+		} else {
2521
+			EE_Error::add_error(__('The test message was not sent', 'event_espresso'), __FILE__, __FUNCTION__,
2522
+				__LINE__);
2523
+		}
2524
+	}
2525
+    
2526
+    
2527
+	/**
2528
+	 * _generate_new_templates
2529
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
2530
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
2531
+	 * for the event.
2532
+	 *
2533
+	 *
2534
+	 * @param  string $messenger     the messenger we are generating templates for
2535
+	 * @param array   $message_types array of message types that the templates are generated for.
2536
+	 * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
2537
+	 *                               indicate the message_template_group being used as the base.
2538
+	 *
2539
+	 * @param bool    $global
2540
+	 *
2541
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
2542
+	 *                               encountering problems.
2543
+	 * @throws \EE_Error
2544
+	 */
2545
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
2546
+	{
2547
+        
2548
+		//if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we just don't generate any templates.
2549
+		if (empty($message_types)) {
2550
+			return true;
2551
+		}
2552
+        
2553
+		return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
2554
+	}
2555
+    
2556
+    
2557
+	/**
2558
+	 * [_trash_or_restore_message_template]
2559
+	 *
2560
+	 * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
2561
+	 * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
2562
+	 *                        an individual context (FALSE).
2563
+	 *
2564
+	 * @return void
2565
+	 */
2566
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
2567
+	{
2568
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2569
+		$MTP = EEM_Message_Template_Group::instance();
2570
+        
2571
+		$success = 1;
2572
+        
2573
+		//incoming GRP_IDs
2574
+		if ($all) {
2575
+			//Checkboxes
2576
+			if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2577
+				//if array has more than one element then success message should be plural.
2578
+				//todo: what about nonce?
2579
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2580 2580
                 
2581
-                //cycle through checkboxes
2582
-                while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2583
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2584
-                    if ( ! $trashed_or_restored) {
2585
-                        $success = 0;
2586
-                    }
2587
-                }
2588
-            } else {
2589
-                //grab single GRP_ID and handle
2590
-                $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
2591
-                if ( ! empty($GRP_ID)) {
2592
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2593
-                    if ( ! $trashed_or_restored) {
2594
-                        $success = 0;
2595
-                    }
2596
-                } else {
2597
-                    $success = 0;
2598
-                }
2599
-            }
2581
+				//cycle through checkboxes
2582
+				while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2583
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2584
+					if ( ! $trashed_or_restored) {
2585
+						$success = 0;
2586
+					}
2587
+				}
2588
+			} else {
2589
+				//grab single GRP_ID and handle
2590
+				$GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
2591
+				if ( ! empty($GRP_ID)) {
2592
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
2593
+					if ( ! $trashed_or_restored) {
2594
+						$success = 0;
2595
+					}
2596
+				} else {
2597
+					$success = 0;
2598
+				}
2599
+			}
2600 2600
             
2601
-        }
2601
+		}
2602 2602
         
2603
-        $action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2603
+		$action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2604 2604
         
2605
-        $action_desc = ! empty($this->_req_data['template_switch']) ? __('switched') : $action_desc;
2605
+		$action_desc = ! empty($this->_req_data['template_switch']) ? __('switched') : $action_desc;
2606 2606
         
2607
-        $item_desc = $all ? _n('Message Template Group', 'Message Template Groups', $success,
2608
-            'event_espresso') : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
2607
+		$item_desc = $all ? _n('Message Template Group', 'Message Template Groups', $success,
2608
+			'event_espresso') : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
2609 2609
         
2610
-        $item_desc = ! empty($this->_req_data['template_switch']) ? _n('template', 'templates', $success,
2611
-            'event_espresso') : $item_desc;
2610
+		$item_desc = ! empty($this->_req_data['template_switch']) ? _n('template', 'templates', $success,
2611
+			'event_espresso') : $item_desc;
2612 2612
         
2613
-        $this->_redirect_after_action($success, $item_desc, $action_desc, array());
2613
+		$this->_redirect_after_action($success, $item_desc, $action_desc, array());
2614 2614
         
2615
-    }
2615
+	}
2616 2616
     
2617 2617
     
2618
-    /**
2619
-     * [_delete_message_template]
2620
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
2621
-     * @return void
2622
-     */
2623
-    protected function _delete_message_template()
2624
-    {
2625
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2618
+	/**
2619
+	 * [_delete_message_template]
2620
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
2621
+	 * @return void
2622
+	 */
2623
+	protected function _delete_message_template()
2624
+	{
2625
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2626 2626
         
2627
-        //checkboxes
2628
-        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2629
-            //if array has more than one element then success message should be plural
2630
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2627
+		//checkboxes
2628
+		if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2629
+			//if array has more than one element then success message should be plural
2630
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2631 2631
             
2632
-            //cycle through bulk action checkboxes
2633
-            while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2634
-                $success = $this->_delete_mtp_permanently($GRP_ID);
2635
-            }
2636
-        } else {
2637
-            //grab single grp_id and delete
2638
-            $GRP_ID  = absint($this->_req_data['id']);
2639
-            $success = $this->_delete_mtp_permanently($GRP_ID);
2640
-        }
2641
-        
2642
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
2643
-        
2644
-    }
2645
-    
2646
-    
2647
-    /**
2648
-     * helper for permanently deleting a mtP group and all related message_templates
2649
-     *
2650
-     * @param  int  $GRP_ID        The group being deleted
2651
-     * @param  bool $include_group whether to delete the Message Template Group as well.
2652
-     *
2653
-     * @return bool        boolean to indicate the success of the deletes or not.
2654
-     */
2655
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
2656
-    {
2657
-        $success = 1;
2658
-        $MTPG    = EEM_Message_Template_Group::instance();
2659
-        //first let's GET this group
2660
-        $MTG = $MTPG->get_one_by_ID($GRP_ID);
2661
-        //then delete permanently all the related Message Templates
2662
-        $deleted = $MTG->delete_related_permanently('Message_Template');
2663
-        
2664
-        if ($deleted === 0) {
2665
-            $success = 0;
2666
-        }
2667
-        
2668
-        //now delete permanently this particular group
2669
-        
2670
-        if ($include_group && ! $MTG->delete_permanently()) {
2671
-            $success = 0;
2672
-        }
2673
-        
2674
-        return $success;
2675
-    }
2676
-    
2677
-    
2678
-    /**
2679
-     *    _learn_more_about_message_templates_link
2680
-     * @access protected
2681
-     * @return string
2682
-     */
2683
-    protected function _learn_more_about_message_templates_link()
2684
-    {
2685
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __('learn more about how message templates works',
2686
-            'event_espresso') . '</a>';
2687
-    }
2688
-    
2689
-    
2690
-    /**
2691
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
2692
-     * ajax and other routes.
2693
-     * @return void
2694
-     */
2695
-    protected function _settings()
2696
-    {
2697
-        
2698
-        
2699
-        $this->_set_m_mt_settings();
2700
-        
2701
-        $selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2702
-        
2703
-        //let's setup the messenger tabs
2704
-        $this->_template_args['admin_page_header']         = EEH_Tabbed_Content::tab_text_links($this->_m_mt_settings['messenger_tabs'],
2705
-            'messenger_links', '|', $selected_messenger);
2706
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
2707
-        $this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
2708
-        
2709
-        $this->display_admin_page_with_sidebar();
2710
-        
2711
-    }
2712
-    
2713
-    
2714
-    /**
2715
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
2716
-     *
2717
-     * @access protected
2718
-     * @return void
2719
-     */
2720
-    protected function _set_m_mt_settings()
2721
-    {
2722
-        //first if this is already set then lets get out no need to regenerate data.
2723
-        if ( ! empty($this->_m_mt_settings)) {
2724
-            return;
2725
-        }
2726
-        
2727
-        //$selected_messenger = isset( $this->_req_data['selected_messenger'] ) ? $this->_req_data['selected_messenger'] : 'email';
2728
-        
2729
-        //get all installed messengers and message_types
2730
-        /** @type EE_messenger[] $messengers */
2731
-        $messengers = $this->_message_resource_manager->installed_messengers();
2732
-        /** @type EE_message_type[] $message_types */
2733
-        $message_types = $this->_message_resource_manager->installed_message_types();
2734
-        
2735
-        
2736
-        //assemble the array for the _tab_text_links helper
2737
-        
2738
-        foreach ($messengers as $messenger) {
2739
-            $this->_m_mt_settings['messenger_tabs'][$messenger->name] = array(
2740
-                'label' => ucwords($messenger->label['singular']),
2741
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name) ? 'messenger-active' : '',
2742
-                'href'  => $messenger->name,
2743
-                'title' => __('Modify this Messenger', 'event_espresso'),
2744
-                'slug'  => $messenger->name,
2745
-                'obj'   => $messenger
2746
-            );
2632
+			//cycle through bulk action checkboxes
2633
+			while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
2634
+				$success = $this->_delete_mtp_permanently($GRP_ID);
2635
+			}
2636
+		} else {
2637
+			//grab single grp_id and delete
2638
+			$GRP_ID  = absint($this->_req_data['id']);
2639
+			$success = $this->_delete_mtp_permanently($GRP_ID);
2640
+		}
2641
+        
2642
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
2643
+        
2644
+	}
2645
+    
2646
+    
2647
+	/**
2648
+	 * helper for permanently deleting a mtP group and all related message_templates
2649
+	 *
2650
+	 * @param  int  $GRP_ID        The group being deleted
2651
+	 * @param  bool $include_group whether to delete the Message Template Group as well.
2652
+	 *
2653
+	 * @return bool        boolean to indicate the success of the deletes or not.
2654
+	 */
2655
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
2656
+	{
2657
+		$success = 1;
2658
+		$MTPG    = EEM_Message_Template_Group::instance();
2659
+		//first let's GET this group
2660
+		$MTG = $MTPG->get_one_by_ID($GRP_ID);
2661
+		//then delete permanently all the related Message Templates
2662
+		$deleted = $MTG->delete_related_permanently('Message_Template');
2663
+        
2664
+		if ($deleted === 0) {
2665
+			$success = 0;
2666
+		}
2667
+        
2668
+		//now delete permanently this particular group
2669
+        
2670
+		if ($include_group && ! $MTG->delete_permanently()) {
2671
+			$success = 0;
2672
+		}
2673
+        
2674
+		return $success;
2675
+	}
2676
+    
2677
+    
2678
+	/**
2679
+	 *    _learn_more_about_message_templates_link
2680
+	 * @access protected
2681
+	 * @return string
2682
+	 */
2683
+	protected function _learn_more_about_message_templates_link()
2684
+	{
2685
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __('learn more about how message templates works',
2686
+			'event_espresso') . '</a>';
2687
+	}
2688
+    
2689
+    
2690
+	/**
2691
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
2692
+	 * ajax and other routes.
2693
+	 * @return void
2694
+	 */
2695
+	protected function _settings()
2696
+	{
2697
+        
2698
+        
2699
+		$this->_set_m_mt_settings();
2700
+        
2701
+		$selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2702
+        
2703
+		//let's setup the messenger tabs
2704
+		$this->_template_args['admin_page_header']         = EEH_Tabbed_Content::tab_text_links($this->_m_mt_settings['messenger_tabs'],
2705
+			'messenger_links', '|', $selected_messenger);
2706
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
2707
+		$this->_template_args['after_admin_page_content']  = '</div><!-- end .ui-widget -->';
2708
+        
2709
+		$this->display_admin_page_with_sidebar();
2710
+        
2711
+	}
2712
+    
2713
+    
2714
+	/**
2715
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
2716
+	 *
2717
+	 * @access protected
2718
+	 * @return void
2719
+	 */
2720
+	protected function _set_m_mt_settings()
2721
+	{
2722
+		//first if this is already set then lets get out no need to regenerate data.
2723
+		if ( ! empty($this->_m_mt_settings)) {
2724
+			return;
2725
+		}
2726
+        
2727
+		//$selected_messenger = isset( $this->_req_data['selected_messenger'] ) ? $this->_req_data['selected_messenger'] : 'email';
2728
+        
2729
+		//get all installed messengers and message_types
2730
+		/** @type EE_messenger[] $messengers */
2731
+		$messengers = $this->_message_resource_manager->installed_messengers();
2732
+		/** @type EE_message_type[] $message_types */
2733
+		$message_types = $this->_message_resource_manager->installed_message_types();
2734
+        
2735
+        
2736
+		//assemble the array for the _tab_text_links helper
2737
+        
2738
+		foreach ($messengers as $messenger) {
2739
+			$this->_m_mt_settings['messenger_tabs'][$messenger->name] = array(
2740
+				'label' => ucwords($messenger->label['singular']),
2741
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name) ? 'messenger-active' : '',
2742
+				'href'  => $messenger->name,
2743
+				'title' => __('Modify this Messenger', 'event_espresso'),
2744
+				'slug'  => $messenger->name,
2745
+				'obj'   => $messenger
2746
+			);
2747 2747
             
2748 2748
             
2749
-            $message_types_for_messenger = $messenger->get_valid_message_types();
2749
+			$message_types_for_messenger = $messenger->get_valid_message_types();
2750 2750
             
2751
-            foreach ($message_types as $message_type) {
2752
-                //first we need to verify that this message type is valid with this messenger. Cause if it isn't then it shouldn't show in either the inactive OR active metabox.
2753
-                if ( ! in_array($message_type->name, $message_types_for_messenger)) {
2754
-                    continue;
2755
-                }
2751
+			foreach ($message_types as $message_type) {
2752
+				//first we need to verify that this message type is valid with this messenger. Cause if it isn't then it shouldn't show in either the inactive OR active metabox.
2753
+				if ( ! in_array($message_type->name, $message_types_for_messenger)) {
2754
+					continue;
2755
+				}
2756 2756
                 
2757
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger($messenger->name,
2758
-                    $message_type->name) ? 'active' : 'inactive';
2757
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger($messenger->name,
2758
+					$message_type->name) ? 'active' : 'inactive';
2759 2759
                 
2760
-                $this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
2761
-                    'label'    => ucwords($message_type->label['singular']),
2762
-                    'class'    => 'message-type-' . $a_or_i,
2763
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
2764
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
2765
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
2766
-                    'title'    => $a_or_i == 'active'
2767
-                        ? __('Drag this message type to the Inactive window to deactivate', 'event_espresso')
2768
-                        : __('Drag this message type to the messenger to activate', 'event_espresso'),
2769
-                    'content'  => $a_or_i == 'active'
2770
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
2771
-                        : $this->_message_type_settings_content($message_type, $messenger),
2772
-                    'slug'     => $message_type->name,
2773
-                    'active'   => $a_or_i == 'active' ? true : false,
2774
-                    'obj'      => $message_type
2775
-                );
2776
-            }
2777
-        }
2778
-    }
2779
-    
2780
-    
2781
-    /**
2782
-     * This just prepares the content for the message type settings
2783
-     *
2784
-     * @param  object  $message_type The message type object
2785
-     * @param  object  $messenger    The messenger object
2786
-     * @param  boolean $active       Whether the message type is active or not
2787
-     *
2788
-     * @return string                html output for the content
2789
-     */
2790
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
2791
-    {
2792
-        //get message type fields
2793
-        $fields                                         = $message_type->get_admin_settings_fields();
2794
-        $settings_template_args['template_form_fields'] = '';
2795
-        
2796
-        if ( ! empty($fields) && $active) {
2760
+				$this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
2761
+					'label'    => ucwords($message_type->label['singular']),
2762
+					'class'    => 'message-type-' . $a_or_i,
2763
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
2764
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
2765
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
2766
+					'title'    => $a_or_i == 'active'
2767
+						? __('Drag this message type to the Inactive window to deactivate', 'event_espresso')
2768
+						: __('Drag this message type to the messenger to activate', 'event_espresso'),
2769
+					'content'  => $a_or_i == 'active'
2770
+						? $this->_message_type_settings_content($message_type, $messenger, true)
2771
+						: $this->_message_type_settings_content($message_type, $messenger),
2772
+					'slug'     => $message_type->name,
2773
+					'active'   => $a_or_i == 'active' ? true : false,
2774
+					'obj'      => $message_type
2775
+				);
2776
+			}
2777
+		}
2778
+	}
2779
+    
2780
+    
2781
+	/**
2782
+	 * This just prepares the content for the message type settings
2783
+	 *
2784
+	 * @param  object  $message_type The message type object
2785
+	 * @param  object  $messenger    The messenger object
2786
+	 * @param  boolean $active       Whether the message type is active or not
2787
+	 *
2788
+	 * @return string                html output for the content
2789
+	 */
2790
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
2791
+	{
2792
+		//get message type fields
2793
+		$fields                                         = $message_type->get_admin_settings_fields();
2794
+		$settings_template_args['template_form_fields'] = '';
2795
+        
2796
+		if ( ! empty($fields) && $active) {
2797 2797
             
2798
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
2798
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
2799 2799
             
2800
-            foreach ($fields as $fldname => $fldprops) {
2801
-                $field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
2802
-                $template_form_field[$field_id] = array(
2803
-                    'name'       => 'message_type_settings[' . $fldname . ']',
2804
-                    'label'      => $fldprops['label'],
2805
-                    'input'      => $fldprops['field_type'],
2806
-                    'type'       => $fldprops['value_type'],
2807
-                    'required'   => $fldprops['required'],
2808
-                    'validation' => $fldprops['validation'],
2809
-                    'value'      => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2810
-                    'options'    => isset($fldprops['options']) ? $fldprops['options'] : array(),
2811
-                    'default'    => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2812
-                    'css_class'  => 'no-drag',
2813
-                    'format'     => $fldprops['format']
2814
-                );
2815
-            }
2800
+			foreach ($fields as $fldname => $fldprops) {
2801
+				$field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
2802
+				$template_form_field[$field_id] = array(
2803
+					'name'       => 'message_type_settings[' . $fldname . ']',
2804
+					'label'      => $fldprops['label'],
2805
+					'input'      => $fldprops['field_type'],
2806
+					'type'       => $fldprops['value_type'],
2807
+					'required'   => $fldprops['required'],
2808
+					'validation' => $fldprops['validation'],
2809
+					'value'      => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2810
+					'options'    => isset($fldprops['options']) ? $fldprops['options'] : array(),
2811
+					'default'    => isset($existing_settings[$fldname]) ? $existing_settings[$fldname] : $fldprops['default'],
2812
+					'css_class'  => 'no-drag',
2813
+					'format'     => $fldprops['format']
2814
+				);
2815
+			}
2816 2816
             
2817 2817
             
2818
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field) ? $this->_generate_admin_form_fields($template_form_field,
2819
-                'string', 'ee_mt_activate_form') : '';
2820
-        }
2821
-        
2822
-        $settings_template_args['description'] = $message_type->description;
2823
-        //we also need some hidden fields
2824
-        $settings_template_args['hidden_fields'] = array(
2825
-            'message_type_settings[messenger]'    => array(
2826
-                'type'  => 'hidden',
2827
-                'value' => $messenger->name
2828
-            ),
2829
-            'message_type_settings[message_type]' => array(
2830
-                'type'  => 'hidden',
2831
-                'value' => $message_type->name
2832
-            ),
2833
-            'type'                                => array(
2834
-                'type'  => 'hidden',
2835
-                'value' => 'message_type'
2836
-            )
2837
-        );
2838
-        
2839
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields($settings_template_args['hidden_fields'],
2840
-            'array');
2841
-        $settings_template_args['show_form']     = empty($settings_template_args['template_form_fields']) ? ' hidden' : '';
2842
-        
2843
-        
2844
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
2845
-        $content  = EEH_Template::display_template($template, $settings_template_args, true);
2846
-        
2847
-        return $content;
2848
-    }
2849
-    
2850
-    
2851
-    /**
2852
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
2853
-     *
2854
-     * @access protected
2855
-     * @return void
2856
-     */
2857
-    protected function _messages_settings_metaboxes()
2858
-    {
2859
-        $this->_set_m_mt_settings();
2860
-        $m_boxes         = $mt_boxes = array();
2861
-        $m_template_args = $mt_template_args = array();
2862
-        
2863
-        $selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2864
-        
2865
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
2866
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
2867
-                $hide_on_message  = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
2868
-                $hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
2869
-                //messenger meta boxes
2870
-                $active                                 = $selected_messenger == $messenger ? true : false;
2871
-                $active_mt_tabs                         = isset($this->_m_mt_settings['message_type_tabs'][$messenger]['active'])
2872
-                    ? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
2873
-                    : '';
2874
-                $m_boxes[$messenger . '_a_box']         = sprintf(
2875
-                    __('%s Settings', 'event_espresso'),
2876
-                    $tab_array['label']
2877
-                );
2878
-                $m_template_args[$messenger . '_a_box'] = array(
2879
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2880
-                    'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2881
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2882
-                        : '',
2883
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
2884
-                    'hidden'                 => $active ? '' : ' hidden',
2885
-                    'hide_on_message'        => $hide_on_message,
2886
-                    'messenger'              => $messenger,
2887
-                    'active'                 => $active
2888
-                );
2889
-                // message type meta boxes
2890
-                // (which is really just the inactive container for each messenger
2891
-                // showing inactive message types for that messenger)
2892
-                $mt_boxes[$messenger . '_i_box']         = __('Inactive Message Types', 'event_espresso');
2893
-                $mt_template_args[$messenger . '_i_box'] = array(
2894
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2895
-                    'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2896
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2897
-                        : '',
2898
-                    'hidden'                 => $active ? '' : ' hidden',
2899
-                    'hide_on_message'        => $hide_on_message,
2900
-                    'hide_off_message'       => $hide_off_message,
2901
-                    'messenger'              => $messenger,
2902
-                    'active'                 => $active
2903
-                );
2904
-            }
2905
-        }
2906
-        
2907
-        
2908
-        //register messenger metaboxes
2909
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
2910
-        foreach ($m_boxes as $box => $label) {
2911
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
2912
-            $msgr          = str_replace('_a_box', '', $box);
2913
-            add_meta_box(
2914
-                'espresso_' . $msgr . '_settings',
2915
-                $label,
2916
-                function ($post, $metabox) {
2917
-                    echo EEH_Template::display_template($metabox["args"]["template_path"],
2918
-                        $metabox["args"]["template_args"], true);
2919
-                },
2920
-                $this->_current_screen->id,
2921
-                'normal',
2922
-                'high',
2923
-                $callback_args
2924
-            );
2925
-        }
2926
-        
2927
-        //register message type metaboxes
2928
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
2929
-        foreach ($mt_boxes as $box => $label) {
2930
-            $callback_args = array(
2931
-                'template_path' => $mt_template_path,
2932
-                'template_args' => $mt_template_args[$box]
2933
-            );
2934
-            $mt            = str_replace('_i_box', '', $box);
2935
-            add_meta_box(
2936
-                'espresso_' . $mt . '_inactive_mts',
2937
-                $label,
2938
-                function ($post, $metabox) {
2939
-                    echo EEH_Template::display_template($metabox["args"]["template_path"],
2940
-                        $metabox["args"]["template_args"], true);
2941
-                },
2942
-                $this->_current_screen->id,
2943
-                'side',
2944
-                'high',
2945
-                $callback_args
2946
-            );
2947
-        }
2948
-        
2949
-        //register metabox for global messages settings but only when on the main site.  On single site installs this will
2950
-        //always result in the metabox showing, on multisite installs the metabox will only show on the main site.
2951
-        if (is_main_site()) {
2952
-            add_meta_box(
2953
-                'espresso_global_message_settings',
2954
-                __('Global Message Settings', 'event_espresso'),
2955
-                array($this, 'global_messages_settings_metabox_content'),
2956
-                $this->_current_screen->id,
2957
-                'normal',
2958
-                'low',
2959
-                array()
2960
-            );
2961
-        }
2962
-        
2963
-    }
2964
-    
2965
-    
2966
-    /**
2967
-     *  This generates the content for the global messages settings metabox.
2968
-     * @return string
2969
-     */
2970
-    public function global_messages_settings_metabox_content()
2971
-    {
2972
-        $form = $this->_generate_global_settings_form();
2973
-        echo $form->form_open(
2974
-                $this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
2975
-                'POST'
2976
-            )
2977
-             . $form->get_html()
2978
-             . $form->form_close();
2979
-    }
2980
-    
2981
-    
2982
-    /**
2983
-     * This generates and returns the form object for the global messages settings.
2984
-     * @return EE_Form_Section_Proper
2985
-     */
2986
-    protected function _generate_global_settings_form()
2987
-    {
2988
-        EE_Registry::instance()->load_helper('HTML');
2989
-        /** @var EE_Network_Core_Config $network_config */
2990
-        $network_config = EE_Registry::instance()->NET_CFG->core;
2991
-        
2992
-        return new EE_Form_Section_Proper(
2993
-            array(
2994
-                'name'            => 'global_messages_settings',
2995
-                'html_id'         => 'global_messages_settings',
2996
-                'html_class'      => 'form-table',
2997
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2998
-                'subsections'     => apply_filters(
2999
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3000
-                    array(
3001
-                        'do_messages_on_same_request' => new EE_Select_Input(
3002
-                            array(
3003
-                                true  => __("On the same request", "event_espresso"),
3004
-                                false => __("On a separate request", "event_espresso")
3005
-                            ),
3006
-                            array(
3007
-                                'default'         => $network_config->do_messages_on_same_request,
3008
-                                'html_label_text' => __('Generate and send all messages:', 'event_espresso'),
3009
-                                'html_help_text'  => __('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.',
3010
-                                    'event_espresso'),
3011
-                            )
3012
-                        ),
3013
-                        'update_settings'             => new EE_Submit_Input(
3014
-                            array(
3015
-                                'default'         => __('Update', 'event_espresso'),
3016
-                                'html_label_text' => '&nbsp'
3017
-                            )
3018
-                        )
3019
-                    )
3020
-                )
3021
-            )
3022
-        );
3023
-    }
3024
-    
3025
-    
3026
-    /**
3027
-     * This handles updating the global settings set on the admin page.
3028
-     * @throws \EE_Error
3029
-     */
3030
-    protected function _update_global_settings()
3031
-    {
3032
-        /** @var EE_Network_Core_Config $network_config */
3033
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3034
-        $form           = $this->_generate_global_settings_form();
3035
-        if ($form->was_submitted()) {
3036
-            $form->receive_form_submission();
3037
-            if ($form->is_valid()) {
3038
-                $valid_data = $form->valid_data();
3039
-                foreach ($valid_data as $property => $value) {
3040
-                    $setter = 'set_' . $property;
3041
-                    if (method_exists($network_config, $setter)) {
3042
-                        $network_config->{$setter}($value);
3043
-                    } else if (
3044
-                        property_exists($network_config, $property)
3045
-                        && $network_config->{$property} !== $value
3046
-                    ) {
3047
-                        $network_config->{$property} = $value;
3048
-                    }
3049
-                }
3050
-                //only update if the form submission was valid!
3051
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3052
-                EE_Error::overwrite_success();
3053
-                EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3054
-            }
3055
-        }
3056
-        $this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3057
-    }
3058
-    
3059
-    
3060
-    /**
3061
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3062
-     *
3063
-     * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3064
-     *
3065
-     * @return string            html formatted tabs
3066
-     */
3067
-    protected function _get_mt_tabs($tab_array)
3068
-    {
3069
-        $tab_array = (array)$tab_array;
3070
-        $template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3071
-        $tabs      = '';
3072
-        
3073
-        foreach ($tab_array as $tab) {
3074
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3075
-        }
3076
-        
3077
-        return $tabs;
3078
-    }
3079
-    
3080
-    
3081
-    /**
3082
-     * This prepares the content of the messenger meta box admin settings
3083
-     *
3084
-     * @param  EE_messenger $messenger The messenger we're setting up content for
3085
-     *
3086
-     * @return string            html formatted content
3087
-     */
3088
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3089
-    {
3090
-        
3091
-        $fields                                         = $messenger->get_admin_settings_fields();
3092
-        $settings_template_args['template_form_fields'] = '';
3093
-        
3094
-        //is $messenger active?
3095
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3096
-        
3097
-        
3098
-        if ( ! empty($fields)) {
2818
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field) ? $this->_generate_admin_form_fields($template_form_field,
2819
+				'string', 'ee_mt_activate_form') : '';
2820
+		}
2821
+        
2822
+		$settings_template_args['description'] = $message_type->description;
2823
+		//we also need some hidden fields
2824
+		$settings_template_args['hidden_fields'] = array(
2825
+			'message_type_settings[messenger]'    => array(
2826
+				'type'  => 'hidden',
2827
+				'value' => $messenger->name
2828
+			),
2829
+			'message_type_settings[message_type]' => array(
2830
+				'type'  => 'hidden',
2831
+				'value' => $message_type->name
2832
+			),
2833
+			'type'                                => array(
2834
+				'type'  => 'hidden',
2835
+				'value' => 'message_type'
2836
+			)
2837
+		);
2838
+        
2839
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields($settings_template_args['hidden_fields'],
2840
+			'array');
2841
+		$settings_template_args['show_form']     = empty($settings_template_args['template_form_fields']) ? ' hidden' : '';
2842
+        
2843
+        
2844
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
2845
+		$content  = EEH_Template::display_template($template, $settings_template_args, true);
2846
+        
2847
+		return $content;
2848
+	}
2849
+    
2850
+    
2851
+	/**
2852
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
2853
+	 *
2854
+	 * @access protected
2855
+	 * @return void
2856
+	 */
2857
+	protected function _messages_settings_metaboxes()
2858
+	{
2859
+		$this->_set_m_mt_settings();
2860
+		$m_boxes         = $mt_boxes = array();
2861
+		$m_template_args = $mt_template_args = array();
2862
+        
2863
+		$selected_messenger = isset($this->_req_data['selected_messenger']) ? $this->_req_data['selected_messenger'] : 'email';
2864
+        
2865
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
2866
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
2867
+				$hide_on_message  = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
2868
+				$hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
2869
+				//messenger meta boxes
2870
+				$active                                 = $selected_messenger == $messenger ? true : false;
2871
+				$active_mt_tabs                         = isset($this->_m_mt_settings['message_type_tabs'][$messenger]['active'])
2872
+					? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
2873
+					: '';
2874
+				$m_boxes[$messenger . '_a_box']         = sprintf(
2875
+					__('%s Settings', 'event_espresso'),
2876
+					$tab_array['label']
2877
+				);
2878
+				$m_template_args[$messenger . '_a_box'] = array(
2879
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2880
+					'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2881
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2882
+						: '',
2883
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
2884
+					'hidden'                 => $active ? '' : ' hidden',
2885
+					'hide_on_message'        => $hide_on_message,
2886
+					'messenger'              => $messenger,
2887
+					'active'                 => $active
2888
+				);
2889
+				// message type meta boxes
2890
+				// (which is really just the inactive container for each messenger
2891
+				// showing inactive message types for that messenger)
2892
+				$mt_boxes[$messenger . '_i_box']         = __('Inactive Message Types', 'event_espresso');
2893
+				$mt_template_args[$messenger . '_i_box'] = array(
2894
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2895
+					'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2896
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2897
+						: '',
2898
+					'hidden'                 => $active ? '' : ' hidden',
2899
+					'hide_on_message'        => $hide_on_message,
2900
+					'hide_off_message'       => $hide_off_message,
2901
+					'messenger'              => $messenger,
2902
+					'active'                 => $active
2903
+				);
2904
+			}
2905
+		}
2906
+        
2907
+        
2908
+		//register messenger metaboxes
2909
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
2910
+		foreach ($m_boxes as $box => $label) {
2911
+			$callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
2912
+			$msgr          = str_replace('_a_box', '', $box);
2913
+			add_meta_box(
2914
+				'espresso_' . $msgr . '_settings',
2915
+				$label,
2916
+				function ($post, $metabox) {
2917
+					echo EEH_Template::display_template($metabox["args"]["template_path"],
2918
+						$metabox["args"]["template_args"], true);
2919
+				},
2920
+				$this->_current_screen->id,
2921
+				'normal',
2922
+				'high',
2923
+				$callback_args
2924
+			);
2925
+		}
2926
+        
2927
+		//register message type metaboxes
2928
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
2929
+		foreach ($mt_boxes as $box => $label) {
2930
+			$callback_args = array(
2931
+				'template_path' => $mt_template_path,
2932
+				'template_args' => $mt_template_args[$box]
2933
+			);
2934
+			$mt            = str_replace('_i_box', '', $box);
2935
+			add_meta_box(
2936
+				'espresso_' . $mt . '_inactive_mts',
2937
+				$label,
2938
+				function ($post, $metabox) {
2939
+					echo EEH_Template::display_template($metabox["args"]["template_path"],
2940
+						$metabox["args"]["template_args"], true);
2941
+				},
2942
+				$this->_current_screen->id,
2943
+				'side',
2944
+				'high',
2945
+				$callback_args
2946
+			);
2947
+		}
2948
+        
2949
+		//register metabox for global messages settings but only when on the main site.  On single site installs this will
2950
+		//always result in the metabox showing, on multisite installs the metabox will only show on the main site.
2951
+		if (is_main_site()) {
2952
+			add_meta_box(
2953
+				'espresso_global_message_settings',
2954
+				__('Global Message Settings', 'event_espresso'),
2955
+				array($this, 'global_messages_settings_metabox_content'),
2956
+				$this->_current_screen->id,
2957
+				'normal',
2958
+				'low',
2959
+				array()
2960
+			);
2961
+		}
2962
+        
2963
+	}
2964
+    
2965
+    
2966
+	/**
2967
+	 *  This generates the content for the global messages settings metabox.
2968
+	 * @return string
2969
+	 */
2970
+	public function global_messages_settings_metabox_content()
2971
+	{
2972
+		$form = $this->_generate_global_settings_form();
2973
+		echo $form->form_open(
2974
+				$this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
2975
+				'POST'
2976
+			)
2977
+			 . $form->get_html()
2978
+			 . $form->form_close();
2979
+	}
2980
+    
2981
+    
2982
+	/**
2983
+	 * This generates and returns the form object for the global messages settings.
2984
+	 * @return EE_Form_Section_Proper
2985
+	 */
2986
+	protected function _generate_global_settings_form()
2987
+	{
2988
+		EE_Registry::instance()->load_helper('HTML');
2989
+		/** @var EE_Network_Core_Config $network_config */
2990
+		$network_config = EE_Registry::instance()->NET_CFG->core;
2991
+        
2992
+		return new EE_Form_Section_Proper(
2993
+			array(
2994
+				'name'            => 'global_messages_settings',
2995
+				'html_id'         => 'global_messages_settings',
2996
+				'html_class'      => 'form-table',
2997
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
2998
+				'subsections'     => apply_filters(
2999
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3000
+					array(
3001
+						'do_messages_on_same_request' => new EE_Select_Input(
3002
+							array(
3003
+								true  => __("On the same request", "event_espresso"),
3004
+								false => __("On a separate request", "event_espresso")
3005
+							),
3006
+							array(
3007
+								'default'         => $network_config->do_messages_on_same_request,
3008
+								'html_label_text' => __('Generate and send all messages:', 'event_espresso'),
3009
+								'html_help_text'  => __('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.',
3010
+									'event_espresso'),
3011
+							)
3012
+						),
3013
+						'update_settings'             => new EE_Submit_Input(
3014
+							array(
3015
+								'default'         => __('Update', 'event_espresso'),
3016
+								'html_label_text' => '&nbsp'
3017
+							)
3018
+						)
3019
+					)
3020
+				)
3021
+			)
3022
+		);
3023
+	}
3024
+    
3025
+    
3026
+	/**
3027
+	 * This handles updating the global settings set on the admin page.
3028
+	 * @throws \EE_Error
3029
+	 */
3030
+	protected function _update_global_settings()
3031
+	{
3032
+		/** @var EE_Network_Core_Config $network_config */
3033
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3034
+		$form           = $this->_generate_global_settings_form();
3035
+		if ($form->was_submitted()) {
3036
+			$form->receive_form_submission();
3037
+			if ($form->is_valid()) {
3038
+				$valid_data = $form->valid_data();
3039
+				foreach ($valid_data as $property => $value) {
3040
+					$setter = 'set_' . $property;
3041
+					if (method_exists($network_config, $setter)) {
3042
+						$network_config->{$setter}($value);
3043
+					} else if (
3044
+						property_exists($network_config, $property)
3045
+						&& $network_config->{$property} !== $value
3046
+					) {
3047
+						$network_config->{$property} = $value;
3048
+					}
3049
+				}
3050
+				//only update if the form submission was valid!
3051
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3052
+				EE_Error::overwrite_success();
3053
+				EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3054
+			}
3055
+		}
3056
+		$this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3057
+	}
3058
+    
3059
+    
3060
+	/**
3061
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3062
+	 *
3063
+	 * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3064
+	 *
3065
+	 * @return string            html formatted tabs
3066
+	 */
3067
+	protected function _get_mt_tabs($tab_array)
3068
+	{
3069
+		$tab_array = (array)$tab_array;
3070
+		$template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3071
+		$tabs      = '';
3072
+        
3073
+		foreach ($tab_array as $tab) {
3074
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3075
+		}
3076
+        
3077
+		return $tabs;
3078
+	}
3079
+    
3080
+    
3081
+	/**
3082
+	 * This prepares the content of the messenger meta box admin settings
3083
+	 *
3084
+	 * @param  EE_messenger $messenger The messenger we're setting up content for
3085
+	 *
3086
+	 * @return string            html formatted content
3087
+	 */
3088
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3089
+	{
3090
+        
3091
+		$fields                                         = $messenger->get_admin_settings_fields();
3092
+		$settings_template_args['template_form_fields'] = '';
3093
+        
3094
+		//is $messenger active?
3095
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3096
+        
3097
+        
3098
+		if ( ! empty($fields)) {
3099 3099
             
3100
-            $existing_settings = $messenger->get_existing_admin_settings();
3100
+			$existing_settings = $messenger->get_existing_admin_settings();
3101 3101
             
3102
-            foreach ($fields as $fldname => $fldprops) {
3103
-                $field_id                       = $messenger->name . '-' . $fldname;
3104
-                $template_form_field[$field_id] = array(
3105
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3106
-                    'label'      => $fldprops['label'],
3107
-                    'input'      => $fldprops['field_type'],
3108
-                    'type'       => $fldprops['value_type'],
3109
-                    'required'   => $fldprops['required'],
3110
-                    'validation' => $fldprops['validation'],
3111
-                    'value'      => isset($existing_settings[$field_id])
3112
-                        ? $existing_settings[$field_id]
3113
-                        : $fldprops['default'],
3114
-                    'css_class'  => '',
3115
-                    'format'     => $fldprops['format']
3116
-                );
3117
-            }
3102
+			foreach ($fields as $fldname => $fldprops) {
3103
+				$field_id                       = $messenger->name . '-' . $fldname;
3104
+				$template_form_field[$field_id] = array(
3105
+					'name'       => 'messenger_settings[' . $field_id . ']',
3106
+					'label'      => $fldprops['label'],
3107
+					'input'      => $fldprops['field_type'],
3108
+					'type'       => $fldprops['value_type'],
3109
+					'required'   => $fldprops['required'],
3110
+					'validation' => $fldprops['validation'],
3111
+					'value'      => isset($existing_settings[$field_id])
3112
+						? $existing_settings[$field_id]
3113
+						: $fldprops['default'],
3114
+					'css_class'  => '',
3115
+					'format'     => $fldprops['format']
3116
+				);
3117
+			}
3118 3118
             
3119 3119
             
3120
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3121
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3122
-                : '';
3123
-        }
3124
-        
3125
-        //we also need some hidden fields
3126
-        $settings_template_args['hidden_fields'] = array(
3127
-            'messenger_settings[messenger]' => array(
3128
-                'type'  => 'hidden',
3129
-                'value' => $messenger->name
3130
-            ),
3131
-            'type'                          => array(
3132
-                'type'  => 'hidden',
3133
-                'value' => 'messenger'
3134
-            )
3135
-        );
3136
-        
3137
-        //make sure any active message types that are existing are included in the hidden fields
3138
-        if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3139
-            foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3140
-                $settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3141
-                    'type'  => 'hidden',
3142
-                    'value' => $mt
3143
-                );
3144
-            }
3145
-        }
3146
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3147
-            $settings_template_args['hidden_fields'],
3148
-            'array'
3149
-        );
3150
-        $active                                  = $this->_message_resource_manager->is_messenger_active($messenger->name);
3151
-        
3152
-        $settings_template_args['messenger']           = $messenger->name;
3153
-        $settings_template_args['description']         = $messenger->description;
3154
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3155
-        
3156
-        
3157
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active($messenger->name)
3158
-            ? $settings_template_args['show_hide_edit_form']
3159
-            : ' hidden';
3160
-        
3161
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3162
-            ? ' hidden'
3163
-            : $settings_template_args['show_hide_edit_form'];
3164
-        
3165
-        
3166
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3167
-        $settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3168
-        $settings_template_args['on_off_status'] = $active ? true : false;
3169
-        $template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3170
-        $content                                 = EEH_Template::display_template($template, $settings_template_args,
3171
-            true);
3172
-        
3173
-        return $content;
3174
-    }
3175
-    
3176
-    
3177
-    /**
3178
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3179
-     */
3180
-    public function activate_messenger_toggle()
3181
-    {
3182
-        $success = true;
3183
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3184
-        //let's check that we have required data
3185
-        if ( ! isset($this->_req_data['messenger'])) {
3186
-            EE_Error::add_error(
3187
-                __('Messenger name needed to toggle activation. None given', 'event_espresso'),
3188
-                __FILE__,
3189
-                __FUNCTION__,
3190
-                __LINE__
3191
-            );
3192
-            $success = false;
3193
-        }
3194
-        
3195
-        //do a nonce check here since we're not arriving via a normal route
3196
-        $nonce     = isset($this->_req_data['activate_nonce']) ? sanitize_text_field($this->_req_data['activate_nonce']) : '';
3197
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3198
-        
3199
-        $this->_verify_nonce($nonce, $nonce_ref);
3200
-        
3201
-        
3202
-        if ( ! isset($this->_req_data['status'])) {
3203
-            EE_Error::add_error(
3204
-                __(
3205
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3206
-                    'event_espresso'
3207
-                ),
3208
-                __FILE__,
3209
-                __FUNCTION__,
3210
-                __LINE__
3211
-            );
3212
-            $success = false;
3213
-        }
3214
-        
3215
-        //do check to verify we have a valid status.
3216
-        $status = $this->_req_data['status'];
3217
-        
3218
-        if ($status != 'off' && $status != 'on') {
3219
-            EE_Error::add_error(
3220
-                sprintf(
3221
-                    __('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3222
-                    $this->_req_data['status']
3223
-                ),
3224
-                __FILE__,
3225
-                __FUNCTION__,
3226
-                __LINE__
3227
-            );
3228
-            $success = false;
3229
-        }
3230
-        
3231
-        if ($success) {
3232
-            //made it here?  Stop dawdling then!!
3233
-            $success = $status == 'off'
3234
-                ? $this->_deactivate_messenger($this->_req_data['messenger'])
3235
-                : $this->_activate_messenger($this->_req_data['messenger']);
3236
-        }
3237
-        
3238
-        $this->_template_args['success'] = $success;
3239
-        
3240
-        //no special instructions so let's just do the json return (which should automatically do all the special stuff).
3241
-        $this->_return_json();
3242
-        
3243
-    }
3244
-    
3245
-    
3246
-    /**
3247
-     * used by ajax from the messages settings page to activate|deactivate a message type
3248
-     *
3249
-     */
3250
-    public function activate_mt_toggle()
3251
-    {
3252
-        $success = true;
3253
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3254
-        
3255
-        //let's make sure we have the necessary data
3256
-        if ( ! isset($this->_req_data['message_type'])) {
3257
-            EE_Error::add_error(
3258
-                __('Message Type name needed to toggle activation. None given', 'event_espresso'),
3259
-                __FILE__, __FUNCTION__, __LINE__
3260
-            );
3261
-            $success = false;
3262
-        }
3263
-        
3264
-        if ( ! isset($this->_req_data['messenger'])) {
3265
-            EE_Error::add_error(
3266
-                __('Messenger name needed to toggle activation. None given', 'event_espresso'),
3267
-                __FILE__, __FUNCTION__, __LINE__
3268
-            );
3269
-            $success = false;
3270
-        }
3271
-        
3272
-        if ( ! isset($this->_req_data['status'])) {
3273
-            EE_Error::add_error(
3274
-                __('Messenger status needed to know whether activation or deactivation is happening. No status is given',
3275
-                    'event_espresso'),
3276
-                __FILE__, __FUNCTION__, __LINE__
3277
-            );
3278
-            $success = false;
3279
-        }
3280
-        
3281
-        
3282
-        //do check to verify we have a valid status.
3283
-        $status = $this->_req_data['status'];
3284
-        
3285
-        if ($status != 'activate' && $status != 'deactivate') {
3286
-            EE_Error::add_error(
3287
-                sprintf(
3288
-                    __('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3289
-                    $this->_req_data['status']
3290
-                ),
3291
-                __FILE__, __FUNCTION__, __LINE__
3292
-            );
3293
-            $success = false;
3294
-        }
3295
-        
3296
-        
3297
-        //do a nonce check here since we're not arriving via a normal route
3298
-        $nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3299
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3300
-        
3301
-        $this->_verify_nonce($nonce, $nonce_ref);
3302
-        
3303
-        if ($success) {
3304
-            //made it here? um, what are you waiting for then?
3305
-            $success = $status == 'deactivate'
3306
-                ? $this->_deactivate_message_type_for_messenger($this->_req_data['messenger'],
3307
-                    $this->_req_data['message_type'])
3308
-                : $this->_activate_message_type_for_messenger($this->_req_data['messenger'],
3309
-                    $this->_req_data['message_type']);
3310
-        }
3311
-        
3312
-        $this->_template_args['success'] = $success;
3313
-        $this->_return_json();
3314
-    }
3315
-    
3316
-    
3317
-    /**
3318
-     * Takes care of processing activating a messenger and preparing the appropriate response.
3319
-     *
3320
-     * @param string $messenger_name The name of the messenger being activated
3321
-     *
3322
-     * @return bool
3323
-     */
3324
-    protected function _activate_messenger($messenger_name)
3325
-    {
3326
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3327
-        $active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
3328
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger ? $active_messenger->get_default_message_types() : array();
3329
-        
3330
-        //ensure is active
3331
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3332
-        
3333
-        //set response_data for reload
3334
-        foreach ($message_types_to_activate as $message_type_name) {
3335
-            /** @var EE_message_type $message_type */
3336
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3337
-            if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3338
-                    $message_type_name)
3339
-                && $message_type instanceof EE_message_type
3340
-            ) {
3341
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
3342
-                if ($message_type->get_admin_settings_fields()) {
3343
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
3344
-                }
3345
-            }
3346
-        }
3347
-        
3348
-        //add success message for activating messenger
3349
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3350
-        
3351
-    }
3352
-    
3353
-    
3354
-    /**
3355
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
3356
-     *
3357
-     * @param string $messenger_name The name of the messenger being activated
3358
-     *
3359
-     * @return bool
3360
-     */
3361
-    protected function _deactivate_messenger($messenger_name)
3362
-    {
3363
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3364
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3365
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
3366
-        
3367
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
3368
-    }
3369
-    
3370
-    
3371
-    /**
3372
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
3373
-     *
3374
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
3375
-     * @param string $message_type_name The name of the message type being activated for the messenger
3376
-     *
3377
-     * @return bool
3378
-     */
3379
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
3380
-    {
3381
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3382
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3383
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3384
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
3385
-        
3386
-        //ensure is active
3387
-        $this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
3388
-        
3389
-        //set response for load
3390
-        if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3391
-            $message_type_name)
3392
-        ) {
3393
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
3394
-            if ($message_type_to_activate->get_admin_settings_fields()) {
3395
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
3396
-            }
3397
-        }
3398
-        
3399
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger,
3400
-            $message_type_to_activate);
3401
-    }
3402
-    
3403
-    
3404
-    /**
3405
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
3406
-     *
3407
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
3408
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
3409
-     *
3410
-     * @return bool
3411
-     */
3412
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
3413
-    {
3414
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3415
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3416
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3417
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
3418
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
3419
-        
3420
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger,
3421
-            $message_type_to_deactivate);
3422
-    }
3423
-    
3424
-    
3425
-    /**
3426
-     * This just initializes the defaults for activating messenger and message type responses.
3427
-     */
3428
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
3429
-    {
3430
-        $this->_template_args['data']['active_mts'] = array();
3431
-        $this->_template_args['data']['mt_reload']  = array();
3432
-    }
3433
-    
3434
-    
3435
-    /**
3436
-     * Setup appropriate response for activating a messenger and/or message types
3437
-     *
3438
-     * @param EE_messenger         $messenger
3439
-     * @param EE_message_type|null $message_type
3440
-     *
3441
-     * @return bool
3442
-     * @throws EE_Error
3443
-     */
3444
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
3445
-        $messenger,
3446
-        EE_Message_Type $message_type = null
3447
-    ) {
3448
-        //if $messenger isn't a valid messenger object then get out.
3449
-        if ( ! $messenger instanceof EE_Messenger) {
3450
-            EE_Error::add_error(
3451
-                __('The messenger being activated is not a valid messenger', 'event_espresso'),
3452
-                __FILE__,
3453
-                __FUNCTION__,
3454
-                __LINE__
3455
-            );
3120
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3121
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3122
+				: '';
3123
+		}
3124
+        
3125
+		//we also need some hidden fields
3126
+		$settings_template_args['hidden_fields'] = array(
3127
+			'messenger_settings[messenger]' => array(
3128
+				'type'  => 'hidden',
3129
+				'value' => $messenger->name
3130
+			),
3131
+			'type'                          => array(
3132
+				'type'  => 'hidden',
3133
+				'value' => 'messenger'
3134
+			)
3135
+		);
3136
+        
3137
+		//make sure any active message types that are existing are included in the hidden fields
3138
+		if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3139
+			foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3140
+				$settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3141
+					'type'  => 'hidden',
3142
+					'value' => $mt
3143
+				);
3144
+			}
3145
+		}
3146
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3147
+			$settings_template_args['hidden_fields'],
3148
+			'array'
3149
+		);
3150
+		$active                                  = $this->_message_resource_manager->is_messenger_active($messenger->name);
3151
+        
3152
+		$settings_template_args['messenger']           = $messenger->name;
3153
+		$settings_template_args['description']         = $messenger->description;
3154
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3155
+        
3156
+        
3157
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active($messenger->name)
3158
+			? $settings_template_args['show_hide_edit_form']
3159
+			: ' hidden';
3160
+        
3161
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3162
+			? ' hidden'
3163
+			: $settings_template_args['show_hide_edit_form'];
3164
+        
3165
+        
3166
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3167
+		$settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3168
+		$settings_template_args['on_off_status'] = $active ? true : false;
3169
+		$template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3170
+		$content                                 = EEH_Template::display_template($template, $settings_template_args,
3171
+			true);
3172
+        
3173
+		return $content;
3174
+	}
3175
+    
3176
+    
3177
+	/**
3178
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3179
+	 */
3180
+	public function activate_messenger_toggle()
3181
+	{
3182
+		$success = true;
3183
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3184
+		//let's check that we have required data
3185
+		if ( ! isset($this->_req_data['messenger'])) {
3186
+			EE_Error::add_error(
3187
+				__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3188
+				__FILE__,
3189
+				__FUNCTION__,
3190
+				__LINE__
3191
+			);
3192
+			$success = false;
3193
+		}
3194
+        
3195
+		//do a nonce check here since we're not arriving via a normal route
3196
+		$nonce     = isset($this->_req_data['activate_nonce']) ? sanitize_text_field($this->_req_data['activate_nonce']) : '';
3197
+		$nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3198
+        
3199
+		$this->_verify_nonce($nonce, $nonce_ref);
3200
+        
3201
+        
3202
+		if ( ! isset($this->_req_data['status'])) {
3203
+			EE_Error::add_error(
3204
+				__(
3205
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3206
+					'event_espresso'
3207
+				),
3208
+				__FILE__,
3209
+				__FUNCTION__,
3210
+				__LINE__
3211
+			);
3212
+			$success = false;
3213
+		}
3214
+        
3215
+		//do check to verify we have a valid status.
3216
+		$status = $this->_req_data['status'];
3217
+        
3218
+		if ($status != 'off' && $status != 'on') {
3219
+			EE_Error::add_error(
3220
+				sprintf(
3221
+					__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3222
+					$this->_req_data['status']
3223
+				),
3224
+				__FILE__,
3225
+				__FUNCTION__,
3226
+				__LINE__
3227
+			);
3228
+			$success = false;
3229
+		}
3230
+        
3231
+		if ($success) {
3232
+			//made it here?  Stop dawdling then!!
3233
+			$success = $status == 'off'
3234
+				? $this->_deactivate_messenger($this->_req_data['messenger'])
3235
+				: $this->_activate_messenger($this->_req_data['messenger']);
3236
+		}
3237
+        
3238
+		$this->_template_args['success'] = $success;
3239
+        
3240
+		//no special instructions so let's just do the json return (which should automatically do all the special stuff).
3241
+		$this->_return_json();
3242
+        
3243
+	}
3244
+    
3245
+    
3246
+	/**
3247
+	 * used by ajax from the messages settings page to activate|deactivate a message type
3248
+	 *
3249
+	 */
3250
+	public function activate_mt_toggle()
3251
+	{
3252
+		$success = true;
3253
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3254
+        
3255
+		//let's make sure we have the necessary data
3256
+		if ( ! isset($this->_req_data['message_type'])) {
3257
+			EE_Error::add_error(
3258
+				__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3259
+				__FILE__, __FUNCTION__, __LINE__
3260
+			);
3261
+			$success = false;
3262
+		}
3263
+        
3264
+		if ( ! isset($this->_req_data['messenger'])) {
3265
+			EE_Error::add_error(
3266
+				__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3267
+				__FILE__, __FUNCTION__, __LINE__
3268
+			);
3269
+			$success = false;
3270
+		}
3271
+        
3272
+		if ( ! isset($this->_req_data['status'])) {
3273
+			EE_Error::add_error(
3274
+				__('Messenger status needed to know whether activation or deactivation is happening. No status is given',
3275
+					'event_espresso'),
3276
+				__FILE__, __FUNCTION__, __LINE__
3277
+			);
3278
+			$success = false;
3279
+		}
3280
+        
3281
+        
3282
+		//do check to verify we have a valid status.
3283
+		$status = $this->_req_data['status'];
3284
+        
3285
+		if ($status != 'activate' && $status != 'deactivate') {
3286
+			EE_Error::add_error(
3287
+				sprintf(
3288
+					__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3289
+					$this->_req_data['status']
3290
+				),
3291
+				__FILE__, __FUNCTION__, __LINE__
3292
+			);
3293
+			$success = false;
3294
+		}
3295
+        
3296
+        
3297
+		//do a nonce check here since we're not arriving via a normal route
3298
+		$nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3299
+		$nonce_ref = $this->_req_data['message_type'] . '_nonce';
3300
+        
3301
+		$this->_verify_nonce($nonce, $nonce_ref);
3302
+        
3303
+		if ($success) {
3304
+			//made it here? um, what are you waiting for then?
3305
+			$success = $status == 'deactivate'
3306
+				? $this->_deactivate_message_type_for_messenger($this->_req_data['messenger'],
3307
+					$this->_req_data['message_type'])
3308
+				: $this->_activate_message_type_for_messenger($this->_req_data['messenger'],
3309
+					$this->_req_data['message_type']);
3310
+		}
3311
+        
3312
+		$this->_template_args['success'] = $success;
3313
+		$this->_return_json();
3314
+	}
3315
+    
3316
+    
3317
+	/**
3318
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
3319
+	 *
3320
+	 * @param string $messenger_name The name of the messenger being activated
3321
+	 *
3322
+	 * @return bool
3323
+	 */
3324
+	protected function _activate_messenger($messenger_name)
3325
+	{
3326
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3327
+		$active_messenger          = $this->_message_resource_manager->get_messenger($messenger_name);
3328
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger ? $active_messenger->get_default_message_types() : array();
3329
+        
3330
+		//ensure is active
3331
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_types_to_activate);
3332
+        
3333
+		//set response_data for reload
3334
+		foreach ($message_types_to_activate as $message_type_name) {
3335
+			/** @var EE_message_type $message_type */
3336
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
3337
+			if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3338
+					$message_type_name)
3339
+				&& $message_type instanceof EE_message_type
3340
+			) {
3341
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
3342
+				if ($message_type->get_admin_settings_fields()) {
3343
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
3344
+				}
3345
+			}
3346
+		}
3347
+        
3348
+		//add success message for activating messenger
3349
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
3350
+        
3351
+	}
3352
+    
3353
+    
3354
+	/**
3355
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
3356
+	 *
3357
+	 * @param string $messenger_name The name of the messenger being activated
3358
+	 *
3359
+	 * @return bool
3360
+	 */
3361
+	protected function _deactivate_messenger($messenger_name)
3362
+	{
3363
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3364
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3365
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
3366
+        
3367
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
3368
+	}
3369
+    
3370
+    
3371
+	/**
3372
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
3373
+	 *
3374
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
3375
+	 * @param string $message_type_name The name of the message type being activated for the messenger
3376
+	 *
3377
+	 * @return bool
3378
+	 */
3379
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
3380
+	{
3381
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3382
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3383
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3384
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
3385
+        
3386
+		//ensure is active
3387
+		$this->_message_resource_manager->activate_messenger($messenger_name, $message_type_name);
3388
+        
3389
+		//set response for load
3390
+		if ($this->_message_resource_manager->is_message_type_active_for_messenger($messenger_name,
3391
+			$message_type_name)
3392
+		) {
3393
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
3394
+			if ($message_type_to_activate->get_admin_settings_fields()) {
3395
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
3396
+			}
3397
+		}
3398
+        
3399
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger,
3400
+			$message_type_to_activate);
3401
+	}
3402
+    
3403
+    
3404
+	/**
3405
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
3406
+	 *
3407
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
3408
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
3409
+	 *
3410
+	 * @return bool
3411
+	 */
3412
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
3413
+	{
3414
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
3415
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
3416
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
3417
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
3418
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
3419
+        
3420
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger,
3421
+			$message_type_to_deactivate);
3422
+	}
3423
+    
3424
+    
3425
+	/**
3426
+	 * This just initializes the defaults for activating messenger and message type responses.
3427
+	 */
3428
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
3429
+	{
3430
+		$this->_template_args['data']['active_mts'] = array();
3431
+		$this->_template_args['data']['mt_reload']  = array();
3432
+	}
3433
+    
3434
+    
3435
+	/**
3436
+	 * Setup appropriate response for activating a messenger and/or message types
3437
+	 *
3438
+	 * @param EE_messenger         $messenger
3439
+	 * @param EE_message_type|null $message_type
3440
+	 *
3441
+	 * @return bool
3442
+	 * @throws EE_Error
3443
+	 */
3444
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
3445
+		$messenger,
3446
+		EE_Message_Type $message_type = null
3447
+	) {
3448
+		//if $messenger isn't a valid messenger object then get out.
3449
+		if ( ! $messenger instanceof EE_Messenger) {
3450
+			EE_Error::add_error(
3451
+				__('The messenger being activated is not a valid messenger', 'event_espresso'),
3452
+				__FILE__,
3453
+				__FUNCTION__,
3454
+				__LINE__
3455
+			);
3456 3456
             
3457
-            return false;
3458
-        }
3459
-        //activated
3460
-        if ($this->_template_args['data']['active_mts']) {
3461
-            EE_Error::overwrite_success();
3462
-            //activated a message type with the messenger
3463
-            if ($message_type instanceof EE_message_type) {
3464
-                EE_Error::add_success(
3465
-                    sprintf(
3466
-                        __('%s message type has been successfully activated with the %s messenger', 'event_espresso'),
3467
-                        ucwords($message_type->label['singular']),
3468
-                        ucwords($messenger->label['singular'])
3469
-                    )
3470
-                );
3457
+			return false;
3458
+		}
3459
+		//activated
3460
+		if ($this->_template_args['data']['active_mts']) {
3461
+			EE_Error::overwrite_success();
3462
+			//activated a message type with the messenger
3463
+			if ($message_type instanceof EE_message_type) {
3464
+				EE_Error::add_success(
3465
+					sprintf(
3466
+						__('%s message type has been successfully activated with the %s messenger', 'event_espresso'),
3467
+						ucwords($message_type->label['singular']),
3468
+						ucwords($messenger->label['singular'])
3469
+					)
3470
+				);
3471 3471
                 
3472
-                //if message type was invoice then let's make sure we activate the invoice payment method.
3473
-                if ($message_type->name == 'invoice') {
3474
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
3475
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
3476
-                    if ($pm instanceof EE_Payment_Method) {
3477
-                        EE_Error::add_attention(__('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.',
3478
-                            'event_espresso'));
3479
-                    }
3480
-                }
3481
-                //just toggles the entire messenger
3482
-            } else {
3483
-                EE_Error::add_success(
3484
-                    sprintf(
3485
-                        __('%s messenger has been successfully activated', 'event_espresso'),
3486
-                        ucwords($messenger->label['singular'])
3487
-                    )
3488
-                );
3489
-            }
3472
+				//if message type was invoice then let's make sure we activate the invoice payment method.
3473
+				if ($message_type->name == 'invoice') {
3474
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
3475
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
3476
+					if ($pm instanceof EE_Payment_Method) {
3477
+						EE_Error::add_attention(__('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.',
3478
+							'event_espresso'));
3479
+					}
3480
+				}
3481
+				//just toggles the entire messenger
3482
+			} else {
3483
+				EE_Error::add_success(
3484
+					sprintf(
3485
+						__('%s messenger has been successfully activated', 'event_espresso'),
3486
+						ucwords($messenger->label['singular'])
3487
+					)
3488
+				);
3489
+			}
3490 3490
             
3491
-            return true;
3491
+			return true;
3492 3492
             
3493
-            //possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
3494
-            //message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
3495
-            //in which case we just give a success message for the messenger being successfully activated.
3496
-        } else {
3497
-            if ( ! $messenger->get_default_message_types()) {
3498
-                //messenger doesn't have any default message types so still a success.
3499
-                EE_Error::add_success(
3500
-                    sprintf(
3501
-                        __('%s messenger was successfully activated.', 'event_espresso'),
3502
-                        ucwords($messenger->label['singular'])
3503
-                    )
3504
-                );
3493
+			//possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
3494
+			//message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
3495
+			//in which case we just give a success message for the messenger being successfully activated.
3496
+		} else {
3497
+			if ( ! $messenger->get_default_message_types()) {
3498
+				//messenger doesn't have any default message types so still a success.
3499
+				EE_Error::add_success(
3500
+					sprintf(
3501
+						__('%s messenger was successfully activated.', 'event_espresso'),
3502
+						ucwords($messenger->label['singular'])
3503
+					)
3504
+				);
3505 3505
                 
3506
-                return true;
3507
-            } else {
3508
-                EE_Error::add_error(
3509
-                    $message_type instanceof EE_message_type
3510
-                        ? sprintf(
3511
-                        __('%s message type was not successfully activated with the %s messenger', 'event_espresso'),
3512
-                        ucwords($message_type->label['singular']),
3513
-                        ucwords($messenger->label['singular'])
3514
-                    )
3515
-                        : sprintf(
3516
-                        __('%s messenger was not successfully activated', 'event_espresso'),
3517
-                        ucwords($messenger->label['singular'])
3518
-                    ),
3519
-                    __FILE__,
3520
-                    __FUNCTION__,
3521
-                    __LINE__
3522
-                );
3506
+				return true;
3507
+			} else {
3508
+				EE_Error::add_error(
3509
+					$message_type instanceof EE_message_type
3510
+						? sprintf(
3511
+						__('%s message type was not successfully activated with the %s messenger', 'event_espresso'),
3512
+						ucwords($message_type->label['singular']),
3513
+						ucwords($messenger->label['singular'])
3514
+					)
3515
+						: sprintf(
3516
+						__('%s messenger was not successfully activated', 'event_espresso'),
3517
+						ucwords($messenger->label['singular'])
3518
+					),
3519
+					__FILE__,
3520
+					__FUNCTION__,
3521
+					__LINE__
3522
+				);
3523 3523
                 
3524
-                return false;
3525
-            }
3526
-        }
3527
-    }
3528
-    
3529
-    
3530
-    /**
3531
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
3532
-     *
3533
-     * @param EE_messenger         $messenger
3534
-     * @param EE_message_type|null $message_type
3535
-     *
3536
-     * @return bool
3537
-     */
3538
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
3539
-        $messenger,
3540
-        EE_message_type $message_type = null
3541
-    ) {
3542
-        EE_Error::overwrite_success();
3543
-        
3544
-        //if $messenger isn't a valid messenger object then get out.
3545
-        if ( ! $messenger instanceof EE_Messenger) {
3546
-            EE_Error::add_error(
3547
-                __('The messenger being deactivated is not a valid messenger', 'event_espresso'),
3548
-                __FILE__,
3549
-                __FUNCTION__,
3550
-                __LINE__
3551
-            );
3524
+				return false;
3525
+			}
3526
+		}
3527
+	}
3528
+    
3529
+    
3530
+	/**
3531
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
3532
+	 *
3533
+	 * @param EE_messenger         $messenger
3534
+	 * @param EE_message_type|null $message_type
3535
+	 *
3536
+	 * @return bool
3537
+	 */
3538
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
3539
+		$messenger,
3540
+		EE_message_type $message_type = null
3541
+	) {
3542
+		EE_Error::overwrite_success();
3543
+        
3544
+		//if $messenger isn't a valid messenger object then get out.
3545
+		if ( ! $messenger instanceof EE_Messenger) {
3546
+			EE_Error::add_error(
3547
+				__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
3548
+				__FILE__,
3549
+				__FUNCTION__,
3550
+				__LINE__
3551
+			);
3552 3552
             
3553
-            return false;
3554
-        }
3555
-        
3556
-        if ($message_type instanceof EE_message_type) {
3557
-            $message_type_name = $message_type->name;
3558
-            EE_Error::add_success(
3559
-                sprintf(
3560
-                    __('%s message type has been successfully deactivated for the %s messenger.', 'event_espresso'),
3561
-                    ucwords($message_type->label['singular']),
3562
-                    ucwords($messenger->label['singular'])
3563
-                )
3564
-            );
3565
-        } else {
3566
-            $message_type_name = '';
3567
-            EE_Error::add_success(
3568
-                sprintf(
3569
-                    __('%s messenger has been successfully deactivated.', 'event_espresso'),
3570
-                    ucwords($messenger->label['singular'])
3571
-                )
3572
-            );
3573
-        }
3574
-        
3575
-        //if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
3576
-        if ($messenger->name == 'html' || $message_type_name == 'invoice') {
3577
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
3578
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
3579
-            if ($count_updated > 0) {
3580
-                $msg = $message_type_name == 'invoice'
3581
-                    ? __('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.',
3582
-                        'event_espresso')
3583
-                    : __('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.',
3584
-                        'event_espresso');
3585
-                EE_Error::add_attention($msg);
3586
-            }
3587
-        }
3588
-        
3589
-        return true;
3590
-    }
3591
-    
3592
-    
3593
-    /**
3594
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
3595
-     */
3596
-    public function update_mt_form()
3597
-    {
3598
-        if ( ! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
3599
-            EE_Error::add_error(__('Require message type or messenger to send an updated form'), __FILE__, __FUNCTION__,
3600
-                __LINE__);
3601
-            $this->_return_json();
3602
-        }
3603
-        
3604
-        $message_types = $this->get_installed_message_types();
3605
-        
3606
-        $message_type = $message_types[$this->_req_data['message_type']];
3607
-        $messenger    = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
3608
-        
3609
-        $content                         = $this->_message_type_settings_content($message_type, $messenger, true);
3610
-        $this->_template_args['success'] = true;
3611
-        $this->_template_args['content'] = $content;
3612
-        $this->_return_json();
3613
-    }
3614
-    
3615
-    
3616
-    /**
3617
-     * this handles saving the settings for a messenger or message type
3618
-     *
3619
-     */
3620
-    public function save_settings()
3621
-    {
3622
-        if ( ! isset($this->_req_data['type'])) {
3623
-            EE_Error::add_error(__('Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
3624
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3625
-            $this->_template_args['error'] = true;
3626
-            $this->_return_json();
3627
-        }
3628
-        
3629
-        
3630
-        if ($this->_req_data['type'] == 'messenger') {
3631
-            $settings  = $this->_req_data['messenger_settings']; //this should be an array.
3632
-            $messenger = $settings['messenger'];
3633
-            //let's setup the settings data
3634
-            foreach ($settings as $key => $value) {
3635
-                switch ($key) {
3636
-                    case 'messenger' :
3637
-                        unset($settings['messenger']);
3638
-                        break;
3639
-                    case 'message_types' :
3640
-                        unset($settings['message_types']);
3641
-                        break;
3642
-                    default :
3643
-                        $settings[$key] = $value;
3644
-                        break;
3645
-                }
3646
-            }
3647
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
3648
-        } else if ($this->_req_data['type'] == 'message_type') {
3649
-            $settings     = $this->_req_data['message_type_settings'];
3650
-            $messenger    = $settings['messenger'];
3651
-            $message_type = $settings['message_type'];
3553
+			return false;
3554
+		}
3555
+        
3556
+		if ($message_type instanceof EE_message_type) {
3557
+			$message_type_name = $message_type->name;
3558
+			EE_Error::add_success(
3559
+				sprintf(
3560
+					__('%s message type has been successfully deactivated for the %s messenger.', 'event_espresso'),
3561
+					ucwords($message_type->label['singular']),
3562
+					ucwords($messenger->label['singular'])
3563
+				)
3564
+			);
3565
+		} else {
3566
+			$message_type_name = '';
3567
+			EE_Error::add_success(
3568
+				sprintf(
3569
+					__('%s messenger has been successfully deactivated.', 'event_espresso'),
3570
+					ucwords($messenger->label['singular'])
3571
+				)
3572
+			);
3573
+		}
3574
+        
3575
+		//if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
3576
+		if ($messenger->name == 'html' || $message_type_name == 'invoice') {
3577
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
3578
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
3579
+			if ($count_updated > 0) {
3580
+				$msg = $message_type_name == 'invoice'
3581
+					? __('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.',
3582
+						'event_espresso')
3583
+					: __('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.',
3584
+						'event_espresso');
3585
+				EE_Error::add_attention($msg);
3586
+			}
3587
+		}
3588
+        
3589
+		return true;
3590
+	}
3591
+    
3592
+    
3593
+	/**
3594
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
3595
+	 */
3596
+	public function update_mt_form()
3597
+	{
3598
+		if ( ! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
3599
+			EE_Error::add_error(__('Require message type or messenger to send an updated form'), __FILE__, __FUNCTION__,
3600
+				__LINE__);
3601
+			$this->_return_json();
3602
+		}
3603
+        
3604
+		$message_types = $this->get_installed_message_types();
3605
+        
3606
+		$message_type = $message_types[$this->_req_data['message_type']];
3607
+		$messenger    = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
3608
+        
3609
+		$content                         = $this->_message_type_settings_content($message_type, $messenger, true);
3610
+		$this->_template_args['success'] = true;
3611
+		$this->_template_args['content'] = $content;
3612
+		$this->_return_json();
3613
+	}
3614
+    
3615
+    
3616
+	/**
3617
+	 * this handles saving the settings for a messenger or message type
3618
+	 *
3619
+	 */
3620
+	public function save_settings()
3621
+	{
3622
+		if ( ! isset($this->_req_data['type'])) {
3623
+			EE_Error::add_error(__('Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
3624
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3625
+			$this->_template_args['error'] = true;
3626
+			$this->_return_json();
3627
+		}
3628
+        
3629
+        
3630
+		if ($this->_req_data['type'] == 'messenger') {
3631
+			$settings  = $this->_req_data['messenger_settings']; //this should be an array.
3632
+			$messenger = $settings['messenger'];
3633
+			//let's setup the settings data
3634
+			foreach ($settings as $key => $value) {
3635
+				switch ($key) {
3636
+					case 'messenger' :
3637
+						unset($settings['messenger']);
3638
+						break;
3639
+					case 'message_types' :
3640
+						unset($settings['message_types']);
3641
+						break;
3642
+					default :
3643
+						$settings[$key] = $value;
3644
+						break;
3645
+				}
3646
+			}
3647
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
3648
+		} else if ($this->_req_data['type'] == 'message_type') {
3649
+			$settings     = $this->_req_data['message_type_settings'];
3650
+			$messenger    = $settings['messenger'];
3651
+			$message_type = $settings['message_type'];
3652 3652
             
3653
-            foreach ($settings as $key => $value) {
3654
-                switch ($key) {
3655
-                    case 'messenger' :
3656
-                        unset($settings['messenger']);
3657
-                        break;
3658
-                    case 'message_type' :
3659
-                        unset($settings['message_type']);
3660
-                        break;
3661
-                    default :
3662
-                        $settings[$key] = $value;
3663
-                        break;
3664
-                }
3665
-            }
3653
+			foreach ($settings as $key => $value) {
3654
+				switch ($key) {
3655
+					case 'messenger' :
3656
+						unset($settings['messenger']);
3657
+						break;
3658
+					case 'message_type' :
3659
+						unset($settings['message_type']);
3660
+						break;
3661
+					default :
3662
+						$settings[$key] = $value;
3663
+						break;
3664
+				}
3665
+			}
3666 3666
             
3667
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
3668
-        }
3669
-        
3670
-        //okay we should have the data all setup.  Now we just update!
3671
-        $success = $this->_message_resource_manager->update_active_messengers_option();
3672
-        
3673
-        if ($success) {
3674
-            EE_Error::add_success(__('Settings updated', 'event_espresso'));
3675
-        } else {
3676
-            EE_Error::add_error(__('Settings did not get updated', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3677
-        }
3678
-        
3679
-        $this->_template_args['success'] = $success;
3680
-        $this->_return_json();
3681
-    }
3682
-    
3683
-    
3684
-    
3685
-    
3686
-    /**  EE MESSAGE PROCESSING ACTIONS **/
3687
-    
3688
-    
3689
-    /**
3690
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
3691
-     * However, this does not send immediately, it just queues for sending.
3692
-     *
3693
-     * @since 4.9.0
3694
-     */
3695
-    protected function _generate_now()
3696
-    {
3697
-        $msg_ids = $this->_get_msg_ids_from_request();
3698
-        EED_Messages::generate_now($msg_ids);
3699
-        $this->_redirect_after_action(false, '', '', array(), true);
3700
-    }
3701
-    
3702
-    
3703
-    /**
3704
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
3705
-     * are EEM_Message::status_resend or EEM_Message::status_idle
3706
-     *
3707
-     * @since 4.9.0
3708
-     *
3709
-     */
3710
-    protected function _generate_and_send_now()
3711
-    {
3712
-        $this->_generate_now();
3713
-        $this->_send_now();
3714
-        $this->_redirect_after_action(false, '', '', array(), true);
3715
-    }
3716
-    
3717
-    
3718
-    /**
3719
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
3720
-     *
3721
-     * @since 4.9.0
3722
-     */
3723
-    protected function _queue_for_resending()
3724
-    {
3725
-        $msg_ids = $this->_get_msg_ids_from_request();
3726
-        EED_Messages::queue_for_resending($msg_ids);
3727
-        $this->_redirect_after_action(false, '', '', array(), true);
3728
-    }
3729
-    
3730
-    
3731
-    /**
3732
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
3733
-     *
3734
-     * @since 4.9.0
3735
-     */
3736
-    protected function _send_now()
3737
-    {
3738
-        $msg_ids = $this->_get_msg_ids_from_request();
3739
-        EED_Messages::send_now($msg_ids);
3740
-        $this->_redirect_after_action(false, '', '', array(), true);
3741
-    }
3742
-    
3743
-    
3744
-    /**
3745
-     * Deletes EE_messages for IDs in the request.
3746
-     *
3747
-     * @since 4.9.0
3748
-     */
3749
-    protected function _delete_ee_messages()
3750
-    {
3751
-        $msg_ids       = $this->_get_msg_ids_from_request();
3752
-        $deleted_count = 0;
3753
-        foreach ($msg_ids as $msg_id) {
3754
-            if (EEM_Message::instance()->delete_by_ID($msg_id)) {
3755
-                $deleted_count++;
3756
-            }
3757
-        }
3758
-        if ($deleted_count) {
3759
-            $this->_redirect_after_action(
3760
-                true,
3761
-                _n('message', 'messages', $deleted_count, 'event_espresso'),
3762
-                __('deleted', 'event_espresso')
3763
-            );
3764
-        } else {
3765
-            EE_Error::add_error(
3766
-                _n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
3767
-                __FILE__, __FUNCTION__, __LINE__
3768
-            );
3769
-            $this->_redirect_after_action(false, '', '', array(), true);
3770
-        }
3771
-    }
3772
-    
3773
-    
3774
-    /**
3775
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
3776
-     * @since 4.9.0
3777
-     * @return array
3778
-     */
3779
-    protected function _get_msg_ids_from_request()
3780
-    {
3781
-        if ( ! isset($this->_req_data['MSG_ID'])) {
3782
-            return array();
3783
-        }
3784
-        
3785
-        return is_array($this->_req_data['MSG_ID']) ? array_keys($this->_req_data['MSG_ID']) : array($this->_req_data['MSG_ID']);
3786
-    }
3667
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
3668
+		}
3669
+        
3670
+		//okay we should have the data all setup.  Now we just update!
3671
+		$success = $this->_message_resource_manager->update_active_messengers_option();
3672
+        
3673
+		if ($success) {
3674
+			EE_Error::add_success(__('Settings updated', 'event_espresso'));
3675
+		} else {
3676
+			EE_Error::add_error(__('Settings did not get updated', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
3677
+		}
3678
+        
3679
+		$this->_template_args['success'] = $success;
3680
+		$this->_return_json();
3681
+	}
3682
+    
3683
+    
3684
+    
3685
+    
3686
+	/**  EE MESSAGE PROCESSING ACTIONS **/
3687
+    
3688
+    
3689
+	/**
3690
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
3691
+	 * However, this does not send immediately, it just queues for sending.
3692
+	 *
3693
+	 * @since 4.9.0
3694
+	 */
3695
+	protected function _generate_now()
3696
+	{
3697
+		$msg_ids = $this->_get_msg_ids_from_request();
3698
+		EED_Messages::generate_now($msg_ids);
3699
+		$this->_redirect_after_action(false, '', '', array(), true);
3700
+	}
3701
+    
3702
+    
3703
+	/**
3704
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
3705
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
3706
+	 *
3707
+	 * @since 4.9.0
3708
+	 *
3709
+	 */
3710
+	protected function _generate_and_send_now()
3711
+	{
3712
+		$this->_generate_now();
3713
+		$this->_send_now();
3714
+		$this->_redirect_after_action(false, '', '', array(), true);
3715
+	}
3716
+    
3717
+    
3718
+	/**
3719
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
3720
+	 *
3721
+	 * @since 4.9.0
3722
+	 */
3723
+	protected function _queue_for_resending()
3724
+	{
3725
+		$msg_ids = $this->_get_msg_ids_from_request();
3726
+		EED_Messages::queue_for_resending($msg_ids);
3727
+		$this->_redirect_after_action(false, '', '', array(), true);
3728
+	}
3729
+    
3730
+    
3731
+	/**
3732
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
3733
+	 *
3734
+	 * @since 4.9.0
3735
+	 */
3736
+	protected function _send_now()
3737
+	{
3738
+		$msg_ids = $this->_get_msg_ids_from_request();
3739
+		EED_Messages::send_now($msg_ids);
3740
+		$this->_redirect_after_action(false, '', '', array(), true);
3741
+	}
3742
+    
3743
+    
3744
+	/**
3745
+	 * Deletes EE_messages for IDs in the request.
3746
+	 *
3747
+	 * @since 4.9.0
3748
+	 */
3749
+	protected function _delete_ee_messages()
3750
+	{
3751
+		$msg_ids       = $this->_get_msg_ids_from_request();
3752
+		$deleted_count = 0;
3753
+		foreach ($msg_ids as $msg_id) {
3754
+			if (EEM_Message::instance()->delete_by_ID($msg_id)) {
3755
+				$deleted_count++;
3756
+			}
3757
+		}
3758
+		if ($deleted_count) {
3759
+			$this->_redirect_after_action(
3760
+				true,
3761
+				_n('message', 'messages', $deleted_count, 'event_espresso'),
3762
+				__('deleted', 'event_espresso')
3763
+			);
3764
+		} else {
3765
+			EE_Error::add_error(
3766
+				_n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
3767
+				__FILE__, __FUNCTION__, __LINE__
3768
+			);
3769
+			$this->_redirect_after_action(false, '', '', array(), true);
3770
+		}
3771
+	}
3772
+    
3773
+    
3774
+	/**
3775
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
3776
+	 * @since 4.9.0
3777
+	 * @return array
3778
+	 */
3779
+	protected function _get_msg_ids_from_request()
3780
+	{
3781
+		if ( ! isset($this->_req_data['MSG_ID'])) {
3782
+			return array();
3783
+		}
3784
+        
3785
+		return is_array($this->_req_data['MSG_ID']) ? array_keys($this->_req_data['MSG_ID']) : array($this->_req_data['MSG_ID']);
3786
+	}
3787 3787
     
3788 3788
     
3789 3789
 }
Please login to merge, or discard this patch.
Spacing   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
         $this->_admin_base_url  = EE_MSG_ADMIN_URL;
88 88
         $this->_admin_base_path = EE_MSG_ADMIN;
89 89
         
90
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array)$this->_req_data['activate_state'] : array();
90
+        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state'] : array();
91 91
         
92 92
         $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
93 93
         $this->_load_message_resource_manager();
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
             array('none_selected' => __('Show All Messengers', 'event_espresso')),
220 220
             $messenger_options
221 221
         );
222
-        $input             = new EE_Select_Input(
222
+        $input = new EE_Select_Input(
223 223
             $messenger_options,
224 224
             array(
225 225
                 'html_name'  => 'ee_messenger_filter_by',
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
             array('none_selected' => __('Show All Message Types', 'event_espresso')),
258 258
             $message_type_options
259 259
         );
260
-        $input                = new EE_Select_Input(
260
+        $input = new EE_Select_Input(
261 261
             $message_type_options,
262 262
             array(
263 263
                 'html_name'  => 'ee_message_type_filter_by',
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
             array('none_selected' => __('Show all Contexts', 'event_espresso')),
296 296
             $context_options
297 297
         );
298
-        $input           = new EE_Select_Input(
298
+        $input = new EE_Select_Input(
299 299
             $context_options,
300 300
             array(
301 301
                 'html_name'  => 'ee_context_filter_by',
@@ -676,47 +676,47 @@  discard block
 block discarded – undo
676 676
     
677 677
     public function messages_help_tab()
678 678
     {
679
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
679
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_help_tab.template.php');
680 680
     }
681 681
     
682 682
     
683 683
     public function messengers_help_tab()
684 684
     {
685
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
685
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messenger_help_tab.template.php');
686 686
     }
687 687
     
688 688
     
689 689
     public function message_types_help_tab()
690 690
     {
691
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
691
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_message_type_help_tab.template.php');
692 692
     }
693 693
     
694 694
     
695 695
     public function messages_overview_help_tab()
696 696
     {
697
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
697
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_overview_help_tab.template.php');
698 698
     }
699 699
     
700 700
     
701 701
     public function message_templates_help_tab()
702 702
     {
703
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
703
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_message_templates_help_tab.template.php');
704 704
     }
705 705
     
706 706
     
707 707
     public function edit_message_template_help_tab()
708 708
     {
709
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="' . esc_attr__('Editor Title',
710
-                'event_espresso') . '" />';
711
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="' . esc_attr__('Context Switcher and Preview',
712
-                'event_espresso') . '" />';
713
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="' . esc_attr__('Message Template Form Fields',
714
-                'event_espresso') . '" />';
715
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="' . esc_attr__('Shortcodes Metabox',
716
-                'event_espresso') . '" />';
717
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="' . esc_attr__('Publish Metabox',
718
-                'event_espresso') . '" />';
719
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
709
+        $args['img1'] = '<img src="'.EE_MSG_ASSETS_URL.'images/editor.png'.'" alt="'.esc_attr__('Editor Title',
710
+                'event_espresso').'" />';
711
+        $args['img2'] = '<img src="'.EE_MSG_ASSETS_URL.'images/switch-context.png'.'" alt="'.esc_attr__('Context Switcher and Preview',
712
+                'event_espresso').'" />';
713
+        $args['img3'] = '<img class="left" src="'.EE_MSG_ASSETS_URL.'images/form-fields.png'.'" alt="'.esc_attr__('Message Template Form Fields',
714
+                'event_espresso').'" />';
715
+        $args['img4'] = '<img class="right" src="'.EE_MSG_ASSETS_URL.'images/shortcodes-metabox.png'.'" alt="'.esc_attr__('Shortcodes Metabox',
716
+                'event_espresso').'" />';
717
+        $args['img5'] = '<img class="right" src="'.EE_MSG_ASSETS_URL.'images/publish-meta-box.png'.'" alt="'.esc_attr__('Publish Metabox',
718
+                'event_espresso').'" />';
719
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_templates_editor_help_tab.template.php',
720 720
             $args);
721 721
     }
722 722
     
@@ -725,37 +725,37 @@  discard block
 block discarded – undo
725 725
     {
726 726
         $this->_set_shortcodes();
727 727
         $args['shortcodes'] = $this->_shortcodes;
728
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
728
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_shortcodes_help_tab.template.php',
729 729
             $args);
730 730
     }
731 731
     
732 732
     
733 733
     public function preview_message_help_tab()
734 734
     {
735
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
735
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_preview_help_tab.template.php');
736 736
     }
737 737
     
738 738
     
739 739
     public function settings_help_tab()
740 740
     {
741
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png' . '" alt="' . esc_attr__('Active Email Tab',
742
-                'event_espresso') . '" />';
743
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png' . '" alt="' . esc_attr__('Inactive Email Tab',
744
-                'event_espresso') . '" />';
741
+        $args['img1'] = '<img class="inline-text" src="'.EE_MSG_ASSETS_URL.'images/email-tab-active.png'.'" alt="'.esc_attr__('Active Email Tab',
742
+                'event_espresso').'" />';
743
+        $args['img2'] = '<img class="inline-text" src="'.EE_MSG_ASSETS_URL.'images/email-tab-inactive.png'.'" alt="'.esc_attr__('Inactive Email Tab',
744
+                'event_espresso').'" />';
745 745
         $args['img3'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox" checked="checked"><label for="ee-on-off-toggle-on"></label>';
746 746
         $args['img4'] = '<div class="switch"><input id="ee-on-off-toggle-on" class="ee-on-off-toggle ee-toggle-round-flat" type="checkbox"><label for="ee-on-off-toggle-on"></label>';
747
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
747
+        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'ee_msg_messages_settings_help_tab.template.php', $args);
748 748
     }
749 749
     
750 750
     
751 751
     public function load_scripts_styles()
752 752
     {
753
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
753
+        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL.'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
754 754
         wp_enqueue_style('espresso_ee_msg');
755 755
         
756
-        wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
756
+        wp_register_script('ee-messages-settings', EE_MSG_ASSETS_URL.'ee-messages-settings.js',
757 757
             array('jquery-ui-droppable', 'ee-serialize-full-array'), EVENT_ESPRESSO_VERSION, true);
758
-        wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
758
+        wp_register_script('ee-msg-list-table-js', EE_MSG_ASSETS_URL.'ee_message_admin_list_table.js',
759 759
             array('ee-dialog'), EVENT_ESPRESSO_VERSION);
760 760
     }
761 761
     
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
         
788 788
         $this->_set_shortcodes();
789 789
         
790
-        EE_Registry::$i18n_js_strings['confirm_default_reset']        = sprintf(
790
+        EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
791 791
             __('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.',
792 792
                 'event_espresso'),
793 793
             $this->_message_template_group->messenger_obj()->label['singular'],
@@ -796,7 +796,7 @@  discard block
 block discarded – undo
796 796
         EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = __('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?',
797 797
             'event_espresso');
798 798
         
799
-        wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL . 'ee_message_editor.js', array('jquery'),
799
+        wp_register_script('ee_msgs_edit_js', EE_MSG_ASSETS_URL.'ee_message_editor.js', array('jquery'),
800 800
             EVENT_ESPRESSO_VERSION);
801 801
         
802 802
         wp_enqueue_script('ee_admin_js');
@@ -827,7 +827,7 @@  discard block
 block discarded – undo
827 827
     
828 828
     public function load_scripts_styles_settings()
829 829
     {
830
-        wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL . 'ee_message_settings.css', array(),
830
+        wp_register_style('ee-message-settings', EE_MSG_ASSETS_URL.'ee_message_settings.css', array(),
831 831
             EVENT_ESPRESSO_VERSION);
832 832
         wp_enqueue_style('ee-text-links');
833 833
         wp_enqueue_style('ee-message-settings');
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
             }
894 894
             $status_bulk_actions = $common_bulk_actions;
895 895
             //unset bulk actions not applying to status
896
-            if (! empty($status_bulk_actions)) {
896
+            if ( ! empty($status_bulk_actions)) {
897 897
                 switch ($status) {
898 898
                     case EEM_Message::status_idle:
899 899
                     case EEM_Message::status_resend:
@@ -918,7 +918,7 @@  discard block
 block discarded – undo
918 918
             }
919 919
 
920 920
             //skip adding messenger executing status to views because it will be included with the Failed view.
921
-            if ( $status === EEM_Message::status_messenger_executing ) {
921
+            if ($status === EEM_Message::status_messenger_executing) {
922 922
                 continue;
923 923
             }
924 924
             
@@ -944,7 +944,7 @@  discard block
 block discarded – undo
944 944
         $this->_search_btn_label                   = __('Message Activity', 'event_espresso');
945 945
         $this->_template_args['per_column']        = 6;
946 946
         $this->_template_args['after_list_table']  = $this->_display_legend($this->_message_legend_items());
947
-        $this->_template_args['before_list_table'] = '<h3>' . EEM_Message::instance()->get_pretty_label_for_results() . '</h3>';
947
+        $this->_template_args['before_list_table'] = '<h3>'.EEM_Message::instance()->get_pretty_label_for_results().'</h3>';
948 948
         $this->display_admin_list_table_page_with_no_sidebar();
949 949
     }
950 950
     
@@ -968,37 +968,37 @@  discard block
 block discarded – undo
968 968
         /** @type array $status_items status legend setup */
969 969
         $status_items = array(
970 970
             'sent_status'       => array(
971
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
971
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_sent,
972 972
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence')
973 973
             ),
974 974
             'idle_status'       => array(
975
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
975
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_idle,
976 976
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence')
977 977
             ),
978 978
             'failed_status'     => array(
979
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
979
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_failed,
980 980
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence')
981 981
             ),
982 982
             'messenger_executing_status' => array(
983
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
983
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_messenger_executing,
984 984
                 'desc' => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence')
985 985
             ),
986 986
             'resend_status'     => array(
987
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
987
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_resend,
988 988
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence')
989 989
             ),
990 990
             'incomplete_status' => array(
991
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
991
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_incomplete,
992 992
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence')
993 993
             ),
994 994
             'retry_status'      => array(
995
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
995
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_retry,
996 996
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence')
997 997
             )
998 998
         );
999 999
         if (EEM_Message::debug()) {
1000 1000
             $status_items['debug_only_status'] = array(
1001
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1001
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Message::status_debug_only,
1002 1002
                 'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence')
1003 1003
             );
1004 1004
         }
@@ -1010,10 +1010,10 @@  discard block
 block discarded – undo
1010 1010
     protected function _custom_mtps_preview()
1011 1011
     {
1012 1012
         $this->_admin_page_title              = __('Custom Message Templates (Preview)', 'event_espresso');
1013
-        $this->_template_args['preview_img']  = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png" alt="' . esc_attr__('Preview Custom Message Templates screenshot',
1014
-                'event_espresso') . '" />';
1015
-        $this->_template_args['preview_text'] = '<strong>' . __('Custom Message Templates is a feature that is only available in the caffeinated version of Event Espresso.  With the Custom Message Templates feature, you are able to create custom templates and set them per event.',
1016
-                'event_espresso') . '</strong>';
1013
+        $this->_template_args['preview_img']  = '<img src="'.EE_MSG_ASSETS_URL.'images/custom_mtps_preview.png" alt="'.esc_attr__('Preview Custom Message Templates screenshot',
1014
+                'event_espresso').'" />';
1015
+        $this->_template_args['preview_text'] = '<strong>'.__('Custom Message Templates is a feature that is only available in the caffeinated version of Event Espresso.  With the Custom Message Templates feature, you are able to create custom templates and set them per event.',
1016
+                'event_espresso').'</strong>';
1017 1017
         $this->display_admin_caf_preview_page('custom_message_types', false);
1018 1018
     }
1019 1019
     
@@ -1261,7 +1261,7 @@  discard block
 block discarded – undo
1261 1261
                             //let's verify if we need this extra field via the shortcodes parameter.
1262 1262
                             $continue = false;
1263 1263
                             if (isset($extra_array['shortcodes_required'])) {
1264
-                                foreach ((array)$extra_array['shortcodes_required'] as $shortcode) {
1264
+                                foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1265 1265
                                     if ( ! array_key_exists($shortcode, $this->_shortcodes)) {
1266 1266
                                         $continue = true;
1267 1267
                                     }
@@ -1271,9 +1271,9 @@  discard block
 block discarded – undo
1271 1271
                                 }
1272 1272
                             }
1273 1273
                             
1274
-                            $field_id                                = $reference_field . '-' . $extra_field . '-content';
1274
+                            $field_id                                = $reference_field.'-'.$extra_field.'-content';
1275 1275
                             $template_form_fields[$field_id]         = $extra_array;
1276
-                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields[' . $reference_field . '][content][' . $extra_field . ']';
1276
+                            $template_form_fields[$field_id]['name'] = 'MTP_template_fields['.$reference_field.'][content]['.$extra_field.']';
1277 1277
                             $css_class                               = isset($extra_array['css_class']) ? $extra_array['css_class'] : '';
1278 1278
                             
1279 1279
                             $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
@@ -1283,7 +1283,7 @@  discard block
 block discarded – undo
1283 1283
                                                                                 is_array($validators[$extra_field])
1284 1284
                                                                                 && isset($validators[$extra_field]['msg'])
1285 1285
                                                                             )
1286
-                                ? 'validate-error ' . $css_class
1286
+                                ? 'validate-error '.$css_class
1287 1287
                                 : $css_class;
1288 1288
                             
1289 1289
                             $template_form_fields[$field_id]['value'] = ! empty($message_templates) && isset($content[$extra_field])
@@ -1311,11 +1311,11 @@  discard block
 block discarded – undo
1311 1311
                                 
1312 1312
                             }/**/
1313 1313
                         }
1314
-                        $templatefield_MTP_id          = $reference_field . '-MTP_ID';
1315
-                        $templatefield_templatename_id = $reference_field . '-name';
1314
+                        $templatefield_MTP_id          = $reference_field.'-MTP_ID';
1315
+                        $templatefield_templatename_id = $reference_field.'-name';
1316 1316
                         
1317 1317
                         $template_form_fields[$templatefield_MTP_id] = array(
1318
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1318
+                            'name'       => 'MTP_template_fields['.$reference_field.'][MTP_ID]',
1319 1319
                             'label'      => null,
1320 1320
                             'input'      => 'hidden',
1321 1321
                             'type'       => 'int',
@@ -1328,7 +1328,7 @@  discard block
 block discarded – undo
1328 1328
                         );
1329 1329
                         
1330 1330
                         $template_form_fields[$templatefield_templatename_id] = array(
1331
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1331
+                            'name'       => 'MTP_template_fields['.$reference_field.'][name]',
1332 1332
                             'label'      => null,
1333 1333
                             'input'      => 'hidden',
1334 1334
                             'type'       => 'string',
@@ -1342,9 +1342,9 @@  discard block
 block discarded – undo
1342 1342
                     }
1343 1343
                     continue; //skip the next stuff, we got the necessary fields here for this dataset.
1344 1344
                 } else {
1345
-                    $field_id                                 = $template_field . '-content';
1345
+                    $field_id                                 = $template_field.'-content';
1346 1346
                     $template_form_fields[$field_id]          = $field_setup_array;
1347
-                    $template_form_fields[$field_id]['name']  = 'MTP_template_fields[' . $template_field . '][content]';
1347
+                    $template_form_fields[$field_id]['name']  = 'MTP_template_fields['.$template_field.'][content]';
1348 1348
                     $message_template                         = isset($message_templates[$context][$template_field])
1349 1349
                         ? $message_templates[$context][$template_field]
1350 1350
                         : null;
@@ -1365,7 +1365,7 @@  discard block
 block discarded – undo
1365 1365
                     $template_form_fields[$field_id]['css_class'] = ! empty($v_fields)
1366 1366
                                                                     && in_array($template_field, $v_fields)
1367 1367
                                                                     && isset($validators[$template_field]['msg'])
1368
-                        ? 'validate-error ' . $css_class
1368
+                        ? 'validate-error '.$css_class
1369 1369
                         : $css_class;
1370 1370
                     
1371 1371
                     //shortcode selector
@@ -1376,12 +1376,12 @@  discard block
 block discarded – undo
1376 1376
                 
1377 1377
                 //k took care of content field(s) now let's take care of others.
1378 1378
                 
1379
-                $templatefield_MTP_id                = $template_field . '-MTP_ID';
1380
-                $templatefield_field_templatename_id = $template_field . '-name';
1379
+                $templatefield_MTP_id                = $template_field.'-MTP_ID';
1380
+                $templatefield_field_templatename_id = $template_field.'-name';
1381 1381
                 
1382 1382
                 //foreach template field there are actually two form fields created
1383 1383
                 $template_form_fields[$templatefield_MTP_id] = array(
1384
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1384
+                    'name'       => 'MTP_template_fields['.$template_field.'][MTP_ID]',
1385 1385
                     'label'      => null,
1386 1386
                     'input'      => 'hidden',
1387 1387
                     'type'       => 'int',
@@ -1394,7 +1394,7 @@  discard block
 block discarded – undo
1394 1394
                 );
1395 1395
                 
1396 1396
                 $template_form_fields[$templatefield_field_templatename_id] = array(
1397
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1397
+                    'name'       => 'MTP_template_fields['.$template_field.'][name]',
1398 1398
                     'label'      => null,
1399 1399
                     'input'      => 'hidden',
1400 1400
                     'type'       => 'string',
@@ -1512,7 +1512,7 @@  discard block
 block discarded – undo
1512 1512
                 'format'     => '%d',
1513 1513
                 'db-col'     => 'MTP_deleted'
1514 1514
             );
1515
-            $sidebar_form_fields['ee-msg-author']  = array(
1515
+            $sidebar_form_fields['ee-msg-author'] = array(
1516 1516
                 'name'       => 'MTP_user_id',
1517 1517
                 'label'      => __('Author', 'event_espresso'),
1518 1518
                 'input'      => 'hidden',
@@ -1531,17 +1531,17 @@  discard block
 block discarded – undo
1531 1531
                 'value' => $action
1532 1532
             );
1533 1533
             
1534
-            $sidebar_form_fields['ee-msg-id']        = array(
1534
+            $sidebar_form_fields['ee-msg-id'] = array(
1535 1535
                 'name'  => 'id',
1536 1536
                 'input' => 'hidden',
1537 1537
                 'type'  => 'int',
1538 1538
                 'value' => $GRP_ID
1539 1539
             );
1540 1540
             $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1541
-                'name'  => $action . '_nonce',
1541
+                'name'  => $action.'_nonce',
1542 1542
                 'input' => 'hidden',
1543 1543
                 'type'  => 'string',
1544
-                'value' => wp_create_nonce($action . '_nonce')
1544
+                'value' => wp_create_nonce($action.'_nonce')
1545 1545
             );
1546 1546
             
1547 1547
             if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
@@ -1573,7 +1573,7 @@  discard block
 block discarded – undo
1573 1573
         );
1574 1574
         
1575 1575
         //add preview button
1576
-        $preview_url    = parent::add_query_args_and_nonce(
1576
+        $preview_url = parent::add_query_args_and_nonce(
1577 1577
             array(
1578 1578
                 'message_type' => $message_template_group->message_type(),
1579 1579
                 'messenger'    => $message_template_group->messenger(),
@@ -1583,8 +1583,8 @@  discard block
 block discarded – undo
1583 1583
             ),
1584 1584
             $this->_admin_base_url
1585 1585
         );
1586
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">' . __('Preview',
1587
-                'event_espresso') . '</a>';
1586
+        $preview_button = '<a href="'.$preview_url.'" class="button-secondary messages-preview-button">'.__('Preview',
1587
+                'event_espresso').'</a>';
1588 1588
         
1589 1589
         
1590 1590
         //setup context switcher
@@ -1612,8 +1612,8 @@  discard block
 block discarded – undo
1612 1612
         $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1613 1613
         
1614 1614
         $this->_template_path = $this->_template_args['GRP_ID']
1615
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1616
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1615
+            ? EE_MSG_TEMPLATE_PATH.'ee_msg_details_main_edit_meta_box.template.php'
1616
+            : EE_MSG_TEMPLATE_PATH.'ee_msg_details_main_add_meta_box.template.php';
1617 1617
         
1618 1618
         //send along EE_Message_Template_Group object for further template use.
1619 1619
         $this->_template_args['MTP'] = $message_template_group;
@@ -1648,7 +1648,7 @@  discard block
 block discarded – undo
1648 1648
     
1649 1649
     public function _add_form_element_before()
1650 1650
     {
1651
-        return '<form method="post" action="' . $this->_template_args["edit_message_template_form_url"] . '" id="ee-msg-edit-frm">';
1651
+        return '<form method="post" action="'.$this->_template_args["edit_message_template_form_url"].'" id="ee-msg-edit-frm">';
1652 1652
     }
1653 1653
     
1654 1654
     public function _add_form_element_after()
@@ -1843,14 +1843,14 @@  discard block
 block discarded – undo
1843 1843
         }
1844 1844
         
1845 1845
         //let's add a button to go back to the edit view
1846
-        $query_args             = array(
1846
+        $query_args = array(
1847 1847
             'id'      => $this->_req_data['GRP_ID'],
1848 1848
             'context' => $this->_req_data['context'],
1849 1849
             'action'  => 'edit_message_template'
1850 1850
         );
1851 1851
         $go_back_url            = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1852
-        $preview_button         = '<a href="' . $go_back_url . '" class="button-secondary messages-preview-go-back-button">' . __('Go Back to Edit',
1853
-                'event_espresso') . '</a>';
1852
+        $preview_button         = '<a href="'.$go_back_url.'" class="button-secondary messages-preview-go-back-button">'.__('Go Back to Edit',
1853
+                'event_espresso').'</a>';
1854 1854
         $message_types          = $this->get_installed_message_types();
1855 1855
         $active_messenger       = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
1856 1856
         $active_messenger_label = $active_messenger instanceof EE_messenger
@@ -1864,7 +1864,7 @@  discard block
 block discarded – undo
1864 1864
         );
1865 1865
         //setup display of preview.
1866 1866
         $this->_admin_page_title                    = $preview_title;
1867
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . stripslashes($preview);
1867
+        $this->_template_args['admin_page_content'] = $preview_button.'<br />'.stripslashes($preview);
1868 1868
         $this->_template_args['data']['force_json'] = true;
1869 1869
         
1870 1870
         return '';
@@ -1946,7 +1946,7 @@  discard block
 block discarded – undo
1946 1946
         }
1947 1947
         
1948 1948
         //setup variation select values for the currently selected template.
1949
-        $variations               = $this->_message_template_group->get_template_pack()->get_variations(
1949
+        $variations = $this->_message_template_group->get_template_pack()->get_variations(
1950 1950
             $this->_message_template_group->messenger(),
1951 1951
             $this->_message_template_group->message_type()
1952 1952
         );
@@ -1960,12 +1960,12 @@  discard block
 block discarded – undo
1960 1960
         
1961 1961
         $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
1962 1962
         
1963
-        $template_args['template_packs_selector']        = EEH_Form_Fields::select_input(
1963
+        $template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
1964 1964
             'MTP_template_pack',
1965 1965
             $tp_select_values,
1966 1966
             $this->_message_template_group->get_template_pack_name()
1967 1967
         );
1968
-        $template_args['variations_selector']            = EEH_Form_Fields::select_input(
1968
+        $template_args['variations_selector'] = EEH_Form_Fields::select_input(
1969 1969
             'MTP_template_variation',
1970 1970
             $variations_select_values,
1971 1971
             $this->_message_template_group->get_template_pack_variation()
@@ -1975,7 +1975,7 @@  discard block
 block discarded – undo
1975 1975
         $template_args['template_pack_description']      = $template_pack_labels->template_pack_description;
1976 1976
         $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
1977 1977
         
1978
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
1978
+        $template = EE_MSG_TEMPLATE_PATH.'template_pack_and_variations_metabox.template.php';
1979 1979
         
1980 1980
         EEH_Template::display_template($template, $template_args);
1981 1981
     }
@@ -2004,7 +2004,7 @@  discard block
 block discarded – undo
2004 2004
         if ( ! empty($fields)) {
2005 2005
             //yup there be fields
2006 2006
             foreach ($fields as $field => $config) {
2007
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2007
+                $field_id = $this->_message_template_group->messenger().'_'.$field;
2008 2008
                 $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2009 2009
                 $default  = isset($config['default']) ? $config['default'] : '';
2010 2010
                 $default  = isset($config['value']) ? $config['value'] : $default;
@@ -2019,7 +2019,7 @@  discard block
 block discarded – undo
2019 2019
                     : $fix;
2020 2020
                 
2021 2021
                 $template_form_fields[$field_id] = array(
2022
-                    'name'       => 'test_settings_fld[' . $field . ']',
2022
+                    'name'       => 'test_settings_fld['.$field.']',
2023 2023
                     'label'      => $config['label'],
2024 2024
                     'input'      => $config['input'],
2025 2025
                     'type'       => $config['type'],
@@ -2049,7 +2049,7 @@  discard block
 block discarded – undo
2049 2049
         }
2050 2050
         
2051 2051
         //and button
2052
-        $test_settings_html .= '<p>' . __('Need to reset this message type and start over?', 'event_espresso') . '</p>';
2052
+        $test_settings_html .= '<p>'.__('Need to reset this message type and start over?', 'event_espresso').'</p>';
2053 2053
         $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2054 2054
         $test_settings_html .= $this->get_action_link_or_button(
2055 2055
             'reset_to_default',
@@ -2080,7 +2080,7 @@  discard block
 block discarded – undo
2080 2080
             'linked_input_id' => $linked_input_id
2081 2081
         );
2082 2082
         
2083
-        return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2083
+        return EEH_Template::display_template(EE_MSG_TEMPLATE_PATH.'shortcode_selector_skeleton.template.php',
2084 2084
             $template_args, true);
2085 2085
     }
2086 2086
     
@@ -2098,7 +2098,7 @@  discard block
 block discarded – undo
2098 2098
         //$messenger = $this->_message_template_group->messenger_obj();
2099 2099
         //now let's set the content depending on the status of the shortcodes array
2100 2100
         if (empty($shortcodes)) {
2101
-            $content = '<p>' . __('There are no valid shortcodes available', 'event_espresso') . '</p>';
2101
+            $content = '<p>'.__('There are no valid shortcodes available', 'event_espresso').'</p>';
2102 2102
             echo $content;
2103 2103
         } else {
2104 2104
             //$alt = 0;
@@ -2215,7 +2215,7 @@  discard block
 block discarded – undo
2215 2215
                     <?php
2216 2216
                 }
2217 2217
                 //setup nonce_url
2218
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2218
+                wp_nonce_field($args['action'].'_nonce', $args['action'].'_nonce', false);
2219 2219
                 ?>
2220 2220
                 <select name="context">
2221 2221
                     <?php
@@ -2313,7 +2313,7 @@  discard block
 block discarded – undo
2313 2313
             : '';
2314 2314
         $context      = ucwords(str_replace('_', ' ', $context_slug));
2315 2315
         
2316
-        $item_desc = $messenger_label && $message_type_label ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' ' : '';
2316
+        $item_desc = $messenger_label && $message_type_label ? $messenger_label.' '.$message_type_label.' '.$context.' ' : '';
2317 2317
         $item_desc .= 'Message Template';
2318 2318
         $query_args  = array();
2319 2319
         $edit_array  = array();
@@ -2682,8 +2682,8 @@  discard block
 block discarded – undo
2682 2682
      */
2683 2683
     protected function _learn_more_about_message_templates_link()
2684 2684
     {
2685
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >' . __('learn more about how message templates works',
2686
-            'event_espresso') . '</a>';
2685
+        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'.__('learn more about how message templates works',
2686
+            'event_espresso').'</a>';
2687 2687
     }
2688 2688
     
2689 2689
     
@@ -2759,10 +2759,10 @@  discard block
 block discarded – undo
2759 2759
                 
2760 2760
                 $this->_m_mt_settings['message_type_tabs'][$messenger->name][$a_or_i][$message_type->name] = array(
2761 2761
                     'label'    => ucwords($message_type->label['singular']),
2762
-                    'class'    => 'message-type-' . $a_or_i,
2763
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
2764
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
2765
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
2762
+                    'class'    => 'message-type-'.$a_or_i,
2763
+                    'slug_id'  => $message_type->name.'-messagetype-'.$messenger->name,
2764
+                    'mt_nonce' => wp_create_nonce($message_type->name.'_nonce'),
2765
+                    'href'     => 'espresso_'.$message_type->name.'_message_type_settings',
2766 2766
                     'title'    => $a_or_i == 'active'
2767 2767
                         ? __('Drag this message type to the Inactive window to deactivate', 'event_espresso')
2768 2768
                         : __('Drag this message type to the messenger to activate', 'event_espresso'),
@@ -2798,9 +2798,9 @@  discard block
 block discarded – undo
2798 2798
             $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
2799 2799
             
2800 2800
             foreach ($fields as $fldname => $fldprops) {
2801
-                $field_id                       = $messenger->name . '-' . $message_type->name . '-' . $fldname;
2801
+                $field_id                       = $messenger->name.'-'.$message_type->name.'-'.$fldname;
2802 2802
                 $template_form_field[$field_id] = array(
2803
-                    'name'       => 'message_type_settings[' . $fldname . ']',
2803
+                    'name'       => 'message_type_settings['.$fldname.']',
2804 2804
                     'label'      => $fldprops['label'],
2805 2805
                     'input'      => $fldprops['field_type'],
2806 2806
                     'type'       => $fldprops['value_type'],
@@ -2841,7 +2841,7 @@  discard block
 block discarded – undo
2841 2841
         $settings_template_args['show_form']     = empty($settings_template_args['template_form_fields']) ? ' hidden' : '';
2842 2842
         
2843 2843
         
2844
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
2844
+        $template = EE_MSG_TEMPLATE_PATH.'ee_msg_mt_settings_content.template.php';
2845 2845
         $content  = EEH_Template::display_template($template, $settings_template_args, true);
2846 2846
         
2847 2847
         return $content;
@@ -2871,11 +2871,11 @@  discard block
 block discarded – undo
2871 2871
                 $active_mt_tabs                         = isset($this->_m_mt_settings['message_type_tabs'][$messenger]['active'])
2872 2872
                     ? $this->_m_mt_settings['message_type_tabs'][$messenger]['active']
2873 2873
                     : '';
2874
-                $m_boxes[$messenger . '_a_box']         = sprintf(
2874
+                $m_boxes[$messenger.'_a_box']         = sprintf(
2875 2875
                     __('%s Settings', 'event_espresso'),
2876 2876
                     $tab_array['label']
2877 2877
                 );
2878
-                $m_template_args[$messenger . '_a_box'] = array(
2878
+                $m_template_args[$messenger.'_a_box'] = array(
2879 2879
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2880 2880
                     'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2881 2881
                         ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
@@ -2889,8 +2889,8 @@  discard block
 block discarded – undo
2889 2889
                 // message type meta boxes
2890 2890
                 // (which is really just the inactive container for each messenger
2891 2891
                 // showing inactive message types for that messenger)
2892
-                $mt_boxes[$messenger . '_i_box']         = __('Inactive Message Types', 'event_espresso');
2893
-                $mt_template_args[$messenger . '_i_box'] = array(
2892
+                $mt_boxes[$messenger.'_i_box']         = __('Inactive Message Types', 'event_espresso');
2893
+                $mt_template_args[$messenger.'_i_box'] = array(
2894 2894
                     'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
2895 2895
                     'inactive_message_types' => isset($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
2896 2896
                         ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][$messenger]['inactive'])
@@ -2906,14 +2906,14 @@  discard block
 block discarded – undo
2906 2906
         
2907 2907
         
2908 2908
         //register messenger metaboxes
2909
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
2909
+        $m_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_mt_meta_box.template.php';
2910 2910
         foreach ($m_boxes as $box => $label) {
2911 2911
             $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[$box]);
2912 2912
             $msgr          = str_replace('_a_box', '', $box);
2913 2913
             add_meta_box(
2914
-                'espresso_' . $msgr . '_settings',
2914
+                'espresso_'.$msgr.'_settings',
2915 2915
                 $label,
2916
-                function ($post, $metabox) {
2916
+                function($post, $metabox) {
2917 2917
                     echo EEH_Template::display_template($metabox["args"]["template_path"],
2918 2918
                         $metabox["args"]["template_args"], true);
2919 2919
                 },
@@ -2925,17 +2925,17 @@  discard block
 block discarded – undo
2925 2925
         }
2926 2926
         
2927 2927
         //register message type metaboxes
2928
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
2928
+        $mt_template_path = EE_MSG_TEMPLATE_PATH.'ee_msg_details_messenger_meta_box.template.php';
2929 2929
         foreach ($mt_boxes as $box => $label) {
2930 2930
             $callback_args = array(
2931 2931
                 'template_path' => $mt_template_path,
2932 2932
                 'template_args' => $mt_template_args[$box]
2933 2933
             );
2934
-            $mt            = str_replace('_i_box', '', $box);
2934
+            $mt = str_replace('_i_box', '', $box);
2935 2935
             add_meta_box(
2936
-                'espresso_' . $mt . '_inactive_mts',
2936
+                'espresso_'.$mt.'_inactive_mts',
2937 2937
                 $label,
2938
-                function ($post, $metabox) {
2938
+                function($post, $metabox) {
2939 2939
                     echo EEH_Template::display_template($metabox["args"]["template_path"],
2940 2940
                         $metabox["args"]["template_args"], true);
2941 2941
                 },
@@ -3037,7 +3037,7 @@  discard block
 block discarded – undo
3037 3037
             if ($form->is_valid()) {
3038 3038
                 $valid_data = $form->valid_data();
3039 3039
                 foreach ($valid_data as $property => $value) {
3040
-                    $setter = 'set_' . $property;
3040
+                    $setter = 'set_'.$property;
3041 3041
                     if (method_exists($network_config, $setter)) {
3042 3042
                         $network_config->{$setter}($value);
3043 3043
                     } else if (
@@ -3066,8 +3066,8 @@  discard block
 block discarded – undo
3066 3066
      */
3067 3067
     protected function _get_mt_tabs($tab_array)
3068 3068
     {
3069
-        $tab_array = (array)$tab_array;
3070
-        $template  = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3069
+        $tab_array = (array) $tab_array;
3070
+        $template  = EE_MSG_TEMPLATE_PATH.'ee_msg_details_mt_settings_tab_item.template.php';
3071 3071
         $tabs      = '';
3072 3072
         
3073 3073
         foreach ($tab_array as $tab) {
@@ -3100,9 +3100,9 @@  discard block
 block discarded – undo
3100 3100
             $existing_settings = $messenger->get_existing_admin_settings();
3101 3101
             
3102 3102
             foreach ($fields as $fldname => $fldprops) {
3103
-                $field_id                       = $messenger->name . '-' . $fldname;
3103
+                $field_id                       = $messenger->name.'-'.$fldname;
3104 3104
                 $template_form_field[$field_id] = array(
3105
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3105
+                    'name'       => 'messenger_settings['.$field_id.']',
3106 3106
                     'label'      => $fldprops['label'],
3107 3107
                     'input'      => $fldprops['field_type'],
3108 3108
                     'type'       => $fldprops['value_type'],
@@ -3137,7 +3137,7 @@  discard block
 block discarded – undo
3137 3137
         //make sure any active message types that are existing are included in the hidden fields
3138 3138
         if (isset($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'])) {
3139 3139
             foreach ($this->_m_mt_settings['message_type_tabs'][$messenger->name]['active'] as $mt => $values) {
3140
-                $settings_template_args['hidden_fields']['messenger_settings[message_types][' . $mt . ']'] = array(
3140
+                $settings_template_args['hidden_fields']['messenger_settings[message_types]['.$mt.']'] = array(
3141 3141
                     'type'  => 'hidden',
3142 3142
                     'value' => $mt
3143 3143
                 );
@@ -3147,7 +3147,7 @@  discard block
 block discarded – undo
3147 3147
             $settings_template_args['hidden_fields'],
3148 3148
             'array'
3149 3149
         );
3150
-        $active                                  = $this->_message_resource_manager->is_messenger_active($messenger->name);
3150
+        $active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3151 3151
         
3152 3152
         $settings_template_args['messenger']           = $messenger->name;
3153 3153
         $settings_template_args['description']         = $messenger->description;
@@ -3164,9 +3164,9 @@  discard block
 block discarded – undo
3164 3164
         
3165 3165
         
3166 3166
         $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3167
-        $settings_template_args['nonce']         = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3167
+        $settings_template_args['nonce']         = wp_create_nonce('activate_'.$messenger->name.'_toggle_nonce');
3168 3168
         $settings_template_args['on_off_status'] = $active ? true : false;
3169
-        $template                                = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3169
+        $template                                = EE_MSG_TEMPLATE_PATH.'ee_msg_m_settings_content.template.php';
3170 3170
         $content                                 = EEH_Template::display_template($template, $settings_template_args,
3171 3171
             true);
3172 3172
         
@@ -3194,7 +3194,7 @@  discard block
 block discarded – undo
3194 3194
         
3195 3195
         //do a nonce check here since we're not arriving via a normal route
3196 3196
         $nonce     = isset($this->_req_data['activate_nonce']) ? sanitize_text_field($this->_req_data['activate_nonce']) : '';
3197
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3197
+        $nonce_ref = 'activate_'.$this->_req_data['messenger'].'_toggle_nonce';
3198 3198
         
3199 3199
         $this->_verify_nonce($nonce, $nonce_ref);
3200 3200
         
@@ -3296,7 +3296,7 @@  discard block
 block discarded – undo
3296 3296
         
3297 3297
         //do a nonce check here since we're not arriving via a normal route
3298 3298
         $nonce     = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3299
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3299
+        $nonce_ref = $this->_req_data['message_type'].'_nonce';
3300 3300
         
3301 3301
         $this->_verify_nonce($nonce, $nonce_ref);
3302 3302
         
Please login to merge, or discard this patch.
admin_pages/messages/EE_Message_List_Table.class.php 2 patches
Indentation   +427 added lines, -427 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if (! defined('EVENT_ESPRESSO_VERSION')) {
3
-    exit('NO direct script access allowed');
3
+	exit('NO direct script access allowed');
4 4
 }
5 5
 
6 6
 /**
@@ -15,430 +15,430 @@  discard block
 block discarded – undo
15 15
 {
16 16
 
17 17
 
18
-    /**
19
-     * @return Messages_Admin_Page
20
-     */
21
-    public function get_admin_page()
22
-    {
23
-        return $this->_admin_page;
24
-    }
25
-
26
-
27
-    protected function _setup_data()
28
-    {
29
-        $this->_data           = $this->_get_messages($this->_per_page, $this->_view);
30
-        $this->_all_data_count = $this->_get_messages($this->_per_page, $this->_view, true);
31
-    }
32
-
33
-
34
-    protected function _set_properties()
35
-    {
36
-        $this->_wp_list_args = array(
37
-            'singular' => __('Message', 'event_espresso'),
38
-            'plural'   => __('Messages', 'event_espresso'),
39
-            'ajax'     => true,
40
-            'screen'   => $this->get_admin_page()->get_current_screen()->id,
41
-        );
42
-
43
-        $this->_columns = array(
44
-            'cb'           => '<input type="checkbox" />',
45
-            'to'           => __('To', 'event_espresso'),
46
-            'from'         => __('From', 'event_espresso'),
47
-            'messenger'    => __('Messenger', 'event_espresso'),
48
-            'message_type' => __('Message Type', 'event_espresso'),
49
-            'context'      => __('Context', 'event_espresso'),
50
-            'modified'     => __('Modified', 'event_espresso'),
51
-            'action'       => __('Actions', 'event_espresso'),
52
-            'msg_id'       => __('ID', 'event_espresso'),
53
-        );
54
-
55
-        $this->_sortable_columns = array(
56
-            'modified'     => array('MSG_modified' => true),
57
-            'message_type' => array('MSG_message_type' => false),
58
-            'messenger'    => array('MSG_messenger' => false),
59
-            'to'           => array('MSG_to' => false),
60
-            'from'         => array('MSG_from' => false),
61
-            'context'      => array('MSG_context' => false),
62
-            'msg_id'       => array('MSG_ID', false),
63
-        );
64
-
65
-        $this->_primary_column = 'to';
66
-
67
-        $this->_hidden_columns = array(
68
-            'msg_id',
69
-        );
70
-    }
71
-
72
-
73
-    /**
74
-     * This simply sets up the row class for the table rows.
75
-     * Allows for easier overriding of child methods for setting up sorting.
76
-     *
77
-     * @param  object $item the current item
78
-     * @return string
79
-     */
80
-    protected function _get_row_class($item)
81
-    {
82
-        $class = parent::_get_row_class($item);
83
-        //add status class
84
-        $class .= ' ee-status-strip msg-status-' . $item->STS_ID();
85
-        if ($this->_has_checkbox_column) {
86
-            $class .= ' has-checkbox-column';
87
-        }
88
-        return $class;
89
-    }
90
-
91
-
92
-    /**
93
-     * _get_table_filters
94
-     * We use this to assemble and return any filters that are associated with this table that help further refine what
95
-     * get's shown in the table.
96
-     *
97
-     * @abstract
98
-     * @access protected
99
-     * @return string
100
-     * @throws \EE_Error
101
-     */
102
-    protected function _get_table_filters()
103
-    {
104
-        $filters = array();
105
-
106
-        //get select_inputs
107
-        $select_inputs = array(
108
-            $this->_get_messengers_dropdown_filter(),
109
-            $this->_get_message_types_dropdown_filter(),
110
-            $this->_get_contexts_for_message_types_dropdown_filter(),
111
-        );
112
-
113
-        //set filters to select inputs if they aren't empty
114
-        foreach ($select_inputs as $select_input) {
115
-            if ($select_input) {
116
-                $filters[] = $select_input;
117
-            }
118
-        }
119
-        return $filters;
120
-    }
121
-
122
-
123
-    protected function _add_view_counts()
124
-    {
125
-        foreach ($this->_views as $view => $args) {
126
-            $this->_views[$view]['count'] = $this->_get_messages($this->_per_page, $view, true, true);
127
-        }
128
-    }
129
-
130
-
131
-    /**
132
-     * @param EE_Message $message
133
-     * @return string   checkbox
134
-     * @throws \EE_Error
135
-     */
136
-    public function column_cb($message)
137
-    {
138
-        return sprintf('<input type="checkbox" name="MSG_ID[%s]" value="1" />', $message->ID());
139
-    }
140
-
141
-
142
-    /**
143
-     * @param EE_Message $message
144
-     * @return string
145
-     * @throws \EE_Error
146
-     */
147
-    public function column_msg_id(EE_Message $message)
148
-    {
149
-        return $message->ID();
150
-    }
151
-
152
-
153
-    /**
154
-     * @param EE_Message $message
155
-     * @return string    The recipient of the message
156
-     * @throws \EE_Error
157
-     */
158
-    public function column_to(EE_Message $message)
159
-    {
160
-        EE_Registry::instance()->load_helper('URL');
161
-        $actions           = array();
162
-        $actions['delete'] = '<a href="'
163
-                             . EEH_URL::add_query_args_and_nonce(
164
-                array(
165
-                    'page'   => 'espresso_messages',
166
-                    'action' => 'delete_ee_message',
167
-                    'MSG_ID' => $message->ID(),
168
-                ),
169
-                admin_url('admin.php')
170
-            )
171
-                             . '">' . __('Delete', 'event_espresso') . '</a>';
172
-        return esc_html($message->to()) . $this->row_actions($actions);
173
-    }
174
-
175
-
176
-    /**
177
-     * @param EE_Message $message
178
-     * @return string   The sender of the message
179
-     */
180
-    public function column_from(EE_Message $message)
181
-    {
182
-        return esc_html($message->from());
183
-    }
184
-
185
-
186
-    /**
187
-     * @param EE_Message $message
188
-     * @return string  The messenger used to send the message.
189
-     */
190
-    public function column_messenger(EE_Message $message)
191
-    {
192
-        return ucwords($message->messenger_label());
193
-    }
194
-
195
-
196
-    /**
197
-     * @param EE_Message $message
198
-     * @return string  The message type used to generate the message.
199
-     */
200
-    public function column_message_type(EE_Message $message)
201
-    {
202
-        return ucwords($message->message_type_label());
203
-    }
204
-
205
-
206
-    /**
207
-     * @param EE_Message $message
208
-     * @return string  The context the message was generated for.
209
-     */
210
-    public function column_context(EE_Message $message)
211
-    {
212
-        return $message->context_label();
213
-    }
214
-
215
-
216
-    /**
217
-     * @param EE_Message $message
218
-     * @return string    The timestamp when this message was last modified.
219
-     */
220
-    public function column_modified(EE_Message $message)
221
-    {
222
-        return $message->modified();
223
-    }
224
-
225
-
226
-    /**
227
-     * @param EE_Message $message
228
-     * @return string   Actions that can be done on the current message.
229
-     */
230
-    public function column_action(EE_Message $message)
231
-    {
232
-        EE_Registry::instance()->load_helper('MSG_Template');
233
-        $action_links = array(
234
-            'view'                => EEH_MSG_Template::get_message_action_link('view', $message),
235
-            'error'               => EEH_MSG_Template::get_message_action_link('error', $message),
236
-            'generate_now'        => EEH_MSG_Template::get_message_action_link('generate_now', $message),
237
-            'send_now'            => EEH_MSG_Template::get_message_action_link('send_now', $message),
238
-            'queue_for_resending' => EEH_MSG_Template::get_message_action_link('queue_for_resending', $message),
239
-            'view_transaction'    => EEH_MSG_Template::get_message_action_link('view_transaction', $message),
240
-        );
241
-        $content      = '';
242
-        switch ($message->STS_ID()) {
243
-            case EEM_Message::status_sent :
244
-                $content = $action_links['view'] . $action_links['queue_for_resending'] . $action_links['view_transaction'];
245
-                break;
246
-            case EEM_Message::status_resend :
247
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
248
-                break;
249
-            case EEM_Message::status_retry :
250
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['error'] . $action_links['view_transaction'];
251
-                break;
252
-            case EEM_Message::status_failed :
253
-            case EEM_Message::status_debug_only :
254
-                $content = $action_links['error'] . $action_links['view_transaction'];
255
-                break;
256
-            case EEM_Message::status_idle :
257
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
258
-                break;
259
-            case EEM_Message::status_incomplete;
260
-                $content = $action_links['generate_now'] . $action_links['view_transaction'];
261
-                break;
262
-        }
263
-        return $content;
264
-    }
265
-
266
-
267
-    /**
268
-     * Retrieve the EE_Message objects for the list table.
269
-     *
270
-     * @param int    $perpage The number of items per page
271
-     * @param string $view    The view items are being retrieved for
272
-     * @param bool   $count   Whether to just return a count or not.
273
-     * @param bool   $all     Disregard any paging info (no limit on data returned).
274
-     * @return int|EE_Message[]
275
-     * @throws \EE_Error
276
-     */
277
-    protected function _get_messages($perpage = 10, $view = 'all', $count = false, $all = false)
278
-    {
279
-
280
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
281
-            ? $this->_req_data['paged']
282
-            : 1;
283
-
284
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
285
-            ? $this->_req_data['perpage']
286
-            : $perpage;
287
-
288
-        $offset       = ($current_page - 1) * $per_page;
289
-        $limit        = $all || $count ? null : array($offset, $per_page);
290
-        $query_params = array(
291
-            'order_by' => empty($this->_req_data['orderby']) ? 'MSG_modified' : $this->_req_data['orderby'],
292
-            'order'    => empty($this->_req_data['order']) ? 'DESC' : $this->_req_data['order'],
293
-            'limit'    => $limit,
294
-        );
295
-
296
-        /**
297
-         * Any filters coming in from other routes?
298
-         */
299
-        if (isset($this->_req_data['filterby'])) {
300
-            $query_params = array_merge($query_params, EEM_Message::instance()->filter_by_query_params());
301
-            if ( ! $count) {
302
-                $query_params['group_by'] = 'MSG_ID';
303
-            }
304
-        }
305
-
306
-        //view conditionals
307
-        if ($view !== 'all' && $count && $all) {
308
-            $query_params[0]['AND*view_conditional'] = array(
309
-                'STS_ID' => strtoupper($view),
310
-            );
311
-        }
312
-
313
-        if (! $all && ! empty($this->_req_data['status']) && $this->_req_data['status'] !== 'all') {
314
-            $query_params[0]['AND*view_conditional'] = $this->_req_data === EEM_Message::status_failed
315
-                ? array(
316
-                    'STS_ID' => array(
317
-                        'IN',
318
-                        array(EEM_Message::status_failed, EEM_Message::status_messenger_executing)
319
-                    )
320
-                )
321
-                : array( 'STS_ID' => strtoupper($this->_req_data['status']) );
322
-        }
323
-
324
-        if (! $all && ! empty($this->_req_data['s'])) {
325
-            $search_string         = '%' . $this->_req_data['s'] . '%';
326
-            $query_params[0]['OR'] = array(
327
-                'MSG_to'      => array('LIKE', $search_string),
328
-                'MSG_from'    => array('LIKE', $search_string),
329
-                'MSG_subject' => array('LIKE', $search_string),
330
-                'MSG_content' => array('LIKE', $search_string),
331
-            );
332
-        }
333
-
334
-        //account for debug only status.  We don't show Messages with the EEM_Message::status_debug_only to clients when
335
-        //the messages system is in debug mode.
336
-        //Note: for backward compat with previous iterations, this is necessary because there may be EEM_Message::status_debug_only
337
-        //messages in the database.
338
-        if (! EEM_Message::debug()) {
339
-            $query_params[0]['AND*debug_only_conditional'] = array(
340
-                'STS_ID' => array('!=', EEM_Message::status_debug_only),
341
-            );
342
-        }
343
-
344
-        //account for filters
345
-        if (! $all
346
-            && isset($this->_req_data['ee_messenger_filter_by'])
347
-            && $this->_req_data['ee_messenger_filter_by'] !== 'none_selected'
348
-        ) {
349
-            $query_params[0]['AND*messenger_filter'] = array(
350
-                'MSG_messenger' => $this->_req_data['ee_messenger_filter_by'],
351
-            );
352
-        }
353
-        if (! $all
354
-            && ! empty($this->_req_data['ee_message_type_filter_by'])
355
-            && $this->_req_data['ee_message_type_filter_by'] !== 'none_selected'
356
-        ) {
357
-            $query_params[0]['AND*message_type_filter'] = array(
358
-                'MSG_message_type' => $this->_req_data['ee_message_type_filter_by'],
359
-            );
360
-        }
361
-
362
-        if (! $all
363
-            && ! empty($this->_req_data['ee_context_filter_by'])
364
-            && $this->_req_data['ee_context_filter_by'] !== 'none_selected'
365
-        ) {
366
-            $query_params[0]['AND*context_filter'] = array(
367
-                'MSG_context' => array('IN', explode(',', $this->_req_data['ee_context_filter_by'])),
368
-            );
369
-        }
370
-
371
-        return $count
372
-            /** @type int */
373
-            ? EEM_Message::instance()->count($query_params, null, true)
374
-            /** @type EE_Message[] */
375
-            : EEM_Message::instance()->get_all($query_params);
376
-    }
377
-
378
-
379
-    /**
380
-     * Generate dropdown filter select input for messengers.
381
-     *
382
-     * @return string
383
-     */
384
-    protected function _get_messengers_dropdown_filter()
385
-    {
386
-        $messenger_options                    = array();
387
-        $active_messages_grouped_by_messenger = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
388
-
389
-        //setup array of messenger options
390
-        foreach ($active_messages_grouped_by_messenger as $active_message) {
391
-            if ($active_message instanceof EE_Message) {
392
-                $messenger_options[$active_message->messenger()] = ucwords($active_message->messenger_label());
393
-            }
394
-        }
395
-        return $this->get_admin_page()->get_messengers_select_input($messenger_options);
396
-    }
397
-
398
-
399
-    /**
400
-     * Generate dropdown filter select input for message types
401
-     *
402
-     * @return string
403
-     */
404
-    protected function _get_message_types_dropdown_filter()
405
-    {
406
-        $message_type_options                    = array();
407
-        $active_messages_grouped_by_message_type = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
408
-
409
-        //setup array of message type options
410
-        foreach ($active_messages_grouped_by_message_type as $active_message) {
411
-            if ($active_message instanceof EE_Message) {
412
-                $message_type_options[$active_message->message_type()] = ucwords($active_message->message_type_label());
413
-            }
414
-        }
415
-        return $this->get_admin_page()->get_message_types_select_input($message_type_options);
416
-    }
417
-
418
-
419
-    /**
420
-     * Generate dropdown filter select input for message type contexts
421
-     *
422
-     * @return string
423
-     */
424
-    protected function _get_contexts_for_message_types_dropdown_filter()
425
-    {
426
-        $context_options                    = array();
427
-        $active_messages_grouped_by_context = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
428
-
429
-        //setup array of context options
430
-        foreach ($active_messages_grouped_by_context as $active_message) {
431
-            if ($active_message instanceof EE_Message) {
432
-                $message_type = $active_message->message_type_object();
433
-                if ($message_type instanceof EE_message_type) {
434
-                    foreach ($message_type->get_contexts() as $context => $context_details) {
435
-                        if (isset($context_details['label'])) {
436
-                            $context_options[$context] = $context_details['label'];
437
-                        }
438
-                    }
439
-                }
440
-            }
441
-        }
442
-        return $this->get_admin_page()->get_contexts_for_message_types_select_input($context_options);
443
-    }
18
+	/**
19
+	 * @return Messages_Admin_Page
20
+	 */
21
+	public function get_admin_page()
22
+	{
23
+		return $this->_admin_page;
24
+	}
25
+
26
+
27
+	protected function _setup_data()
28
+	{
29
+		$this->_data           = $this->_get_messages($this->_per_page, $this->_view);
30
+		$this->_all_data_count = $this->_get_messages($this->_per_page, $this->_view, true);
31
+	}
32
+
33
+
34
+	protected function _set_properties()
35
+	{
36
+		$this->_wp_list_args = array(
37
+			'singular' => __('Message', 'event_espresso'),
38
+			'plural'   => __('Messages', 'event_espresso'),
39
+			'ajax'     => true,
40
+			'screen'   => $this->get_admin_page()->get_current_screen()->id,
41
+		);
42
+
43
+		$this->_columns = array(
44
+			'cb'           => '<input type="checkbox" />',
45
+			'to'           => __('To', 'event_espresso'),
46
+			'from'         => __('From', 'event_espresso'),
47
+			'messenger'    => __('Messenger', 'event_espresso'),
48
+			'message_type' => __('Message Type', 'event_espresso'),
49
+			'context'      => __('Context', 'event_espresso'),
50
+			'modified'     => __('Modified', 'event_espresso'),
51
+			'action'       => __('Actions', 'event_espresso'),
52
+			'msg_id'       => __('ID', 'event_espresso'),
53
+		);
54
+
55
+		$this->_sortable_columns = array(
56
+			'modified'     => array('MSG_modified' => true),
57
+			'message_type' => array('MSG_message_type' => false),
58
+			'messenger'    => array('MSG_messenger' => false),
59
+			'to'           => array('MSG_to' => false),
60
+			'from'         => array('MSG_from' => false),
61
+			'context'      => array('MSG_context' => false),
62
+			'msg_id'       => array('MSG_ID', false),
63
+		);
64
+
65
+		$this->_primary_column = 'to';
66
+
67
+		$this->_hidden_columns = array(
68
+			'msg_id',
69
+		);
70
+	}
71
+
72
+
73
+	/**
74
+	 * This simply sets up the row class for the table rows.
75
+	 * Allows for easier overriding of child methods for setting up sorting.
76
+	 *
77
+	 * @param  object $item the current item
78
+	 * @return string
79
+	 */
80
+	protected function _get_row_class($item)
81
+	{
82
+		$class = parent::_get_row_class($item);
83
+		//add status class
84
+		$class .= ' ee-status-strip msg-status-' . $item->STS_ID();
85
+		if ($this->_has_checkbox_column) {
86
+			$class .= ' has-checkbox-column';
87
+		}
88
+		return $class;
89
+	}
90
+
91
+
92
+	/**
93
+	 * _get_table_filters
94
+	 * We use this to assemble and return any filters that are associated with this table that help further refine what
95
+	 * get's shown in the table.
96
+	 *
97
+	 * @abstract
98
+	 * @access protected
99
+	 * @return string
100
+	 * @throws \EE_Error
101
+	 */
102
+	protected function _get_table_filters()
103
+	{
104
+		$filters = array();
105
+
106
+		//get select_inputs
107
+		$select_inputs = array(
108
+			$this->_get_messengers_dropdown_filter(),
109
+			$this->_get_message_types_dropdown_filter(),
110
+			$this->_get_contexts_for_message_types_dropdown_filter(),
111
+		);
112
+
113
+		//set filters to select inputs if they aren't empty
114
+		foreach ($select_inputs as $select_input) {
115
+			if ($select_input) {
116
+				$filters[] = $select_input;
117
+			}
118
+		}
119
+		return $filters;
120
+	}
121
+
122
+
123
+	protected function _add_view_counts()
124
+	{
125
+		foreach ($this->_views as $view => $args) {
126
+			$this->_views[$view]['count'] = $this->_get_messages($this->_per_page, $view, true, true);
127
+		}
128
+	}
129
+
130
+
131
+	/**
132
+	 * @param EE_Message $message
133
+	 * @return string   checkbox
134
+	 * @throws \EE_Error
135
+	 */
136
+	public function column_cb($message)
137
+	{
138
+		return sprintf('<input type="checkbox" name="MSG_ID[%s]" value="1" />', $message->ID());
139
+	}
140
+
141
+
142
+	/**
143
+	 * @param EE_Message $message
144
+	 * @return string
145
+	 * @throws \EE_Error
146
+	 */
147
+	public function column_msg_id(EE_Message $message)
148
+	{
149
+		return $message->ID();
150
+	}
151
+
152
+
153
+	/**
154
+	 * @param EE_Message $message
155
+	 * @return string    The recipient of the message
156
+	 * @throws \EE_Error
157
+	 */
158
+	public function column_to(EE_Message $message)
159
+	{
160
+		EE_Registry::instance()->load_helper('URL');
161
+		$actions           = array();
162
+		$actions['delete'] = '<a href="'
163
+							 . EEH_URL::add_query_args_and_nonce(
164
+				array(
165
+					'page'   => 'espresso_messages',
166
+					'action' => 'delete_ee_message',
167
+					'MSG_ID' => $message->ID(),
168
+				),
169
+				admin_url('admin.php')
170
+			)
171
+							 . '">' . __('Delete', 'event_espresso') . '</a>';
172
+		return esc_html($message->to()) . $this->row_actions($actions);
173
+	}
174
+
175
+
176
+	/**
177
+	 * @param EE_Message $message
178
+	 * @return string   The sender of the message
179
+	 */
180
+	public function column_from(EE_Message $message)
181
+	{
182
+		return esc_html($message->from());
183
+	}
184
+
185
+
186
+	/**
187
+	 * @param EE_Message $message
188
+	 * @return string  The messenger used to send the message.
189
+	 */
190
+	public function column_messenger(EE_Message $message)
191
+	{
192
+		return ucwords($message->messenger_label());
193
+	}
194
+
195
+
196
+	/**
197
+	 * @param EE_Message $message
198
+	 * @return string  The message type used to generate the message.
199
+	 */
200
+	public function column_message_type(EE_Message $message)
201
+	{
202
+		return ucwords($message->message_type_label());
203
+	}
204
+
205
+
206
+	/**
207
+	 * @param EE_Message $message
208
+	 * @return string  The context the message was generated for.
209
+	 */
210
+	public function column_context(EE_Message $message)
211
+	{
212
+		return $message->context_label();
213
+	}
214
+
215
+
216
+	/**
217
+	 * @param EE_Message $message
218
+	 * @return string    The timestamp when this message was last modified.
219
+	 */
220
+	public function column_modified(EE_Message $message)
221
+	{
222
+		return $message->modified();
223
+	}
224
+
225
+
226
+	/**
227
+	 * @param EE_Message $message
228
+	 * @return string   Actions that can be done on the current message.
229
+	 */
230
+	public function column_action(EE_Message $message)
231
+	{
232
+		EE_Registry::instance()->load_helper('MSG_Template');
233
+		$action_links = array(
234
+			'view'                => EEH_MSG_Template::get_message_action_link('view', $message),
235
+			'error'               => EEH_MSG_Template::get_message_action_link('error', $message),
236
+			'generate_now'        => EEH_MSG_Template::get_message_action_link('generate_now', $message),
237
+			'send_now'            => EEH_MSG_Template::get_message_action_link('send_now', $message),
238
+			'queue_for_resending' => EEH_MSG_Template::get_message_action_link('queue_for_resending', $message),
239
+			'view_transaction'    => EEH_MSG_Template::get_message_action_link('view_transaction', $message),
240
+		);
241
+		$content      = '';
242
+		switch ($message->STS_ID()) {
243
+			case EEM_Message::status_sent :
244
+				$content = $action_links['view'] . $action_links['queue_for_resending'] . $action_links['view_transaction'];
245
+				break;
246
+			case EEM_Message::status_resend :
247
+				$content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
248
+				break;
249
+			case EEM_Message::status_retry :
250
+				$content = $action_links['view'] . $action_links['send_now'] . $action_links['error'] . $action_links['view_transaction'];
251
+				break;
252
+			case EEM_Message::status_failed :
253
+			case EEM_Message::status_debug_only :
254
+				$content = $action_links['error'] . $action_links['view_transaction'];
255
+				break;
256
+			case EEM_Message::status_idle :
257
+				$content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
258
+				break;
259
+			case EEM_Message::status_incomplete;
260
+				$content = $action_links['generate_now'] . $action_links['view_transaction'];
261
+				break;
262
+		}
263
+		return $content;
264
+	}
265
+
266
+
267
+	/**
268
+	 * Retrieve the EE_Message objects for the list table.
269
+	 *
270
+	 * @param int    $perpage The number of items per page
271
+	 * @param string $view    The view items are being retrieved for
272
+	 * @param bool   $count   Whether to just return a count or not.
273
+	 * @param bool   $all     Disregard any paging info (no limit on data returned).
274
+	 * @return int|EE_Message[]
275
+	 * @throws \EE_Error
276
+	 */
277
+	protected function _get_messages($perpage = 10, $view = 'all', $count = false, $all = false)
278
+	{
279
+
280
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
281
+			? $this->_req_data['paged']
282
+			: 1;
283
+
284
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
285
+			? $this->_req_data['perpage']
286
+			: $perpage;
287
+
288
+		$offset       = ($current_page - 1) * $per_page;
289
+		$limit        = $all || $count ? null : array($offset, $per_page);
290
+		$query_params = array(
291
+			'order_by' => empty($this->_req_data['orderby']) ? 'MSG_modified' : $this->_req_data['orderby'],
292
+			'order'    => empty($this->_req_data['order']) ? 'DESC' : $this->_req_data['order'],
293
+			'limit'    => $limit,
294
+		);
295
+
296
+		/**
297
+		 * Any filters coming in from other routes?
298
+		 */
299
+		if (isset($this->_req_data['filterby'])) {
300
+			$query_params = array_merge($query_params, EEM_Message::instance()->filter_by_query_params());
301
+			if ( ! $count) {
302
+				$query_params['group_by'] = 'MSG_ID';
303
+			}
304
+		}
305
+
306
+		//view conditionals
307
+		if ($view !== 'all' && $count && $all) {
308
+			$query_params[0]['AND*view_conditional'] = array(
309
+				'STS_ID' => strtoupper($view),
310
+			);
311
+		}
312
+
313
+		if (! $all && ! empty($this->_req_data['status']) && $this->_req_data['status'] !== 'all') {
314
+			$query_params[0]['AND*view_conditional'] = $this->_req_data === EEM_Message::status_failed
315
+				? array(
316
+					'STS_ID' => array(
317
+						'IN',
318
+						array(EEM_Message::status_failed, EEM_Message::status_messenger_executing)
319
+					)
320
+				)
321
+				: array( 'STS_ID' => strtoupper($this->_req_data['status']) );
322
+		}
323
+
324
+		if (! $all && ! empty($this->_req_data['s'])) {
325
+			$search_string         = '%' . $this->_req_data['s'] . '%';
326
+			$query_params[0]['OR'] = array(
327
+				'MSG_to'      => array('LIKE', $search_string),
328
+				'MSG_from'    => array('LIKE', $search_string),
329
+				'MSG_subject' => array('LIKE', $search_string),
330
+				'MSG_content' => array('LIKE', $search_string),
331
+			);
332
+		}
333
+
334
+		//account for debug only status.  We don't show Messages with the EEM_Message::status_debug_only to clients when
335
+		//the messages system is in debug mode.
336
+		//Note: for backward compat with previous iterations, this is necessary because there may be EEM_Message::status_debug_only
337
+		//messages in the database.
338
+		if (! EEM_Message::debug()) {
339
+			$query_params[0]['AND*debug_only_conditional'] = array(
340
+				'STS_ID' => array('!=', EEM_Message::status_debug_only),
341
+			);
342
+		}
343
+
344
+		//account for filters
345
+		if (! $all
346
+			&& isset($this->_req_data['ee_messenger_filter_by'])
347
+			&& $this->_req_data['ee_messenger_filter_by'] !== 'none_selected'
348
+		) {
349
+			$query_params[0]['AND*messenger_filter'] = array(
350
+				'MSG_messenger' => $this->_req_data['ee_messenger_filter_by'],
351
+			);
352
+		}
353
+		if (! $all
354
+			&& ! empty($this->_req_data['ee_message_type_filter_by'])
355
+			&& $this->_req_data['ee_message_type_filter_by'] !== 'none_selected'
356
+		) {
357
+			$query_params[0]['AND*message_type_filter'] = array(
358
+				'MSG_message_type' => $this->_req_data['ee_message_type_filter_by'],
359
+			);
360
+		}
361
+
362
+		if (! $all
363
+			&& ! empty($this->_req_data['ee_context_filter_by'])
364
+			&& $this->_req_data['ee_context_filter_by'] !== 'none_selected'
365
+		) {
366
+			$query_params[0]['AND*context_filter'] = array(
367
+				'MSG_context' => array('IN', explode(',', $this->_req_data['ee_context_filter_by'])),
368
+			);
369
+		}
370
+
371
+		return $count
372
+			/** @type int */
373
+			? EEM_Message::instance()->count($query_params, null, true)
374
+			/** @type EE_Message[] */
375
+			: EEM_Message::instance()->get_all($query_params);
376
+	}
377
+
378
+
379
+	/**
380
+	 * Generate dropdown filter select input for messengers.
381
+	 *
382
+	 * @return string
383
+	 */
384
+	protected function _get_messengers_dropdown_filter()
385
+	{
386
+		$messenger_options                    = array();
387
+		$active_messages_grouped_by_messenger = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
388
+
389
+		//setup array of messenger options
390
+		foreach ($active_messages_grouped_by_messenger as $active_message) {
391
+			if ($active_message instanceof EE_Message) {
392
+				$messenger_options[$active_message->messenger()] = ucwords($active_message->messenger_label());
393
+			}
394
+		}
395
+		return $this->get_admin_page()->get_messengers_select_input($messenger_options);
396
+	}
397
+
398
+
399
+	/**
400
+	 * Generate dropdown filter select input for message types
401
+	 *
402
+	 * @return string
403
+	 */
404
+	protected function _get_message_types_dropdown_filter()
405
+	{
406
+		$message_type_options                    = array();
407
+		$active_messages_grouped_by_message_type = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
408
+
409
+		//setup array of message type options
410
+		foreach ($active_messages_grouped_by_message_type as $active_message) {
411
+			if ($active_message instanceof EE_Message) {
412
+				$message_type_options[$active_message->message_type()] = ucwords($active_message->message_type_label());
413
+			}
414
+		}
415
+		return $this->get_admin_page()->get_message_types_select_input($message_type_options);
416
+	}
417
+
418
+
419
+	/**
420
+	 * Generate dropdown filter select input for message type contexts
421
+	 *
422
+	 * @return string
423
+	 */
424
+	protected function _get_contexts_for_message_types_dropdown_filter()
425
+	{
426
+		$context_options                    = array();
427
+		$active_messages_grouped_by_context = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
428
+
429
+		//setup array of context options
430
+		foreach ($active_messages_grouped_by_context as $active_message) {
431
+			if ($active_message instanceof EE_Message) {
432
+				$message_type = $active_message->message_type_object();
433
+				if ($message_type instanceof EE_message_type) {
434
+					foreach ($message_type->get_contexts() as $context => $context_details) {
435
+						if (isset($context_details['label'])) {
436
+							$context_options[$context] = $context_details['label'];
437
+						}
438
+					}
439
+				}
440
+			}
441
+		}
442
+		return $this->get_admin_page()->get_contexts_for_message_types_select_input($context_options);
443
+	}
444 444
 } //end EE_Message_List_Table class
445 445
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if (! defined('EVENT_ESPRESSO_VERSION')) {
2
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3 3
     exit('NO direct script access allowed');
4 4
 }
5 5
 
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
     {
82 82
         $class = parent::_get_row_class($item);
83 83
         //add status class
84
-        $class .= ' ee-status-strip msg-status-' . $item->STS_ID();
84
+        $class .= ' ee-status-strip msg-status-'.$item->STS_ID();
85 85
         if ($this->_has_checkbox_column) {
86 86
             $class .= ' has-checkbox-column';
87 87
         }
@@ -168,8 +168,8 @@  discard block
 block discarded – undo
168 168
                 ),
169 169
                 admin_url('admin.php')
170 170
             )
171
-                             . '">' . __('Delete', 'event_espresso') . '</a>';
172
-        return esc_html($message->to()) . $this->row_actions($actions);
171
+                             . '">'.__('Delete', 'event_espresso').'</a>';
172
+        return esc_html($message->to()).$this->row_actions($actions);
173 173
     }
174 174
 
175 175
 
@@ -238,26 +238,26 @@  discard block
 block discarded – undo
238 238
             'queue_for_resending' => EEH_MSG_Template::get_message_action_link('queue_for_resending', $message),
239 239
             'view_transaction'    => EEH_MSG_Template::get_message_action_link('view_transaction', $message),
240 240
         );
241
-        $content      = '';
241
+        $content = '';
242 242
         switch ($message->STS_ID()) {
243 243
             case EEM_Message::status_sent :
244
-                $content = $action_links['view'] . $action_links['queue_for_resending'] . $action_links['view_transaction'];
244
+                $content = $action_links['view'].$action_links['queue_for_resending'].$action_links['view_transaction'];
245 245
                 break;
246 246
             case EEM_Message::status_resend :
247
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
247
+                $content = $action_links['view'].$action_links['send_now'].$action_links['view_transaction'];
248 248
                 break;
249 249
             case EEM_Message::status_retry :
250
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['error'] . $action_links['view_transaction'];
250
+                $content = $action_links['view'].$action_links['send_now'].$action_links['error'].$action_links['view_transaction'];
251 251
                 break;
252 252
             case EEM_Message::status_failed :
253 253
             case EEM_Message::status_debug_only :
254
-                $content = $action_links['error'] . $action_links['view_transaction'];
254
+                $content = $action_links['error'].$action_links['view_transaction'];
255 255
                 break;
256 256
             case EEM_Message::status_idle :
257
-                $content = $action_links['view'] . $action_links['send_now'] . $action_links['view_transaction'];
257
+                $content = $action_links['view'].$action_links['send_now'].$action_links['view_transaction'];
258 258
                 break;
259 259
             case EEM_Message::status_incomplete;
260
-                $content = $action_links['generate_now'] . $action_links['view_transaction'];
260
+                $content = $action_links['generate_now'].$action_links['view_transaction'];
261 261
                 break;
262 262
         }
263 263
         return $content;
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
             );
311 311
         }
312 312
 
313
-        if (! $all && ! empty($this->_req_data['status']) && $this->_req_data['status'] !== 'all') {
313
+        if ( ! $all && ! empty($this->_req_data['status']) && $this->_req_data['status'] !== 'all') {
314 314
             $query_params[0]['AND*view_conditional'] = $this->_req_data === EEM_Message::status_failed
315 315
                 ? array(
316 316
                     'STS_ID' => array(
@@ -318,11 +318,11 @@  discard block
 block discarded – undo
318 318
                         array(EEM_Message::status_failed, EEM_Message::status_messenger_executing)
319 319
                     )
320 320
                 )
321
-                : array( 'STS_ID' => strtoupper($this->_req_data['status']) );
321
+                : array('STS_ID' => strtoupper($this->_req_data['status']));
322 322
         }
323 323
 
324
-        if (! $all && ! empty($this->_req_data['s'])) {
325
-            $search_string         = '%' . $this->_req_data['s'] . '%';
324
+        if ( ! $all && ! empty($this->_req_data['s'])) {
325
+            $search_string         = '%'.$this->_req_data['s'].'%';
326 326
             $query_params[0]['OR'] = array(
327 327
                 'MSG_to'      => array('LIKE', $search_string),
328 328
                 'MSG_from'    => array('LIKE', $search_string),
@@ -335,14 +335,14 @@  discard block
 block discarded – undo
335 335
         //the messages system is in debug mode.
336 336
         //Note: for backward compat with previous iterations, this is necessary because there may be EEM_Message::status_debug_only
337 337
         //messages in the database.
338
-        if (! EEM_Message::debug()) {
338
+        if ( ! EEM_Message::debug()) {
339 339
             $query_params[0]['AND*debug_only_conditional'] = array(
340 340
                 'STS_ID' => array('!=', EEM_Message::status_debug_only),
341 341
             );
342 342
         }
343 343
 
344 344
         //account for filters
345
-        if (! $all
345
+        if ( ! $all
346 346
             && isset($this->_req_data['ee_messenger_filter_by'])
347 347
             && $this->_req_data['ee_messenger_filter_by'] !== 'none_selected'
348 348
         ) {
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
                 'MSG_messenger' => $this->_req_data['ee_messenger_filter_by'],
351 351
             );
352 352
         }
353
-        if (! $all
353
+        if ( ! $all
354 354
             && ! empty($this->_req_data['ee_message_type_filter_by'])
355 355
             && $this->_req_data['ee_message_type_filter_by'] !== 'none_selected'
356 356
         ) {
@@ -359,7 +359,7 @@  discard block
 block discarded – undo
359 359
             );
360 360
         }
361 361
 
362
-        if (! $all
362
+        if ( ! $all
363 363
             && ! empty($this->_req_data['ee_context_filter_by'])
364 364
             && $this->_req_data['ee_context_filter_by'] !== 'none_selected'
365 365
         ) {
Please login to merge, or discard this patch.
core/db_models/EEM_Message.model.php 1 patch
Indentation   +472 added lines, -472 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -12,481 +12,481 @@  discard block
 block discarded – undo
12 12
 class EEM_Message extends EEM_Base implements EEI_Query_Filter
13 13
 {
14 14
 
15
-    // private instance of the Message object
16
-    protected static $_instance = null;
15
+	// private instance of the Message object
16
+	protected static $_instance = null;
17 17
 
18 18
 
19
-    /**
20
-     * This priority indicates a message should be generated and sent ASAP
21
-     *
22
-     * @type int
23
-     */
24
-    const priority_high = 10;
19
+	/**
20
+	 * This priority indicates a message should be generated and sent ASAP
21
+	 *
22
+	 * @type int
23
+	 */
24
+	const priority_high = 10;
25 25
 
26 26
 
27
-    /**
28
-     * This priority indicates a message should be generated ASAP and queued for sending.
29
-     *
30
-     * @type
31
-     */
32
-    const priority_medium = 20;
33
-
34
-
35
-    /**
36
-     * This priority indicates a message should be queued for generating.
37
-     *
38
-     * @type int
39
-     */
40
-    const priority_low = 30;
41
-
42
-
43
-    /**
44
-     * indicates this message was sent at the time modified
45
-     */
46
-    const status_sent = 'MSN';
47
-
48
-
49
-    /**
50
-     * indicates this message is waiting to be sent
51
-     */
52
-    const status_idle = 'MID';
53
-
54
-
55
-    /**
56
-     * indicates an attempt was a made to send this message
57
-     * at the scheduled time, but it failed at the time modified.  This differs from MDO status in that it will ALWAYS
58
-     * appear to the end user.
59
-     */
60
-    const status_failed = 'MFL';
61
-
62
-
63
-    /**
64
-     * indicates the message has been flagged for resending (at the time modified).
65
-     */
66
-    const status_resend = 'MRS';
67
-
68
-
69
-    /**
70
-     * indicates the message has been flagged for generation but has not been generated yet.  Messages always start as
71
-     * this status when added to the queue.
72
-     */
73
-    const status_incomplete = 'MIC';
74
-
75
-
76
-    /**
77
-     * Indicates everything was generated fine for the message, however, the messenger was unable to send.
78
-     * This status means that its possible to retry sending the message.
79
-     */
80
-    const status_retry = 'MRT';
81
-
82
-
83
-    /**
84
-     * This is used for more informational messages that may not indicate anything is broken but still cannot be
85
-     * generated or sent correctly. An example of a message that would get flagged this way would be when a not
86
-     * approved message was queued for generation, but at time of generation, the attached registration(s) are
87
-     * approved. So the message queued for generation is no longer valid.  Messages for this status will only persist
88
-     * in the db and be viewable in the message activity list table when the messages system is in debug mode.
89
-     *
90
-     * @see EEM_Message::debug()
91
-     */
92
-    const status_debug_only = 'MDO';
93
-
94
-
95
-    /**
96
-     * This status is given to messages it is processed by the messenger send method.
97
-     * Messages with this status should rarely be seen in the Message List table, but if they are, that's usually
98
-     * indicative of a PHP timeout or memory limit issue.
99
-     */
100
-    const status_messenger_executing = 'MEX';
101
-
102
-
103
-    /**
104
-     *    Private constructor to prevent direct creation.
105
-     *
106
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and
107
-     *                         any incoming timezone data that gets saved).  Note this just sends the timezone info to
108
-     *                         the date time model field objects.  Default is null (and will be assumed using the set
109
-     *                         timezone in the 'timezone_string' wp option)
110
-     * @return EEM_Message
111
-     */
112
-    protected function __construct($timezone = null)
113
-    {
114
-        $this->singular_item = __('Message', 'event_espresso');
115
-        $this->plural_item   = __('Messages', 'event_espresso');
116
-
117
-        //used for token generator
118
-        EE_Registry::instance()->load_helper('URL');
119
-
120
-        $this->_tables = array(
121
-            'Message' => new EE_Primary_Table('esp_message', 'MSG_ID'),
122
-        );
123
-
124
-        $allowed_priority = array(
125
-            self::priority_high   => __('high', 'event_espresso'),
126
-            self::priority_medium => __('medium', 'event_espresso'),
127
-            self::priority_low    => __('low', 'event_espresso'),
128
-        );
129
-
130
-        $this->_fields          = array(
131
-            'Message' => array(
132
-                'MSG_ID'             => new EE_Primary_Key_Int_Field('MSG_ID', __('Message ID', 'event_espresso')),
133
-                'MSG_token'          => new EE_Plain_Text_Field('MSG_token',
134
-                    __('Unique Token used to represent this row in publicly viewable contexts (eg. a url).',
135
-                        'event_espresso'), false, EEH_URL::generate_unique_token()),
136
-                'GRP_ID'             => new EE_Foreign_Key_Int_Field('GRP_ID',
137
-                    __('Foreign key to the EEM_Message_Template_Group table.', 'event_espresso'), true, 0,
138
-                    'Message_Template_Group'),
139
-                'TXN_ID'             => new EE_Foreign_Key_Int_Field('TXN_ID',
140
-                    __('Foreign key to the related EE_Transaction.  This is required to give context for regenerating the specific message',
141
-                        'event_espresso'), true, 0, 'Transaction'),
142
-                'MSG_messenger'      => new EE_Plain_Text_Field('MSG_messenger',
143
-                    __('Corresponds to the EE_messenger::name used to send this message. This will also be used to attempt any resending of the message.',
144
-                        'event_espresso'), false, 'email'),
145
-                'MSG_message_type'   => new EE_Plain_Text_Field('MSG_message_type',
146
-                    __('Corresponds to the EE_message_type::name used to generate this message.', 'event_espresso'),
147
-                    false, 'receipt'),
148
-                'MSG_context'        => new EE_Plain_Text_Field('MSG_context', __('Context', 'event_espresso'), false),
149
-                'MSG_recipient_ID'   => new EE_Foreign_Key_Int_Field('MSG_recipient_ID',
150
-                    __('Recipient ID', 'event_espresso'), true, null, array('Registration', 'Attendee', 'WP_User')),
151
-                'MSG_recipient_type' => new EE_Any_Foreign_Model_Name_Field('MSG_recipient_type',
152
-                    __('Recipient Type', 'event_espresso'), true, null, array('Registration', 'Attendee', 'WP_User')),
153
-                'MSG_content'        => new EE_Maybe_Serialized_Text_Field('MSG_content',
154
-                    __('Content', 'event_espresso'), true, ''),
155
-                'MSG_to'             => new EE_Maybe_Serialized_Text_Field('MSG_to', __('Address To', 'event_espresso'),
156
-                    true),
157
-                'MSG_from'           => new EE_Maybe_Serialized_Text_Field('MSG_from',
158
-                    __('Address From', 'event_espresso'), true),
159
-                'MSG_subject'        => new EE_Maybe_Serialized_Text_Field('MSG_subject',
160
-                    __('Subject', 'event_espresso'), true, ''),
161
-                'MSG_priority'       => new EE_Enum_Integer_Field('MSG_priority', __('Priority', 'event_espresso'),
162
-                    false, self::priority_low, $allowed_priority),
163
-                'STS_ID'             => new EE_Foreign_Key_String_Field('STS_ID', __('Status', 'event_espresso'), false,
164
-                    self::status_incomplete, 'Status'),
165
-                'MSG_created'        => new EE_Datetime_Field('MSG_created', __('Created', 'event_espresso'), false,
166
-                    EE_Datetime_Field::now),
167
-                'MSG_modified'       => new EE_Datetime_Field('MSG_modified', __('Modified', 'event_espresso'), true,
168
-                    EE_Datetime_Field::now),
169
-            ),
170
-        );
171
-        $this->_model_relations = array(
172
-            'Attendee'               => new EE_Belongs_To_Any_Relation(),
173
-            'Registration'           => new EE_Belongs_To_Any_Relation(),
174
-            'WP_User'                => new EE_Belongs_To_Any_Relation(),
175
-            'Message_Template_Group' => new EE_Belongs_To_Relation(),
176
-            'Transaction'            => new EE_Belongs_To_Relation(),
177
-        );
178
-        parent::__construct($timezone);
179
-    }
180
-
181
-
182
-    /**
183
-     * @return \EE_Message
184
-     */
185
-    public function create_default_object()
186
-    {
187
-        /** @type EE_Message $message */
188
-        $message = parent::create_default_object();
189
-        if ($message instanceof EE_Message) {
190
-            return EE_Message_Factory::set_messenger_and_message_type($message);
191
-        }
192
-        return null;
193
-    }
194
-
195
-
196
-    /**
197
-     * @param mixed $cols_n_values
198
-     * @return \EE_Message
199
-     */
200
-    public function instantiate_class_from_array_or_object($cols_n_values)
201
-    {
202
-        /** @type EE_Message $message */
203
-        $message = parent::instantiate_class_from_array_or_object($cols_n_values);
204
-        if ($message instanceof EE_Message) {
205
-            return EE_Message_Factory::set_messenger_and_message_type($message);
206
-        }
207
-        return null;
208
-    }
209
-
210
-
211
-    /**
212
-     * Returns whether or not a message of that type was sent for a given attendee.
213
-     *
214
-     * @param EE_Attendee|int $attendee
215
-     * @param string          $message_type the message type slug
216
-     * @return boolean
217
-     */
218
-    public function message_sent_for_attendee($attendee, $message_type)
219
-    {
220
-        $attendee_ID = EEM_Attendee::instance()->ensure_is_ID($attendee);
221
-        return $this->exists(array(
222
-            array(
223
-                'Attendee.ATT_ID'  => $attendee_ID,
224
-                'MSG_message_type' => $message_type,
225
-                'STS_ID'           => array('IN', $this->stati_indicating_sent()),
226
-            ),
227
-        ));
228
-    }
229
-
230
-
231
-    /**
232
-     * Returns whether or not a message of that type was sent for a given registration
233
-     *
234
-     * @param EE_Registration|int $registration
235
-     * @param string              $message_type the message type slug
236
-     * @return boolean
237
-     */
238
-    public function message_sent_for_registration($registration, $message_type)
239
-    {
240
-        $registrationID = EEM_Registration::instance()->ensure_is_ID($registration);
241
-        return $this->exists(array(
242
-            array(
243
-                'Registration.REG_ID' => $registrationID,
244
-                'MSG_message_type'    => $message_type,
245
-                'STS_ID'              => array('IN', $this->stati_indicating_sent()),
246
-            ),
247
-        ));
248
-    }
249
-
250
-
251
-    /**
252
-     * This retrieves an EE_Message object from the db matching the given token string.
253
-     *
254
-     * @param string $token
255
-     * @return EE_Message
256
-     */
257
-    public function get_one_by_token($token)
258
-    {
259
-        return $this->get_one(array(
260
-            array(
261
-                'MSG_token' => $token,
262
-            ),
263
-        ));
264
-    }
265
-
266
-
267
-    /**
268
-     * Returns stati that indicate the message HAS been sent
269
-     *
270
-     * @return array of strings for possible stati
271
-     */
272
-    public function stati_indicating_sent()
273
-    {
274
-        return apply_filters('FHEE__EEM_Message__stati_indicating_sent', array(self::status_sent));
275
-    }
276
-
277
-
278
-    /**
279
-     * Returns stati that indicate the message is waiting to be sent.
280
-     *
281
-     * @return array of strings for possible stati.
282
-     */
283
-    public function stati_indicating_to_send()
284
-    {
285
-        return apply_filters('FHEE__EEM_Message__stati_indicating_to_send',
286
-            array(self::status_idle, self::status_resend));
287
-    }
288
-
289
-
290
-    /**
291
-     * Returns stati that indicate the message has failed sending
292
-     *
293
-     * @return array  array of strings for possible stati.
294
-     */
295
-    public function stati_indicating_failed_sending()
296
-    {
297
-        $failed_stati = array(
298
-            self::status_failed,
299
-            self::status_retry,
300
-            self::status_messenger_executing,
301
-        );
302
-        //if WP_DEBUG is set, then let's include debug_only fails
303
-        if (WP_DEBUG) {
304
-            $failed_stati[] = self::status_debug_only;
305
-        }
306
-        return apply_filters('FHEE__EEM_Message__stati_indicating_failed_sending', $failed_stati);
307
-    }
308
-
309
-
310
-    /**
311
-     * Returns filterable array of all EEM_Message statuses.
312
-     *
313
-     * @return array
314
-     */
315
-    public function all_statuses()
316
-    {
317
-        return apply_filters(
318
-            'FHEE__EEM_Message__all_statuses',
319
-            array(
320
-                EEM_Message::status_sent,
321
-                EEM_Message::status_incomplete,
322
-                EEM_Message::status_idle,
323
-                EEM_Message::status_resend,
324
-                EEM_Message::status_retry,
325
-                EEM_Message::status_failed,
326
-                EEM_Message::status_messenger_executing,
327
-                EEM_Message::status_debug_only,
328
-            )
329
-        );
330
-    }
331
-
332
-    /**
333
-     * Detects any specific query variables in the request and uses those to setup appropriate
334
-     * filter for any queries.
335
-     *
336
-     * @return array
337
-     */
338
-    public function filter_by_query_params()
339
-    {
340
-        // expected possible query_vars, the key in this array matches an expected key in the request,
341
-        // the value, matches the corresponding EEM_Base child reference.
342
-        $expected_vars   = $this->_expected_vars_for_query_inject();
343
-        $query_params[0] = array();
344
-        foreach ($expected_vars as $request_key => $model_name) {
345
-            $request_value = EE_Registry::instance()->REQ->get($request_key);
346
-            if ($request_value) {
347
-                //special case
348
-                switch ($request_key) {
349
-                    case '_REG_ID' :
350
-                        $query_params[0]['AND**filter_by']['OR**filter_by_REG_ID'] = array(
351
-                            'Transaction.Registration.REG_ID' => $request_value,
352
-                        );
353
-                        break;
354
-                    case 'EVT_ID' :
355
-                        $query_params[0]['AND**filter_by']['OR**filter_by_EVT_ID'] = array(
356
-                            'Transaction.Registration.EVT_ID' => $request_value,
357
-                        );
358
-                        break;
359
-                    default :
360
-                        $query_params[0]['AND**filter_by']['OR**filter_by_' . $request_key][$model_name . '.' . $request_key] = $request_value;
361
-                        break;
362
-                }
363
-            }
364
-        }
365
-        return $query_params;
366
-    }
367
-
368
-
369
-    /**
370
-     * @return string
371
-     */
372
-    public function get_pretty_label_for_results()
373
-    {
374
-        $expected_vars = $this->_expected_vars_for_query_inject();
375
-        $pretty_label  = '';
376
-        $label_parts   = array();
377
-        foreach ($expected_vars as $request_key => $model_name) {
378
-            $model = EE_Registry::instance()->load_model($model_name);
379
-            if ($model_field_value = EE_Registry::instance()->REQ->get($request_key)) {
380
-                switch ($request_key) {
381
-                    case '_REG_ID' :
382
-                        $label_parts[] = sprintf(
383
-                            esc_html__('Registration with the ID: %s', 'event_espresso'),
384
-                            $model_field_value
385
-                        );
386
-                        break;
387
-                    case 'ATT_ID' :
388
-                        /** @var EE_Attendee $attendee */
389
-                        $attendee      = $model->get_one_by_ID($model_field_value);
390
-                        $label_parts[] = $attendee instanceof EE_Attendee
391
-                            ? sprintf(esc_html__('Attendee %s', 'event_espresso'), $attendee->full_name())
392
-                            : sprintf(esc_html__('Attendee ID: %s', 'event_espresso'), $model_field_value);
393
-                        break;
394
-                    case 'ID' :
395
-                        /** @var EE_WP_User $wpUser */
396
-                        $wpUser        = $model->get_one_by_ID($model_field_value);
397
-                        $label_parts[] = $wpUser instanceof EE_WP_User
398
-                            ? sprintf(esc_html__('WP User: %s', 'event_espresso'), $wpUser->name())
399
-                            : sprintf(esc_html__('WP User ID: %s', 'event_espresso'), $model_field_value);
400
-                        break;
401
-                    case 'TXN_ID' :
402
-                        $label_parts[] = sprintf(
403
-                            esc_html__('Transaction with the ID: %s', 'event_espresso'),
404
-                            $model_field_value
405
-                        );
406
-                        break;
407
-                    case 'EVT_ID' :
408
-                        /** @var EE_Event $Event */
409
-                        $Event         = $model->get_one_by_ID($model_field_value);
410
-                        $label_parts[] = $Event instanceof EE_Event
411
-                            ? sprintf(esc_html__('for the Event: %s', 'event_espresso'), $Event->name())
412
-                            : sprintf(esc_html__('for the Event with ID: %s', 'event_espresso'), $model_field_value);
413
-                        break;
414
-                }
415
-            }
416
-        }
417
-
418
-        if ($label_parts) {
419
-
420
-            //prepend to the last element of $label_parts an "and".
421
-            if (count($label_parts) > 1) {
422
-                $label_parts_index_to_prepend               = count($label_parts) - 1;
423
-                $label_parts[$label_parts_index_to_prepend] = 'and' . $label_parts[$label_parts_index_to_prepend];
424
-            }
425
-
426
-            $pretty_label .= sprintf(
427
-                esc_html_x(
428
-                    'Showing messages for %s',
429
-                    'A label for the messages returned in a query that are filtered by items in the query. This could be Transaction, Event, Attendee, Registration, or WP_User.',
430
-                    'event_espresso'
431
-                ),
432
-                implode(', ', $label_parts)
433
-            );
434
-        }
435
-        return $pretty_label;
436
-    }
437
-
438
-
439
-    /**
440
-     * This returns the array of expected variables for the EEI_Query_Filter methods being implemented
441
-     * The array is in the format:
442
-     * array(
443
-     *  {$field_name} => {$model_name}
444
-     * );
445
-     *
446
-     * @since 4.9.0
447
-     * @return array
448
-     */
449
-    protected function _expected_vars_for_query_inject()
450
-    {
451
-        return array(
452
-            '_REG_ID' => 'Registration',
453
-            'ATT_ID'  => 'Attendee',
454
-            'ID'      => 'WP_User',
455
-            'TXN_ID'  => 'Transaction',
456
-            'EVT_ID'  => 'Event',
457
-        );
458
-    }
459
-
460
-
461
-    /**
462
-     * This returns whether EEM_Message is in debug mode or not.
463
-     * Currently "debug mode" is used to control the handling of the EEM_Message::debug_only status when
464
-     * generating/sending messages. Debug mode can be set by either:
465
-     * 1. Sending in a value for the $set_debug argument
466
-     * 2. Defining `EE_DEBUG_MESSAGES` constant in wp-config.php
467
-     * 3. Overriding the above via the provided filter.
468
-     *
469
-     * @param bool|null $set_debug      If provided, then the debug mode will be set internally until reset via the
470
-     *                                  provided boolean. When no argument is provided (default null) then the debug
471
-     *                                  mode will be returned.
472
-     * @return bool         true means Messages is in debug mode.  false means messages system is not in debug mode.
473
-     */
474
-    public static function debug($set_debug = null)
475
-    {
476
-        static $is_debugging = null;
477
-
478
-        //initialize (use constant if set).
479
-        if (is_null($set_debug) && is_null($is_debugging)) {
480
-            $is_debugging = defined('EE_DEBUG_MESSAGES') && EE_DEBUG_MESSAGES;
481
-        }
482
-
483
-        if ( ! is_null($set_debug)) {
484
-            $is_debugging = filter_var($set_debug, FILTER_VALIDATE_BOOLEAN);
485
-        }
486
-
487
-        //return filtered value
488
-        return apply_filters('FHEE__EEM_Message__debug', $is_debugging);
489
-    }
27
+	/**
28
+	 * This priority indicates a message should be generated ASAP and queued for sending.
29
+	 *
30
+	 * @type
31
+	 */
32
+	const priority_medium = 20;
33
+
34
+
35
+	/**
36
+	 * This priority indicates a message should be queued for generating.
37
+	 *
38
+	 * @type int
39
+	 */
40
+	const priority_low = 30;
41
+
42
+
43
+	/**
44
+	 * indicates this message was sent at the time modified
45
+	 */
46
+	const status_sent = 'MSN';
47
+
48
+
49
+	/**
50
+	 * indicates this message is waiting to be sent
51
+	 */
52
+	const status_idle = 'MID';
53
+
54
+
55
+	/**
56
+	 * indicates an attempt was a made to send this message
57
+	 * at the scheduled time, but it failed at the time modified.  This differs from MDO status in that it will ALWAYS
58
+	 * appear to the end user.
59
+	 */
60
+	const status_failed = 'MFL';
61
+
62
+
63
+	/**
64
+	 * indicates the message has been flagged for resending (at the time modified).
65
+	 */
66
+	const status_resend = 'MRS';
67
+
68
+
69
+	/**
70
+	 * indicates the message has been flagged for generation but has not been generated yet.  Messages always start as
71
+	 * this status when added to the queue.
72
+	 */
73
+	const status_incomplete = 'MIC';
74
+
75
+
76
+	/**
77
+	 * Indicates everything was generated fine for the message, however, the messenger was unable to send.
78
+	 * This status means that its possible to retry sending the message.
79
+	 */
80
+	const status_retry = 'MRT';
81
+
82
+
83
+	/**
84
+	 * This is used for more informational messages that may not indicate anything is broken but still cannot be
85
+	 * generated or sent correctly. An example of a message that would get flagged this way would be when a not
86
+	 * approved message was queued for generation, but at time of generation, the attached registration(s) are
87
+	 * approved. So the message queued for generation is no longer valid.  Messages for this status will only persist
88
+	 * in the db and be viewable in the message activity list table when the messages system is in debug mode.
89
+	 *
90
+	 * @see EEM_Message::debug()
91
+	 */
92
+	const status_debug_only = 'MDO';
93
+
94
+
95
+	/**
96
+	 * This status is given to messages it is processed by the messenger send method.
97
+	 * Messages with this status should rarely be seen in the Message List table, but if they are, that's usually
98
+	 * indicative of a PHP timeout or memory limit issue.
99
+	 */
100
+	const status_messenger_executing = 'MEX';
101
+
102
+
103
+	/**
104
+	 *    Private constructor to prevent direct creation.
105
+	 *
106
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and
107
+	 *                         any incoming timezone data that gets saved).  Note this just sends the timezone info to
108
+	 *                         the date time model field objects.  Default is null (and will be assumed using the set
109
+	 *                         timezone in the 'timezone_string' wp option)
110
+	 * @return EEM_Message
111
+	 */
112
+	protected function __construct($timezone = null)
113
+	{
114
+		$this->singular_item = __('Message', 'event_espresso');
115
+		$this->plural_item   = __('Messages', 'event_espresso');
116
+
117
+		//used for token generator
118
+		EE_Registry::instance()->load_helper('URL');
119
+
120
+		$this->_tables = array(
121
+			'Message' => new EE_Primary_Table('esp_message', 'MSG_ID'),
122
+		);
123
+
124
+		$allowed_priority = array(
125
+			self::priority_high   => __('high', 'event_espresso'),
126
+			self::priority_medium => __('medium', 'event_espresso'),
127
+			self::priority_low    => __('low', 'event_espresso'),
128
+		);
129
+
130
+		$this->_fields          = array(
131
+			'Message' => array(
132
+				'MSG_ID'             => new EE_Primary_Key_Int_Field('MSG_ID', __('Message ID', 'event_espresso')),
133
+				'MSG_token'          => new EE_Plain_Text_Field('MSG_token',
134
+					__('Unique Token used to represent this row in publicly viewable contexts (eg. a url).',
135
+						'event_espresso'), false, EEH_URL::generate_unique_token()),
136
+				'GRP_ID'             => new EE_Foreign_Key_Int_Field('GRP_ID',
137
+					__('Foreign key to the EEM_Message_Template_Group table.', 'event_espresso'), true, 0,
138
+					'Message_Template_Group'),
139
+				'TXN_ID'             => new EE_Foreign_Key_Int_Field('TXN_ID',
140
+					__('Foreign key to the related EE_Transaction.  This is required to give context for regenerating the specific message',
141
+						'event_espresso'), true, 0, 'Transaction'),
142
+				'MSG_messenger'      => new EE_Plain_Text_Field('MSG_messenger',
143
+					__('Corresponds to the EE_messenger::name used to send this message. This will also be used to attempt any resending of the message.',
144
+						'event_espresso'), false, 'email'),
145
+				'MSG_message_type'   => new EE_Plain_Text_Field('MSG_message_type',
146
+					__('Corresponds to the EE_message_type::name used to generate this message.', 'event_espresso'),
147
+					false, 'receipt'),
148
+				'MSG_context'        => new EE_Plain_Text_Field('MSG_context', __('Context', 'event_espresso'), false),
149
+				'MSG_recipient_ID'   => new EE_Foreign_Key_Int_Field('MSG_recipient_ID',
150
+					__('Recipient ID', 'event_espresso'), true, null, array('Registration', 'Attendee', 'WP_User')),
151
+				'MSG_recipient_type' => new EE_Any_Foreign_Model_Name_Field('MSG_recipient_type',
152
+					__('Recipient Type', 'event_espresso'), true, null, array('Registration', 'Attendee', 'WP_User')),
153
+				'MSG_content'        => new EE_Maybe_Serialized_Text_Field('MSG_content',
154
+					__('Content', 'event_espresso'), true, ''),
155
+				'MSG_to'             => new EE_Maybe_Serialized_Text_Field('MSG_to', __('Address To', 'event_espresso'),
156
+					true),
157
+				'MSG_from'           => new EE_Maybe_Serialized_Text_Field('MSG_from',
158
+					__('Address From', 'event_espresso'), true),
159
+				'MSG_subject'        => new EE_Maybe_Serialized_Text_Field('MSG_subject',
160
+					__('Subject', 'event_espresso'), true, ''),
161
+				'MSG_priority'       => new EE_Enum_Integer_Field('MSG_priority', __('Priority', 'event_espresso'),
162
+					false, self::priority_low, $allowed_priority),
163
+				'STS_ID'             => new EE_Foreign_Key_String_Field('STS_ID', __('Status', 'event_espresso'), false,
164
+					self::status_incomplete, 'Status'),
165
+				'MSG_created'        => new EE_Datetime_Field('MSG_created', __('Created', 'event_espresso'), false,
166
+					EE_Datetime_Field::now),
167
+				'MSG_modified'       => new EE_Datetime_Field('MSG_modified', __('Modified', 'event_espresso'), true,
168
+					EE_Datetime_Field::now),
169
+			),
170
+		);
171
+		$this->_model_relations = array(
172
+			'Attendee'               => new EE_Belongs_To_Any_Relation(),
173
+			'Registration'           => new EE_Belongs_To_Any_Relation(),
174
+			'WP_User'                => new EE_Belongs_To_Any_Relation(),
175
+			'Message_Template_Group' => new EE_Belongs_To_Relation(),
176
+			'Transaction'            => new EE_Belongs_To_Relation(),
177
+		);
178
+		parent::__construct($timezone);
179
+	}
180
+
181
+
182
+	/**
183
+	 * @return \EE_Message
184
+	 */
185
+	public function create_default_object()
186
+	{
187
+		/** @type EE_Message $message */
188
+		$message = parent::create_default_object();
189
+		if ($message instanceof EE_Message) {
190
+			return EE_Message_Factory::set_messenger_and_message_type($message);
191
+		}
192
+		return null;
193
+	}
194
+
195
+
196
+	/**
197
+	 * @param mixed $cols_n_values
198
+	 * @return \EE_Message
199
+	 */
200
+	public function instantiate_class_from_array_or_object($cols_n_values)
201
+	{
202
+		/** @type EE_Message $message */
203
+		$message = parent::instantiate_class_from_array_or_object($cols_n_values);
204
+		if ($message instanceof EE_Message) {
205
+			return EE_Message_Factory::set_messenger_and_message_type($message);
206
+		}
207
+		return null;
208
+	}
209
+
210
+
211
+	/**
212
+	 * Returns whether or not a message of that type was sent for a given attendee.
213
+	 *
214
+	 * @param EE_Attendee|int $attendee
215
+	 * @param string          $message_type the message type slug
216
+	 * @return boolean
217
+	 */
218
+	public function message_sent_for_attendee($attendee, $message_type)
219
+	{
220
+		$attendee_ID = EEM_Attendee::instance()->ensure_is_ID($attendee);
221
+		return $this->exists(array(
222
+			array(
223
+				'Attendee.ATT_ID'  => $attendee_ID,
224
+				'MSG_message_type' => $message_type,
225
+				'STS_ID'           => array('IN', $this->stati_indicating_sent()),
226
+			),
227
+		));
228
+	}
229
+
230
+
231
+	/**
232
+	 * Returns whether or not a message of that type was sent for a given registration
233
+	 *
234
+	 * @param EE_Registration|int $registration
235
+	 * @param string              $message_type the message type slug
236
+	 * @return boolean
237
+	 */
238
+	public function message_sent_for_registration($registration, $message_type)
239
+	{
240
+		$registrationID = EEM_Registration::instance()->ensure_is_ID($registration);
241
+		return $this->exists(array(
242
+			array(
243
+				'Registration.REG_ID' => $registrationID,
244
+				'MSG_message_type'    => $message_type,
245
+				'STS_ID'              => array('IN', $this->stati_indicating_sent()),
246
+			),
247
+		));
248
+	}
249
+
250
+
251
+	/**
252
+	 * This retrieves an EE_Message object from the db matching the given token string.
253
+	 *
254
+	 * @param string $token
255
+	 * @return EE_Message
256
+	 */
257
+	public function get_one_by_token($token)
258
+	{
259
+		return $this->get_one(array(
260
+			array(
261
+				'MSG_token' => $token,
262
+			),
263
+		));
264
+	}
265
+
266
+
267
+	/**
268
+	 * Returns stati that indicate the message HAS been sent
269
+	 *
270
+	 * @return array of strings for possible stati
271
+	 */
272
+	public function stati_indicating_sent()
273
+	{
274
+		return apply_filters('FHEE__EEM_Message__stati_indicating_sent', array(self::status_sent));
275
+	}
276
+
277
+
278
+	/**
279
+	 * Returns stati that indicate the message is waiting to be sent.
280
+	 *
281
+	 * @return array of strings for possible stati.
282
+	 */
283
+	public function stati_indicating_to_send()
284
+	{
285
+		return apply_filters('FHEE__EEM_Message__stati_indicating_to_send',
286
+			array(self::status_idle, self::status_resend));
287
+	}
288
+
289
+
290
+	/**
291
+	 * Returns stati that indicate the message has failed sending
292
+	 *
293
+	 * @return array  array of strings for possible stati.
294
+	 */
295
+	public function stati_indicating_failed_sending()
296
+	{
297
+		$failed_stati = array(
298
+			self::status_failed,
299
+			self::status_retry,
300
+			self::status_messenger_executing,
301
+		);
302
+		//if WP_DEBUG is set, then let's include debug_only fails
303
+		if (WP_DEBUG) {
304
+			$failed_stati[] = self::status_debug_only;
305
+		}
306
+		return apply_filters('FHEE__EEM_Message__stati_indicating_failed_sending', $failed_stati);
307
+	}
308
+
309
+
310
+	/**
311
+	 * Returns filterable array of all EEM_Message statuses.
312
+	 *
313
+	 * @return array
314
+	 */
315
+	public function all_statuses()
316
+	{
317
+		return apply_filters(
318
+			'FHEE__EEM_Message__all_statuses',
319
+			array(
320
+				EEM_Message::status_sent,
321
+				EEM_Message::status_incomplete,
322
+				EEM_Message::status_idle,
323
+				EEM_Message::status_resend,
324
+				EEM_Message::status_retry,
325
+				EEM_Message::status_failed,
326
+				EEM_Message::status_messenger_executing,
327
+				EEM_Message::status_debug_only,
328
+			)
329
+		);
330
+	}
331
+
332
+	/**
333
+	 * Detects any specific query variables in the request and uses those to setup appropriate
334
+	 * filter for any queries.
335
+	 *
336
+	 * @return array
337
+	 */
338
+	public function filter_by_query_params()
339
+	{
340
+		// expected possible query_vars, the key in this array matches an expected key in the request,
341
+		// the value, matches the corresponding EEM_Base child reference.
342
+		$expected_vars   = $this->_expected_vars_for_query_inject();
343
+		$query_params[0] = array();
344
+		foreach ($expected_vars as $request_key => $model_name) {
345
+			$request_value = EE_Registry::instance()->REQ->get($request_key);
346
+			if ($request_value) {
347
+				//special case
348
+				switch ($request_key) {
349
+					case '_REG_ID' :
350
+						$query_params[0]['AND**filter_by']['OR**filter_by_REG_ID'] = array(
351
+							'Transaction.Registration.REG_ID' => $request_value,
352
+						);
353
+						break;
354
+					case 'EVT_ID' :
355
+						$query_params[0]['AND**filter_by']['OR**filter_by_EVT_ID'] = array(
356
+							'Transaction.Registration.EVT_ID' => $request_value,
357
+						);
358
+						break;
359
+					default :
360
+						$query_params[0]['AND**filter_by']['OR**filter_by_' . $request_key][$model_name . '.' . $request_key] = $request_value;
361
+						break;
362
+				}
363
+			}
364
+		}
365
+		return $query_params;
366
+	}
367
+
368
+
369
+	/**
370
+	 * @return string
371
+	 */
372
+	public function get_pretty_label_for_results()
373
+	{
374
+		$expected_vars = $this->_expected_vars_for_query_inject();
375
+		$pretty_label  = '';
376
+		$label_parts   = array();
377
+		foreach ($expected_vars as $request_key => $model_name) {
378
+			$model = EE_Registry::instance()->load_model($model_name);
379
+			if ($model_field_value = EE_Registry::instance()->REQ->get($request_key)) {
380
+				switch ($request_key) {
381
+					case '_REG_ID' :
382
+						$label_parts[] = sprintf(
383
+							esc_html__('Registration with the ID: %s', 'event_espresso'),
384
+							$model_field_value
385
+						);
386
+						break;
387
+					case 'ATT_ID' :
388
+						/** @var EE_Attendee $attendee */
389
+						$attendee      = $model->get_one_by_ID($model_field_value);
390
+						$label_parts[] = $attendee instanceof EE_Attendee
391
+							? sprintf(esc_html__('Attendee %s', 'event_espresso'), $attendee->full_name())
392
+							: sprintf(esc_html__('Attendee ID: %s', 'event_espresso'), $model_field_value);
393
+						break;
394
+					case 'ID' :
395
+						/** @var EE_WP_User $wpUser */
396
+						$wpUser        = $model->get_one_by_ID($model_field_value);
397
+						$label_parts[] = $wpUser instanceof EE_WP_User
398
+							? sprintf(esc_html__('WP User: %s', 'event_espresso'), $wpUser->name())
399
+							: sprintf(esc_html__('WP User ID: %s', 'event_espresso'), $model_field_value);
400
+						break;
401
+					case 'TXN_ID' :
402
+						$label_parts[] = sprintf(
403
+							esc_html__('Transaction with the ID: %s', 'event_espresso'),
404
+							$model_field_value
405
+						);
406
+						break;
407
+					case 'EVT_ID' :
408
+						/** @var EE_Event $Event */
409
+						$Event         = $model->get_one_by_ID($model_field_value);
410
+						$label_parts[] = $Event instanceof EE_Event
411
+							? sprintf(esc_html__('for the Event: %s', 'event_espresso'), $Event->name())
412
+							: sprintf(esc_html__('for the Event with ID: %s', 'event_espresso'), $model_field_value);
413
+						break;
414
+				}
415
+			}
416
+		}
417
+
418
+		if ($label_parts) {
419
+
420
+			//prepend to the last element of $label_parts an "and".
421
+			if (count($label_parts) > 1) {
422
+				$label_parts_index_to_prepend               = count($label_parts) - 1;
423
+				$label_parts[$label_parts_index_to_prepend] = 'and' . $label_parts[$label_parts_index_to_prepend];
424
+			}
425
+
426
+			$pretty_label .= sprintf(
427
+				esc_html_x(
428
+					'Showing messages for %s',
429
+					'A label for the messages returned in a query that are filtered by items in the query. This could be Transaction, Event, Attendee, Registration, or WP_User.',
430
+					'event_espresso'
431
+				),
432
+				implode(', ', $label_parts)
433
+			);
434
+		}
435
+		return $pretty_label;
436
+	}
437
+
438
+
439
+	/**
440
+	 * This returns the array of expected variables for the EEI_Query_Filter methods being implemented
441
+	 * The array is in the format:
442
+	 * array(
443
+	 *  {$field_name} => {$model_name}
444
+	 * );
445
+	 *
446
+	 * @since 4.9.0
447
+	 * @return array
448
+	 */
449
+	protected function _expected_vars_for_query_inject()
450
+	{
451
+		return array(
452
+			'_REG_ID' => 'Registration',
453
+			'ATT_ID'  => 'Attendee',
454
+			'ID'      => 'WP_User',
455
+			'TXN_ID'  => 'Transaction',
456
+			'EVT_ID'  => 'Event',
457
+		);
458
+	}
459
+
460
+
461
+	/**
462
+	 * This returns whether EEM_Message is in debug mode or not.
463
+	 * Currently "debug mode" is used to control the handling of the EEM_Message::debug_only status when
464
+	 * generating/sending messages. Debug mode can be set by either:
465
+	 * 1. Sending in a value for the $set_debug argument
466
+	 * 2. Defining `EE_DEBUG_MESSAGES` constant in wp-config.php
467
+	 * 3. Overriding the above via the provided filter.
468
+	 *
469
+	 * @param bool|null $set_debug      If provided, then the debug mode will be set internally until reset via the
470
+	 *                                  provided boolean. When no argument is provided (default null) then the debug
471
+	 *                                  mode will be returned.
472
+	 * @return bool         true means Messages is in debug mode.  false means messages system is not in debug mode.
473
+	 */
474
+	public static function debug($set_debug = null)
475
+	{
476
+		static $is_debugging = null;
477
+
478
+		//initialize (use constant if set).
479
+		if (is_null($set_debug) && is_null($is_debugging)) {
480
+			$is_debugging = defined('EE_DEBUG_MESSAGES') && EE_DEBUG_MESSAGES;
481
+		}
482
+
483
+		if ( ! is_null($set_debug)) {
484
+			$is_debugging = filter_var($set_debug, FILTER_VALIDATE_BOOLEAN);
485
+		}
486
+
487
+		//return filtered value
488
+		return apply_filters('FHEE__EEM_Message__debug', $is_debugging);
489
+	}
490 490
 
491 491
 
492 492
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Status.model.php 1 patch
Indentation   +275 added lines, -275 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -25,291 +25,291 @@  discard block
 block discarded – undo
25 25
 class EEM_Status extends EEM_Base
26 26
 {
27 27
 
28
-    // private instance of the Attendee object
29
-    protected static $_instance = null;
28
+	// private instance of the Attendee object
29
+	protected static $_instance = null;
30 30
 
31 31
 
32
-    /**
33
-     * @return EEM_Status
34
-     */
35
-    protected function __construct($timezone = null)
36
-    {
37
-        $this->singular_item    = __('Status', 'event_espresso');
38
-        $this->plural_item      = __('Stati', 'event_espresso');
39
-        $this->_tables          = array(
40
-            'StatusTable' => new EE_Primary_Table('esp_status', 'STS_ID'),
41
-        );
42
-        $this->_fields          = array(
43
-            'StatusTable' => array(
44
-                'STS_ID'       => new EE_Primary_Key_String_Field('STS_ID', __('Status ID', 'event_espresso')),
45
-                'STS_code'     => new EE_Plain_Text_Field('STS_code', __('Status Code', 'event_espresso'), false, ''),
46
-                'STS_type'     => new EE_Enum_Text_Field(
47
-                    'STS_type',
48
-                    __("Type", "event_espresso"),
49
-                    false,
50
-                    'event',
51
-                    array(
52
-                        'event'        => __("Event", "event_espresso"),//deprecated
53
-                        'registration' => __("Registration", "event_espresso"),
54
-                        'transaction'  => __("Transaction", "event_espresso"),
55
-                        'payment'      => __("Payment", "event_espresso"),
56
-                        'email'        => __("Email", "event_espresso"),
57
-                        'message'      => __("Message", "event_espresso"),
58
-                    )),
59
-                'STS_can_edit' => new EE_Boolean_Field('STS_can_edit', __('Editable?', 'event_espresso'), false),
60
-                'STS_desc'     => new EE_Simple_HTML_Field('STS_desc', __("Description", "event_espresso"), false, ''),
61
-                'STS_open'     => new EE_Boolean_Field('STS_open', __("Open?", "event_espresso"), false, false),
62
-            ),
63
-        );
64
-        $this->_model_relations = array(
65
-            'Registration' => new EE_Has_Many_Relation(),
66
-            'Transaction'  => new EE_Has_Many_Relation(),
67
-            'Payment'      => new EE_Has_Many_Relation(),
68
-        );
69
-        //this model is generally available for reading
70
-        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
32
+	/**
33
+	 * @return EEM_Status
34
+	 */
35
+	protected function __construct($timezone = null)
36
+	{
37
+		$this->singular_item    = __('Status', 'event_espresso');
38
+		$this->plural_item      = __('Stati', 'event_espresso');
39
+		$this->_tables          = array(
40
+			'StatusTable' => new EE_Primary_Table('esp_status', 'STS_ID'),
41
+		);
42
+		$this->_fields          = array(
43
+			'StatusTable' => array(
44
+				'STS_ID'       => new EE_Primary_Key_String_Field('STS_ID', __('Status ID', 'event_espresso')),
45
+				'STS_code'     => new EE_Plain_Text_Field('STS_code', __('Status Code', 'event_espresso'), false, ''),
46
+				'STS_type'     => new EE_Enum_Text_Field(
47
+					'STS_type',
48
+					__("Type", "event_espresso"),
49
+					false,
50
+					'event',
51
+					array(
52
+						'event'        => __("Event", "event_espresso"),//deprecated
53
+						'registration' => __("Registration", "event_espresso"),
54
+						'transaction'  => __("Transaction", "event_espresso"),
55
+						'payment'      => __("Payment", "event_espresso"),
56
+						'email'        => __("Email", "event_espresso"),
57
+						'message'      => __("Message", "event_espresso"),
58
+					)),
59
+				'STS_can_edit' => new EE_Boolean_Field('STS_can_edit', __('Editable?', 'event_espresso'), false),
60
+				'STS_desc'     => new EE_Simple_HTML_Field('STS_desc', __("Description", "event_espresso"), false, ''),
61
+				'STS_open'     => new EE_Boolean_Field('STS_open', __("Open?", "event_espresso"), false, false),
62
+			),
63
+		);
64
+		$this->_model_relations = array(
65
+			'Registration' => new EE_Has_Many_Relation(),
66
+			'Transaction'  => new EE_Has_Many_Relation(),
67
+			'Payment'      => new EE_Has_Many_Relation(),
68
+		);
69
+		//this model is generally available for reading
70
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
71 71
 
72
-        parent::__construct($timezone);
73
-    }
72
+		parent::__construct($timezone);
73
+	}
74 74
 
75 75
 
76
-    /**
77
-     * This method provides the localized singular or plural string for a given status id
78
-     *
79
-     * @param  array   $statuses This should be an array of statuses in the format array( $status_id, $status_code ).
80
-     *                           That way if there isn't a translation in the index we'll return the default code.
81
-     * @param  boolean $plural   Whether to return plural string or not. Note, nearly all of the plural strings are the
82
-     *                           same as the singular (in English), however, this may NOT be the case with other
83
-     *                           languages
84
-     * @param  string  $schema   This can be either 'upper', 'lower', or 'sentence'.  Basically indicates how we want
85
-     *                           the status string returned ( UPPER, lower, Sentence)
86
-     * @throws EE_Error
87
-     * @return array             an array of translated strings for the incoming status id.
88
-     */
89
-    public function localized_status($statuses, $plural = false, $schema = 'upper')
90
-    {
91
-        //note these are all in lower case because ucwords() on upper case will NOT convert.
92
-        $translation_array = array(
93
-            EEM_Registration::status_id_pending_payment => array(
94
-                __('pending payment', 'event_espresso'), //singular
95
-                __('pending payments', 'event_espresso') //plural
96
-            ),
97
-            EEM_Registration::status_id_approved        => array(
98
-                __('approved', 'event_espresso'), //singular
99
-                __('approved', 'event_espresso') //plural
100
-            ),
101
-            EEM_Registration::status_id_not_approved    => array(
102
-                __('not approved', 'event_espresso'),
103
-                __('not approved', 'event_espresso'),
104
-            ),
105
-            EEM_Registration::status_id_cancelled       => array(
106
-                __('cancelled', 'event_espresso'),
107
-                __('cancelled', 'event_espresso'),
108
-            ),
109
-            EEM_Registration::status_id_incomplete      => array(
110
-                __('incomplete', 'event_espresso'),
111
-                __('incomplete', 'event_espresso'),
112
-            ),
113
-            EEM_Registration::status_id_declined        => array(
114
-                __('declined', 'event_espresso'),
115
-                __('declined', 'event_espresso'),
116
-            ),
117
-            EEM_Registration::status_id_wait_list       => array(
118
-                __('wait list', 'event_espresso'),
119
-                __('wait list', 'event_espresso'),
120
-            ),
121
-            EEM_Transaction::overpaid_status_code       => array(
122
-                __('overpaid', 'event_espresso'),
123
-                __('overpaid', 'event_espresso'),
124
-            ),
125
-            EEM_Transaction::complete_status_code       => array(
126
-                __('complete', 'event_espresso'),
127
-                __('complete', 'event_espresso'),
128
-            ),
129
-            EEM_Transaction::incomplete_status_code     => array(
130
-                __('incomplete', 'event_espresso'),
131
-                __('incomplete', 'event_espresso'),
132
-            ),
133
-            EEM_Transaction::failed_status_code         => array(
134
-                __('failed', 'event_espresso'),
135
-                __('failed', 'event_espresso'),
136
-            ),
137
-            EEM_Transaction::abandoned_status_code      => array(
138
-                __('abandoned', 'event_espresso'),
139
-                __('abandoned', 'event_espresso'),
140
-            ),
141
-            EEM_Payment::status_id_approved             => array(
142
-                __('accepted', 'event_espresso'),
143
-                __('accepted', 'event_espresso'),
144
-            ),
145
-            EEM_Payment::status_id_pending              => array(
146
-                __('pending', 'event_espresso'),
147
-                __('pending', 'event_espresso'),
148
-            ),
149
-            EEM_Payment::status_id_cancelled            => array(
150
-                __('cancelled', 'event_espresso'),
151
-                __('cancelled', 'event_espresso'),
152
-            ),
153
-            EEM_Payment::status_id_declined             => array(
154
-                __('declined', 'event_espresso'),
155
-                __('declined', 'event_espresso'),
156
-            ),
157
-            EEM_Payment::status_id_failed               => array(
158
-                __('failed', 'event_espresso'),
159
-                __('failed', 'event_espresso'),
160
-            ),
161
-            //following statuses are NOT part of the EEM_Status but to keep things centralized we include in here.
162
-            EEM_Event::sold_out                         => array(
163
-                __('sold out', 'event_espresso'),
164
-                __('sold out', 'event_espresso'),
165
-            ),
166
-            EEM_Event::postponed                        => array(
167
-                __('postponed', 'event_espresso'),
168
-                __('Postponed', 'event_espresso'),
169
-            ),
170
-            EEM_Event::cancelled                        => array(
171
-                __('cancelled', 'event_espresso'),
172
-                __('cancelled', 'event_espresso'),
173
-            ),
174
-            EE_Ticket::archived                         => array(
175
-                __('archived', 'event_espresso'),
176
-                __('archived', 'event_espresso'),
177
-            ),
178
-            EE_Ticket::expired                          => array(
179
-                __('expired', 'event_espresso'),
180
-                __('expired', 'event_espresso'),
181
-            ),
182
-            EE_Ticket::sold_out                         => array(
183
-                __('sold out', 'event_espresso'),
184
-                __('sold out', 'event_espresso'),
185
-            ),
186
-            EE_Ticket::pending                          => array(
187
-                __('upcoming', 'event_espresso'),
188
-                __('upcoming', 'event_espresso'),
189
-            ),
190
-            EE_Ticket::onsale                           => array(
191
-                __('on sale', 'event_espresso'),
192
-                __('on sale', 'event_espresso'),
193
-            ),
194
-            EE_Datetime::cancelled                      => array(
195
-                __('cancelled', 'event_espresso'),
196
-                __('cancelled', 'event_espresso'),
197
-            ),
198
-            EE_Datetime::sold_out                       => array(
199
-                __('sold out', 'event_espresso'),
200
-                __('sold out', 'event_espresso'),
201
-            ),
202
-            EE_Datetime::expired                        => array(
203
-                __('expired', 'event_espresso'),
204
-                __('expired', 'event_espresso'),
205
-            ),
206
-            EE_Datetime::inactive                       => array(
207
-                __('inactive', 'event_espresso'),
208
-                __('inactive', 'event_espresso'),
209
-            ),
210
-            EE_Datetime::upcoming                       => array(
211
-                __('upcoming', 'event_espresso'),
212
-                __('upcoming', 'event_espresso'),
213
-            ),
214
-            EE_Datetime::active                         => array(
215
-                __('active', 'event_espresso'),
216
-                __('active', 'event_espresso'),
217
-            ),
218
-            EE_Datetime::postponed                      => array(
219
-                __('postponed', 'event_espresso'),
220
-                __('postponed', 'event_espresso'),
221
-            ),
222
-            //messages related
223
-            EEM_Message::status_sent                    => array(
224
-                __('sent', 'event_espresso'),
225
-                __('sent', 'event_espresso'),
226
-            ),
227
-            EEM_Message::status_idle                    => array(
228
-                __('queued for sending', 'event_espresso'),
229
-                __('queued for sending', 'event_espresso'),
230
-            ),
231
-            EEM_Message::status_failed                  => array(
232
-                __('failed', 'event_espresso'),
233
-                __('failed', 'event_espresso'),
234
-            ),
235
-            EEM_Message::status_debug_only              => array(
236
-                __('debug only', 'event_espresso'),
237
-                __('debug only', 'event_espresso'),
238
-            ),
239
-            EEM_Message::status_messenger_executing     => array(
240
-                __('messenger is executing', 'event_espresso'),
241
-                __('messenger is executing', 'event_espresso'),
242
-            ),
243
-            EEM_Message::status_resend                  => array(
244
-                __('queued for resending', 'event_espresso'),
245
-                __('queued for resending', 'event_espresso'),
246
-            ),
247
-            EEM_Message::status_incomplete              => array(
248
-                __('queued for generating', 'event_espresso'),
249
-                __('queued for generating', 'event_espresso'),
250
-            ),
251
-            EEM_Message::status_retry                   => array(
252
-                __('failed sending, can be retried', 'event_espresso'),
253
-                __('failed sending, can be retried', 'event_espresso'),
254
-            ),
255
-            EEM_CPT_Base::post_status_publish           => array(
256
-                __('published', 'event_espresso'),
257
-                __('published', 'event_espresso'),
258
-            ),
259
-            EEM_CPT_Base::post_status_future            => array(
260
-                __('scheduled', 'event_espresso'),
261
-                __('scheduled', 'event_espresso'),
262
-            ),
263
-            EEM_CPT_Base::post_status_draft             => array(
264
-                __('draft', 'event_espresso'),
265
-                __('draft', 'event_espresso'),
266
-            ),
267
-            EEM_CPT_Base::post_status_pending           => array(
268
-                __('pending', 'event_espresso'),
269
-                __('pending', 'event_espresso'),
270
-            ),
271
-            EEM_CPT_Base::post_status_private           => array(
272
-                __('private', 'event_espresso'),
273
-                __('private', 'event_espresso'),
274
-            ),
275
-            EEM_CPT_Base::post_status_trashed           => array(
276
-                __('trashed', 'event_espresso'),
277
-                __('trashed', 'event_espresso'),
278
-            ),
279
-        );
76
+	/**
77
+	 * This method provides the localized singular or plural string for a given status id
78
+	 *
79
+	 * @param  array   $statuses This should be an array of statuses in the format array( $status_id, $status_code ).
80
+	 *                           That way if there isn't a translation in the index we'll return the default code.
81
+	 * @param  boolean $plural   Whether to return plural string or not. Note, nearly all of the plural strings are the
82
+	 *                           same as the singular (in English), however, this may NOT be the case with other
83
+	 *                           languages
84
+	 * @param  string  $schema   This can be either 'upper', 'lower', or 'sentence'.  Basically indicates how we want
85
+	 *                           the status string returned ( UPPER, lower, Sentence)
86
+	 * @throws EE_Error
87
+	 * @return array             an array of translated strings for the incoming status id.
88
+	 */
89
+	public function localized_status($statuses, $plural = false, $schema = 'upper')
90
+	{
91
+		//note these are all in lower case because ucwords() on upper case will NOT convert.
92
+		$translation_array = array(
93
+			EEM_Registration::status_id_pending_payment => array(
94
+				__('pending payment', 'event_espresso'), //singular
95
+				__('pending payments', 'event_espresso') //plural
96
+			),
97
+			EEM_Registration::status_id_approved        => array(
98
+				__('approved', 'event_espresso'), //singular
99
+				__('approved', 'event_espresso') //plural
100
+			),
101
+			EEM_Registration::status_id_not_approved    => array(
102
+				__('not approved', 'event_espresso'),
103
+				__('not approved', 'event_espresso'),
104
+			),
105
+			EEM_Registration::status_id_cancelled       => array(
106
+				__('cancelled', 'event_espresso'),
107
+				__('cancelled', 'event_espresso'),
108
+			),
109
+			EEM_Registration::status_id_incomplete      => array(
110
+				__('incomplete', 'event_espresso'),
111
+				__('incomplete', 'event_espresso'),
112
+			),
113
+			EEM_Registration::status_id_declined        => array(
114
+				__('declined', 'event_espresso'),
115
+				__('declined', 'event_espresso'),
116
+			),
117
+			EEM_Registration::status_id_wait_list       => array(
118
+				__('wait list', 'event_espresso'),
119
+				__('wait list', 'event_espresso'),
120
+			),
121
+			EEM_Transaction::overpaid_status_code       => array(
122
+				__('overpaid', 'event_espresso'),
123
+				__('overpaid', 'event_espresso'),
124
+			),
125
+			EEM_Transaction::complete_status_code       => array(
126
+				__('complete', 'event_espresso'),
127
+				__('complete', 'event_espresso'),
128
+			),
129
+			EEM_Transaction::incomplete_status_code     => array(
130
+				__('incomplete', 'event_espresso'),
131
+				__('incomplete', 'event_espresso'),
132
+			),
133
+			EEM_Transaction::failed_status_code         => array(
134
+				__('failed', 'event_espresso'),
135
+				__('failed', 'event_espresso'),
136
+			),
137
+			EEM_Transaction::abandoned_status_code      => array(
138
+				__('abandoned', 'event_espresso'),
139
+				__('abandoned', 'event_espresso'),
140
+			),
141
+			EEM_Payment::status_id_approved             => array(
142
+				__('accepted', 'event_espresso'),
143
+				__('accepted', 'event_espresso'),
144
+			),
145
+			EEM_Payment::status_id_pending              => array(
146
+				__('pending', 'event_espresso'),
147
+				__('pending', 'event_espresso'),
148
+			),
149
+			EEM_Payment::status_id_cancelled            => array(
150
+				__('cancelled', 'event_espresso'),
151
+				__('cancelled', 'event_espresso'),
152
+			),
153
+			EEM_Payment::status_id_declined             => array(
154
+				__('declined', 'event_espresso'),
155
+				__('declined', 'event_espresso'),
156
+			),
157
+			EEM_Payment::status_id_failed               => array(
158
+				__('failed', 'event_espresso'),
159
+				__('failed', 'event_espresso'),
160
+			),
161
+			//following statuses are NOT part of the EEM_Status but to keep things centralized we include in here.
162
+			EEM_Event::sold_out                         => array(
163
+				__('sold out', 'event_espresso'),
164
+				__('sold out', 'event_espresso'),
165
+			),
166
+			EEM_Event::postponed                        => array(
167
+				__('postponed', 'event_espresso'),
168
+				__('Postponed', 'event_espresso'),
169
+			),
170
+			EEM_Event::cancelled                        => array(
171
+				__('cancelled', 'event_espresso'),
172
+				__('cancelled', 'event_espresso'),
173
+			),
174
+			EE_Ticket::archived                         => array(
175
+				__('archived', 'event_espresso'),
176
+				__('archived', 'event_espresso'),
177
+			),
178
+			EE_Ticket::expired                          => array(
179
+				__('expired', 'event_espresso'),
180
+				__('expired', 'event_espresso'),
181
+			),
182
+			EE_Ticket::sold_out                         => array(
183
+				__('sold out', 'event_espresso'),
184
+				__('sold out', 'event_espresso'),
185
+			),
186
+			EE_Ticket::pending                          => array(
187
+				__('upcoming', 'event_espresso'),
188
+				__('upcoming', 'event_espresso'),
189
+			),
190
+			EE_Ticket::onsale                           => array(
191
+				__('on sale', 'event_espresso'),
192
+				__('on sale', 'event_espresso'),
193
+			),
194
+			EE_Datetime::cancelled                      => array(
195
+				__('cancelled', 'event_espresso'),
196
+				__('cancelled', 'event_espresso'),
197
+			),
198
+			EE_Datetime::sold_out                       => array(
199
+				__('sold out', 'event_espresso'),
200
+				__('sold out', 'event_espresso'),
201
+			),
202
+			EE_Datetime::expired                        => array(
203
+				__('expired', 'event_espresso'),
204
+				__('expired', 'event_espresso'),
205
+			),
206
+			EE_Datetime::inactive                       => array(
207
+				__('inactive', 'event_espresso'),
208
+				__('inactive', 'event_espresso'),
209
+			),
210
+			EE_Datetime::upcoming                       => array(
211
+				__('upcoming', 'event_espresso'),
212
+				__('upcoming', 'event_espresso'),
213
+			),
214
+			EE_Datetime::active                         => array(
215
+				__('active', 'event_espresso'),
216
+				__('active', 'event_espresso'),
217
+			),
218
+			EE_Datetime::postponed                      => array(
219
+				__('postponed', 'event_espresso'),
220
+				__('postponed', 'event_espresso'),
221
+			),
222
+			//messages related
223
+			EEM_Message::status_sent                    => array(
224
+				__('sent', 'event_espresso'),
225
+				__('sent', 'event_espresso'),
226
+			),
227
+			EEM_Message::status_idle                    => array(
228
+				__('queued for sending', 'event_espresso'),
229
+				__('queued for sending', 'event_espresso'),
230
+			),
231
+			EEM_Message::status_failed                  => array(
232
+				__('failed', 'event_espresso'),
233
+				__('failed', 'event_espresso'),
234
+			),
235
+			EEM_Message::status_debug_only              => array(
236
+				__('debug only', 'event_espresso'),
237
+				__('debug only', 'event_espresso'),
238
+			),
239
+			EEM_Message::status_messenger_executing     => array(
240
+				__('messenger is executing', 'event_espresso'),
241
+				__('messenger is executing', 'event_espresso'),
242
+			),
243
+			EEM_Message::status_resend                  => array(
244
+				__('queued for resending', 'event_espresso'),
245
+				__('queued for resending', 'event_espresso'),
246
+			),
247
+			EEM_Message::status_incomplete              => array(
248
+				__('queued for generating', 'event_espresso'),
249
+				__('queued for generating', 'event_espresso'),
250
+			),
251
+			EEM_Message::status_retry                   => array(
252
+				__('failed sending, can be retried', 'event_espresso'),
253
+				__('failed sending, can be retried', 'event_espresso'),
254
+			),
255
+			EEM_CPT_Base::post_status_publish           => array(
256
+				__('published', 'event_espresso'),
257
+				__('published', 'event_espresso'),
258
+			),
259
+			EEM_CPT_Base::post_status_future            => array(
260
+				__('scheduled', 'event_espresso'),
261
+				__('scheduled', 'event_espresso'),
262
+			),
263
+			EEM_CPT_Base::post_status_draft             => array(
264
+				__('draft', 'event_espresso'),
265
+				__('draft', 'event_espresso'),
266
+			),
267
+			EEM_CPT_Base::post_status_pending           => array(
268
+				__('pending', 'event_espresso'),
269
+				__('pending', 'event_espresso'),
270
+			),
271
+			EEM_CPT_Base::post_status_private           => array(
272
+				__('private', 'event_espresso'),
273
+				__('private', 'event_espresso'),
274
+			),
275
+			EEM_CPT_Base::post_status_trashed           => array(
276
+				__('trashed', 'event_espresso'),
277
+				__('trashed', 'event_espresso'),
278
+			),
279
+		);
280 280
 
281
-        $translation_array = apply_filters('FHEE__EEM_Status__localized_status__translation_array', $translation_array);
281
+		$translation_array = apply_filters('FHEE__EEM_Status__localized_status__translation_array', $translation_array);
282 282
 
283
-        if ( ! is_array($statuses)) {
284
-            throw new EE_Error(__('The incoming statuses argument must be an array with keys as the $status_id and values as the $status_code',
285
-                'event_espresso'));
286
-        }
283
+		if ( ! is_array($statuses)) {
284
+			throw new EE_Error(__('The incoming statuses argument must be an array with keys as the $status_id and values as the $status_code',
285
+				'event_espresso'));
286
+		}
287 287
 
288
-        $translation = array();
288
+		$translation = array();
289 289
 
290
-        foreach ($statuses as $id => $code) {
291
-            if (isset($translation_array[$id])) {
292
-                $translation[$id] = $plural ? $translation_array[$id][1] : $translation_array[$id][0];
293
-            } else {
294
-                $translation[$id] = $code;
295
-            }
290
+		foreach ($statuses as $id => $code) {
291
+			if (isset($translation_array[$id])) {
292
+				$translation[$id] = $plural ? $translation_array[$id][1] : $translation_array[$id][0];
293
+			} else {
294
+				$translation[$id] = $code;
295
+			}
296 296
 
297
-            //schema
298
-            switch ($schema) {
299
-                case 'lower' :
300
-                    $translation[$id] = strtolower($translation[$id]); //even though these start in lower case, this will catch any statuses added via filter.
301
-                    break;
302
-                case 'sentence' :
303
-                    $translation[$id] = ucwords($translation[$id]);
304
-                    break;
305
-                case 'upper' :
306
-                    $translation[$id] = strtoupper($translation[$id]);
307
-                    break;
308
-            }
309
-        }
297
+			//schema
298
+			switch ($schema) {
299
+				case 'lower' :
300
+					$translation[$id] = strtolower($translation[$id]); //even though these start in lower case, this will catch any statuses added via filter.
301
+					break;
302
+				case 'sentence' :
303
+					$translation[$id] = ucwords($translation[$id]);
304
+					break;
305
+				case 'upper' :
306
+					$translation[$id] = strtoupper($translation[$id]);
307
+					break;
308
+			}
309
+		}
310 310
 
311
-        return $translation;
312
-    }
311
+		return $translation;
312
+	}
313 313
 
314 314
 
315 315
 }
Please login to merge, or discard this patch.
core/libraries/messages/EE_Message_Repository.lib.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if (! defined('EVENT_ESPRESSO_VERSION')) {
2
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3 3
     exit('No direct script access allowed');
4 4
 }
5 5
 
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
     {
39 39
         $attached = parent::add($message);
40 40
         //ensure $info is an array if not already
41
-        $info = $info === null ? $info = array() : (array)$info;
41
+        $info = $info === null ? $info = array() : (array) $info;
42 42
         $data = $this->_init_data($info, $attached, $message);
43 43
         if ($attached) {
44 44
             $this->set_info($message, $data);
@@ -103,10 +103,10 @@  discard block
 block discarded – undo
103 103
     {
104 104
         $save_tracking = array('updated' => 0, 'notupdated' => 0, 'errors' => array());
105 105
 
106
-        if (! $do_hooks_only) {
106
+        if ( ! $do_hooks_only) {
107 107
             $this->rewind();
108 108
             //exit early if there is nothing to save.
109
-            if (! $this->count() > 0) {
109
+            if ( ! $this->count() > 0) {
110 110
                 return $save_tracking;
111 111
             }
112 112
 
Please login to merge, or discard this patch.
Indentation   +251 added lines, -251 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if (! defined('EVENT_ESPRESSO_VERSION')) {
3
-    exit('No direct script access allowed');
3
+	exit('No direct script access allowed');
4 4
 }
5 5
 
6 6
 
@@ -16,256 +16,256 @@  discard block
 block discarded – undo
16 16
 {
17 17
 
18 18
 
19
-    /**
20
-     *    EE_Message_Repository constructor
21
-     */
22
-    public function __construct()
23
-    {
24
-        $this->interface = 'EE_Message';
25
-        parent::__construct();
26
-    }
27
-
28
-
29
-    /**
30
-     * Add the EE_Message to the repository.
31
-     * This also ensures that the MSG_token is saves as a part of the info for retrieval.
32
-     *
33
-     * @param EE_Message $message
34
-     * @param mixed      $info Any included data is saved in the attached object info array indexed by 'data'
35
-     * @return bool
36
-     */
37
-    public function add($message, $info = null)
38
-    {
39
-        $attached = parent::add($message);
40
-        //ensure $info is an array if not already
41
-        $info = $info === null ? $info = array() : (array)$info;
42
-        $data = $this->_init_data($info, $attached, $message);
43
-        if ($attached) {
44
-            $this->set_info($message, $data);
45
-        }
46
-        return $attached;
47
-    }
48
-
49
-
50
-    /**
51
-     * Initializes the data from the incoming info.
52
-     *
53
-     * @param array      $info     incoming data.
54
-     * @param bool       $attached Indicates whether the object was attached successfully.
55
-     * @param EE_Message $message
56
-     * @return array
57
-     */
58
-    protected function _init_data($info, $attached, $message)
59
-    {
60
-        $data = array(
61
-            'test_send'               => false,
62
-            'preview'                 => false,
63
-            'data_handler_class_name' => '',
64
-            'data'                    => array(
65
-                'MSG_generation_data' => array(),
66
-            ),
67
-        );
68
-        if (isset($info['preview'])) {
69
-            $data['preview'] = $info['preview'];
70
-            unset($info['preview']);
71
-        }
72
-        if (isset($info['test_send'])) {
73
-            $data['test_send'] = $info['test_send'];
74
-            unset($info['test_send']);
75
-        }
76
-        if (isset($info['data_handler_class_name'])) {
77
-            $data['data_handler_class_name'] = $info['data_handler_class_name'];
78
-            unset($info['data_handler_class_name']);
79
-        }
80
-        if ($attached && $message->STS_ID() === EEM_Message::status_incomplete) {
81
-            $generation_data = isset($info['MSG_generation_data']) ? $info['MSG_generation_data'] : array();
82
-            //if data isn't in $info...let's see if its available via the message object
83
-            $generation_data = ! $generation_data ? $message->get_generation_data() : $generation_data;
84
-            //still empty then let's just use info
85
-            $generation_data                     = ! $generation_data ? $info : $generation_data;
86
-            $data['data']['MSG_generation_data'] = $generation_data;
87
-        }
88
-        return $data;
89
-    }
90
-
91
-
92
-    /**
93
-     * Save all EE_Message objects to the db.
94
-     *
95
-     * @param bool $do_hooks_only  When true, only the hooks related to saving are fired.
96
-     * @return array array(
97
-     *                  'updated' => 0, //count of how many messages updated
98
-     *                  'notupdated' => 0, //count of how many messages not updated.
99
-     *                  'errors' => array( $token ), //array of message object tokens that had errors in saving
100
-     *                  )
101
-     */
102
-    public function saveAll($do_hooks_only = false)
103
-    {
104
-        $save_tracking = array('updated' => 0, 'notupdated' => 0, 'errors' => array());
105
-
106
-        if (! $do_hooks_only) {
107
-            $this->rewind();
108
-            //exit early if there is nothing to save.
109
-            if (! $this->count() > 0) {
110
-                return $save_tracking;
111
-            }
112
-
113
-            while ($this->valid()) {
114
-                $saved = $this->current()->save();
115
-                if ($saved === false) {
116
-                    $save_tracking['errors'][] = $this->current()->MSG_token();
117
-                } elseif ($saved) {
118
-                    $save_tracking['updated']++;
119
-                } else {
120
-                    $save_tracking['notupdated']++;
121
-                }
122
-                //maybe persist generation data if this is an incomplete EE_Message.
123
-                $this->_maybe_persist_attached_data();
124
-
125
-                $this->next();
126
-            }
127
-        }
128
-        do_action('AHEE__EE_Message_Repository__saveAll__after', $save_tracking, $this, $do_hooks_only);
129
-        return $save_tracking;
130
-    }
131
-
132
-
133
-    /**
134
-     * Retrieves a EE_Message from the repository that matches the given token.
135
-     *
136
-     * @param string $token Token.
137
-     * @return EE_Message | null
138
-     */
139
-    public function getMessageByToken($token)
140
-    {
141
-        $this->rewind();
142
-        while ($this->valid()) {
143
-            if ($this->current()->MSG_token() === $token) {
144
-                $message = $this->current();
145
-                $this->rewind();
146
-                return $message;
147
-            }
148
-            $this->next();
149
-        }
150
-        return null;
151
-    }
152
-
153
-
154
-    /**
155
-     * This retrieves any data required for generation that may be saved with the current EE_Message in storage.
156
-     *
157
-     * @return array();
158
-     */
159
-    public function get_generation_data()
160
-    {
161
-        //first verify we're at a valid iterator point.
162
-        if ( ! $this->valid()) {
163
-            return array();
164
-        }
165
-        $info = $this->getInfo();
166
-        return isset($info['data']) && isset($info['data']['MSG_generation_data']) ? $info['data']['MSG_generation_data'] : array();
167
-    }
168
-
169
-
170
-    /**
171
-     * Retrieves the data_handler_class_name or reference associated with the current EE_Message object in the iterator.
172
-     *
173
-     * @return string
174
-     */
175
-    public function get_data_handler()
176
-    {
177
-        if ( ! $this->valid()) {
178
-            return '';
179
-        }
180
-        $info = $this->getInfo();
181
-        return isset($info['data_handler_class_name']) ? $info['data_handler_class_name'] : '';
182
-    }
183
-
184
-
185
-    /**
186
-     * Returns whether this EE_Message is for a preview or not.
187
-     *
188
-     * @return bool
189
-     */
190
-    public function is_preview()
191
-    {
192
-        if ( ! $this->valid()) {
193
-            return false;
194
-        }
195
-        $info = $this->getInfo();
196
-        return $info['preview'];
197
-    }
198
-
199
-
200
-    /**
201
-     * Returns whether the current message pointed to is for a test send.
202
-     *
203
-     * @return bool
204
-     */
205
-    public function is_test_send()
206
-    {
207
-        if ( ! $this->valid()) {
208
-            return false;
209
-        }
210
-        $info = $this->getInfo();
211
-        return $info['test_send'];
212
-    }
213
-
214
-
215
-    /**
216
-     *  This checks if the current EE_Message in the iterator is incomplete. If it is, then
217
-     *  data is attached for later retrieval (batch generation).
218
-     */
219
-    protected function _maybe_persist_attached_data()
220
-    {
221
-        if ( ! $this->valid()) {
222
-            return;
223
-        }
224
-
225
-        $info                    = $this->getInfo();
226
-        $data_handler_class_name = isset($info['data_handler_class_name']) ? $info['data_handler_class_name'] : '';
227
-        $data                    = isset($info['data']) && isset($info['data']['MSG_generation_data']) ? $info['data']['MSG_generation_data'] : array();
228
-        if ($data && $this->current()->STS_ID() === EEM_Message::status_incomplete) {
229
-            $this->current()->set_generation_data($data);
230
-            $this->current()->set_field_or_extra_meta('data_handler_class_name', $data_handler_class_name);
231
-        }
232
-    }
233
-
234
-
235
-    /**
236
-     * This method returns a count of messages in the repository that have a given priority.
237
-     *
238
-     * @param int   $priority the priority that is being filtered for the count.
239
-     * @param array $status   the optional status(es) that will also be filtered by when priority matches.
240
-     * @return int  count of messages in the queue matching the conditions.
241
-     */
242
-    public function count_by_priority_and_status($priority, $status = array())
243
-    {
244
-        if ( ! empty($status)) {
245
-            $status = is_array($status) ? $status : array($status);
246
-        }
247
-
248
-        $count = 0;
249
-        $this->rewind();
250
-        while ($this->valid()) {
251
-            if ($this->current()->priority() === $priority && (($status && in_array($this->current()->STS_ID(),
252
-                            $status)) || ! $status)
253
-            ) {
254
-                $count++;
255
-            }
256
-            $this->next();
257
-        }
258
-        return $count;
259
-    }
260
-
261
-
262
-    /**
263
-     * @return EE_Message
264
-     */
265
-    public function current()
266
-    {
267
-        return parent::current();
268
-    }
19
+	/**
20
+	 *    EE_Message_Repository constructor
21
+	 */
22
+	public function __construct()
23
+	{
24
+		$this->interface = 'EE_Message';
25
+		parent::__construct();
26
+	}
27
+
28
+
29
+	/**
30
+	 * Add the EE_Message to the repository.
31
+	 * This also ensures that the MSG_token is saves as a part of the info for retrieval.
32
+	 *
33
+	 * @param EE_Message $message
34
+	 * @param mixed      $info Any included data is saved in the attached object info array indexed by 'data'
35
+	 * @return bool
36
+	 */
37
+	public function add($message, $info = null)
38
+	{
39
+		$attached = parent::add($message);
40
+		//ensure $info is an array if not already
41
+		$info = $info === null ? $info = array() : (array)$info;
42
+		$data = $this->_init_data($info, $attached, $message);
43
+		if ($attached) {
44
+			$this->set_info($message, $data);
45
+		}
46
+		return $attached;
47
+	}
48
+
49
+
50
+	/**
51
+	 * Initializes the data from the incoming info.
52
+	 *
53
+	 * @param array      $info     incoming data.
54
+	 * @param bool       $attached Indicates whether the object was attached successfully.
55
+	 * @param EE_Message $message
56
+	 * @return array
57
+	 */
58
+	protected function _init_data($info, $attached, $message)
59
+	{
60
+		$data = array(
61
+			'test_send'               => false,
62
+			'preview'                 => false,
63
+			'data_handler_class_name' => '',
64
+			'data'                    => array(
65
+				'MSG_generation_data' => array(),
66
+			),
67
+		);
68
+		if (isset($info['preview'])) {
69
+			$data['preview'] = $info['preview'];
70
+			unset($info['preview']);
71
+		}
72
+		if (isset($info['test_send'])) {
73
+			$data['test_send'] = $info['test_send'];
74
+			unset($info['test_send']);
75
+		}
76
+		if (isset($info['data_handler_class_name'])) {
77
+			$data['data_handler_class_name'] = $info['data_handler_class_name'];
78
+			unset($info['data_handler_class_name']);
79
+		}
80
+		if ($attached && $message->STS_ID() === EEM_Message::status_incomplete) {
81
+			$generation_data = isset($info['MSG_generation_data']) ? $info['MSG_generation_data'] : array();
82
+			//if data isn't in $info...let's see if its available via the message object
83
+			$generation_data = ! $generation_data ? $message->get_generation_data() : $generation_data;
84
+			//still empty then let's just use info
85
+			$generation_data                     = ! $generation_data ? $info : $generation_data;
86
+			$data['data']['MSG_generation_data'] = $generation_data;
87
+		}
88
+		return $data;
89
+	}
90
+
91
+
92
+	/**
93
+	 * Save all EE_Message objects to the db.
94
+	 *
95
+	 * @param bool $do_hooks_only  When true, only the hooks related to saving are fired.
96
+	 * @return array array(
97
+	 *                  'updated' => 0, //count of how many messages updated
98
+	 *                  'notupdated' => 0, //count of how many messages not updated.
99
+	 *                  'errors' => array( $token ), //array of message object tokens that had errors in saving
100
+	 *                  )
101
+	 */
102
+	public function saveAll($do_hooks_only = false)
103
+	{
104
+		$save_tracking = array('updated' => 0, 'notupdated' => 0, 'errors' => array());
105
+
106
+		if (! $do_hooks_only) {
107
+			$this->rewind();
108
+			//exit early if there is nothing to save.
109
+			if (! $this->count() > 0) {
110
+				return $save_tracking;
111
+			}
112
+
113
+			while ($this->valid()) {
114
+				$saved = $this->current()->save();
115
+				if ($saved === false) {
116
+					$save_tracking['errors'][] = $this->current()->MSG_token();
117
+				} elseif ($saved) {
118
+					$save_tracking['updated']++;
119
+				} else {
120
+					$save_tracking['notupdated']++;
121
+				}
122
+				//maybe persist generation data if this is an incomplete EE_Message.
123
+				$this->_maybe_persist_attached_data();
124
+
125
+				$this->next();
126
+			}
127
+		}
128
+		do_action('AHEE__EE_Message_Repository__saveAll__after', $save_tracking, $this, $do_hooks_only);
129
+		return $save_tracking;
130
+	}
131
+
132
+
133
+	/**
134
+	 * Retrieves a EE_Message from the repository that matches the given token.
135
+	 *
136
+	 * @param string $token Token.
137
+	 * @return EE_Message | null
138
+	 */
139
+	public function getMessageByToken($token)
140
+	{
141
+		$this->rewind();
142
+		while ($this->valid()) {
143
+			if ($this->current()->MSG_token() === $token) {
144
+				$message = $this->current();
145
+				$this->rewind();
146
+				return $message;
147
+			}
148
+			$this->next();
149
+		}
150
+		return null;
151
+	}
152
+
153
+
154
+	/**
155
+	 * This retrieves any data required for generation that may be saved with the current EE_Message in storage.
156
+	 *
157
+	 * @return array();
158
+	 */
159
+	public function get_generation_data()
160
+	{
161
+		//first verify we're at a valid iterator point.
162
+		if ( ! $this->valid()) {
163
+			return array();
164
+		}
165
+		$info = $this->getInfo();
166
+		return isset($info['data']) && isset($info['data']['MSG_generation_data']) ? $info['data']['MSG_generation_data'] : array();
167
+	}
168
+
169
+
170
+	/**
171
+	 * Retrieves the data_handler_class_name or reference associated with the current EE_Message object in the iterator.
172
+	 *
173
+	 * @return string
174
+	 */
175
+	public function get_data_handler()
176
+	{
177
+		if ( ! $this->valid()) {
178
+			return '';
179
+		}
180
+		$info = $this->getInfo();
181
+		return isset($info['data_handler_class_name']) ? $info['data_handler_class_name'] : '';
182
+	}
183
+
184
+
185
+	/**
186
+	 * Returns whether this EE_Message is for a preview or not.
187
+	 *
188
+	 * @return bool
189
+	 */
190
+	public function is_preview()
191
+	{
192
+		if ( ! $this->valid()) {
193
+			return false;
194
+		}
195
+		$info = $this->getInfo();
196
+		return $info['preview'];
197
+	}
198
+
199
+
200
+	/**
201
+	 * Returns whether the current message pointed to is for a test send.
202
+	 *
203
+	 * @return bool
204
+	 */
205
+	public function is_test_send()
206
+	{
207
+		if ( ! $this->valid()) {
208
+			return false;
209
+		}
210
+		$info = $this->getInfo();
211
+		return $info['test_send'];
212
+	}
213
+
214
+
215
+	/**
216
+	 *  This checks if the current EE_Message in the iterator is incomplete. If it is, then
217
+	 *  data is attached for later retrieval (batch generation).
218
+	 */
219
+	protected function _maybe_persist_attached_data()
220
+	{
221
+		if ( ! $this->valid()) {
222
+			return;
223
+		}
224
+
225
+		$info                    = $this->getInfo();
226
+		$data_handler_class_name = isset($info['data_handler_class_name']) ? $info['data_handler_class_name'] : '';
227
+		$data                    = isset($info['data']) && isset($info['data']['MSG_generation_data']) ? $info['data']['MSG_generation_data'] : array();
228
+		if ($data && $this->current()->STS_ID() === EEM_Message::status_incomplete) {
229
+			$this->current()->set_generation_data($data);
230
+			$this->current()->set_field_or_extra_meta('data_handler_class_name', $data_handler_class_name);
231
+		}
232
+	}
233
+
234
+
235
+	/**
236
+	 * This method returns a count of messages in the repository that have a given priority.
237
+	 *
238
+	 * @param int   $priority the priority that is being filtered for the count.
239
+	 * @param array $status   the optional status(es) that will also be filtered by when priority matches.
240
+	 * @return int  count of messages in the queue matching the conditions.
241
+	 */
242
+	public function count_by_priority_and_status($priority, $status = array())
243
+	{
244
+		if ( ! empty($status)) {
245
+			$status = is_array($status) ? $status : array($status);
246
+		}
247
+
248
+		$count = 0;
249
+		$this->rewind();
250
+		while ($this->valid()) {
251
+			if ($this->current()->priority() === $priority && (($status && in_array($this->current()->STS_ID(),
252
+							$status)) || ! $status)
253
+			) {
254
+				$count++;
255
+			}
256
+			$this->next();
257
+		}
258
+		return $count;
259
+	}
260
+
261
+
262
+	/**
263
+	 * @return EE_Message
264
+	 */
265
+	public function current()
266
+	{
267
+		return parent::current();
268
+	}
269 269
 
270 270
 
271 271
 }
272 272
\ No newline at end of file
Please login to merge, or discard this patch.
core/libraries/messages/EE_Messages_Queue.lib.php 2 patches
Indentation   +677 added lines, -677 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use \EventEspresso\core\exceptions\SendMessageException;
3 3
 
4 4
 if (! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 
8 8
 /**
@@ -18,681 +18,681 @@  discard block
 block discarded – undo
18 18
 {
19 19
 
20 20
 
21
-    /**
22
-     * @type    string  reference for sending action
23
-     */
24
-    const action_sending = 'sending';
25
-
26
-    /**
27
-     * @type    string  reference for generation action
28
-     */
29
-    const action_generating = 'generation';
30
-
31
-
32
-    /**
33
-     * @type EE_Message_Repository $_message_repository
34
-     */
35
-    protected $_message_repository;
36
-
37
-    /**
38
-     * Sets the limit of how many messages are generated per process.
39
-     *
40
-     * @type int
41
-     */
42
-    protected $_batch_count;
43
-
44
-    /**
45
-     * Sets the limit of how many messages can be sent per hour.
46
-     *
47
-     * @type int
48
-     */
49
-    protected $_rate_limit;
50
-
51
-    /**
52
-     * This is an array of cached queue items being stored in this object.
53
-     * The array keys will be the ID of the EE_Message in the db if saved.  If the EE_Message
54
-     * is not saved to the db then its key will be an increment of "UNS" (i.e. UNS1, UNS2 etc.)
55
-     *
56
-     * @type EE_Message[]
57
-     */
58
-    protected $_cached_queue_items;
59
-
60
-    /**
61
-     * Tracks the number of unsaved queue items.
62
-     *
63
-     * @type int
64
-     */
65
-    protected $_unsaved_count = 0;
66
-
67
-    /**
68
-     * used to record if a do_messenger_hooks has already been called for a message type.  This prevents multiple
69
-     * hooks getting fired if users have setup their action/filter hooks to prevent duplicate calls.
70
-     *
71
-     * @type array
72
-     */
73
-    protected $_did_hook = array();
74
-
75
-
76
-    /**
77
-     * Constructor.
78
-     * Setup all the initial properties and load a EE_Message_Repository.
79
-     *
80
-     * @param \EE_Message_Repository $message_repository
81
-     */
82
-    public function __construct(EE_Message_Repository $message_repository)
83
-    {
84
-        $this->_batch_count        = apply_filters('FHEE__EE_Messages_Queue___batch_count', 50);
85
-        $this->_rate_limit         = $this->get_rate_limit();
86
-        $this->_message_repository = $message_repository;
87
-    }
88
-
89
-
90
-    /**
91
-     * Add a EE_Message object to the queue
92
-     *
93
-     * @param EE_Message $message
94
-     * @param array      $data         This will be an array of data to attach to the object in the repository.  If the
95
-     *                                 object is persisted, this data will be saved on an extra_meta object related to
96
-     *                                 EE_Message.
97
-     * @param  bool      $preview      Whether this EE_Message represents a preview or not.
98
-     * @param  bool      $test_send    This indicates whether to do a test send instead of actual send. A test send will
99
-     *                                 use the messenger send method but typically is based on preview data.
100
-     * @return bool          Whether the message was successfully added to the repository or not.
101
-     */
102
-    public function add(EE_Message $message, $data = array(), $preview = false, $test_send = false)
103
-    {
104
-        $data['preview']   = $preview;
105
-        $data['test_send'] = $test_send;
106
-        return $this->_message_repository->add($message, $data);
107
-    }
108
-
109
-
110
-    /**
111
-     * Removes EE_Message from _queue that matches the given EE_Message if the pointer is on a matching EE_Message
112
-     *
113
-     * @param EE_Message $message The message to detach from the queue
114
-     * @param bool       $persist This flag indicates whether to attempt to delete the object from the db as well.
115
-     * @return bool
116
-     */
117
-    public function remove(EE_Message $message, $persist = false)
118
-    {
119
-        if ($persist && $this->_message_repository->current() !== $message) {
120
-            //get pointer on right message
121
-            if ($this->_message_repository->has($message)) {
122
-                $this->_message_repository->rewind();
123
-                while ($this->_message_repository->valid()) {
124
-                    if ($this->_message_repository->current() === $message) {
125
-                        break;
126
-                    }
127
-                    $this->_message_repository->next();
128
-                }
129
-            } else {
130
-                return false;
131
-            }
132
-        }
133
-        return $persist ? $this->_message_repository->delete() : $this->_message_repository->remove($message);
134
-    }
135
-
136
-
137
-    /**
138
-     * Persists all queued EE_Message objects to the db.
139
-     *
140
-     * @param bool $do_hooks_only       @see EE_Message_Repository::saveAll
141
-     * @return array @see EE_Messages_Repository::saveAll() for return values.
142
-     */
143
-    public function save($do_hooks_only = false)
144
-    {
145
-        return $this->_message_repository->saveAll($do_hooks_only);
146
-    }
147
-
148
-
149
-    /**
150
-     * @return EE_Message_Repository
151
-     */
152
-    public function get_message_repository()
153
-    {
154
-        return $this->_message_repository;
155
-    }
156
-
157
-
158
-    /**
159
-     * This does the following things:
160
-     * 1. Checks if there is a lock on generation (prevents race conditions).  If there is a lock then exits (return
161
-     * false).
162
-     * 2. If no lock, sets lock, then retrieves a batch of non-generated EE_Message objects and adds to queue
163
-     * 3. Returns bool.  True = batch ready.  False = no batch ready (or nothing available for generation).
164
-     * Note: Callers should make sure they release the lock otherwise batch generation will be prevented from
165
-     * continuing. The lock is on a transient that is set to expire after one hour as a fallback in case locks are not
166
-     * removed.
167
-     *
168
-     * @return bool  true if successfully retrieved batch, false no batch ready.
169
-     */
170
-    public function get_batch_to_generate()
171
-    {
172
-        if ($this->is_locked(EE_Messages_Queue::action_generating)) {
173
-            return false;
174
-        }
175
-
176
-        //lock batch generation to prevent race conditions.
177
-        $this->lock_queue(EE_Messages_Queue::action_generating);
178
-
179
-        $query_args = array(
180
-            // key 0 = where conditions
181
-            0          => array('STS_ID' => EEM_Message::status_incomplete),
182
-            'order_by' => $this->_get_priority_orderby(),
183
-            'limit'    => $this->_batch_count,
184
-        );
185
-        $messages   = EEM_Message::instance()->get_all($query_args);
186
-
187
-        if ( ! $messages) {
188
-            return false; //nothing to generate
189
-        }
190
-
191
-        foreach ($messages as $message) {
192
-            if ($message instanceof EE_Message) {
193
-                $data = $message->all_extra_meta_array();
194
-                $this->add($message, $data);
195
-            }
196
-        }
197
-        return true;
198
-    }
199
-
200
-
201
-    /**
202
-     * This does the following things:
203
-     * 1. Checks if there is a lock on sending (prevents race conditions).  If there is a lock then exits (return
204
-     * false).
205
-     * 2. Grabs the allowed number of messages to send for the rate_limit.  If cannot send any more messages, then
206
-     * return false.
207
-     * 2. If no lock, sets lock, then retrieves a batch of EE_Message objects, adds to queue and triggers execution.
208
-     * 3. On success or unsuccessful send, sets status appropriately.
209
-     * 4. Saves messages via the queue
210
-     * 5. Releases lock.
211
-     *
212
-     * @return bool  true on success, false if something preventing sending (i.e. lock set).  Note: true does not
213
-     *               necessarily mean that all messages were successfully sent.  It just means that this method
214
-     *               successfully completed. On true, client may want to call $this->count_STS_in_queue(
215
-     *               EEM_Message::status_failed ) to see if any failed EE_Message objects.  Each failed message object
216
-     *               will also have a saved error message on it to assist with notifying user.
217
-     */
218
-    public function get_to_send_batch_and_send()
219
-    {
220
-        if ($this->is_locked(EE_Messages_Queue::action_sending) || $this->_rate_limit < 1) {
221
-            return false;
222
-        }
223
-
224
-        $this->lock_queue(EE_Messages_Queue::action_sending);
225
-
226
-        $batch = $this->_batch_count < $this->_rate_limit ? $this->_batch_count : $this->_rate_limit;
227
-
228
-        $query_args = array(
229
-            // key 0 = where conditions
230
-            0          => array('STS_ID' => array('IN', EEM_Message::instance()->stati_indicating_to_send())),
231
-            'order_by' => $this->_get_priority_orderby(),
232
-            'limit'    => $batch,
233
-        );
234
-
235
-        $messages_to_send = EEM_Message::instance()->get_all($query_args);
236
-
237
-
238
-        //any to send?
239
-        if ( ! $messages_to_send) {
240
-            $this->unlock_queue(EE_Messages_Queue::action_sending);
241
-            return false;
242
-        }
243
-
244
-        //add to queue.
245
-        foreach ($messages_to_send as $message) {
246
-            if ($message instanceof EE_Message) {
247
-                $this->add($message);
248
-            }
249
-        }
250
-
251
-        //send messages  (this also updates the rate limit)
252
-        $this->execute();
253
-
254
-        //release lock
255
-        $this->unlock_queue(EE_Messages_Queue::action_sending);
256
-        return true;
257
-    }
258
-
259
-
260
-    /**
261
-     * Locks the queue so that no other queues can call the "batch" methods.
262
-     *
263
-     * @param   string $type The type of queue being locked.
264
-     */
265
-    public function lock_queue($type = EE_Messages_Queue::action_generating)
266
-    {
267
-        set_transient($this->_get_lock_key($type), 1, $this->_get_lock_expiry($type));
268
-    }
269
-
270
-
271
-    /**
272
-     * Unlocks the queue so that batch methods can be used.
273
-     *
274
-     * @param   string $type The type of queue being unlocked.
275
-     */
276
-    public function unlock_queue($type = EE_Messages_Queue::action_generating)
277
-    {
278
-        delete_transient($this->_get_lock_key($type));
279
-    }
280
-
281
-
282
-    /**
283
-     * Retrieve the key used for the lock transient.
284
-     *
285
-     * @param string $type The type of lock.
286
-     * @return string
287
-     */
288
-    protected function _get_lock_key($type = EE_Messages_Queue::action_generating)
289
-    {
290
-        return '_ee_lock_' . $type;
291
-    }
292
-
293
-
294
-    /**
295
-     * Retrieve the expiry time for the lock transient.
296
-     *
297
-     * @param string $type The type of lock
298
-     * @return int   time to expiry in seconds.
299
-     */
300
-    protected function _get_lock_expiry($type = EE_Messages_Queue::action_generating)
301
-    {
302
-        return (int)apply_filters('FHEE__EE_Messages_Queue__lock_expiry', HOUR_IN_SECONDS, $type);
303
-    }
304
-
305
-
306
-    /**
307
-     * Returns the key used for rate limit transient.
308
-     *
309
-     * @return string
310
-     */
311
-    protected function _get_rate_limit_key()
312
-    {
313
-        return '_ee_rate_limit';
314
-    }
315
-
316
-
317
-    /**
318
-     * Returns the rate limit expiry time.
319
-     *
320
-     * @return int
321
-     */
322
-    protected function _get_rate_limit_expiry()
323
-    {
324
-        return (int)apply_filters('FHEE__EE_Messages_Queue__rate_limit_expiry', HOUR_IN_SECONDS);
325
-    }
326
-
327
-
328
-    /**
329
-     * Returns the default rate limit for sending messages.
330
-     *
331
-     * @return int
332
-     */
333
-    protected function _default_rate_limit()
334
-    {
335
-        return (int)apply_filters('FHEE__EE_Messages_Queue___rate_limit', 200);
336
-    }
337
-
338
-
339
-    /**
340
-     * Return the orderby array for priority.
341
-     *
342
-     * @return array
343
-     */
344
-    protected function _get_priority_orderby()
345
-    {
346
-        return array(
347
-            'MSG_priority' => 'ASC',
348
-            'MSG_modified' => 'DESC',
349
-        );
350
-    }
351
-
352
-
353
-    /**
354
-     * Returns whether batch methods are "locked" or not.
355
-     *
356
-     * @param  string $type The type of lock being checked for.
357
-     * @return bool
358
-     */
359
-    public function is_locked($type = EE_Messages_Queue::action_generating)
360
-    {
361
-        /**
362
-         * This filters the default is_locked behaviour.
363
-         */
364
-        $is_locked = filter_var(
365
-            apply_filters(
366
-                'FHEE__EE_Messages_Queue__is_locked',
367
-                get_transient($this->_get_lock_key($type)),
368
-                $this
369
-            ),
370
-            FILTER_VALIDATE_BOOLEAN
371
-        );
372
-
373
-        /**
374
-         * @see usage of this filter in EE_Messages_Queue::initiate_request_by_priority() method.
375
-         *            Also implemented here because messages processed on the same request should not have any locks applied.
376
-         */
377
-        if (
378
-            apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
379
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
380
-        ) {
381
-            $is_locked = false;
382
-        }
383
-
384
-
385
-        return $is_locked;
386
-    }
387
-
388
-
389
-    /**
390
-     * Retrieves the rate limit that may be cached as a transient.
391
-     * If the rate limit is not set, then this sets the default rate limit and expiry and returns it.
392
-     *
393
-     * @return int
394
-     */
395
-    public function get_rate_limit()
396
-    {
397
-        if ( ! $rate_limit = get_transient($this->_get_rate_limit_key())) {
398
-            $rate_limit = $this->_default_rate_limit();
399
-            set_transient($this->_get_rate_limit_key(), $rate_limit, $this->_get_rate_limit_key());
400
-        }
401
-        return $rate_limit;
402
-    }
403
-
404
-
405
-    /**
406
-     * This updates existing rate limit with the new limit which is the old minus the batch.
407
-     *
408
-     * @param int $batch_completed This sets the new rate limit based on the given batch that was completed.
409
-     */
410
-    public function set_rate_limit($batch_completed)
411
-    {
412
-        //first get the most up to date rate limit (in case its expired and reset)
413
-        $rate_limit = $this->get_rate_limit();
414
-        $new_limit  = $rate_limit - $batch_completed;
415
-        //updating the transient option directly to avoid resetting the expiry.
416
-        update_option('_transient_' . $this->_get_rate_limit_key(), $new_limit);
417
-    }
418
-
419
-
420
-    /**
421
-     * This method checks the queue for ANY EE_Message objects with a priority matching the given priority passed in.
422
-     * If that exists, then we immediately initiate a non-blocking request to do the requested action type.
423
-     * Note: Keep in mind that there is the possibility that the request will not execute if there is already another
424
-     * request running on a queue for the given task.
425
-     *
426
-     * @param string $task     This indicates what type of request is going to be initiated.
427
-     * @param int    $priority This indicates the priority that triggers initiating the request.
428
-     */
429
-    public function initiate_request_by_priority($task = 'generate', $priority = EEM_Message::priority_high)
430
-    {
431
-        //determine what status is matched with the priority as part of the trigger conditions.
432
-        $status = $task == 'generate'
433
-            ? EEM_Message::status_incomplete
434
-            : EEM_Message::instance()->stati_indicating_to_send();
435
-        // always make sure we save because either this will get executed immediately on a separate request
436
-        // or remains in the queue for the regularly scheduled queue batch.
437
-        $this->save();
438
-        /**
439
-         * This filter/option allows users to override processing of messages on separate requests and instead have everything
440
-         * happen on the same request.  If this is utilized remember:
441
-         * - message priorities don't matter
442
-         * - existing unprocessed messages in the queue will not get processed unless manually triggered.
443
-         * - things will be perceived to take longer to happen for end users (i.e. registrations) because of the additional
444
-         *   processing happening on the same request.
445
-         * - any race condition protection (locks) are removed because they don't apply when things are processed on
446
-         *   the same request.
447
-         */
448
-        if (
449
-            apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
450
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
451
-        ) {
452
-            $messages_processor = EE_Registry::instance()->load_lib('Messages_Processor');
453
-            if ($messages_processor instanceof EE_Messages_Processor) {
454
-                return $messages_processor->process_immediately_from_queue($this);
455
-            }
456
-            //if we get here then that means the messages processor couldn't be loaded so messages will just remain
457
-            //queued for manual triggering by end user.
458
-        }
459
-
460
-        if ($this->_message_repository->count_by_priority_and_status($priority, $status)) {
461
-            EE_Messages_Scheduler::initiate_scheduled_non_blocking_request($task);
462
-        }
463
-    }
464
-
465
-
466
-    /**
467
-     *  Loops through the EE_Message objects in the _queue and calls the messenger send methods for each message.
468
-     *
469
-     * @param   bool     $save                    Used to indicate whether to save the message queue after sending
470
-     *                                            (default will save).
471
-     * @param   mixed    $sending_messenger       (optional) When the sending messenger is different than
472
-     *                                            what is on the EE_Message object in the queue.
473
-     *                                            For instance, showing the browser view of an email message,
474
-     *                                            or giving a pdf generated view of an html document.
475
-     *                                            This should be an instance of EE_messenger but if you call this
476
-     *                                            method
477
-     *                                            intending it to be a sending messenger but a valid one could not be
478
-     *                                            retrieved then send in an instance of EE_Error that contains the
479
-     *                                            related error message.
480
-     * @param   bool|int $by_priority             When set, this indicates that only messages
481
-     *                                            matching the given priority should be executed.
482
-     * @return int        Number of messages sent.  Note, 0 does not mean that no messages were processed.
483
-     *                                            Also, if the messenger is an request type messenger (or a preview),
484
-     *                                            its entirely possible that the messenger will exit before
485
-     */
486
-    public function execute($save = true, $sending_messenger = null, $by_priority = false)
487
-    {
488
-        $messages_sent   = 0;
489
-        $this->_did_hook = array();
490
-        $this->_message_repository->rewind();
491
-
492
-        while ($this->_message_repository->valid()) {
493
-            $error_messages = array();
494
-            /** @type EE_Message $message */
495
-            $message = $this->_message_repository->current();
496
-            //only process things that are queued for sending
497
-            if (! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
498
-                $this->_message_repository->next();
499
-                continue;
500
-            }
501
-            //if $by_priority is set and does not match then continue;
502
-            if ($by_priority && $by_priority != $message->priority()) {
503
-                $this->_message_repository->next();
504
-                continue;
505
-            }
506
-            //error checking
507
-            if (! $message->valid_messenger()) {
508
-                $error_messages[] = sprintf(
509
-                    __('The %s messenger is not active at time of sending.', 'event_espresso'),
510
-                    $message->messenger()
511
-                );
512
-            }
513
-            if (! $message->valid_message_type()) {
514
-                $error_messages[] = sprintf(
515
-                    __('The %s message type is not active at the time of sending.', 'event_espresso'),
516
-                    $message->message_type()
517
-                );
518
-            }
519
-            // if there was supposed to be a sending messenger for this message, but it was invalid/inactive,
520
-            // then it will instead be an EE_Error object, so let's check for that
521
-            if ($sending_messenger instanceof EE_Error) {
522
-                $error_messages[] = $sending_messenger->getMessage();
523
-            }
524
-            // if there are no errors, then let's process the message
525
-            if (empty($error_messages)) {
526
-                if ($save) {
527
-                    $message->set_messenger_is_executing();
528
-                }
529
-                if ($this->_process_message($message, $sending_messenger)) {
530
-                    $messages_sent++;
531
-                }
532
-            }
533
-            $this->_set_error_message($message, $error_messages);
534
-            //add modified time
535
-            $message->set_modified(time());
536
-            //we save each message after its processed to make sure its status persists in case PHP times-out or runs
537
-            //out of memory. @see https://events.codebasehq.com/projects/event-espresso/tickets/10281
538
-            if ($save) {
539
-                $message->save();
540
-            }
541
-
542
-            $this->_message_repository->next();
543
-        }
544
-        if ($save) {
545
-            $this->save(true);
546
-        }
547
-        return $messages_sent;
548
-    }
549
-
550
-
551
-    /**
552
-     * _process_message
553
-     *
554
-     * @param EE_Message $message
555
-     * @param mixed      $sending_messenger (optional)
556
-     * @return bool
557
-     */
558
-    protected function _process_message(EE_Message $message, $sending_messenger = null)
559
-    {
560
-        // these *should* have been validated in the execute() method above
561
-        $messenger    = $message->messenger_object();
562
-        $message_type = $message->message_type_object();
563
-        //do actions for sending messenger if it differs from generating messenger and swap values.
564
-        if (
565
-            $sending_messenger instanceof EE_messenger
566
-            && $messenger instanceof EE_messenger
567
-            && $sending_messenger->name != $messenger->name
568
-        ) {
569
-            $messenger->do_secondary_messenger_hooks($sending_messenger->name);
570
-            $messenger = $sending_messenger;
571
-        }
572
-        // send using messenger, but double check objects
573
-        if ($messenger instanceof EE_messenger && $message_type instanceof EE_message_type) {
574
-            //set hook for message type (but only if not using another messenger to send).
575
-            if ( ! isset($this->_did_hook[$message_type->name])) {
576
-                $message_type->do_messenger_hooks($messenger);
577
-                $this->_did_hook[$message_type->name] = 1;
578
-            }
579
-            //if preview then use preview method
580
-            return $this->_message_repository->is_preview()
581
-                ? $this->_do_preview($message, $messenger, $message_type, $this->_message_repository->is_test_send())
582
-                : $this->_do_send($message, $messenger, $message_type);
583
-        }
584
-        return false;
585
-    }
586
-
587
-
588
-    /**
589
-     * The intention of this method is to count how many EE_Message objects
590
-     * are in the queue with a given status.
591
-     * Example usage:
592
-     * After a caller calls the "EE_Message_Queue::execute()" method, the caller can check if there were any failed
593
-     * sends by calling $queue->count_STS_in_queue( EEM_Message_Queue::status_failed ).
594
-     *
595
-     * @param array $status Stati to check for in queue
596
-     * @return int  Count of EE_Message's matching the given status.
597
-     */
598
-    public function count_STS_in_queue($status)
599
-    {
600
-        $count  = 0;
601
-        $status = is_array($status) ? $status : array($status);
602
-        $this->_message_repository->rewind();
603
-        foreach ($this->_message_repository as $message) {
604
-            if (in_array($message->STS_ID(), $status)) {
605
-                $count++;
606
-            }
607
-        }
608
-        return $count;
609
-    }
610
-
611
-
612
-    /**
613
-     * Executes the get_preview method on the provided messenger.
614
-     *
615
-     * @param EE_Message      $message
616
-     * @param EE_messenger    $messenger
617
-     * @param EE_message_type $message_type
618
-     * @param                 $test_send
619
-     * @return bool   true means all went well, false means, not so much.
620
-     */
621
-    protected function _do_preview(
622
-        EE_Message $message,
623
-        EE_messenger $messenger,
624
-        EE_message_type $message_type,
625
-        $test_send
626
-    ) {
627
-        if ($preview = $messenger->get_preview($message, $message_type, $test_send)) {
628
-            if ( ! $test_send) {
629
-                $message->set_content($preview);
630
-            }
631
-            $message->set_STS_ID(EEM_Message::status_sent);
632
-            return true;
633
-        } else {
634
-            $message->set_STS_ID(EEM_Message::status_failed);
635
-            return false;
636
-        }
637
-    }
638
-
639
-
640
-    /**
641
-     * Executes the send method on the provided messenger
642
-     * EE_Messengers are expected to:
643
-     * - return true if the send was successful.
644
-     * - return false if the send was unsuccessful but can be tried again.
645
-     * - throw an Exception if the send was unsuccessful and cannot be tried again.
646
-     *
647
-     * @param EE_Message      $message
648
-     * @param EE_messenger    $messenger
649
-     * @param EE_message_type $message_type
650
-     * @return bool true means all went well, false means, not so much.
651
-     */
652
-    protected function _do_send(EE_Message $message, EE_messenger $messenger, EE_message_type $message_type)
653
-    {
654
-        try {
655
-            if ($messenger->send_message($message, $message_type)) {
656
-                $message->set_STS_ID(EEM_Message::status_sent);
657
-                return true;
658
-            } else {
659
-                $message->set_STS_ID(EEM_Message::status_retry);
660
-                return false;
661
-            }
662
-        } catch (SendMessageException $e) {
663
-            $message->set_STS_ID(EEM_Message::status_failed);
664
-            $message->set_error_message($e->getMessage());
665
-            return false;
666
-        }
667
-    }
668
-
669
-
670
-    /**
671
-     * This sets any necessary error messages on the message object and its status to failed.
672
-     *
673
-     * @param EE_Message $message
674
-     * @param array      $error_messages the response from the messenger.
675
-     */
676
-    protected function _set_error_message(EE_Message $message, $error_messages)
677
-    {
678
-        $error_messages = (array)$error_messages;
679
-        if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_failed_sending())) {
680
-            $notices          = EE_Error::has_notices();
681
-            $error_messages[] = __(
682
-                'Messenger and Message Type were valid and active, but the messenger send method failed.',
683
-                'event_espresso'
684
-            );
685
-            if ($notices === 1) {
686
-                $notices           = EE_Error::get_vanilla_notices();
687
-                $notices['errors'] = isset($notices['errors']) ? $notices['errors'] : array();
688
-                $error_messages[]  = implode("\n", $notices['errors']);
689
-            }
690
-        }
691
-        if (count($error_messages) > 0) {
692
-            $msg = __('Message was not executed successfully.', 'event_espresso');
693
-            $msg = $msg . "\n" . implode("\n", $error_messages);
694
-            $message->set_error_message($msg);
695
-        }
696
-    }
21
+	/**
22
+	 * @type    string  reference for sending action
23
+	 */
24
+	const action_sending = 'sending';
25
+
26
+	/**
27
+	 * @type    string  reference for generation action
28
+	 */
29
+	const action_generating = 'generation';
30
+
31
+
32
+	/**
33
+	 * @type EE_Message_Repository $_message_repository
34
+	 */
35
+	protected $_message_repository;
36
+
37
+	/**
38
+	 * Sets the limit of how many messages are generated per process.
39
+	 *
40
+	 * @type int
41
+	 */
42
+	protected $_batch_count;
43
+
44
+	/**
45
+	 * Sets the limit of how many messages can be sent per hour.
46
+	 *
47
+	 * @type int
48
+	 */
49
+	protected $_rate_limit;
50
+
51
+	/**
52
+	 * This is an array of cached queue items being stored in this object.
53
+	 * The array keys will be the ID of the EE_Message in the db if saved.  If the EE_Message
54
+	 * is not saved to the db then its key will be an increment of "UNS" (i.e. UNS1, UNS2 etc.)
55
+	 *
56
+	 * @type EE_Message[]
57
+	 */
58
+	protected $_cached_queue_items;
59
+
60
+	/**
61
+	 * Tracks the number of unsaved queue items.
62
+	 *
63
+	 * @type int
64
+	 */
65
+	protected $_unsaved_count = 0;
66
+
67
+	/**
68
+	 * used to record if a do_messenger_hooks has already been called for a message type.  This prevents multiple
69
+	 * hooks getting fired if users have setup their action/filter hooks to prevent duplicate calls.
70
+	 *
71
+	 * @type array
72
+	 */
73
+	protected $_did_hook = array();
74
+
75
+
76
+	/**
77
+	 * Constructor.
78
+	 * Setup all the initial properties and load a EE_Message_Repository.
79
+	 *
80
+	 * @param \EE_Message_Repository $message_repository
81
+	 */
82
+	public function __construct(EE_Message_Repository $message_repository)
83
+	{
84
+		$this->_batch_count        = apply_filters('FHEE__EE_Messages_Queue___batch_count', 50);
85
+		$this->_rate_limit         = $this->get_rate_limit();
86
+		$this->_message_repository = $message_repository;
87
+	}
88
+
89
+
90
+	/**
91
+	 * Add a EE_Message object to the queue
92
+	 *
93
+	 * @param EE_Message $message
94
+	 * @param array      $data         This will be an array of data to attach to the object in the repository.  If the
95
+	 *                                 object is persisted, this data will be saved on an extra_meta object related to
96
+	 *                                 EE_Message.
97
+	 * @param  bool      $preview      Whether this EE_Message represents a preview or not.
98
+	 * @param  bool      $test_send    This indicates whether to do a test send instead of actual send. A test send will
99
+	 *                                 use the messenger send method but typically is based on preview data.
100
+	 * @return bool          Whether the message was successfully added to the repository or not.
101
+	 */
102
+	public function add(EE_Message $message, $data = array(), $preview = false, $test_send = false)
103
+	{
104
+		$data['preview']   = $preview;
105
+		$data['test_send'] = $test_send;
106
+		return $this->_message_repository->add($message, $data);
107
+	}
108
+
109
+
110
+	/**
111
+	 * Removes EE_Message from _queue that matches the given EE_Message if the pointer is on a matching EE_Message
112
+	 *
113
+	 * @param EE_Message $message The message to detach from the queue
114
+	 * @param bool       $persist This flag indicates whether to attempt to delete the object from the db as well.
115
+	 * @return bool
116
+	 */
117
+	public function remove(EE_Message $message, $persist = false)
118
+	{
119
+		if ($persist && $this->_message_repository->current() !== $message) {
120
+			//get pointer on right message
121
+			if ($this->_message_repository->has($message)) {
122
+				$this->_message_repository->rewind();
123
+				while ($this->_message_repository->valid()) {
124
+					if ($this->_message_repository->current() === $message) {
125
+						break;
126
+					}
127
+					$this->_message_repository->next();
128
+				}
129
+			} else {
130
+				return false;
131
+			}
132
+		}
133
+		return $persist ? $this->_message_repository->delete() : $this->_message_repository->remove($message);
134
+	}
135
+
136
+
137
+	/**
138
+	 * Persists all queued EE_Message objects to the db.
139
+	 *
140
+	 * @param bool $do_hooks_only       @see EE_Message_Repository::saveAll
141
+	 * @return array @see EE_Messages_Repository::saveAll() for return values.
142
+	 */
143
+	public function save($do_hooks_only = false)
144
+	{
145
+		return $this->_message_repository->saveAll($do_hooks_only);
146
+	}
147
+
148
+
149
+	/**
150
+	 * @return EE_Message_Repository
151
+	 */
152
+	public function get_message_repository()
153
+	{
154
+		return $this->_message_repository;
155
+	}
156
+
157
+
158
+	/**
159
+	 * This does the following things:
160
+	 * 1. Checks if there is a lock on generation (prevents race conditions).  If there is a lock then exits (return
161
+	 * false).
162
+	 * 2. If no lock, sets lock, then retrieves a batch of non-generated EE_Message objects and adds to queue
163
+	 * 3. Returns bool.  True = batch ready.  False = no batch ready (or nothing available for generation).
164
+	 * Note: Callers should make sure they release the lock otherwise batch generation will be prevented from
165
+	 * continuing. The lock is on a transient that is set to expire after one hour as a fallback in case locks are not
166
+	 * removed.
167
+	 *
168
+	 * @return bool  true if successfully retrieved batch, false no batch ready.
169
+	 */
170
+	public function get_batch_to_generate()
171
+	{
172
+		if ($this->is_locked(EE_Messages_Queue::action_generating)) {
173
+			return false;
174
+		}
175
+
176
+		//lock batch generation to prevent race conditions.
177
+		$this->lock_queue(EE_Messages_Queue::action_generating);
178
+
179
+		$query_args = array(
180
+			// key 0 = where conditions
181
+			0          => array('STS_ID' => EEM_Message::status_incomplete),
182
+			'order_by' => $this->_get_priority_orderby(),
183
+			'limit'    => $this->_batch_count,
184
+		);
185
+		$messages   = EEM_Message::instance()->get_all($query_args);
186
+
187
+		if ( ! $messages) {
188
+			return false; //nothing to generate
189
+		}
190
+
191
+		foreach ($messages as $message) {
192
+			if ($message instanceof EE_Message) {
193
+				$data = $message->all_extra_meta_array();
194
+				$this->add($message, $data);
195
+			}
196
+		}
197
+		return true;
198
+	}
199
+
200
+
201
+	/**
202
+	 * This does the following things:
203
+	 * 1. Checks if there is a lock on sending (prevents race conditions).  If there is a lock then exits (return
204
+	 * false).
205
+	 * 2. Grabs the allowed number of messages to send for the rate_limit.  If cannot send any more messages, then
206
+	 * return false.
207
+	 * 2. If no lock, sets lock, then retrieves a batch of EE_Message objects, adds to queue and triggers execution.
208
+	 * 3. On success or unsuccessful send, sets status appropriately.
209
+	 * 4. Saves messages via the queue
210
+	 * 5. Releases lock.
211
+	 *
212
+	 * @return bool  true on success, false if something preventing sending (i.e. lock set).  Note: true does not
213
+	 *               necessarily mean that all messages were successfully sent.  It just means that this method
214
+	 *               successfully completed. On true, client may want to call $this->count_STS_in_queue(
215
+	 *               EEM_Message::status_failed ) to see if any failed EE_Message objects.  Each failed message object
216
+	 *               will also have a saved error message on it to assist with notifying user.
217
+	 */
218
+	public function get_to_send_batch_and_send()
219
+	{
220
+		if ($this->is_locked(EE_Messages_Queue::action_sending) || $this->_rate_limit < 1) {
221
+			return false;
222
+		}
223
+
224
+		$this->lock_queue(EE_Messages_Queue::action_sending);
225
+
226
+		$batch = $this->_batch_count < $this->_rate_limit ? $this->_batch_count : $this->_rate_limit;
227
+
228
+		$query_args = array(
229
+			// key 0 = where conditions
230
+			0          => array('STS_ID' => array('IN', EEM_Message::instance()->stati_indicating_to_send())),
231
+			'order_by' => $this->_get_priority_orderby(),
232
+			'limit'    => $batch,
233
+		);
234
+
235
+		$messages_to_send = EEM_Message::instance()->get_all($query_args);
236
+
237
+
238
+		//any to send?
239
+		if ( ! $messages_to_send) {
240
+			$this->unlock_queue(EE_Messages_Queue::action_sending);
241
+			return false;
242
+		}
243
+
244
+		//add to queue.
245
+		foreach ($messages_to_send as $message) {
246
+			if ($message instanceof EE_Message) {
247
+				$this->add($message);
248
+			}
249
+		}
250
+
251
+		//send messages  (this also updates the rate limit)
252
+		$this->execute();
253
+
254
+		//release lock
255
+		$this->unlock_queue(EE_Messages_Queue::action_sending);
256
+		return true;
257
+	}
258
+
259
+
260
+	/**
261
+	 * Locks the queue so that no other queues can call the "batch" methods.
262
+	 *
263
+	 * @param   string $type The type of queue being locked.
264
+	 */
265
+	public function lock_queue($type = EE_Messages_Queue::action_generating)
266
+	{
267
+		set_transient($this->_get_lock_key($type), 1, $this->_get_lock_expiry($type));
268
+	}
269
+
270
+
271
+	/**
272
+	 * Unlocks the queue so that batch methods can be used.
273
+	 *
274
+	 * @param   string $type The type of queue being unlocked.
275
+	 */
276
+	public function unlock_queue($type = EE_Messages_Queue::action_generating)
277
+	{
278
+		delete_transient($this->_get_lock_key($type));
279
+	}
280
+
281
+
282
+	/**
283
+	 * Retrieve the key used for the lock transient.
284
+	 *
285
+	 * @param string $type The type of lock.
286
+	 * @return string
287
+	 */
288
+	protected function _get_lock_key($type = EE_Messages_Queue::action_generating)
289
+	{
290
+		return '_ee_lock_' . $type;
291
+	}
292
+
293
+
294
+	/**
295
+	 * Retrieve the expiry time for the lock transient.
296
+	 *
297
+	 * @param string $type The type of lock
298
+	 * @return int   time to expiry in seconds.
299
+	 */
300
+	protected function _get_lock_expiry($type = EE_Messages_Queue::action_generating)
301
+	{
302
+		return (int)apply_filters('FHEE__EE_Messages_Queue__lock_expiry', HOUR_IN_SECONDS, $type);
303
+	}
304
+
305
+
306
+	/**
307
+	 * Returns the key used for rate limit transient.
308
+	 *
309
+	 * @return string
310
+	 */
311
+	protected function _get_rate_limit_key()
312
+	{
313
+		return '_ee_rate_limit';
314
+	}
315
+
316
+
317
+	/**
318
+	 * Returns the rate limit expiry time.
319
+	 *
320
+	 * @return int
321
+	 */
322
+	protected function _get_rate_limit_expiry()
323
+	{
324
+		return (int)apply_filters('FHEE__EE_Messages_Queue__rate_limit_expiry', HOUR_IN_SECONDS);
325
+	}
326
+
327
+
328
+	/**
329
+	 * Returns the default rate limit for sending messages.
330
+	 *
331
+	 * @return int
332
+	 */
333
+	protected function _default_rate_limit()
334
+	{
335
+		return (int)apply_filters('FHEE__EE_Messages_Queue___rate_limit', 200);
336
+	}
337
+
338
+
339
+	/**
340
+	 * Return the orderby array for priority.
341
+	 *
342
+	 * @return array
343
+	 */
344
+	protected function _get_priority_orderby()
345
+	{
346
+		return array(
347
+			'MSG_priority' => 'ASC',
348
+			'MSG_modified' => 'DESC',
349
+		);
350
+	}
351
+
352
+
353
+	/**
354
+	 * Returns whether batch methods are "locked" or not.
355
+	 *
356
+	 * @param  string $type The type of lock being checked for.
357
+	 * @return bool
358
+	 */
359
+	public function is_locked($type = EE_Messages_Queue::action_generating)
360
+	{
361
+		/**
362
+		 * This filters the default is_locked behaviour.
363
+		 */
364
+		$is_locked = filter_var(
365
+			apply_filters(
366
+				'FHEE__EE_Messages_Queue__is_locked',
367
+				get_transient($this->_get_lock_key($type)),
368
+				$this
369
+			),
370
+			FILTER_VALIDATE_BOOLEAN
371
+		);
372
+
373
+		/**
374
+		 * @see usage of this filter in EE_Messages_Queue::initiate_request_by_priority() method.
375
+		 *            Also implemented here because messages processed on the same request should not have any locks applied.
376
+		 */
377
+		if (
378
+			apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
379
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
380
+		) {
381
+			$is_locked = false;
382
+		}
383
+
384
+
385
+		return $is_locked;
386
+	}
387
+
388
+
389
+	/**
390
+	 * Retrieves the rate limit that may be cached as a transient.
391
+	 * If the rate limit is not set, then this sets the default rate limit and expiry and returns it.
392
+	 *
393
+	 * @return int
394
+	 */
395
+	public function get_rate_limit()
396
+	{
397
+		if ( ! $rate_limit = get_transient($this->_get_rate_limit_key())) {
398
+			$rate_limit = $this->_default_rate_limit();
399
+			set_transient($this->_get_rate_limit_key(), $rate_limit, $this->_get_rate_limit_key());
400
+		}
401
+		return $rate_limit;
402
+	}
403
+
404
+
405
+	/**
406
+	 * This updates existing rate limit with the new limit which is the old minus the batch.
407
+	 *
408
+	 * @param int $batch_completed This sets the new rate limit based on the given batch that was completed.
409
+	 */
410
+	public function set_rate_limit($batch_completed)
411
+	{
412
+		//first get the most up to date rate limit (in case its expired and reset)
413
+		$rate_limit = $this->get_rate_limit();
414
+		$new_limit  = $rate_limit - $batch_completed;
415
+		//updating the transient option directly to avoid resetting the expiry.
416
+		update_option('_transient_' . $this->_get_rate_limit_key(), $new_limit);
417
+	}
418
+
419
+
420
+	/**
421
+	 * This method checks the queue for ANY EE_Message objects with a priority matching the given priority passed in.
422
+	 * If that exists, then we immediately initiate a non-blocking request to do the requested action type.
423
+	 * Note: Keep in mind that there is the possibility that the request will not execute if there is already another
424
+	 * request running on a queue for the given task.
425
+	 *
426
+	 * @param string $task     This indicates what type of request is going to be initiated.
427
+	 * @param int    $priority This indicates the priority that triggers initiating the request.
428
+	 */
429
+	public function initiate_request_by_priority($task = 'generate', $priority = EEM_Message::priority_high)
430
+	{
431
+		//determine what status is matched with the priority as part of the trigger conditions.
432
+		$status = $task == 'generate'
433
+			? EEM_Message::status_incomplete
434
+			: EEM_Message::instance()->stati_indicating_to_send();
435
+		// always make sure we save because either this will get executed immediately on a separate request
436
+		// or remains in the queue for the regularly scheduled queue batch.
437
+		$this->save();
438
+		/**
439
+		 * This filter/option allows users to override processing of messages on separate requests and instead have everything
440
+		 * happen on the same request.  If this is utilized remember:
441
+		 * - message priorities don't matter
442
+		 * - existing unprocessed messages in the queue will not get processed unless manually triggered.
443
+		 * - things will be perceived to take longer to happen for end users (i.e. registrations) because of the additional
444
+		 *   processing happening on the same request.
445
+		 * - any race condition protection (locks) are removed because they don't apply when things are processed on
446
+		 *   the same request.
447
+		 */
448
+		if (
449
+			apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', false)
450
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
451
+		) {
452
+			$messages_processor = EE_Registry::instance()->load_lib('Messages_Processor');
453
+			if ($messages_processor instanceof EE_Messages_Processor) {
454
+				return $messages_processor->process_immediately_from_queue($this);
455
+			}
456
+			//if we get here then that means the messages processor couldn't be loaded so messages will just remain
457
+			//queued for manual triggering by end user.
458
+		}
459
+
460
+		if ($this->_message_repository->count_by_priority_and_status($priority, $status)) {
461
+			EE_Messages_Scheduler::initiate_scheduled_non_blocking_request($task);
462
+		}
463
+	}
464
+
465
+
466
+	/**
467
+	 *  Loops through the EE_Message objects in the _queue and calls the messenger send methods for each message.
468
+	 *
469
+	 * @param   bool     $save                    Used to indicate whether to save the message queue after sending
470
+	 *                                            (default will save).
471
+	 * @param   mixed    $sending_messenger       (optional) When the sending messenger is different than
472
+	 *                                            what is on the EE_Message object in the queue.
473
+	 *                                            For instance, showing the browser view of an email message,
474
+	 *                                            or giving a pdf generated view of an html document.
475
+	 *                                            This should be an instance of EE_messenger but if you call this
476
+	 *                                            method
477
+	 *                                            intending it to be a sending messenger but a valid one could not be
478
+	 *                                            retrieved then send in an instance of EE_Error that contains the
479
+	 *                                            related error message.
480
+	 * @param   bool|int $by_priority             When set, this indicates that only messages
481
+	 *                                            matching the given priority should be executed.
482
+	 * @return int        Number of messages sent.  Note, 0 does not mean that no messages were processed.
483
+	 *                                            Also, if the messenger is an request type messenger (or a preview),
484
+	 *                                            its entirely possible that the messenger will exit before
485
+	 */
486
+	public function execute($save = true, $sending_messenger = null, $by_priority = false)
487
+	{
488
+		$messages_sent   = 0;
489
+		$this->_did_hook = array();
490
+		$this->_message_repository->rewind();
491
+
492
+		while ($this->_message_repository->valid()) {
493
+			$error_messages = array();
494
+			/** @type EE_Message $message */
495
+			$message = $this->_message_repository->current();
496
+			//only process things that are queued for sending
497
+			if (! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
498
+				$this->_message_repository->next();
499
+				continue;
500
+			}
501
+			//if $by_priority is set and does not match then continue;
502
+			if ($by_priority && $by_priority != $message->priority()) {
503
+				$this->_message_repository->next();
504
+				continue;
505
+			}
506
+			//error checking
507
+			if (! $message->valid_messenger()) {
508
+				$error_messages[] = sprintf(
509
+					__('The %s messenger is not active at time of sending.', 'event_espresso'),
510
+					$message->messenger()
511
+				);
512
+			}
513
+			if (! $message->valid_message_type()) {
514
+				$error_messages[] = sprintf(
515
+					__('The %s message type is not active at the time of sending.', 'event_espresso'),
516
+					$message->message_type()
517
+				);
518
+			}
519
+			// if there was supposed to be a sending messenger for this message, but it was invalid/inactive,
520
+			// then it will instead be an EE_Error object, so let's check for that
521
+			if ($sending_messenger instanceof EE_Error) {
522
+				$error_messages[] = $sending_messenger->getMessage();
523
+			}
524
+			// if there are no errors, then let's process the message
525
+			if (empty($error_messages)) {
526
+				if ($save) {
527
+					$message->set_messenger_is_executing();
528
+				}
529
+				if ($this->_process_message($message, $sending_messenger)) {
530
+					$messages_sent++;
531
+				}
532
+			}
533
+			$this->_set_error_message($message, $error_messages);
534
+			//add modified time
535
+			$message->set_modified(time());
536
+			//we save each message after its processed to make sure its status persists in case PHP times-out or runs
537
+			//out of memory. @see https://events.codebasehq.com/projects/event-espresso/tickets/10281
538
+			if ($save) {
539
+				$message->save();
540
+			}
541
+
542
+			$this->_message_repository->next();
543
+		}
544
+		if ($save) {
545
+			$this->save(true);
546
+		}
547
+		return $messages_sent;
548
+	}
549
+
550
+
551
+	/**
552
+	 * _process_message
553
+	 *
554
+	 * @param EE_Message $message
555
+	 * @param mixed      $sending_messenger (optional)
556
+	 * @return bool
557
+	 */
558
+	protected function _process_message(EE_Message $message, $sending_messenger = null)
559
+	{
560
+		// these *should* have been validated in the execute() method above
561
+		$messenger    = $message->messenger_object();
562
+		$message_type = $message->message_type_object();
563
+		//do actions for sending messenger if it differs from generating messenger and swap values.
564
+		if (
565
+			$sending_messenger instanceof EE_messenger
566
+			&& $messenger instanceof EE_messenger
567
+			&& $sending_messenger->name != $messenger->name
568
+		) {
569
+			$messenger->do_secondary_messenger_hooks($sending_messenger->name);
570
+			$messenger = $sending_messenger;
571
+		}
572
+		// send using messenger, but double check objects
573
+		if ($messenger instanceof EE_messenger && $message_type instanceof EE_message_type) {
574
+			//set hook for message type (but only if not using another messenger to send).
575
+			if ( ! isset($this->_did_hook[$message_type->name])) {
576
+				$message_type->do_messenger_hooks($messenger);
577
+				$this->_did_hook[$message_type->name] = 1;
578
+			}
579
+			//if preview then use preview method
580
+			return $this->_message_repository->is_preview()
581
+				? $this->_do_preview($message, $messenger, $message_type, $this->_message_repository->is_test_send())
582
+				: $this->_do_send($message, $messenger, $message_type);
583
+		}
584
+		return false;
585
+	}
586
+
587
+
588
+	/**
589
+	 * The intention of this method is to count how many EE_Message objects
590
+	 * are in the queue with a given status.
591
+	 * Example usage:
592
+	 * After a caller calls the "EE_Message_Queue::execute()" method, the caller can check if there were any failed
593
+	 * sends by calling $queue->count_STS_in_queue( EEM_Message_Queue::status_failed ).
594
+	 *
595
+	 * @param array $status Stati to check for in queue
596
+	 * @return int  Count of EE_Message's matching the given status.
597
+	 */
598
+	public function count_STS_in_queue($status)
599
+	{
600
+		$count  = 0;
601
+		$status = is_array($status) ? $status : array($status);
602
+		$this->_message_repository->rewind();
603
+		foreach ($this->_message_repository as $message) {
604
+			if (in_array($message->STS_ID(), $status)) {
605
+				$count++;
606
+			}
607
+		}
608
+		return $count;
609
+	}
610
+
611
+
612
+	/**
613
+	 * Executes the get_preview method on the provided messenger.
614
+	 *
615
+	 * @param EE_Message      $message
616
+	 * @param EE_messenger    $messenger
617
+	 * @param EE_message_type $message_type
618
+	 * @param                 $test_send
619
+	 * @return bool   true means all went well, false means, not so much.
620
+	 */
621
+	protected function _do_preview(
622
+		EE_Message $message,
623
+		EE_messenger $messenger,
624
+		EE_message_type $message_type,
625
+		$test_send
626
+	) {
627
+		if ($preview = $messenger->get_preview($message, $message_type, $test_send)) {
628
+			if ( ! $test_send) {
629
+				$message->set_content($preview);
630
+			}
631
+			$message->set_STS_ID(EEM_Message::status_sent);
632
+			return true;
633
+		} else {
634
+			$message->set_STS_ID(EEM_Message::status_failed);
635
+			return false;
636
+		}
637
+	}
638
+
639
+
640
+	/**
641
+	 * Executes the send method on the provided messenger
642
+	 * EE_Messengers are expected to:
643
+	 * - return true if the send was successful.
644
+	 * - return false if the send was unsuccessful but can be tried again.
645
+	 * - throw an Exception if the send was unsuccessful and cannot be tried again.
646
+	 *
647
+	 * @param EE_Message      $message
648
+	 * @param EE_messenger    $messenger
649
+	 * @param EE_message_type $message_type
650
+	 * @return bool true means all went well, false means, not so much.
651
+	 */
652
+	protected function _do_send(EE_Message $message, EE_messenger $messenger, EE_message_type $message_type)
653
+	{
654
+		try {
655
+			if ($messenger->send_message($message, $message_type)) {
656
+				$message->set_STS_ID(EEM_Message::status_sent);
657
+				return true;
658
+			} else {
659
+				$message->set_STS_ID(EEM_Message::status_retry);
660
+				return false;
661
+			}
662
+		} catch (SendMessageException $e) {
663
+			$message->set_STS_ID(EEM_Message::status_failed);
664
+			$message->set_error_message($e->getMessage());
665
+			return false;
666
+		}
667
+	}
668
+
669
+
670
+	/**
671
+	 * This sets any necessary error messages on the message object and its status to failed.
672
+	 *
673
+	 * @param EE_Message $message
674
+	 * @param array      $error_messages the response from the messenger.
675
+	 */
676
+	protected function _set_error_message(EE_Message $message, $error_messages)
677
+	{
678
+		$error_messages = (array)$error_messages;
679
+		if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_failed_sending())) {
680
+			$notices          = EE_Error::has_notices();
681
+			$error_messages[] = __(
682
+				'Messenger and Message Type were valid and active, but the messenger send method failed.',
683
+				'event_espresso'
684
+			);
685
+			if ($notices === 1) {
686
+				$notices           = EE_Error::get_vanilla_notices();
687
+				$notices['errors'] = isset($notices['errors']) ? $notices['errors'] : array();
688
+				$error_messages[]  = implode("\n", $notices['errors']);
689
+			}
690
+		}
691
+		if (count($error_messages) > 0) {
692
+			$msg = __('Message was not executed successfully.', 'event_espresso');
693
+			$msg = $msg . "\n" . implode("\n", $error_messages);
694
+			$message->set_error_message($msg);
695
+		}
696
+	}
697 697
 
698 698
 } //end EE_Messages_Queue class
699 699
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 use \EventEspresso\core\exceptions\SendMessageException;
3 3
 
4
-if (! defined('EVENT_ESPRESSO_VERSION')) {
4
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5 5
     exit('No direct script access allowed');
6 6
 }
7 7
 
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
             'order_by' => $this->_get_priority_orderby(),
183 183
             'limit'    => $this->_batch_count,
184 184
         );
185
-        $messages   = EEM_Message::instance()->get_all($query_args);
185
+        $messages = EEM_Message::instance()->get_all($query_args);
186 186
 
187 187
         if ( ! $messages) {
188 188
             return false; //nothing to generate
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
      */
288 288
     protected function _get_lock_key($type = EE_Messages_Queue::action_generating)
289 289
     {
290
-        return '_ee_lock_' . $type;
290
+        return '_ee_lock_'.$type;
291 291
     }
292 292
 
293 293
 
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
      */
300 300
     protected function _get_lock_expiry($type = EE_Messages_Queue::action_generating)
301 301
     {
302
-        return (int)apply_filters('FHEE__EE_Messages_Queue__lock_expiry', HOUR_IN_SECONDS, $type);
302
+        return (int) apply_filters('FHEE__EE_Messages_Queue__lock_expiry', HOUR_IN_SECONDS, $type);
303 303
     }
304 304
 
305 305
 
@@ -321,7 +321,7 @@  discard block
 block discarded – undo
321 321
      */
322 322
     protected function _get_rate_limit_expiry()
323 323
     {
324
-        return (int)apply_filters('FHEE__EE_Messages_Queue__rate_limit_expiry', HOUR_IN_SECONDS);
324
+        return (int) apply_filters('FHEE__EE_Messages_Queue__rate_limit_expiry', HOUR_IN_SECONDS);
325 325
     }
326 326
 
327 327
 
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
      */
333 333
     protected function _default_rate_limit()
334 334
     {
335
-        return (int)apply_filters('FHEE__EE_Messages_Queue___rate_limit', 200);
335
+        return (int) apply_filters('FHEE__EE_Messages_Queue___rate_limit', 200);
336 336
     }
337 337
 
338 338
 
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
         $rate_limit = $this->get_rate_limit();
414 414
         $new_limit  = $rate_limit - $batch_completed;
415 415
         //updating the transient option directly to avoid resetting the expiry.
416
-        update_option('_transient_' . $this->_get_rate_limit_key(), $new_limit);
416
+        update_option('_transient_'.$this->_get_rate_limit_key(), $new_limit);
417 417
     }
418 418
 
419 419
 
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
             /** @type EE_Message $message */
495 495
             $message = $this->_message_repository->current();
496 496
             //only process things that are queued for sending
497
-            if (! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
497
+            if ( ! in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_to_send())) {
498 498
                 $this->_message_repository->next();
499 499
                 continue;
500 500
             }
@@ -504,13 +504,13 @@  discard block
 block discarded – undo
504 504
                 continue;
505 505
             }
506 506
             //error checking
507
-            if (! $message->valid_messenger()) {
507
+            if ( ! $message->valid_messenger()) {
508 508
                 $error_messages[] = sprintf(
509 509
                     __('The %s messenger is not active at time of sending.', 'event_espresso'),
510 510
                     $message->messenger()
511 511
                 );
512 512
             }
513
-            if (! $message->valid_message_type()) {
513
+            if ( ! $message->valid_message_type()) {
514 514
                 $error_messages[] = sprintf(
515 515
                     __('The %s message type is not active at the time of sending.', 'event_espresso'),
516 516
                     $message->message_type()
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
      */
676 676
     protected function _set_error_message(EE_Message $message, $error_messages)
677 677
     {
678
-        $error_messages = (array)$error_messages;
678
+        $error_messages = (array) $error_messages;
679 679
         if (in_array($message->STS_ID(), EEM_Message::instance()->stati_indicating_failed_sending())) {
680 680
             $notices          = EE_Error::has_notices();
681 681
             $error_messages[] = __(
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
         }
691 691
         if (count($error_messages) > 0) {
692 692
             $msg = __('Message was not executed successfully.', 'event_espresso');
693
-            $msg = $msg . "\n" . implode("\n", $error_messages);
693
+            $msg = $msg."\n".implode("\n", $error_messages);
694 694
             $message->set_error_message($msg);
695 695
         }
696 696
     }
Please login to merge, or discard this patch.
core/db_classes/EE_Message.class.php 2 patches
Indentation   +856 added lines, -856 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -12,865 +12,865 @@  discard block
 block discarded – undo
12 12
 class EE_Message extends EE_Base_Class implements EEI_Admin_Links
13 13
 {
14 14
 
15
-    /**
16
-     * @deprecated 4.9.0  Added for backward compat with add-on's
17
-     * @type null
18
-     */
19
-    public $template_pack;
20
-
21
-    /**
22
-     * @deprecated 4.9.0 Added for backward compat with add-on's
23
-     * @type null
24
-     */
25
-    public $template_variation;
26
-
27
-    /**
28
-     * @deprecated 4.9.0 Added for backward compat with add-on's
29
-     * @type string
30
-     */
31
-    public $content = '';
32
-
33
-
34
-    /**
35
-     * @type EE_messenger $_messenger
36
-     */
37
-    protected $_messenger = null;
38
-
39
-    /**
40
-     * @type EE_message_type $_message_type
41
-     */
42
-    protected $_message_type = null;
43
-
44
-
45
-    /**
46
-     * @param array  $props_n_values
47
-     * @param string $timezone
48
-     * @param array  $date_formats incoming date formats in an array.  First value is the date_format, second is time
49
-     *                             format.
50
-     * @return EE_Message
51
-     */
52
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
53
-    {
54
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
55
-        //if object doesn't exist, let's generate a unique token on instantiation so that its available even before saving to db.
56
-        if ( ! $has_object) {
57
-            EE_Registry::instance()->load_helper('URL');
58
-            $props_n_values['MSG_token'] = EEH_URL::generate_unique_token();
59
-        }
60
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
61
-    }
62
-
63
-
64
-    /**
65
-     * @param array  $props_n_values
66
-     * @param string $timezone
67
-     * @return EE_Message
68
-     */
69
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
70
-    {
71
-        return new self($props_n_values, true, $timezone);
72
-    }
73
-
74
-
75
-    /**
76
-     * Gets MSG_token
77
-     *
78
-     * @return int
79
-     */
80
-    public function MSG_token()
81
-    {
82
-        return $this->get('MSG_token');
83
-    }
84
-
85
-
86
-    /**
87
-     * Sets MSG_token
88
-     *
89
-     * @param int $MSG_token
90
-     */
91
-    public function set_MSG_token($MSG_token)
92
-    {
93
-        $this->set('MSG_token', $MSG_token);
94
-    }
95
-
96
-
97
-    /**
98
-     * Gets GRP_ID
99
-     *
100
-     * @return int
101
-     */
102
-    public function GRP_ID()
103
-    {
104
-        return $this->get('GRP_ID');
105
-    }
106
-
107
-
108
-    /**
109
-     * Sets GRP_ID
110
-     *
111
-     * @param int $GRP_ID
112
-     */
113
-    public function set_GRP_ID($GRP_ID)
114
-    {
115
-        $this->set('GRP_ID', $GRP_ID);
116
-    }
117
-
118
-
119
-    /**
120
-     * Gets TXN_ID
121
-     *
122
-     * @return int
123
-     */
124
-    public function TXN_ID()
125
-    {
126
-        return $this->get('TXN_ID');
127
-    }
128
-
129
-
130
-    /**
131
-     * Sets TXN_ID
132
-     *
133
-     * @param int $TXN_ID
134
-     */
135
-    public function set_TXN_ID($TXN_ID)
136
-    {
137
-        $this->set('TXN_ID', $TXN_ID);
138
-    }
139
-
140
-
141
-    /**
142
-     * Gets messenger
143
-     *
144
-     * @return string
145
-     */
146
-    public function messenger()
147
-    {
148
-        return $this->get('MSG_messenger');
149
-    }
150
-
151
-
152
-    /**
153
-     * Sets messenger
154
-     *
155
-     * @param string $messenger
156
-     */
157
-    public function set_messenger($messenger)
158
-    {
159
-        $this->set('MSG_messenger', $messenger);
160
-    }
161
-
162
-
163
-    /**
164
-     * Returns corresponding messenger object for the set messenger on this message
165
-     *
166
-     * @return EE_messenger | null
167
-     */
168
-    public function messenger_object()
169
-    {
170
-        return $this->_messenger;
171
-    }
172
-
173
-
174
-    /**
175
-     * Sets messenger
176
-     *
177
-     * @param EE_messenger $messenger
178
-     */
179
-    public function set_messenger_object(EE_messenger $messenger)
180
-    {
181
-        $this->_messenger = $messenger;
182
-    }
183
-
184
-
185
-    /**
186
-     * validates messenger
187
-     *
188
-     * @param bool $throw_exceptions
189
-     * @return bool
190
-     * @throws \EE_Error
191
-     */
192
-    public function valid_messenger($throw_exceptions = false)
193
-    {
194
-        if ($this->_messenger instanceof EE_messenger) {
195
-            return true;
196
-        }
197
-        if ($throw_exceptions) {
198
-            throw new EE_Error(
199
-                sprintf(
200
-                    __(
201
-                        'The "%1$s" messenger set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
202
-                        'event_espresso'
203
-                    ),
204
-                    $this->messenger()
205
-                )
206
-            );
207
-        }
208
-        return false;
209
-    }
210
-
211
-
212
-    /**
213
-     * This returns the set localized label for the messenger on this message.
214
-     * Note, if unable to retrieve the EE_messenger object then will just return the messenger slug saved
215
-     * with this message.
216
-     *
217
-     * @param   bool $plural whether to return the plural label or not.
218
-     * @return string
219
-     */
220
-    public function messenger_label($plural = false)
221
-    {
222
-        $label_type = $plural ? 'plural' : 'singular';
223
-        $messenger  = $this->messenger_object();
224
-        return $messenger instanceof EE_messenger ? $messenger->label[$label_type] : $this->messenger();
225
-    }
226
-
227
-
228
-    /**
229
-     * Gets message_type
230
-     *
231
-     * @return string
232
-     */
233
-    public function message_type()
234
-    {
235
-        return $this->get('MSG_message_type');
236
-    }
237
-
238
-
239
-    /**
240
-     * Sets message_type
241
-     *
242
-     * @param string $message_type
243
-     */
244
-    public function set_message_type($message_type)
245
-    {
246
-        $this->set('MSG_message_type', $message_type);
247
-    }
248
-
249
-
250
-    /**
251
-     * Returns the message type object for the set message type on this message
252
-     *
253
-     * @return EE_message_type | null
254
-     */
255
-    public function message_type_object()
256
-    {
257
-        return $this->_message_type;
258
-    }
259
-
260
-
261
-    /**
262
-     * Sets message_type
263
-     *
264
-     * @param EE_message_type $message_type
265
-     * @param bool            $set_priority   This indicates whether to set the priority to whatever the priority is on
266
-     *                                        the message type or not.
267
-     */
268
-    public function set_message_type_object(EE_message_type $message_type, $set_priority = false)
269
-    {
270
-        $this->_message_type = $message_type;
271
-        if ($set_priority) {
272
-            $this->set_priority($this->_message_type->get_priority());
273
-        }
274
-    }
275
-
276
-
277
-    /**
278
-     * validates message_type
279
-     *
280
-     * @param bool $throw_exceptions
281
-     * @return bool
282
-     * @throws \EE_Error
283
-     */
284
-    public function valid_message_type($throw_exceptions = false)
285
-    {
286
-        if ($this->_message_type instanceof EE_message_type) {
287
-            return true;
288
-        }
289
-        if ($throw_exceptions) {
290
-            throw new EE_Error(
291
-                sprintf(
292
-                    __(
293
-                        'The %1$s message type set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
294
-                        'event_espresso'
295
-                    ),
296
-                    $this->message_type()
297
-                )
298
-            );
299
-        }
300
-        return false;
301
-    }
302
-
303
-
304
-    /**
305
-     * validates messenger and message_type (that they are valid EE_messenger and EE_message_type objects).
306
-     *
307
-     * @param bool $throw_exceptions
308
-     * @return bool
309
-     * @throws \EE_Error
310
-     */
311
-    public function is_valid($throw_exceptions = false)
312
-    {
313
-        if ($this->valid_messenger($throw_exceptions) && $this->valid_message_type($throw_exceptions)) {
314
-            return true;
315
-        }
316
-        return false;
317
-    }
318
-
319
-
320
-    /**
321
-     * This validates whether the internal messenger and message type objects are valid for sending.
322
-     * Three checks are done:
323
-     * 1. There is a valid messenger object.
324
-     * 2. There is a valid message type object.
325
-     * 3. The message type object is active for the messenger.
326
-     *
327
-     * @throws EE_Error  But only if $throw_exceptions is set to true.
328
-     * @param bool $throw_exceptions
329
-     * @return bool
330
-     */
331
-    public function is_valid_for_sending_or_generation($throw_exceptions = false)
332
-    {
333
-        $valid = false;
334
-        if ($this->is_valid($throw_exceptions)) {
335
-            /** @var EE_Message_Resource_Manager $message_resource_manager */
336
-            $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
337
-            $valid                    = $message_resource_manager->is_message_type_active_for_messenger($this->messenger(),
338
-                $this->message_type());
339
-            if ( ! $valid && $throw_exceptions) {
340
-                throw new EE_Error(
341
-                    sprintf(
342
-                        __('The %1$s message type is not a valid message type for the %2$s messenger so it will not be sent.',
343
-                            'event_espresso'),
344
-                        $this->message_type(),
345
-                        $this->messenger()
346
-                    )
347
-                );
348
-            }
349
-        }
350
-        return $valid;
351
-    }
352
-
353
-
354
-    /**
355
-     * This returns the set localized label for the message type on this message.
356
-     * Note, if unable to retrieve the EE_message_type object then will just return the message type slug saved
357
-     * with this message.
358
-     *
359
-     * @param   bool $plural whether to return the plural label or not.
360
-     * @return string
361
-     */
362
-    public function message_type_label($plural = false)
363
-    {
364
-        $label_type   = $plural ? 'plural' : 'singular';
365
-        $message_type = $this->message_type_object();
366
-        return $message_type instanceof EE_message_type ? $message_type->label[$label_type] : $this->message_type();
367
-    }
368
-
369
-
370
-    /**
371
-     * Gets context
372
-     *
373
-     * @return string
374
-     */
375
-    public function context()
376
-    {
377
-        return $this->get('MSG_context');
378
-    }
379
-
380
-
381
-    /**
382
-     * This returns the corresponding localized label for the given context slug, if possible from installed message
383
-     * types. Otherwise, this will just return the set context slug on this object.
384
-     *
385
-     * @return string
386
-     */
387
-    public function context_label()
388
-    {
389
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
390
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
391
-        $contexts                 = $message_resource_manager->get_all_contexts();
392
-        return isset($contexts[$this->context()]) ? $contexts[$this->context()] : $this->context();
393
-    }
394
-
395
-
396
-    /**
397
-     * Sets context
398
-     *
399
-     * @param string $context
400
-     */
401
-    public function set_context($context)
402
-    {
403
-        $this->set('MSG_context', $context);
404
-    }
405
-
406
-
407
-    /**
408
-     * Gets recipient_ID
409
-     *
410
-     * @return int
411
-     */
412
-    public function recipient_ID()
413
-    {
414
-        return $this->get('MSG_recipient_ID');
415
-    }
416
-
417
-
418
-    /**
419
-     * Sets recipient_ID
420
-     *
421
-     * @param string $recipient_ID
422
-     */
423
-    public function set_recipient_ID($recipient_ID)
424
-    {
425
-        $this->set('MSG_recipient_ID', $recipient_ID);
426
-    }
427
-
428
-
429
-    /**
430
-     * Gets recipient_type
431
-     *
432
-     * @return string
433
-     */
434
-    public function recipient_type()
435
-    {
436
-        return $this->get('MSG_recipient_type');
437
-    }
438
-
439
-
440
-    /**
441
-     * Return the related object matching the recipient type and ID.
442
-     *
443
-     * @return EE_Base_Class | null
444
-     */
445
-    public function recipient_object()
446
-    {
447
-        if ( ! $this->recipient_type() || ! $this->recipient_ID()) {
448
-            return null;
449
-        }
450
-
451
-        return $this->get_first_related($this->recipient_type());
452
-    }
453
-
454
-
455
-    /**
456
-     * Sets recipient_type
457
-     *
458
-     * @param string $recipient_type
459
-     */
460
-    public function set_recipient_type($recipient_type)
461
-    {
462
-        $this->set('MSG_recipient_type', $recipient_type);
463
-    }
464
-
465
-
466
-    /**
467
-     * Gets content
468
-     *
469
-     * @return string
470
-     */
471
-    public function content()
472
-    {
473
-        return $this->get('MSG_content');
474
-    }
475
-
476
-
477
-    /**
478
-     * Sets content
479
-     *
480
-     * @param string $content
481
-     */
482
-    public function set_content($content)
483
-    {
484
-        $this->set('MSG_content', $content);
485
-    }
486
-
487
-
488
-    /**
489
-     * Gets subject
490
-     *
491
-     * @return string
492
-     */
493
-    public function subject()
494
-    {
495
-        return $this->get('MSG_subject');
496
-    }
497
-
498
-
499
-    /**
500
-     * Sets subject
501
-     *
502
-     * @param string $subject
503
-     */
504
-    public function set_subject($subject)
505
-    {
506
-        $this->set('MSG_subject', $subject);
507
-    }
508
-
509
-
510
-    /**
511
-     * Gets to
512
-     *
513
-     * @return string
514
-     */
515
-    public function to()
516
-    {
517
-        $to = $this->get('MSG_to');
518
-        return empty($to) ? __('No recipient', 'event_espresso') : $to;
519
-    }
520
-
521
-
522
-    /**
523
-     * Sets to
524
-     *
525
-     * @param string $to
526
-     */
527
-    public function set_to($to)
528
-    {
529
-        $this->set('MSG_to', $to);
530
-    }
531
-
532
-
533
-    /**
534
-     * Gets from
535
-     *
536
-     * @return string
537
-     */
538
-    public function from()
539
-    {
540
-        return $this->get('MSG_from');
541
-    }
542
-
543
-
544
-    /**
545
-     * Sets from
546
-     *
547
-     * @param string $from
548
-     */
549
-    public function set_from($from)
550
-    {
551
-        $this->set('MSG_from', $from);
552
-    }
553
-
554
-
555
-    /**
556
-     * Gets priority
557
-     *
558
-     * @return int
559
-     */
560
-    public function priority()
561
-    {
562
-        return $this->get('MSG_priority');
563
-    }
564
-
565
-
566
-    /**
567
-     * Sets priority
568
-     * Note.  Send Now Messengers always override any priority that may be set on a Message.  So
569
-     * this method calls the send_now method to verify that.
570
-     *
571
-     * @param int $priority
572
-     */
573
-    public function set_priority($priority)
574
-    {
575
-        $priority = $this->send_now() ? EEM_Message::priority_high : $priority;
576
-        parent::set('MSG_priority', $priority);
577
-    }
578
-
579
-
580
-    /**
581
-     * Overrides parent::set method so we can capture any sets for priority.
582
-     *
583
-     * @see parent::set() for phpdocs
584
-     * @param string $field_name
585
-     * @param mixed  $field_value
586
-     * @param bool   $use_default
587
-     * @throws EE_Error
588
-     */
589
-    public function set($field_name, $field_value, $use_default = false)
590
-    {
591
-        if ($field_name === 'MSG_priority') {
592
-            $this->set_priority($field_value);
593
-        }
594
-        parent::set($field_name, $field_value, $use_default);
595
-    }
596
-
597
-
598
-    /**
599
-     * @return bool
600
-     * @throws \EE_Error
601
-     */
602
-    public function send_now()
603
-    {
604
-        $send_now = $this->valid_messenger() && $this->messenger_object()->send_now() ? EEM_Message::priority_high : $this->priority();
605
-        return $send_now === EEM_Message::priority_high ? true : false;
606
-    }
607
-
608
-
609
-    /**
610
-     * Gets STS_ID
611
-     *
612
-     * @return string
613
-     */
614
-    public function STS_ID()
615
-    {
616
-        return $this->get('STS_ID');
617
-    }
618
-
619
-
620
-    /**
621
-     * Sets STS_ID
622
-     *
623
-     * @param string $STS_ID
624
-     */
625
-    public function set_STS_ID($STS_ID)
626
-    {
627
-        $this->set('STS_ID', $STS_ID);
628
-    }
629
-
630
-
631
-    /**
632
-     * Gets created
633
-     *
634
-     * @return string
635
-     */
636
-    public function created()
637
-    {
638
-        return $this->get('MSG_created');
639
-    }
640
-
641
-
642
-    /**
643
-     * Sets created
644
-     *
645
-     * @param string $created
646
-     */
647
-    public function set_created($created)
648
-    {
649
-        $this->set('MSG_created', $created);
650
-    }
651
-
652
-
653
-    /**
654
-     * Gets modified
655
-     *
656
-     * @return string
657
-     */
658
-    public function modified()
659
-    {
660
-        return $this->get('MSG_modified');
661
-    }
662
-
663
-
664
-    /**
665
-     * Sets modified
666
-     *
667
-     * @param string $modified
668
-     */
669
-    public function set_modified($modified)
670
-    {
671
-        $this->set('MSG_modified', $modified);
672
-    }
673
-
674
-
675
-    /**
676
-     * Sets generation data for this message.
677
-     *
678
-     * @param mixed $data
679
-     */
680
-    public function set_generation_data($data)
681
-    {
682
-        $this->set_field_or_extra_meta('MSG_generation_data', $data);
683
-    }
684
-
685
-
686
-    /**
687
-     * Returns any set generation data for this message.
688
-     *
689
-     * @return mixed|null
690
-     */
691
-    public function get_generation_data()
692
-    {
693
-        return $this->get_field_or_extra_meta('MSG_generation_data');
694
-    }
695
-
696
-
697
-    /**
698
-     * Gets any error message.
699
-     *
700
-     * @return mixed|null
701
-     */
702
-    public function error_message()
703
-    {
704
-        return $this->get_field_or_extra_meta('MSG_error');
705
-    }
706
-
707
-
708
-    /**
709
-     * Sets an error message.
710
-     *
711
-     * @param $message
712
-     * @return bool|int
713
-     */
714
-    public function set_error_message($message)
715
-    {
716
-        return $this->set_field_or_extra_meta('MSG_error', $message);
717
-    }
718
-
719
-
720
-    /**
721
-     * This retrieves the associated template pack with this message.
722
-     *
723
-     * @return EE_Messages_Template_Pack | null
724
-     */
725
-    public function get_template_pack()
726
-    {
727
-        /**
728
-         * This is deprecated functionality that will be removed eventually but included here now for backward compat.
729
-         */
730
-        if ( ! empty($this->template_pack)) {
731
-            return $this->template_pack;
732
-        }
733
-        /** @type EE_Message_Template_Group $grp */
734
-        $grp = $this->get_first_related('Message_Template_Group');
735
-        //if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
736
-        if ( ! $grp instanceof EE_Message_Template_Group) {
737
-            $grp = EEM_Message_Template_Group::instance()->get_one(
738
-                array(
739
-                    array(
740
-                        'MTP_messenger'    => $this->messenger(),
741
-                        'MTP_message_type' => $this->message_type(),
742
-                        'MTP_is_global'    => true,
743
-                    ),
744
-                )
745
-            );
746
-        }
747
-
748
-        return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack() : null;
749
-    }
750
-
751
-
752
-    /**
753
-     * Retrieves the variation used for generating this message.
754
-     *
755
-     * @return string
756
-     */
757
-    public function get_template_pack_variation()
758
-    {
759
-        /**
760
-         * This is deprecated functionality that will be removed eventually but included here now for backward compat.
761
-         */
762
-        if ( ! empty($this->template_variation)) {
763
-            return $this->template_variation;
764
-        }
765
-
766
-        /** @type EE_Message_Template_Group $grp */
767
-        $grp = $this->get_first_related('Message_Template_Group');
768
-
769
-        //if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
770
-        if ( ! $grp instanceof EE_Message_Template_Group) {
771
-            $grp = EEM_Message_Template_Group::instance()->get_one(
772
-                array(
773
-                    array(
774
-                        'MTP_messenger'    => $this->messenger(),
775
-                        'MTP_message_type' => $this->message_type(),
776
-                        'MTP_is_global'    => true,
777
-                    ),
778
-                )
779
-            );
780
-        }
781
-
782
-        return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack_variation() : '';
783
-    }
784
-
785
-    /**
786
-     * Return the link to the admin details for the object.
787
-     *
788
-     * @return string
789
-     */
790
-    public function get_admin_details_link()
791
-    {
792
-        EE_Registry::instance()->load_helper('URL');
793
-        EE_Registry::instance()->load_helper('MSG_Template');
794
-        switch ($this->STS_ID()) {
795
-            case EEM_Message::status_failed :
796
-            case EEM_Message::status_debug_only :
797
-                return EEH_MSG_Template::generate_error_display_trigger($this);
798
-                break;
799
-
800
-            case EEM_Message::status_sent :
801
-                return EEH_MSG_Template::generate_browser_trigger($this);
802
-                break;
803
-
804
-            default :
805
-                return '';
806
-        }
807
-    }
808
-
809
-    /**
810
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
811
-     *
812
-     * @return string
813
-     */
814
-    public function get_admin_edit_link()
815
-    {
816
-        return $this->get_admin_details_link();
817
-    }
818
-
819
-    /**
820
-     * Returns the link to a settings page for the object.
821
-     *
822
-     * @return string
823
-     */
824
-    public function get_admin_settings_link()
825
-    {
826
-        EE_Registry::instance()->load_helper('URL');
827
-        return EEH_URL::add_query_args_and_nonce(
828
-            array(
829
-                'page'   => 'espresso_messages',
830
-                'action' => 'settings',
831
-            ),
832
-            admin_url('admin.php')
833
-        );
834
-    }
835
-
836
-    /**
837
-     * Returns the link to the "overview" for the object (typically the "list table" view).
838
-     *
839
-     * @return string
840
-     */
841
-    public function get_admin_overview_link()
842
-    {
843
-        EE_Registry::instance()->load_helper('URL');
844
-        return EEH_URL::add_query_args_and_nonce(
845
-            array(
846
-                'page'   => 'espresso_messages',
847
-                'action' => 'default',
848
-            ),
849
-            admin_url('admin.php')
850
-        );
851
-    }
852
-
853
-
854
-    /**
855
-     * This sets the EEM_Message::status_messenger_executing class on the message and the appropriate error message for
856
-     * it.
857
-     * Note this also SAVES the current message object to the db because it adds an error message to accompany the status.
858
-     *
859
-     */
860
-    public function set_messenger_is_executing()
861
-    {
862
-        $this->set_STS_ID( EEM_Message::status_messenger_executing );
863
-        $this->set_error_message(
864
-            esc_html__(
865
-                'A message with this status indicates that there was a problem that occurred while the message was being
15
+	/**
16
+	 * @deprecated 4.9.0  Added for backward compat with add-on's
17
+	 * @type null
18
+	 */
19
+	public $template_pack;
20
+
21
+	/**
22
+	 * @deprecated 4.9.0 Added for backward compat with add-on's
23
+	 * @type null
24
+	 */
25
+	public $template_variation;
26
+
27
+	/**
28
+	 * @deprecated 4.9.0 Added for backward compat with add-on's
29
+	 * @type string
30
+	 */
31
+	public $content = '';
32
+
33
+
34
+	/**
35
+	 * @type EE_messenger $_messenger
36
+	 */
37
+	protected $_messenger = null;
38
+
39
+	/**
40
+	 * @type EE_message_type $_message_type
41
+	 */
42
+	protected $_message_type = null;
43
+
44
+
45
+	/**
46
+	 * @param array  $props_n_values
47
+	 * @param string $timezone
48
+	 * @param array  $date_formats incoming date formats in an array.  First value is the date_format, second is time
49
+	 *                             format.
50
+	 * @return EE_Message
51
+	 */
52
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
53
+	{
54
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
55
+		//if object doesn't exist, let's generate a unique token on instantiation so that its available even before saving to db.
56
+		if ( ! $has_object) {
57
+			EE_Registry::instance()->load_helper('URL');
58
+			$props_n_values['MSG_token'] = EEH_URL::generate_unique_token();
59
+		}
60
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
61
+	}
62
+
63
+
64
+	/**
65
+	 * @param array  $props_n_values
66
+	 * @param string $timezone
67
+	 * @return EE_Message
68
+	 */
69
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
70
+	{
71
+		return new self($props_n_values, true, $timezone);
72
+	}
73
+
74
+
75
+	/**
76
+	 * Gets MSG_token
77
+	 *
78
+	 * @return int
79
+	 */
80
+	public function MSG_token()
81
+	{
82
+		return $this->get('MSG_token');
83
+	}
84
+
85
+
86
+	/**
87
+	 * Sets MSG_token
88
+	 *
89
+	 * @param int $MSG_token
90
+	 */
91
+	public function set_MSG_token($MSG_token)
92
+	{
93
+		$this->set('MSG_token', $MSG_token);
94
+	}
95
+
96
+
97
+	/**
98
+	 * Gets GRP_ID
99
+	 *
100
+	 * @return int
101
+	 */
102
+	public function GRP_ID()
103
+	{
104
+		return $this->get('GRP_ID');
105
+	}
106
+
107
+
108
+	/**
109
+	 * Sets GRP_ID
110
+	 *
111
+	 * @param int $GRP_ID
112
+	 */
113
+	public function set_GRP_ID($GRP_ID)
114
+	{
115
+		$this->set('GRP_ID', $GRP_ID);
116
+	}
117
+
118
+
119
+	/**
120
+	 * Gets TXN_ID
121
+	 *
122
+	 * @return int
123
+	 */
124
+	public function TXN_ID()
125
+	{
126
+		return $this->get('TXN_ID');
127
+	}
128
+
129
+
130
+	/**
131
+	 * Sets TXN_ID
132
+	 *
133
+	 * @param int $TXN_ID
134
+	 */
135
+	public function set_TXN_ID($TXN_ID)
136
+	{
137
+		$this->set('TXN_ID', $TXN_ID);
138
+	}
139
+
140
+
141
+	/**
142
+	 * Gets messenger
143
+	 *
144
+	 * @return string
145
+	 */
146
+	public function messenger()
147
+	{
148
+		return $this->get('MSG_messenger');
149
+	}
150
+
151
+
152
+	/**
153
+	 * Sets messenger
154
+	 *
155
+	 * @param string $messenger
156
+	 */
157
+	public function set_messenger($messenger)
158
+	{
159
+		$this->set('MSG_messenger', $messenger);
160
+	}
161
+
162
+
163
+	/**
164
+	 * Returns corresponding messenger object for the set messenger on this message
165
+	 *
166
+	 * @return EE_messenger | null
167
+	 */
168
+	public function messenger_object()
169
+	{
170
+		return $this->_messenger;
171
+	}
172
+
173
+
174
+	/**
175
+	 * Sets messenger
176
+	 *
177
+	 * @param EE_messenger $messenger
178
+	 */
179
+	public function set_messenger_object(EE_messenger $messenger)
180
+	{
181
+		$this->_messenger = $messenger;
182
+	}
183
+
184
+
185
+	/**
186
+	 * validates messenger
187
+	 *
188
+	 * @param bool $throw_exceptions
189
+	 * @return bool
190
+	 * @throws \EE_Error
191
+	 */
192
+	public function valid_messenger($throw_exceptions = false)
193
+	{
194
+		if ($this->_messenger instanceof EE_messenger) {
195
+			return true;
196
+		}
197
+		if ($throw_exceptions) {
198
+			throw new EE_Error(
199
+				sprintf(
200
+					__(
201
+						'The "%1$s" messenger set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
202
+						'event_espresso'
203
+					),
204
+					$this->messenger()
205
+				)
206
+			);
207
+		}
208
+		return false;
209
+	}
210
+
211
+
212
+	/**
213
+	 * This returns the set localized label for the messenger on this message.
214
+	 * Note, if unable to retrieve the EE_messenger object then will just return the messenger slug saved
215
+	 * with this message.
216
+	 *
217
+	 * @param   bool $plural whether to return the plural label or not.
218
+	 * @return string
219
+	 */
220
+	public function messenger_label($plural = false)
221
+	{
222
+		$label_type = $plural ? 'plural' : 'singular';
223
+		$messenger  = $this->messenger_object();
224
+		return $messenger instanceof EE_messenger ? $messenger->label[$label_type] : $this->messenger();
225
+	}
226
+
227
+
228
+	/**
229
+	 * Gets message_type
230
+	 *
231
+	 * @return string
232
+	 */
233
+	public function message_type()
234
+	{
235
+		return $this->get('MSG_message_type');
236
+	}
237
+
238
+
239
+	/**
240
+	 * Sets message_type
241
+	 *
242
+	 * @param string $message_type
243
+	 */
244
+	public function set_message_type($message_type)
245
+	{
246
+		$this->set('MSG_message_type', $message_type);
247
+	}
248
+
249
+
250
+	/**
251
+	 * Returns the message type object for the set message type on this message
252
+	 *
253
+	 * @return EE_message_type | null
254
+	 */
255
+	public function message_type_object()
256
+	{
257
+		return $this->_message_type;
258
+	}
259
+
260
+
261
+	/**
262
+	 * Sets message_type
263
+	 *
264
+	 * @param EE_message_type $message_type
265
+	 * @param bool            $set_priority   This indicates whether to set the priority to whatever the priority is on
266
+	 *                                        the message type or not.
267
+	 */
268
+	public function set_message_type_object(EE_message_type $message_type, $set_priority = false)
269
+	{
270
+		$this->_message_type = $message_type;
271
+		if ($set_priority) {
272
+			$this->set_priority($this->_message_type->get_priority());
273
+		}
274
+	}
275
+
276
+
277
+	/**
278
+	 * validates message_type
279
+	 *
280
+	 * @param bool $throw_exceptions
281
+	 * @return bool
282
+	 * @throws \EE_Error
283
+	 */
284
+	public function valid_message_type($throw_exceptions = false)
285
+	{
286
+		if ($this->_message_type instanceof EE_message_type) {
287
+			return true;
288
+		}
289
+		if ($throw_exceptions) {
290
+			throw new EE_Error(
291
+				sprintf(
292
+					__(
293
+						'The %1$s message type set for this message is missing or invalid. Please double-check the spelling and verify that the correct files exist.',
294
+						'event_espresso'
295
+					),
296
+					$this->message_type()
297
+				)
298
+			);
299
+		}
300
+		return false;
301
+	}
302
+
303
+
304
+	/**
305
+	 * validates messenger and message_type (that they are valid EE_messenger and EE_message_type objects).
306
+	 *
307
+	 * @param bool $throw_exceptions
308
+	 * @return bool
309
+	 * @throws \EE_Error
310
+	 */
311
+	public function is_valid($throw_exceptions = false)
312
+	{
313
+		if ($this->valid_messenger($throw_exceptions) && $this->valid_message_type($throw_exceptions)) {
314
+			return true;
315
+		}
316
+		return false;
317
+	}
318
+
319
+
320
+	/**
321
+	 * This validates whether the internal messenger and message type objects are valid for sending.
322
+	 * Three checks are done:
323
+	 * 1. There is a valid messenger object.
324
+	 * 2. There is a valid message type object.
325
+	 * 3. The message type object is active for the messenger.
326
+	 *
327
+	 * @throws EE_Error  But only if $throw_exceptions is set to true.
328
+	 * @param bool $throw_exceptions
329
+	 * @return bool
330
+	 */
331
+	public function is_valid_for_sending_or_generation($throw_exceptions = false)
332
+	{
333
+		$valid = false;
334
+		if ($this->is_valid($throw_exceptions)) {
335
+			/** @var EE_Message_Resource_Manager $message_resource_manager */
336
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
337
+			$valid                    = $message_resource_manager->is_message_type_active_for_messenger($this->messenger(),
338
+				$this->message_type());
339
+			if ( ! $valid && $throw_exceptions) {
340
+				throw new EE_Error(
341
+					sprintf(
342
+						__('The %1$s message type is not a valid message type for the %2$s messenger so it will not be sent.',
343
+							'event_espresso'),
344
+						$this->message_type(),
345
+						$this->messenger()
346
+					)
347
+				);
348
+			}
349
+		}
350
+		return $valid;
351
+	}
352
+
353
+
354
+	/**
355
+	 * This returns the set localized label for the message type on this message.
356
+	 * Note, if unable to retrieve the EE_message_type object then will just return the message type slug saved
357
+	 * with this message.
358
+	 *
359
+	 * @param   bool $plural whether to return the plural label or not.
360
+	 * @return string
361
+	 */
362
+	public function message_type_label($plural = false)
363
+	{
364
+		$label_type   = $plural ? 'plural' : 'singular';
365
+		$message_type = $this->message_type_object();
366
+		return $message_type instanceof EE_message_type ? $message_type->label[$label_type] : $this->message_type();
367
+	}
368
+
369
+
370
+	/**
371
+	 * Gets context
372
+	 *
373
+	 * @return string
374
+	 */
375
+	public function context()
376
+	{
377
+		return $this->get('MSG_context');
378
+	}
379
+
380
+
381
+	/**
382
+	 * This returns the corresponding localized label for the given context slug, if possible from installed message
383
+	 * types. Otherwise, this will just return the set context slug on this object.
384
+	 *
385
+	 * @return string
386
+	 */
387
+	public function context_label()
388
+	{
389
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
390
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
391
+		$contexts                 = $message_resource_manager->get_all_contexts();
392
+		return isset($contexts[$this->context()]) ? $contexts[$this->context()] : $this->context();
393
+	}
394
+
395
+
396
+	/**
397
+	 * Sets context
398
+	 *
399
+	 * @param string $context
400
+	 */
401
+	public function set_context($context)
402
+	{
403
+		$this->set('MSG_context', $context);
404
+	}
405
+
406
+
407
+	/**
408
+	 * Gets recipient_ID
409
+	 *
410
+	 * @return int
411
+	 */
412
+	public function recipient_ID()
413
+	{
414
+		return $this->get('MSG_recipient_ID');
415
+	}
416
+
417
+
418
+	/**
419
+	 * Sets recipient_ID
420
+	 *
421
+	 * @param string $recipient_ID
422
+	 */
423
+	public function set_recipient_ID($recipient_ID)
424
+	{
425
+		$this->set('MSG_recipient_ID', $recipient_ID);
426
+	}
427
+
428
+
429
+	/**
430
+	 * Gets recipient_type
431
+	 *
432
+	 * @return string
433
+	 */
434
+	public function recipient_type()
435
+	{
436
+		return $this->get('MSG_recipient_type');
437
+	}
438
+
439
+
440
+	/**
441
+	 * Return the related object matching the recipient type and ID.
442
+	 *
443
+	 * @return EE_Base_Class | null
444
+	 */
445
+	public function recipient_object()
446
+	{
447
+		if ( ! $this->recipient_type() || ! $this->recipient_ID()) {
448
+			return null;
449
+		}
450
+
451
+		return $this->get_first_related($this->recipient_type());
452
+	}
453
+
454
+
455
+	/**
456
+	 * Sets recipient_type
457
+	 *
458
+	 * @param string $recipient_type
459
+	 */
460
+	public function set_recipient_type($recipient_type)
461
+	{
462
+		$this->set('MSG_recipient_type', $recipient_type);
463
+	}
464
+
465
+
466
+	/**
467
+	 * Gets content
468
+	 *
469
+	 * @return string
470
+	 */
471
+	public function content()
472
+	{
473
+		return $this->get('MSG_content');
474
+	}
475
+
476
+
477
+	/**
478
+	 * Sets content
479
+	 *
480
+	 * @param string $content
481
+	 */
482
+	public function set_content($content)
483
+	{
484
+		$this->set('MSG_content', $content);
485
+	}
486
+
487
+
488
+	/**
489
+	 * Gets subject
490
+	 *
491
+	 * @return string
492
+	 */
493
+	public function subject()
494
+	{
495
+		return $this->get('MSG_subject');
496
+	}
497
+
498
+
499
+	/**
500
+	 * Sets subject
501
+	 *
502
+	 * @param string $subject
503
+	 */
504
+	public function set_subject($subject)
505
+	{
506
+		$this->set('MSG_subject', $subject);
507
+	}
508
+
509
+
510
+	/**
511
+	 * Gets to
512
+	 *
513
+	 * @return string
514
+	 */
515
+	public function to()
516
+	{
517
+		$to = $this->get('MSG_to');
518
+		return empty($to) ? __('No recipient', 'event_espresso') : $to;
519
+	}
520
+
521
+
522
+	/**
523
+	 * Sets to
524
+	 *
525
+	 * @param string $to
526
+	 */
527
+	public function set_to($to)
528
+	{
529
+		$this->set('MSG_to', $to);
530
+	}
531
+
532
+
533
+	/**
534
+	 * Gets from
535
+	 *
536
+	 * @return string
537
+	 */
538
+	public function from()
539
+	{
540
+		return $this->get('MSG_from');
541
+	}
542
+
543
+
544
+	/**
545
+	 * Sets from
546
+	 *
547
+	 * @param string $from
548
+	 */
549
+	public function set_from($from)
550
+	{
551
+		$this->set('MSG_from', $from);
552
+	}
553
+
554
+
555
+	/**
556
+	 * Gets priority
557
+	 *
558
+	 * @return int
559
+	 */
560
+	public function priority()
561
+	{
562
+		return $this->get('MSG_priority');
563
+	}
564
+
565
+
566
+	/**
567
+	 * Sets priority
568
+	 * Note.  Send Now Messengers always override any priority that may be set on a Message.  So
569
+	 * this method calls the send_now method to verify that.
570
+	 *
571
+	 * @param int $priority
572
+	 */
573
+	public function set_priority($priority)
574
+	{
575
+		$priority = $this->send_now() ? EEM_Message::priority_high : $priority;
576
+		parent::set('MSG_priority', $priority);
577
+	}
578
+
579
+
580
+	/**
581
+	 * Overrides parent::set method so we can capture any sets for priority.
582
+	 *
583
+	 * @see parent::set() for phpdocs
584
+	 * @param string $field_name
585
+	 * @param mixed  $field_value
586
+	 * @param bool   $use_default
587
+	 * @throws EE_Error
588
+	 */
589
+	public function set($field_name, $field_value, $use_default = false)
590
+	{
591
+		if ($field_name === 'MSG_priority') {
592
+			$this->set_priority($field_value);
593
+		}
594
+		parent::set($field_name, $field_value, $use_default);
595
+	}
596
+
597
+
598
+	/**
599
+	 * @return bool
600
+	 * @throws \EE_Error
601
+	 */
602
+	public function send_now()
603
+	{
604
+		$send_now = $this->valid_messenger() && $this->messenger_object()->send_now() ? EEM_Message::priority_high : $this->priority();
605
+		return $send_now === EEM_Message::priority_high ? true : false;
606
+	}
607
+
608
+
609
+	/**
610
+	 * Gets STS_ID
611
+	 *
612
+	 * @return string
613
+	 */
614
+	public function STS_ID()
615
+	{
616
+		return $this->get('STS_ID');
617
+	}
618
+
619
+
620
+	/**
621
+	 * Sets STS_ID
622
+	 *
623
+	 * @param string $STS_ID
624
+	 */
625
+	public function set_STS_ID($STS_ID)
626
+	{
627
+		$this->set('STS_ID', $STS_ID);
628
+	}
629
+
630
+
631
+	/**
632
+	 * Gets created
633
+	 *
634
+	 * @return string
635
+	 */
636
+	public function created()
637
+	{
638
+		return $this->get('MSG_created');
639
+	}
640
+
641
+
642
+	/**
643
+	 * Sets created
644
+	 *
645
+	 * @param string $created
646
+	 */
647
+	public function set_created($created)
648
+	{
649
+		$this->set('MSG_created', $created);
650
+	}
651
+
652
+
653
+	/**
654
+	 * Gets modified
655
+	 *
656
+	 * @return string
657
+	 */
658
+	public function modified()
659
+	{
660
+		return $this->get('MSG_modified');
661
+	}
662
+
663
+
664
+	/**
665
+	 * Sets modified
666
+	 *
667
+	 * @param string $modified
668
+	 */
669
+	public function set_modified($modified)
670
+	{
671
+		$this->set('MSG_modified', $modified);
672
+	}
673
+
674
+
675
+	/**
676
+	 * Sets generation data for this message.
677
+	 *
678
+	 * @param mixed $data
679
+	 */
680
+	public function set_generation_data($data)
681
+	{
682
+		$this->set_field_or_extra_meta('MSG_generation_data', $data);
683
+	}
684
+
685
+
686
+	/**
687
+	 * Returns any set generation data for this message.
688
+	 *
689
+	 * @return mixed|null
690
+	 */
691
+	public function get_generation_data()
692
+	{
693
+		return $this->get_field_or_extra_meta('MSG_generation_data');
694
+	}
695
+
696
+
697
+	/**
698
+	 * Gets any error message.
699
+	 *
700
+	 * @return mixed|null
701
+	 */
702
+	public function error_message()
703
+	{
704
+		return $this->get_field_or_extra_meta('MSG_error');
705
+	}
706
+
707
+
708
+	/**
709
+	 * Sets an error message.
710
+	 *
711
+	 * @param $message
712
+	 * @return bool|int
713
+	 */
714
+	public function set_error_message($message)
715
+	{
716
+		return $this->set_field_or_extra_meta('MSG_error', $message);
717
+	}
718
+
719
+
720
+	/**
721
+	 * This retrieves the associated template pack with this message.
722
+	 *
723
+	 * @return EE_Messages_Template_Pack | null
724
+	 */
725
+	public function get_template_pack()
726
+	{
727
+		/**
728
+		 * This is deprecated functionality that will be removed eventually but included here now for backward compat.
729
+		 */
730
+		if ( ! empty($this->template_pack)) {
731
+			return $this->template_pack;
732
+		}
733
+		/** @type EE_Message_Template_Group $grp */
734
+		$grp = $this->get_first_related('Message_Template_Group');
735
+		//if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
736
+		if ( ! $grp instanceof EE_Message_Template_Group) {
737
+			$grp = EEM_Message_Template_Group::instance()->get_one(
738
+				array(
739
+					array(
740
+						'MTP_messenger'    => $this->messenger(),
741
+						'MTP_message_type' => $this->message_type(),
742
+						'MTP_is_global'    => true,
743
+					),
744
+				)
745
+			);
746
+		}
747
+
748
+		return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack() : null;
749
+	}
750
+
751
+
752
+	/**
753
+	 * Retrieves the variation used for generating this message.
754
+	 *
755
+	 * @return string
756
+	 */
757
+	public function get_template_pack_variation()
758
+	{
759
+		/**
760
+		 * This is deprecated functionality that will be removed eventually but included here now for backward compat.
761
+		 */
762
+		if ( ! empty($this->template_variation)) {
763
+			return $this->template_variation;
764
+		}
765
+
766
+		/** @type EE_Message_Template_Group $grp */
767
+		$grp = $this->get_first_related('Message_Template_Group');
768
+
769
+		//if no group then let's try to get the first related group by internal messenger and message type (will use global grp).
770
+		if ( ! $grp instanceof EE_Message_Template_Group) {
771
+			$grp = EEM_Message_Template_Group::instance()->get_one(
772
+				array(
773
+					array(
774
+						'MTP_messenger'    => $this->messenger(),
775
+						'MTP_message_type' => $this->message_type(),
776
+						'MTP_is_global'    => true,
777
+					),
778
+				)
779
+			);
780
+		}
781
+
782
+		return $grp instanceof EE_Message_Template_Group ? $grp->get_template_pack_variation() : '';
783
+	}
784
+
785
+	/**
786
+	 * Return the link to the admin details for the object.
787
+	 *
788
+	 * @return string
789
+	 */
790
+	public function get_admin_details_link()
791
+	{
792
+		EE_Registry::instance()->load_helper('URL');
793
+		EE_Registry::instance()->load_helper('MSG_Template');
794
+		switch ($this->STS_ID()) {
795
+			case EEM_Message::status_failed :
796
+			case EEM_Message::status_debug_only :
797
+				return EEH_MSG_Template::generate_error_display_trigger($this);
798
+				break;
799
+
800
+			case EEM_Message::status_sent :
801
+				return EEH_MSG_Template::generate_browser_trigger($this);
802
+				break;
803
+
804
+			default :
805
+				return '';
806
+		}
807
+	}
808
+
809
+	/**
810
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
811
+	 *
812
+	 * @return string
813
+	 */
814
+	public function get_admin_edit_link()
815
+	{
816
+		return $this->get_admin_details_link();
817
+	}
818
+
819
+	/**
820
+	 * Returns the link to a settings page for the object.
821
+	 *
822
+	 * @return string
823
+	 */
824
+	public function get_admin_settings_link()
825
+	{
826
+		EE_Registry::instance()->load_helper('URL');
827
+		return EEH_URL::add_query_args_and_nonce(
828
+			array(
829
+				'page'   => 'espresso_messages',
830
+				'action' => 'settings',
831
+			),
832
+			admin_url('admin.php')
833
+		);
834
+	}
835
+
836
+	/**
837
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
838
+	 *
839
+	 * @return string
840
+	 */
841
+	public function get_admin_overview_link()
842
+	{
843
+		EE_Registry::instance()->load_helper('URL');
844
+		return EEH_URL::add_query_args_and_nonce(
845
+			array(
846
+				'page'   => 'espresso_messages',
847
+				'action' => 'default',
848
+			),
849
+			admin_url('admin.php')
850
+		);
851
+	}
852
+
853
+
854
+	/**
855
+	 * This sets the EEM_Message::status_messenger_executing class on the message and the appropriate error message for
856
+	 * it.
857
+	 * Note this also SAVES the current message object to the db because it adds an error message to accompany the status.
858
+	 *
859
+	 */
860
+	public function set_messenger_is_executing()
861
+	{
862
+		$this->set_STS_ID( EEM_Message::status_messenger_executing );
863
+		$this->set_error_message(
864
+			esc_html__(
865
+				'A message with this status indicates that there was a problem that occurred while the message was being
866 866
                 processed by the messenger.  It is still possible that the message was sent successfully, but at some
867 867
                 point during the processing there was a failure.  This usually is indicative of a timeout issue with PHP 
868 868
                 or memory limits being reached.  If you see this repeatedly you may want to consider upgrading the memory 
869 869
                 available to PHP on your server.',
870
-                'event_espresso'
871
-            )
872
-        );
873
-    }
870
+				'event_espresso'
871
+			)
872
+		);
873
+	}
874 874
 }
875 875
 /* End of file EE_Message.class.php */
876 876
 /* Location: /core/db_classes/EE_Message.class.php */
877 877
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if (! defined('EVENT_ESPRESSO_VERSION')) {
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2 2
     exit('No direct script access allowed');
3 3
 }
4 4
 
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
      */
860 860
     public function set_messenger_is_executing()
861 861
     {
862
-        $this->set_STS_ID( EEM_Message::status_messenger_executing );
862
+        $this->set_STS_ID(EEM_Message::status_messenger_executing);
863 863
         $this->set_error_message(
864 864
             esc_html__(
865 865
                 'A message with this status indicates that there was a problem that occurred while the message was being
Please login to merge, or discard this patch.
modules/single_page_checkout/EED_Single_Page_Checkout.module.php 2 patches
Indentation   +1688 added lines, -1688 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use EventEspresso\core\exceptions\InvalidEntityException;
3 3
 
4 4
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 
8 8
 
@@ -17,1693 +17,1693 @@  discard block
 block discarded – undo
17 17
 class EED_Single_Page_Checkout extends EED_Module
18 18
 {
19 19
 
20
-    /**
21
-     * $_initialized - has the SPCO controller already been initialized ?
22
-     *
23
-     * @access private
24
-     * @var bool $_initialized
25
-     */
26
-    private static $_initialized = false;
27
-
28
-
29
-    /**
30
-     * $_checkout_verified - is the EE_Checkout verified as correct for this request ?
31
-     *
32
-     * @access private
33
-     * @var bool $_valid_checkout
34
-     */
35
-    private static $_checkout_verified = true;
36
-
37
-    /**
38
-     *    $_reg_steps_array - holds initial array of reg steps
39
-     *
40
-     * @access private
41
-     * @var array $_reg_steps_array
42
-     */
43
-    private static $_reg_steps_array = array();
44
-
45
-    /**
46
-     *    $checkout - EE_Checkout object for handling the properties of the current checkout process
47
-     *
48
-     * @access public
49
-     * @var EE_Checkout $checkout
50
-     */
51
-    public $checkout;
52
-
53
-
54
-
55
-    /**
56
-     * @return EED_Single_Page_Checkout
57
-     */
58
-    public static function instance()
59
-    {
60
-        add_filter('EED_Single_Page_Checkout__SPCO_active', '__return_true');
61
-        return parent::get_instance(__CLASS__);
62
-    }
63
-
64
-
65
-
66
-    /**
67
-     * @return EE_CART
68
-     */
69
-    public function cart()
70
-    {
71
-        return $this->checkout->cart;
72
-    }
73
-
74
-
75
-
76
-    /**
77
-     * @return EE_Transaction
78
-     */
79
-    public function transaction()
80
-    {
81
-        return $this->checkout->transaction;
82
-    }
83
-
84
-
85
-
86
-    /**
87
-     *    set_hooks - for hooking into EE Core, other modules, etc
88
-     *
89
-     * @access    public
90
-     * @return    void
91
-     * @throws \EE_Error
92
-     */
93
-    public static function set_hooks()
94
-    {
95
-        EED_Single_Page_Checkout::set_definitions();
96
-    }
97
-
98
-
99
-
100
-    /**
101
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
102
-     *
103
-     * @access    public
104
-     * @return    void
105
-     * @throws \EE_Error
106
-     */
107
-    public static function set_hooks_admin()
108
-    {
109
-        EED_Single_Page_Checkout::set_definitions();
110
-        if ( ! (defined('DOING_AJAX') && DOING_AJAX)) {
111
-            // hook into the top of pre_get_posts to set the reg step routing, which gives other modules or plugins a chance to modify the reg steps, but just before the routes get called
112
-            add_action('pre_get_posts', array('EED_Single_Page_Checkout', 'load_reg_steps'), 1);
113
-            return;
114
-        }
115
-        // going to start an output buffer in case anything gets accidentally output that might disrupt our JSON response
116
-        ob_start();
117
-        EED_Single_Page_Checkout::load_request_handler();
118
-        EED_Single_Page_Checkout::load_reg_steps();
119
-        // set ajax hooks
120
-        add_action('wp_ajax_process_reg_step', array('EED_Single_Page_Checkout', 'process_reg_step'));
121
-        add_action('wp_ajax_nopriv_process_reg_step', array('EED_Single_Page_Checkout', 'process_reg_step'));
122
-        add_action('wp_ajax_display_spco_reg_step', array('EED_Single_Page_Checkout', 'display_reg_step'));
123
-        add_action('wp_ajax_nopriv_display_spco_reg_step', array('EED_Single_Page_Checkout', 'display_reg_step'));
124
-        add_action('wp_ajax_update_reg_step', array('EED_Single_Page_Checkout', 'update_reg_step'));
125
-        add_action('wp_ajax_nopriv_update_reg_step', array('EED_Single_Page_Checkout', 'update_reg_step'));
126
-    }
127
-
128
-
129
-
130
-    /**
131
-     *    process ajax request
132
-     *
133
-     * @param string $ajax_action
134
-     * @throws \EE_Error
135
-     */
136
-    public static function process_ajax_request($ajax_action)
137
-    {
138
-        EE_Registry::instance()->REQ->set('action', $ajax_action);
139
-        EED_Single_Page_Checkout::instance()->_initialize();
140
-    }
141
-
142
-
143
-
144
-    /**
145
-     *    ajax display registration step
146
-     *
147
-     * @throws \EE_Error
148
-     */
149
-    public static function display_reg_step()
150
-    {
151
-        EED_Single_Page_Checkout::process_ajax_request('display_spco_reg_step');
152
-    }
153
-
154
-
155
-
156
-    /**
157
-     *    ajax process registration step
158
-     *
159
-     * @throws \EE_Error
160
-     */
161
-    public static function process_reg_step()
162
-    {
163
-        EED_Single_Page_Checkout::process_ajax_request('process_reg_step');
164
-    }
165
-
166
-
167
-
168
-    /**
169
-     *    ajax process registration step
170
-     *
171
-     * @throws \EE_Error
172
-     */
173
-    public static function update_reg_step()
174
-    {
175
-        EED_Single_Page_Checkout::process_ajax_request('update_reg_step');
176
-    }
177
-
178
-
179
-
180
-    /**
181
-     *   update_checkout
182
-     *
183
-     * @access public
184
-     * @return void
185
-     * @throws \EE_Error
186
-     */
187
-    public static function update_checkout()
188
-    {
189
-        EED_Single_Page_Checkout::process_ajax_request('update_checkout');
190
-    }
191
-
192
-
193
-
194
-    /**
195
-     *    load_request_handler
196
-     *
197
-     * @access    public
198
-     * @return    void
199
-     */
200
-    public static function load_request_handler()
201
-    {
202
-        // load core Request_Handler class
203
-        if ( ! isset(EE_Registry::instance()->REQ)) {
204
-            EE_Registry::instance()->load_core('Request_Handler');
205
-        }
206
-    }
207
-
208
-
209
-
210
-    /**
211
-     *    set_definitions
212
-     *
213
-     * @access    public
214
-     * @return    void
215
-     * @throws \EE_Error
216
-     */
217
-    public static function set_definitions()
218
-    {
219
-        define('SPCO_BASE_PATH', rtrim(str_replace(array('\\', '/'), DS, plugin_dir_path(__FILE__)), DS) . DS);
220
-        define('SPCO_CSS_URL', plugin_dir_url(__FILE__) . 'css' . DS);
221
-        define('SPCO_IMG_URL', plugin_dir_url(__FILE__) . 'img' . DS);
222
-        define('SPCO_JS_URL', plugin_dir_url(__FILE__) . 'js' . DS);
223
-        define('SPCO_INC_PATH', SPCO_BASE_PATH . 'inc' . DS);
224
-        define('SPCO_REG_STEPS_PATH', SPCO_BASE_PATH . 'reg_steps' . DS);
225
-        define('SPCO_TEMPLATES_PATH', SPCO_BASE_PATH . 'templates' . DS);
226
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(SPCO_BASE_PATH, true);
227
-        EE_Registry::$i18n_js_strings['registration_expiration_notice'] = sprintf(
228
-            __('%1$sWe\'re sorry, but you\'re registration time has expired.%2$s%4$sIf you still wish to complete your registration, please return to the %5$sEvent List%6$sEvent List%7$s and reselect your tickets if available. Please except our apologies for any inconvenience this may have caused.%8$s',
229
-                'event_espresso'),
230
-            '<h4 class="important-notice">',
231
-            '</h4>',
232
-            '<br />',
233
-            '<p>',
234
-            '<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
235
-            '">',
236
-            '</a>',
237
-            '</p>'
238
-        );
239
-    }
240
-
241
-
242
-
243
-    /**
244
-     * load_reg_steps
245
-     * loads and instantiates each reg step based on the EE_Registry::instance()->CFG->registration->reg_steps array
246
-     *
247
-     * @access    private
248
-     * @throws EE_Error
249
-     * @return void
250
-     */
251
-    public static function load_reg_steps()
252
-    {
253
-        static $reg_steps_loaded = false;
254
-        if ($reg_steps_loaded) {
255
-            return;
256
-        }
257
-        // filter list of reg_steps
258
-        $reg_steps_to_load = (array)apply_filters(
259
-            'AHEE__SPCO__load_reg_steps__reg_steps_to_load',
260
-            EED_Single_Page_Checkout::get_reg_steps()
261
-        );
262
-        // sort by key (order)
263
-        ksort($reg_steps_to_load);
264
-        // loop through folders
265
-        foreach ($reg_steps_to_load as $order => $reg_step) {
266
-            // we need a
267
-            if (isset($reg_step['file_path'], $reg_step['class_name'], $reg_step['slug'])) {
268
-                // copy over to the reg_steps_array
269
-                EED_Single_Page_Checkout::$_reg_steps_array[$order] = $reg_step;
270
-                // register custom key route for each reg step
271
-                // ie: step=>"slug" - this is the entire reason we load the reg steps array now
272
-                EE_Config::register_route($reg_step['slug'], 'EED_Single_Page_Checkout', 'run', 'step');
273
-                // add AJAX or other hooks
274
-                if (isset($reg_step['has_hooks']) && $reg_step['has_hooks']) {
275
-                    // setup autoloaders if necessary
276
-                    if ( ! class_exists($reg_step['class_name'])) {
277
-                        EEH_Autoloader::register_autoloaders_for_each_file_in_folder($reg_step['file_path'], true);
278
-                    }
279
-                    if (is_callable($reg_step['class_name'], 'set_hooks')) {
280
-                        call_user_func(array($reg_step['class_name'], 'set_hooks'));
281
-                    }
282
-                }
283
-            }
284
-        }
285
-        $reg_steps_loaded = true;
286
-    }
287
-
288
-
289
-
290
-    /**
291
-     *    get_reg_steps
292
-     *
293
-     * @access    public
294
-     * @return    array
295
-     */
296
-    public static function get_reg_steps()
297
-    {
298
-        $reg_steps = EE_Registry::instance()->CFG->registration->reg_steps;
299
-        if (empty($reg_steps)) {
300
-            $reg_steps = array(
301
-                10  => array(
302
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'attendee_information',
303
-                    'class_name' => 'EE_SPCO_Reg_Step_Attendee_Information',
304
-                    'slug'       => 'attendee_information',
305
-                    'has_hooks'  => false,
306
-                ),
307
-                20  => array(
308
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'registration_confirmation',
309
-                    'class_name' => 'EE_SPCO_Reg_Step_Registration_Confirmation',
310
-                    'slug'       => 'registration_confirmation',
311
-                    'has_hooks'  => false,
312
-                ),
313
-                30  => array(
314
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'payment_options',
315
-                    'class_name' => 'EE_SPCO_Reg_Step_Payment_Options',
316
-                    'slug'       => 'payment_options',
317
-                    'has_hooks'  => true,
318
-                ),
319
-                999 => array(
320
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'finalize_registration',
321
-                    'class_name' => 'EE_SPCO_Reg_Step_Finalize_Registration',
322
-                    'slug'       => 'finalize_registration',
323
-                    'has_hooks'  => false,
324
-                ),
325
-            );
326
-        }
327
-        return $reg_steps;
328
-    }
329
-
330
-
331
-
332
-    /**
333
-     *    registration_checkout_for_admin
334
-     *
335
-     * @access    public
336
-     * @return    string
337
-     * @throws \EE_Error
338
-     */
339
-    public static function registration_checkout_for_admin()
340
-    {
341
-        EED_Single_Page_Checkout::load_reg_steps();
342
-        EE_Registry::instance()->REQ->set('step', 'attendee_information');
343
-        EE_Registry::instance()->REQ->set('action', 'display_spco_reg_step');
344
-        EE_Registry::instance()->REQ->set('process_form_submission', false);
345
-        EED_Single_Page_Checkout::instance()->_initialize();
346
-        EED_Single_Page_Checkout::instance()->_display_spco_reg_form();
347
-        return EE_Registry::instance()->REQ->get_output();
348
-    }
349
-
350
-
351
-
352
-    /**
353
-     * process_registration_from_admin
354
-     *
355
-     * @access public
356
-     * @return \EE_Transaction
357
-     * @throws \EE_Error
358
-     */
359
-    public static function process_registration_from_admin()
360
-    {
361
-        EED_Single_Page_Checkout::load_reg_steps();
362
-        EE_Registry::instance()->REQ->set('step', 'attendee_information');
363
-        EE_Registry::instance()->REQ->set('action', 'process_reg_step');
364
-        EE_Registry::instance()->REQ->set('process_form_submission', true);
365
-        EED_Single_Page_Checkout::instance()->_initialize();
366
-        if (EED_Single_Page_Checkout::instance()->checkout->current_step->completed()) {
367
-            $final_reg_step = end(EED_Single_Page_Checkout::instance()->checkout->reg_steps);
368
-            if ($final_reg_step instanceof EE_SPCO_Reg_Step_Finalize_Registration) {
369
-                EED_Single_Page_Checkout::instance()->checkout->set_reg_step_initiated($final_reg_step);
370
-                if ($final_reg_step->process_reg_step()) {
371
-                    $final_reg_step->set_completed();
372
-                    EED_Single_Page_Checkout::instance()->checkout->update_txn_reg_steps_array();
373
-                    return EED_Single_Page_Checkout::instance()->checkout->transaction;
374
-                }
375
-            }
376
-        }
377
-        return null;
378
-    }
379
-
380
-
381
-
382
-    /**
383
-     *    run
384
-     *
385
-     * @access    public
386
-     * @param WP_Query $WP_Query
387
-     * @return    void
388
-     * @throws \EE_Error
389
-     */
390
-    public function run($WP_Query)
391
-    {
392
-        if (
393
-            $WP_Query instanceof WP_Query
394
-            && $WP_Query->is_main_query()
395
-            && apply_filters('FHEE__EED_Single_Page_Checkout__run', true)
396
-            && $this->_is_reg_checkout()
397
-        ) {
398
-            $this->_initialize();
399
-        }
400
-    }
401
-
402
-
403
-
404
-    /**
405
-     * determines whether current url matches reg page url
406
-     *
407
-     * @return bool
408
-     */
409
-    protected function _is_reg_checkout()
410
-    {
411
-        // get current permalink for reg page without any extra query args
412
-        $reg_page_url = \get_permalink(EE_Config::instance()->core->reg_page_id);
413
-        // get request URI for current request, but without the scheme or host
414
-        $current_request_uri = \EEH_URL::filter_input_server_url('REQUEST_URI');
415
-        $current_request_uri = html_entity_decode($current_request_uri);
416
-        // get array of query args from the current request URI
417
-        $query_args = \EEH_URL::get_query_string($current_request_uri);
418
-        // grab page id if it is set
419
-        $page_id = isset($query_args['page_id']) ? absint($query_args['page_id']) : 0;
420
-        // and remove the page id from the query args (we will re-add it later)
421
-        unset($query_args['page_id']);
422
-        // now strip all query args from current request URI
423
-        $current_request_uri = remove_query_arg(array_flip($query_args), $current_request_uri);
424
-        // and re-add the page id if it was set
425
-        if ($page_id) {
426
-            $current_request_uri = add_query_arg('page_id', $page_id, $current_request_uri);
427
-        }
428
-        // remove slashes and ?
429
-        $current_request_uri = trim($current_request_uri, '?/');
430
-        // is current request URI part of the known full reg page URL ?
431
-        return ! empty($current_request_uri) && strpos($reg_page_url, $current_request_uri) !== false;
432
-    }
433
-
434
-
435
-
436
-    /**
437
-     *    run
438
-     *
439
-     * @access    public
440
-     * @param WP_Query $WP_Query
441
-     * @return    void
442
-     * @throws \EE_Error
443
-     */
444
-    public static function init($WP_Query)
445
-    {
446
-        EED_Single_Page_Checkout::instance()->run($WP_Query);
447
-    }
448
-
449
-
450
-
451
-    /**
452
-     *    _initialize - initial module setup
453
-     *
454
-     * @access    private
455
-     * @throws EE_Error
456
-     * @return    void
457
-     */
458
-    private function _initialize()
459
-    {
460
-        // ensure SPCO doesn't run twice
461
-        if (EED_Single_Page_Checkout::$_initialized) {
462
-            return;
463
-        }
464
-        try {
465
-            $this->_verify_session();
466
-            // setup the EE_Checkout object
467
-            $this->checkout = $this->_initialize_checkout();
468
-            // filter checkout
469
-            $this->checkout = apply_filters('FHEE__EED_Single_Page_Checkout___initialize__checkout', $this->checkout);
470
-            // get the $_GET
471
-            $this->_get_request_vars();
472
-            if ($this->_block_bots()) {
473
-                return;
474
-            }
475
-            // filter continue_reg
476
-            $this->checkout->continue_reg = apply_filters('FHEE__EED_Single_Page_Checkout__init___continue_reg', true, $this->checkout);
477
-            // load the reg steps array
478
-            if ( ! $this->_load_and_instantiate_reg_steps()) {
479
-                EED_Single_Page_Checkout::$_initialized = true;
480
-                return;
481
-            }
482
-            // set the current step
483
-            $this->checkout->set_current_step($this->checkout->step);
484
-            // and the next step
485
-            $this->checkout->set_next_step();
486
-            // verify that everything has been setup correctly
487
-            if ( ! ($this->_verify_transaction_and_get_registrations() && $this->_final_verifications())) {
488
-                EED_Single_Page_Checkout::$_initialized = true;
489
-                return;
490
-            }
491
-            // lock the transaction
492
-            $this->checkout->transaction->lock();
493
-            // make sure all of our cached objects are added to their respective model entity mappers
494
-            $this->checkout->refresh_all_entities();
495
-            // set amount owing
496
-            $this->checkout->amount_owing = $this->checkout->transaction->remaining();
497
-            // initialize each reg step, which gives them the chance to potentially alter the process
498
-            $this->_initialize_reg_steps();
499
-            // DEBUG LOG
500
-            //$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
501
-            // get reg form
502
-            if( ! $this->_check_form_submission()) {
503
-                EED_Single_Page_Checkout::$_initialized = true;
504
-                return;
505
-            }
506
-            // checkout the action!!!
507
-            $this->_process_form_action();
508
-            // add some style and make it dance
509
-            $this->add_styles_and_scripts();
510
-            // kk... SPCO has successfully run
511
-            EED_Single_Page_Checkout::$_initialized = true;
512
-            // set no cache headers and constants
513
-            EE_System::do_not_cache();
514
-            // add anchor
515
-            add_action('loop_start', array($this, 'set_checkout_anchor'), 1);
516
-            // remove transaction lock
517
-            add_action('shutdown', array($this, 'unlock_transaction'), 1);
518
-        } catch (Exception $e) {
519
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
520
-        }
521
-    }
522
-
523
-
524
-
525
-    /**
526
-     *    _verify_session
527
-     * checks that the session is valid and not expired
528
-     *
529
-     * @access    private
530
-     * @throws EE_Error
531
-     */
532
-    private function _verify_session()
533
-    {
534
-        if ( ! EE_Registry::instance()->SSN instanceof EE_Session) {
535
-            throw new EE_Error(__('The EE_Session class could not be loaded.', 'event_espresso'));
536
-        }
537
-        // is session still valid ?
538
-        if (EE_Registry::instance()->SSN->expired() && EE_Registry::instance()->REQ->get('e_reg_url_link', '') === '') {
539
-            $this->checkout = new EE_Checkout();
540
-            EE_Registry::instance()->SSN->reset_cart();
541
-            EE_Registry::instance()->SSN->reset_checkout();
542
-            EE_Registry::instance()->SSN->reset_transaction();
543
-            EE_Error::add_attention(EE_Registry::$i18n_js_strings['registration_expiration_notice'], __FILE__,
544
-                __FUNCTION__, __LINE__);
545
-            EE_Registry::instance()->SSN->reset_expired();
546
-        }
547
-    }
548
-
549
-
550
-
551
-    /**
552
-     *    _initialize_checkout
553
-     * loads and instantiates EE_Checkout
554
-     *
555
-     * @access    private
556
-     * @throws EE_Error
557
-     * @return EE_Checkout
558
-     */
559
-    private function _initialize_checkout()
560
-    {
561
-        // look in session for existing checkout
562
-        /** @type EE_Checkout $checkout */
563
-        $checkout = EE_Registry::instance()->SSN->checkout();
564
-        // verify
565
-        if ( ! $checkout instanceof EE_Checkout) {
566
-            // instantiate EE_Checkout object for handling the properties of the current checkout process
567
-            $checkout = EE_Registry::instance()->load_file(SPCO_INC_PATH, 'EE_Checkout', 'class', array(), false);
568
-        } else {
569
-            if ($checkout->current_step->is_final_step() && $checkout->exit_spco() === true) {
570
-                $this->unlock_transaction();
571
-                wp_safe_redirect($checkout->redirect_url);
572
-                exit();
573
-            }
574
-        }
575
-        $checkout = apply_filters('FHEE__EED_Single_Page_Checkout___initialize_checkout__checkout', $checkout);
576
-        // verify again
577
-        if ( ! $checkout instanceof EE_Checkout) {
578
-            throw new EE_Error(__('The EE_Checkout class could not be loaded.', 'event_espresso'));
579
-        }
580
-        // reset anything that needs a clean slate for each request
581
-        $checkout->reset_for_current_request();
582
-        return $checkout;
583
-    }
584
-
585
-
586
-
587
-    /**
588
-     *    _get_request_vars
589
-     *
590
-     * @access    private
591
-     * @return    void
592
-     * @throws \EE_Error
593
-     */
594
-    private function _get_request_vars()
595
-    {
596
-        // load classes
597
-        EED_Single_Page_Checkout::load_request_handler();
598
-        //make sure this request is marked as belonging to EE
599
-        EE_Registry::instance()->REQ->set_espresso_page(true);
600
-        // which step is being requested ?
601
-        $this->checkout->step = EE_Registry::instance()->REQ->get('step', $this->_get_first_step());
602
-        // which step is being edited ?
603
-        $this->checkout->edit_step = EE_Registry::instance()->REQ->get('edit_step', '');
604
-        // and what we're doing on the current step
605
-        $this->checkout->action = EE_Registry::instance()->REQ->get('action', 'display_spco_reg_step');
606
-        // timestamp
607
-        $this->checkout->uts = EE_Registry::instance()->REQ->get('uts', 0);
608
-        // returning to edit ?
609
-        $this->checkout->reg_url_link = EE_Registry::instance()->REQ->get('e_reg_url_link', '');
610
-        // or some other kind of revisit ?
611
-        $this->checkout->revisit = EE_Registry::instance()->REQ->get('revisit', false);
612
-        // and whether or not to generate a reg form for this request
613
-        $this->checkout->generate_reg_form = EE_Registry::instance()->REQ->get('generate_reg_form', true);        // TRUE 	FALSE
614
-        // and whether or not to process a reg form submission for this request
615
-        $this->checkout->process_form_submission = EE_Registry::instance()->REQ->get(
616
-            'process_form_submission',
617
-            $this->checkout->action === 'process_reg_step'
618
-        ); // TRUE 	FALSE
619
-        $this->checkout->process_form_submission = $this->checkout->action !== 'display_spco_reg_step'
620
-            ? $this->checkout->process_form_submission
621
-            : false;        // TRUE 	FALSE
622
-        // $this->_display_request_vars();
623
-    }
624
-
625
-
626
-
627
-    /**
628
-     *  _display_request_vars
629
-     *
630
-     * @access    protected
631
-     * @return    void
632
-     */
633
-    protected function _display_request_vars()
634
-    {
635
-        if ( ! WP_DEBUG) {
636
-            return;
637
-        }
638
-        EEH_Debug_Tools::printr($_REQUEST, '$_REQUEST', __FILE__, __LINE__);
639
-        EEH_Debug_Tools::printr($this->checkout->step, '$this->checkout->step', __FILE__, __LINE__);
640
-        EEH_Debug_Tools::printr($this->checkout->edit_step, '$this->checkout->edit_step', __FILE__, __LINE__);
641
-        EEH_Debug_Tools::printr($this->checkout->action, '$this->checkout->action', __FILE__, __LINE__);
642
-        EEH_Debug_Tools::printr($this->checkout->reg_url_link, '$this->checkout->reg_url_link', __FILE__, __LINE__);
643
-        EEH_Debug_Tools::printr($this->checkout->revisit, '$this->checkout->revisit', __FILE__, __LINE__);
644
-        EEH_Debug_Tools::printr($this->checkout->generate_reg_form, '$this->checkout->generate_reg_form', __FILE__, __LINE__);
645
-        EEH_Debug_Tools::printr($this->checkout->process_form_submission, '$this->checkout->process_form_submission', __FILE__, __LINE__);
646
-    }
647
-
648
-
649
-
650
-    /**
651
-     * _block_bots
652
-     * checks that the incoming request has either of the following set:
653
-     *  a uts (unix timestamp) which indicates that the request was redirected from the Ticket Selector
654
-     *  a REG URL Link, which indicates that the request is a return visit to SPCO for a valid TXN
655
-     * so if you're not coming from the Ticket Selector nor returning for a valid IP...
656
-     * then where you coming from man?
657
-     *
658
-     * @return boolean
659
-     */
660
-    private function _block_bots()
661
-    {
662
-        $invalid_checkout_access = \EED_Invalid_Checkout_Access::getInvalidCheckoutAccess();
663
-        if ($invalid_checkout_access->checkoutAccessIsInvalid($this->checkout)) {
664
-            return true;
665
-        }
666
-        return false;
667
-    }
668
-
669
-
670
-
671
-    /**
672
-     *    _get_first_step
673
-     *  gets slug for first step in $_reg_steps_array
674
-     *
675
-     * @access    private
676
-     * @throws EE_Error
677
-     * @return    array
678
-     */
679
-    private function _get_first_step()
680
-    {
681
-        $first_step = reset(EED_Single_Page_Checkout::$_reg_steps_array);
682
-        return isset($first_step['slug']) ? $first_step['slug'] : 'attendee_information';
683
-    }
684
-
685
-
686
-
687
-    /**
688
-     *    _load_and_instantiate_reg_steps
689
-     *  instantiates each reg step based on the loaded reg_steps array
690
-     *
691
-     * @access    private
692
-     * @throws EE_Error
693
-     * @return    bool
694
-     */
695
-    private function _load_and_instantiate_reg_steps()
696
-    {
697
-        // have reg_steps already been instantiated ?
698
-        if (
699
-            empty($this->checkout->reg_steps)
700
-            || apply_filters('FHEE__Single_Page_Checkout__load_reg_steps__reload_reg_steps', false, $this->checkout)
701
-        ) {
702
-            // if not, then loop through raw reg steps array
703
-            foreach (EED_Single_Page_Checkout::$_reg_steps_array as $order => $reg_step) {
704
-                if ( ! $this->_load_and_instantiate_reg_step($reg_step, $order)) {
705
-                    return false;
706
-                }
707
-            }
708
-            EE_Registry::instance()->CFG->registration->skip_reg_confirmation = true;
709
-            EE_Registry::instance()->CFG->registration->reg_confirmation_last = true;
710
-            // skip the registration_confirmation page ?
711
-            if (EE_Registry::instance()->CFG->registration->skip_reg_confirmation) {
712
-                // just remove it from the reg steps array
713
-                $this->checkout->remove_reg_step('registration_confirmation', false);
714
-            } else if (
715
-                isset($this->checkout->reg_steps['registration_confirmation'])
716
-                && EE_Registry::instance()->CFG->registration->reg_confirmation_last
717
-            ) {
718
-                // set the order to something big like 100
719
-                $this->checkout->set_reg_step_order('registration_confirmation', 100);
720
-            }
721
-            // filter the array for good luck
722
-            $this->checkout->reg_steps = apply_filters(
723
-                'FHEE__Single_Page_Checkout__load_reg_steps__reg_steps',
724
-                $this->checkout->reg_steps
725
-            );
726
-            // finally re-sort based on the reg step class order properties
727
-            $this->checkout->sort_reg_steps();
728
-        } else {
729
-            foreach ($this->checkout->reg_steps as $reg_step) {
730
-                // set all current step stati to FALSE
731
-                $reg_step->set_is_current_step(false);
732
-            }
733
-        }
734
-        if (empty($this->checkout->reg_steps)) {
735
-            EE_Error::add_error(__('No Reg Steps were loaded..', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
736
-            return false;
737
-        }
738
-        // make reg step details available to JS
739
-        $this->checkout->set_reg_step_JSON_info();
740
-        return true;
741
-    }
742
-
743
-
744
-
745
-    /**
746
-     *     _load_and_instantiate_reg_step
747
-     *
748
-     * @access    private
749
-     * @param array $reg_step
750
-     * @param int   $order
751
-     * @return bool
752
-     */
753
-    private function _load_and_instantiate_reg_step($reg_step = array(), $order = 0)
754
-    {
755
-        // we need a file_path, class_name, and slug to add a reg step
756
-        if (isset($reg_step['file_path'], $reg_step['class_name'], $reg_step['slug'])) {
757
-            // if editing a specific step, but this is NOT that step... (and it's not the 'finalize_registration' step)
758
-            if (
759
-                $this->checkout->reg_url_link
760
-                && $this->checkout->step !== $reg_step['slug']
761
-                && $reg_step['slug'] !== 'finalize_registration'
762
-            ) {
763
-                return true;
764
-            }
765
-            // instantiate step class using file path and class name
766
-            $reg_step_obj = EE_Registry::instance()->load_file(
767
-                $reg_step['file_path'],
768
-                $reg_step['class_name'],
769
-                'class',
770
-                $this->checkout,
771
-                false
772
-            );
773
-            // did we gets the goods ?
774
-            if ($reg_step_obj instanceof EE_SPCO_Reg_Step) {
775
-                // set reg step order based on config
776
-                $reg_step_obj->set_order($order);
777
-                // add instantiated reg step object to the master reg steps array
778
-                $this->checkout->add_reg_step($reg_step_obj);
779
-            } else {
780
-                EE_Error::add_error(
781
-                    __('The current step could not be set.', 'event_espresso'),
782
-                    __FILE__, __FUNCTION__, __LINE__
783
-                );
784
-                return false;
785
-            }
786
-        } else {
787
-            if (WP_DEBUG) {
788
-                EE_Error::add_error(
789
-                    sprintf(
790
-                        __('A registration step could not be loaded. One or more of the following data points is invalid:%4$s%5$sFile Path: %1$s%6$s%5$sClass Name: %2$s%6$s%5$sSlug: %3$s%6$s%7$s', 'event_espresso'),
791
-                        isset($reg_step['file_path']) ? $reg_step['file_path'] : '',
792
-                        isset($reg_step['class_name']) ? $reg_step['class_name'] : '',
793
-                        isset($reg_step['slug']) ? $reg_step['slug'] : '',
794
-                        '<ul>',
795
-                        '<li>',
796
-                        '</li>',
797
-                        '</ul>'
798
-                    ),
799
-                    __FILE__, __FUNCTION__, __LINE__
800
-                );
801
-            }
802
-            return false;
803
-        }
804
-        return true;
805
-    }
806
-
807
-
808
-
809
-    /**
810
-     * _verify_transaction_and_get_registrations
811
-     *
812
-     * @access private
813
-     * @return bool
814
-     */
815
-    private function _verify_transaction_and_get_registrations()
816
-    {
817
-        // was there already a valid transaction in the checkout from the session ?
818
-        if ( ! $this->checkout->transaction instanceof EE_Transaction) {
819
-            // get transaction from db or session
820
-            $this->checkout->transaction = $this->checkout->reg_url_link && ! is_admin()
821
-                ? $this->_get_transaction_and_cart_for_previous_visit()
822
-                : $this->_get_cart_for_current_session_and_setup_new_transaction();
823
-            if ( ! $this->checkout->transaction instanceof EE_Transaction) {
824
-                EE_Error::add_error(
825
-                    __('Your Registration and Transaction information could not be retrieved from the db.',
826
-                        'event_espresso'),
827
-                    __FILE__, __FUNCTION__, __LINE__
828
-                );
829
-                $this->checkout->transaction = EE_Transaction::new_instance();
830
-                // add some style and make it dance
831
-                $this->add_styles_and_scripts();
832
-                EED_Single_Page_Checkout::$_initialized = true;
833
-                return false;
834
-            }
835
-            // and the registrations for the transaction
836
-            $this->_get_registrations($this->checkout->transaction);
837
-        }
838
-        return true;
839
-    }
840
-
841
-
842
-
843
-    /**
844
-     * _get_transaction_and_cart_for_previous_visit
845
-     *
846
-     * @access private
847
-     * @return mixed EE_Transaction|NULL
848
-     */
849
-    private function _get_transaction_and_cart_for_previous_visit()
850
-    {
851
-        /** @var $TXN_model EEM_Transaction */
852
-        $TXN_model = EE_Registry::instance()->load_model('Transaction');
853
-        // because the reg_url_link is present in the request, this is a return visit to SPCO, so we'll get the transaction data from the db
854
-        $transaction = $TXN_model->get_transaction_from_reg_url_link($this->checkout->reg_url_link);
855
-        // verify transaction
856
-        if ($transaction instanceof EE_Transaction) {
857
-            // and get the cart that was used for that transaction
858
-            $this->checkout->cart = $this->_get_cart_for_transaction($transaction);
859
-            return $transaction;
860
-        } else {
861
-            EE_Error::add_error(__('Your Registration and Transaction information could not be retrieved from the db.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
862
-            return null;
863
-        }
864
-    }
865
-
866
-
867
-
868
-    /**
869
-     * _get_cart_for_transaction
870
-     *
871
-     * @access private
872
-     * @param EE_Transaction $transaction
873
-     * @return EE_Cart
874
-     */
875
-    private function _get_cart_for_transaction($transaction)
876
-    {
877
-        return $this->checkout->get_cart_for_transaction($transaction);
878
-    }
879
-
880
-
881
-
882
-    /**
883
-     * get_cart_for_transaction
884
-     *
885
-     * @access public
886
-     * @param EE_Transaction $transaction
887
-     * @return EE_Cart
888
-     */
889
-    public function get_cart_for_transaction(EE_Transaction $transaction)
890
-    {
891
-        return $this->checkout->get_cart_for_transaction($transaction);
892
-    }
893
-
894
-
895
-
896
-    /**
897
-     * _get_transaction_and_cart_for_current_session
898
-     *    generates a new EE_Transaction object and adds it to the $_transaction property.
899
-     *
900
-     * @access private
901
-     * @return EE_Transaction
902
-     * @throws \EE_Error
903
-     */
904
-    private function _get_cart_for_current_session_and_setup_new_transaction()
905
-    {
906
-        //  if there's no transaction, then this is the FIRST visit to SPCO
907
-        // so load up the cart ( passing nothing for the TXN because it doesn't exist yet )
908
-        $this->checkout->cart = $this->_get_cart_for_transaction(null);
909
-        // and then create a new transaction
910
-        $transaction = $this->_initialize_transaction();
911
-        // verify transaction
912
-        if ($transaction instanceof EE_Transaction) {
913
-            // save it so that we have an ID for other objects to use
914
-            $transaction->save();
915
-            // and save TXN data to the cart
916
-            $this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn($transaction->ID());
917
-        } else {
918
-            EE_Error::add_error(__('A Valid Transaction could not be initialized.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
919
-        }
920
-        return $transaction;
921
-    }
922
-
923
-
924
-
925
-    /**
926
-     *    generates a new EE_Transaction object and adds it to the $_transaction property.
927
-     *
928
-     * @access private
929
-     * @return mixed EE_Transaction|NULL
930
-     */
931
-    private function _initialize_transaction()
932
-    {
933
-        try {
934
-            // ensure cart totals have been calculated
935
-            $this->checkout->cart->get_grand_total()->recalculate_total_including_taxes();
936
-            // grab the cart grand total
937
-            $cart_total = $this->checkout->cart->get_cart_grand_total();
938
-            // create new TXN
939
-            $transaction = EE_Transaction::new_instance(
940
-                array(
941
-                    'TXN_reg_steps' => $this->checkout->initialize_txn_reg_steps_array(),
942
-                    'TXN_total'     => $cart_total > 0 ? $cart_total : 0,
943
-                    'TXN_paid'      => 0,
944
-                    'STS_ID'        => EEM_Transaction::failed_status_code,
945
-                )
946
-            );
947
-            // save it so that we have an ID for other objects to use
948
-            $transaction->save();
949
-            // set cron job for following up on TXNs after their session has expired
950
-            EE_Cron_Tasks::schedule_expired_transaction_check(
951
-                EE_Registry::instance()->SSN->expiration() + 1,
952
-                $transaction->ID()
953
-            );
954
-            return $transaction;
955
-        } catch (Exception $e) {
956
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
957
-        }
958
-        return null;
959
-    }
960
-
961
-
962
-
963
-    /**
964
-     * _get_registrations
965
-     *
966
-     * @access private
967
-     * @param EE_Transaction $transaction
968
-     * @return void
969
-     * @throws \EventEspresso\core\exceptions\InvalidEntityException
970
-     * @throws \EE_Error
971
-     */
972
-    private function _get_registrations(EE_Transaction $transaction)
973
-    {
974
-        // first step: grab the registrants  { : o
975
-        $registrations = $transaction->registrations($this->checkout->reg_cache_where_params, true);
976
-        // verify registrations have been set
977
-        if (empty($registrations)) {
978
-            // if no cached registrations, then check the db
979
-            $registrations = $transaction->registrations($this->checkout->reg_cache_where_params, false);
980
-            // still nothing ? well as long as this isn't a revisit
981
-            if (empty($registrations) && ! $this->checkout->revisit) {
982
-                // generate new registrations from scratch
983
-                $registrations = $this->_initialize_registrations($transaction);
984
-            }
985
-        }
986
-        // sort by their original registration order
987
-        usort($registrations, array('EED_Single_Page_Checkout', 'sort_registrations_by_REG_count'));
988
-        // then loop thru the array
989
-        foreach ($registrations as $registration) {
990
-            // verify each registration
991
-            if ($registration instanceof EE_Registration) {
992
-                // we display all attendee info for the primary registrant
993
-                if ($this->checkout->reg_url_link === $registration->reg_url_link()
994
-                    && $registration->is_primary_registrant()
995
-                ) {
996
-                    $this->checkout->primary_revisit = true;
997
-                    break;
998
-                } else if ($this->checkout->revisit
999
-                           && $this->checkout->reg_url_link !== $registration->reg_url_link()
1000
-                ) {
1001
-                    // but hide info if it doesn't belong to you
1002
-                    $transaction->clear_cache('Registration', $registration->ID());
1003
-                }
1004
-                $this->checkout->set_reg_status_updated($registration->ID(), false);
1005
-            }
1006
-        }
1007
-    }
1008
-
1009
-
1010
-
1011
-    /**
1012
-     *    adds related EE_Registration objects for each ticket in the cart to the current EE_Transaction object
1013
-     *
1014
-     * @access private
1015
-     * @param EE_Transaction $transaction
1016
-     * @return    array
1017
-     * @throws \EventEspresso\core\exceptions\InvalidEntityException
1018
-     * @throws \EE_Error
1019
-     */
1020
-    private function _initialize_registrations(EE_Transaction $transaction)
1021
-    {
1022
-        $att_nmbr = 0;
1023
-        $registrations = array();
1024
-        if ($transaction instanceof EE_Transaction) {
1025
-            /** @type EE_Registration_Processor $registration_processor */
1026
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
1027
-            $this->checkout->total_ticket_count = $this->checkout->cart->all_ticket_quantity_count();
1028
-            // now let's add the cart items to the $transaction
1029
-            foreach ($this->checkout->cart->get_tickets() as $line_item) {
1030
-                //do the following for each ticket of this type they selected
1031
-                for ($x = 1; $x <= $line_item->quantity(); $x++) {
1032
-                    $att_nmbr++;
1033
-                    /** @var EventEspresso\core\services\commands\registration\CreateRegistrationCommand $CreateRegistrationCommand */
1034
-                    $CreateRegistrationCommand = EE_Registry::instance()
1035
-                                                            ->create(
1036
-                                                                'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
1037
-                                                                array(
1038
-                                                                    $transaction,
1039
-                                                                    $line_item,
1040
-                                                                    $att_nmbr,
1041
-                                                                    $this->checkout->total_ticket_count,
1042
-                                                                )
1043
-                                                            );
1044
-                    // override capabilities for frontend registrations
1045
-                    if ( ! is_admin()) {
1046
-                        $CreateRegistrationCommand->setCapCheck(
1047
-                            new PublicCapabilities('', 'create_new_registration')
1048
-                        );
1049
-                    }
1050
-                    $registration = EE_Registry::instance()->BUS->execute($CreateRegistrationCommand);
1051
-                    if ( ! $registration instanceof EE_Registration) {
1052
-                        throw new InvalidEntityException($registration, 'EE_Registration');
1053
-                    }
1054
-                    $registrations[ $registration->ID() ] = $registration;
1055
-                }
1056
-            }
1057
-            $registration_processor->fix_reg_final_price_rounding_issue($transaction);
1058
-        }
1059
-        return $registrations;
1060
-    }
1061
-
1062
-
1063
-
1064
-    /**
1065
-     * sorts registrations by REG_count
1066
-     *
1067
-     * @access public
1068
-     * @param EE_Registration $reg_A
1069
-     * @param EE_Registration $reg_B
1070
-     * @return int
1071
-     */
1072
-    public static function sort_registrations_by_REG_count(EE_Registration $reg_A, EE_Registration $reg_B)
1073
-    {
1074
-        // this shouldn't ever happen within the same TXN, but oh well
1075
-        if ($reg_A->count() === $reg_B->count()) {
1076
-            return 0;
1077
-        }
1078
-        return ($reg_A->count() > $reg_B->count()) ? 1 : -1;
1079
-    }
1080
-
1081
-
1082
-
1083
-    /**
1084
-     *    _final_verifications
1085
-     * just makes sure that everything is set up correctly before proceeding
1086
-     *
1087
-     * @access    private
1088
-     * @return    bool
1089
-     * @throws \EE_Error
1090
-     */
1091
-    private function _final_verifications()
1092
-    {
1093
-        // filter checkout
1094
-        $this->checkout = apply_filters('FHEE__EED_Single_Page_Checkout___final_verifications__checkout', $this->checkout);
1095
-        //verify that current step is still set correctly
1096
-        if ( ! $this->checkout->current_step instanceof EE_SPCO_Reg_Step) {
1097
-            EE_Error::add_error(
1098
-                __('We\'re sorry but the registration process can not proceed because one or more registration steps were not setup correctly. Please refresh the page and try again or contact support.', 'event_espresso'),
1099
-                __FILE__,
1100
-                __FUNCTION__,
1101
-                __LINE__
1102
-            );
1103
-            return false;
1104
-        }
1105
-        // if returning to SPCO, then verify that primary registrant is set
1106
-        if ( ! empty($this->checkout->reg_url_link)) {
1107
-            $valid_registrant = $this->checkout->transaction->primary_registration();
1108
-            if ( ! $valid_registrant instanceof EE_Registration) {
1109
-                EE_Error::add_error(
1110
-                    __('We\'re sorry but there appears to be an error with the "reg_url_link" or the primary registrant for this transaction. Please refresh the page and try again or contact support.', 'event_espresso'),
1111
-                    __FILE__,
1112
-                    __FUNCTION__,
1113
-                    __LINE__
1114
-                );
1115
-                return false;
1116
-            }
1117
-            $valid_registrant = null;
1118
-            foreach ($this->checkout->transaction->registrations($this->checkout->reg_cache_where_params) as $registration) {
1119
-                if (
1120
-                    $registration instanceof EE_Registration
1121
-                    && $registration->reg_url_link() === $this->checkout->reg_url_link
1122
-                ) {
1123
-                    $valid_registrant = $registration;
1124
-                }
1125
-            }
1126
-            if ( ! $valid_registrant instanceof EE_Registration) {
1127
-                // hmmm... maybe we have the wrong session because the user is opening multiple tabs ?
1128
-                if (EED_Single_Page_Checkout::$_checkout_verified) {
1129
-                    // clear the session, mark the checkout as unverified, and try again
1130
-                    EE_Registry::instance()->SSN->clear_session();
1131
-                    EED_Single_Page_Checkout::$_initialized = false;
1132
-                    EED_Single_Page_Checkout::$_checkout_verified = false;
1133
-                    $this->_initialize();
1134
-                    EE_Error::reset_notices();
1135
-                    return false;
1136
-                }
1137
-                EE_Error::add_error(
1138
-                    __('We\'re sorry but there appears to be an error with the "reg_url_link" or the transaction itself. Please refresh the page and try again or contact support.', 'event_espresso'),
1139
-                    __FILE__,
1140
-                    __FUNCTION__,
1141
-                    __LINE__
1142
-                );
1143
-                return false;
1144
-            }
1145
-        }
1146
-        // now that things have been kinda sufficiently verified,
1147
-        // let's add the checkout to the session so that's available other systems
1148
-        EE_Registry::instance()->SSN->set_checkout($this->checkout);
1149
-        return true;
1150
-    }
1151
-
1152
-
1153
-
1154
-    /**
1155
-     *    _initialize_reg_steps
1156
-     * first makes sure that EE_Transaction_Processor::set_reg_step_initiated() is called as required
1157
-     * then loops thru all of the active reg steps and calls the initialize_reg_step() method
1158
-     *
1159
-     * @access    private
1160
-     * @param bool $reinitializing
1161
-     * @throws \EE_Error
1162
-     */
1163
-    private function _initialize_reg_steps($reinitializing = false)
1164
-    {
1165
-        $this->checkout->set_reg_step_initiated($this->checkout->current_step);
1166
-        // loop thru all steps to call their individual "initialize" methods and set i18n strings for JS
1167
-        foreach ($this->checkout->reg_steps as $reg_step) {
1168
-            if ( ! $reg_step->initialize_reg_step()) {
1169
-                // if not initialized then maybe this step is being removed...
1170
-                if ( ! $reinitializing && $reg_step->is_current_step()) {
1171
-                    // if it was the current step, then we need to start over here
1172
-                    $this->_initialize_reg_steps(true);
1173
-                    return;
1174
-                }
1175
-                continue;
1176
-            }
1177
-            // add css and JS for current step
1178
-            $reg_step->enqueue_styles_and_scripts();
1179
-            // i18n
1180
-            $reg_step->translate_js_strings();
1181
-            if ($reg_step->is_current_step()) {
1182
-                // the text that appears on the reg step form submit button
1183
-                $reg_step->set_submit_button_text();
1184
-            }
1185
-        }
1186
-        // dynamically creates hook point like: AHEE__Single_Page_Checkout___initialize_reg_step__attendee_information
1187
-        do_action("AHEE__Single_Page_Checkout___initialize_reg_step__{$this->checkout->current_step->slug()}", $this->checkout->current_step);
1188
-    }
1189
-
1190
-
1191
-
1192
-    /**
1193
-     * _check_form_submission
1194
-     *
1195
-     * @access private
1196
-     * @return boolean
1197
-     */
1198
-    private function _check_form_submission()
1199
-    {
1200
-        //does this request require the reg form to be generated ?
1201
-        if ($this->checkout->generate_reg_form) {
1202
-            // ever heard that song by Blue Rodeo ?
1203
-            try {
1204
-                $this->checkout->current_step->reg_form = $this->checkout->current_step->generate_reg_form();
1205
-                // if not displaying a form, then check for form submission
1206
-                if (
1207
-                    $this->checkout->process_form_submission
1208
-                    && $this->checkout->current_step->reg_form->was_submitted()
1209
-                ) {
1210
-                    // clear out any old data in case this step is being run again
1211
-                    $this->checkout->current_step->set_valid_data(array());
1212
-                    // capture submitted form data
1213
-                    $this->checkout->current_step->reg_form->receive_form_submission(
1214
-                        apply_filters('FHEE__Single_Page_Checkout___check_form_submission__request_params', EE_Registry::instance()->REQ->params(), $this->checkout)
1215
-                    );
1216
-                    // validate submitted form data
1217
-                    if ( ! $this->checkout->continue_reg || ! $this->checkout->current_step->reg_form->is_valid()) {
1218
-                        // thou shall not pass !!!
1219
-                        $this->checkout->continue_reg = false;
1220
-                        // any form validation errors?
1221
-                        if ($this->checkout->current_step->reg_form->submission_error_message() !== '') {
1222
-                            $submission_error_messages = array();
1223
-                            // bad, bad, bad registrant
1224
-                            foreach ($this->checkout->current_step->reg_form->get_validation_errors_accumulated() as $validation_error) {
1225
-                                if ($validation_error instanceof EE_Validation_Error) {
1226
-                                    $submission_error_messages[] = sprintf(
1227
-                                        __('%s : %s', 'event_espresso'),
1228
-                                        $validation_error->get_form_section()->html_label_text(),
1229
-                                        $validation_error->getMessage()
1230
-                                    );
1231
-                                }
1232
-                            }
1233
-                            EE_Error::add_error(implode('<br />', $submission_error_messages), __FILE__, __FUNCTION__, __LINE__);
1234
-                        }
1235
-                        // well not really... what will happen is we'll just get redirected back to redo the current step
1236
-                        $this->go_to_next_step();
1237
-                        return false;
1238
-                    }
1239
-                }
1240
-            } catch (EE_Error $e) {
1241
-                $e->get_error();
1242
-            }
1243
-        }
1244
-        return true;
1245
-    }
1246
-
1247
-
1248
-
1249
-    /**
1250
-     * _process_action
1251
-     *
1252
-     * @access private
1253
-     * @return void
1254
-     * @throws \EE_Error
1255
-     */
1256
-    private function _process_form_action()
1257
-    {
1258
-        // what cha wanna do?
1259
-        switch ($this->checkout->action) {
1260
-            // AJAX next step reg form
1261
-            case 'display_spco_reg_step' :
1262
-                $this->checkout->redirect = false;
1263
-                if (EE_Registry::instance()->REQ->ajax) {
1264
-                    $this->checkout->json_response->set_reg_step_html($this->checkout->current_step->display_reg_form());
1265
-                }
1266
-                break;
1267
-            default :
1268
-                // meh... do one of those other steps first
1269
-                if ( ! empty($this->checkout->action) && is_callable(array($this->checkout->current_step, $this->checkout->action))) {
1270
-                    // dynamically creates hook point like: AHEE__Single_Page_Checkout__before_attendee_information__process_reg_step
1271
-                    do_action("AHEE__Single_Page_Checkout__before_{$this->checkout->current_step->slug()}__{$this->checkout->action}", $this->checkout->current_step);
1272
-                    // call action on current step
1273
-                    if (call_user_func(array($this->checkout->current_step, $this->checkout->action))) {
1274
-                        // good registrant, you get to proceed
1275
-                        if (
1276
-                            $this->checkout->current_step->success_message() !== ''
1277
-                            && apply_filters(
1278
-                                'FHEE__Single_Page_Checkout___process_form_action__display_success',
1279
-                                false
1280
-                            )
1281
-                        ) {
1282
-                            EE_Error::add_success(
1283
-                                $this->checkout->current_step->success_message()
1284
-                                . '<br />' . $this->checkout->next_step->_instructions()
1285
-                            );
1286
-                        }
1287
-                        // pack it up, pack it in...
1288
-                        $this->_setup_redirect();
1289
-                    }
1290
-                    // dynamically creates hook point like: AHEE__Single_Page_Checkout__after_payment_options__process_reg_step
1291
-                    do_action("AHEE__Single_Page_Checkout__after_{$this->checkout->current_step->slug()}__{$this->checkout->action}", $this->checkout->current_step);
1292
-                } else {
1293
-                    EE_Error::add_error(
1294
-                        sprintf(
1295
-                            __('The requested form action "%s" does not exist for the current "%s" registration step.', 'event_espresso'),
1296
-                            $this->checkout->action,
1297
-                            $this->checkout->current_step->name()
1298
-                        ),
1299
-                        __FILE__,
1300
-                        __FUNCTION__,
1301
-                        __LINE__
1302
-                    );
1303
-                }
1304
-            // end default
1305
-        }
1306
-        // store our progress so far
1307
-        $this->checkout->stash_transaction_and_checkout();
1308
-        // advance to the next step! If you pass GO, collect $200
1309
-        $this->go_to_next_step();
1310
-    }
1311
-
1312
-
1313
-
1314
-    /**
1315
-     *        add_styles_and_scripts
1316
-     *
1317
-     * @access        public
1318
-     * @return        void
1319
-     */
1320
-    public function add_styles_and_scripts()
1321
-    {
1322
-        // i18n
1323
-        $this->translate_js_strings();
1324
-        if ($this->checkout->admin_request) {
1325
-            add_action('admin_enqueue_scripts', array($this, 'enqueue_styles_and_scripts'), 10);
1326
-        } else {
1327
-            add_action('wp_enqueue_scripts', array($this, 'enqueue_styles_and_scripts'), 10);
1328
-        }
1329
-    }
1330
-
1331
-
1332
-
1333
-    /**
1334
-     *        translate_js_strings
1335
-     *
1336
-     * @access        public
1337
-     * @return        void
1338
-     */
1339
-    public function translate_js_strings()
1340
-    {
1341
-        EE_Registry::$i18n_js_strings['revisit'] = $this->checkout->revisit;
1342
-        EE_Registry::$i18n_js_strings['e_reg_url_link'] = $this->checkout->reg_url_link;
1343
-        EE_Registry::$i18n_js_strings['server_error'] = __('An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.', 'event_espresso');
1344
-        EE_Registry::$i18n_js_strings['invalid_json_response'] = __('An invalid response was returned from the server while attempting to process your request. Please refresh the page and try again or contact support.', 'event_espresso');
1345
-        EE_Registry::$i18n_js_strings['validation_error'] = __('There appears to be a problem with the form validation configuration! Please check the admin settings or contact support.', 'event_espresso');
1346
-        EE_Registry::$i18n_js_strings['invalid_payment_method'] = __('There appears to be a problem with the payment method configuration! Please refresh the page and try again or contact support.', 'event_espresso');
1347
-        EE_Registry::$i18n_js_strings['reg_step_error'] = __('This registration step could not be completed. Please refresh the page and try again.', 'event_espresso');
1348
-        EE_Registry::$i18n_js_strings['invalid_coupon'] = __('We\'re sorry but that coupon code does not appear to be valid. If this is incorrect, please contact the site administrator.', 'event_espresso');
1349
-        EE_Registry::$i18n_js_strings['process_registration'] = sprintf(
1350
-            __('Please wait while we process your registration.%sDo not refresh the page or navigate away while this is happening.%sThank you for your patience.', 'event_espresso'),
1351
-            '<br/>',
1352
-            '<br/>'
1353
-        );
1354
-        EE_Registry::$i18n_js_strings['language'] = get_bloginfo('language');
1355
-        EE_Registry::$i18n_js_strings['EESID'] = EE_Registry::instance()->SSN->id();
1356
-        EE_Registry::$i18n_js_strings['currency'] = EE_Registry::instance()->CFG->currency;
1357
-        EE_Registry::$i18n_js_strings['datepicker_yearRange'] = '-150:+20';
1358
-        EE_Registry::$i18n_js_strings['timer_years'] = __('years', 'event_espresso');
1359
-        EE_Registry::$i18n_js_strings['timer_months'] = __('months', 'event_espresso');
1360
-        EE_Registry::$i18n_js_strings['timer_weeks'] = __('weeks', 'event_espresso');
1361
-        EE_Registry::$i18n_js_strings['timer_days'] = __('days', 'event_espresso');
1362
-        EE_Registry::$i18n_js_strings['timer_hours'] = __('hours', 'event_espresso');
1363
-        EE_Registry::$i18n_js_strings['timer_minutes'] = __('minutes', 'event_espresso');
1364
-        EE_Registry::$i18n_js_strings['timer_seconds'] = __('seconds', 'event_espresso');
1365
-        EE_Registry::$i18n_js_strings['timer_year'] = __('year', 'event_espresso');
1366
-        EE_Registry::$i18n_js_strings['timer_month'] = __('month', 'event_espresso');
1367
-        EE_Registry::$i18n_js_strings['timer_week'] = __('week', 'event_espresso');
1368
-        EE_Registry::$i18n_js_strings['timer_day'] = __('day', 'event_espresso');
1369
-        EE_Registry::$i18n_js_strings['timer_hour'] = __('hour', 'event_espresso');
1370
-        EE_Registry::$i18n_js_strings['timer_minute'] = __('minute', 'event_espresso');
1371
-        EE_Registry::$i18n_js_strings['timer_second'] = __('second', 'event_espresso');
1372
-        EE_Registry::$i18n_js_strings['registration_expiration_notice'] = sprintf(
1373
-            __(
1374
-                '%1$sWe\'re sorry, but your registration time has expired.%2$s%3$s%4$sIf you still wish to complete your registration, please return to the %5$sEvent List%6$sEvent List%7$s and reselect your tickets if available. Please except our apologies for any inconvenience this may have caused.%8$s',
1375
-                'event_espresso'
1376
-            ),
1377
-            '<h4 class="important-notice">',
1378
-            '</h4>',
1379
-            '<br />',
1380
-            '<p>',
1381
-            '<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
1382
-            '">',
1383
-            '</a>',
1384
-            '</p>'
1385
-        );
1386
-        EE_Registry::$i18n_js_strings['ajax_submit'] = apply_filters('FHEE__Single_Page_Checkout__translate_js_strings__ajax_submit', true);
1387
-        EE_Registry::$i18n_js_strings['session_extension'] = absint(
1388
-            apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS)
1389
-        );
1390
-        EE_Registry::$i18n_js_strings['session_expiration'] = gmdate(
1391
-            'M d, Y H:i:s', EE_Registry::instance()->SSN->expiration() + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1392
-        );
1393
-    }
1394
-
1395
-
1396
-
1397
-    /**
1398
-     *    enqueue_styles_and_scripts
1399
-     *
1400
-     * @access        public
1401
-     * @return        void
1402
-     * @throws \EE_Error
1403
-     */
1404
-    public function enqueue_styles_and_scripts()
1405
-    {
1406
-        // load css
1407
-        wp_register_style('single_page_checkout', SPCO_CSS_URL . 'single_page_checkout.css', array(), EVENT_ESPRESSO_VERSION);
1408
-        wp_enqueue_style('single_page_checkout');
1409
-        // load JS
1410
-        wp_register_script('jquery_plugin', EE_THIRD_PARTY_URL . 'jquery	.plugin.min.js', array('jquery'), '1.0.1', true);
1411
-        wp_register_script('jquery_countdown', EE_THIRD_PARTY_URL . 'jquery	.countdown.min.js', array('jquery_plugin'), '2.0.2', true);
1412
-        wp_register_script('single_page_checkout', SPCO_JS_URL . 'single_page_checkout.js', array('espresso_core', 'underscore', 'ee_form_section_validation', 'jquery_countdown'), EVENT_ESPRESSO_VERSION, true);
1413
-        $this->checkout->registration_form->enqueue_js();
1414
-        $this->checkout->current_step->reg_form->enqueue_js();
1415
-        wp_enqueue_script('single_page_checkout');
1416
-        /**
1417
-         * global action hook for enqueueing styles and scripts with
1418
-         * spco calls.
1419
-         */
1420
-        do_action('AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts', $this);
1421
-        /**
1422
-         * dynamic action hook for enqueueing styles and scripts with spco calls.
1423
-         * The hook will end up being something like AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__attendee_information
1424
-         */
1425
-        do_action('AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__' . $this->checkout->current_step->slug(), $this);
1426
-    }
1427
-
1428
-
1429
-
1430
-    /**
1431
-     *    display the Registration Single Page Checkout Form
1432
-     *
1433
-     * @access    private
1434
-     * @return    void
1435
-     * @throws \EE_Error
1436
-     */
1437
-    private function _display_spco_reg_form()
1438
-    {
1439
-        // if registering via the admin, just display the reg form for the current step
1440
-        if ($this->checkout->admin_request) {
1441
-            EE_Registry::instance()->REQ->add_output($this->checkout->current_step->display_reg_form());
1442
-        } else {
1443
-            // add powered by EE msg
1444
-            add_action('AHEE__SPCO__reg_form_footer', array('EED_Single_Page_Checkout', 'display_registration_footer'));
1445
-            $empty_cart = count($this->checkout->transaction->registrations($this->checkout->reg_cache_where_params)) < 1
1446
-                ? true
1447
-                : false;
1448
-            EE_Registry::$i18n_js_strings['empty_cart'] = $empty_cart;
1449
-            $cookies_not_set_msg = '';
1450
-            if ($empty_cart && ! isset($_COOKIE['ee_cookie_test'])) {
1451
-                $cookies_not_set_msg = apply_filters(
1452
-                    'FHEE__Single_Page_Checkout__display_spco_reg_form__cookies_not_set_msg',
1453
-                    sprintf(
1454
-                        __(
1455
-                            '%1$s%3$sIt appears your browser is not currently set to accept Cookies%4$s%5$sIn order to register for events, you need to enable cookies.%7$sIf you require assistance, then click the following link to learn how to %8$senable cookies%9$s%6$s%2$s',
1456
-                            'event_espresso'
1457
-                        ),
1458
-                        '<div class="ee-attention">',
1459
-                        '</div>',
1460
-                        '<h6 class="important-notice">',
1461
-                        '</h6>',
1462
-                        '<p>',
1463
-                        '</p>',
1464
-                        '<br />',
1465
-                        '<a href="http://www.whatarecookies.com/enable.asp" target="_blank">',
1466
-                        '</a>'
1467
-                    )
1468
-                );
1469
-            }
1470
-            $this->checkout->registration_form = new EE_Form_Section_Proper(
1471
-                array(
1472
-                    'name'            => 'single-page-checkout',
1473
-                    'html_id'         => 'ee-single-page-checkout-dv',
1474
-                    'layout_strategy' =>
1475
-                        new EE_Template_Layout(
1476
-                            array(
1477
-                                'layout_template_file' => SPCO_TEMPLATES_PATH . 'registration_page_wrapper.template.php',
1478
-                                'template_args'        => array(
1479
-                                    'empty_cart'              => $empty_cart,
1480
-                                    'revisit'                 => $this->checkout->revisit,
1481
-                                    'reg_steps'               => $this->checkout->reg_steps,
1482
-                                    'next_step'               => $this->checkout->next_step instanceof EE_SPCO_Reg_Step
1483
-                                        ? $this->checkout->next_step->slug()
1484
-                                        : '',
1485
-                                    'cancel_page_url'         => $this->checkout->cancel_page_url,
1486
-                                    'empty_msg'               => apply_filters(
1487
-                                        'FHEE__Single_Page_Checkout__display_spco_reg_form__empty_msg',
1488
-                                        sprintf(
1489
-                                            __('You need to %1$sReturn to Events list%2$sselect at least one event%3$s before you can proceed with the registration process.',
1490
-                                                'event_espresso'),
1491
-                                            '<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
1492
-                                            '">',
1493
-                                            '</a>'
1494
-                                        )
1495
-                                    ),
1496
-                                    'cookies_not_set_msg'     => $cookies_not_set_msg,
1497
-                                    'registration_time_limit' => $this->checkout->get_registration_time_limit(),
1498
-                                    'session_expiration'      =>
1499
-                                        date('M d, Y H:i:s', EE_Registry::instance()->SSN->expiration() + (get_option('gmt_offset') * HOUR_IN_SECONDS)),
1500
-                                ),
1501
-                            )
1502
-                        ),
1503
-                )
1504
-            );
1505
-            // load template and add to output sent that gets filtered into the_content()
1506
-            EE_Registry::instance()->REQ->add_output($this->checkout->registration_form->get_html());
1507
-        }
1508
-    }
1509
-
1510
-
1511
-
1512
-    /**
1513
-     *    add_extra_finalize_registration_inputs
1514
-     *
1515
-     * @access    public
1516
-     * @param $next_step
1517
-     * @internal  param string $label
1518
-     * @return void
1519
-     */
1520
-    public function add_extra_finalize_registration_inputs($next_step)
1521
-    {
1522
-        if ($next_step === 'finalize_registration') {
1523
-            echo '<div id="spco-extra-finalize_registration-inputs-dv"></div>';
1524
-        }
1525
-    }
1526
-
1527
-
1528
-
1529
-    /**
1530
-     *    display_registration_footer
1531
-     *
1532
-     * @access    public
1533
-     * @return    string
1534
-     */
1535
-    public static function display_registration_footer()
1536
-    {
1537
-        if (
1538
-        apply_filters(
1539
-            'FHEE__EE_Front__Controller__show_reg_footer',
1540
-            EE_Registry::instance()->CFG->admin->show_reg_footer
1541
-        )
1542
-        ) {
1543
-            add_filter(
1544
-                'FHEE__EEH_Template__powered_by_event_espresso__url',
1545
-                function ($url) {
1546
-                    return apply_filters('FHEE__EE_Front_Controller__registration_footer__url', $url);
1547
-                }
1548
-            );
1549
-            echo apply_filters(
1550
-                'FHEE__EE_Front_Controller__display_registration_footer',
1551
-                \EEH_Template::powered_by_event_espresso(
1552
-                    '',
1553
-                    'espresso-registration-footer-dv',
1554
-                    array('utm_content' => 'registration_checkout')
1555
-                )
1556
-            );
1557
-        }
1558
-        return '';
1559
-    }
1560
-
1561
-
1562
-
1563
-    /**
1564
-     *    unlock_transaction
1565
-     *
1566
-     * @access    public
1567
-     * @return    void
1568
-     * @throws \EE_Error
1569
-     */
1570
-    public function unlock_transaction()
1571
-    {
1572
-        if ($this->checkout->transaction instanceof EE_Transaction) {
1573
-            $this->checkout->transaction->unlock();
1574
-        }
1575
-    }
1576
-
1577
-
1578
-
1579
-    /**
1580
-     *        _setup_redirect
1581
-     *
1582
-     * @access    private
1583
-     * @return void
1584
-     */
1585
-    private function _setup_redirect()
1586
-    {
1587
-        if ($this->checkout->continue_reg && $this->checkout->next_step instanceof EE_SPCO_Reg_Step) {
1588
-            $this->checkout->redirect = true;
1589
-            if (empty($this->checkout->redirect_url)) {
1590
-                $this->checkout->redirect_url = $this->checkout->next_step->reg_step_url();
1591
-            }
1592
-            $this->checkout->redirect_url = apply_filters(
1593
-                'FHEE__EED_Single_Page_Checkout___setup_redirect__checkout_redirect_url',
1594
-                $this->checkout->redirect_url,
1595
-                $this->checkout
1596
-            );
1597
-        }
1598
-    }
1599
-
1600
-
1601
-
1602
-    /**
1603
-     *   handle ajax message responses and redirects
1604
-     *
1605
-     * @access public
1606
-     * @return void
1607
-     * @throws \EE_Error
1608
-     */
1609
-    public function go_to_next_step()
1610
-    {
1611
-        if (EE_Registry::instance()->REQ->ajax) {
1612
-            // capture contents of output buffer we started earlier in the request, and insert into JSON response
1613
-            $this->checkout->json_response->set_unexpected_errors(ob_get_clean());
1614
-        }
1615
-        $this->unlock_transaction();
1616
-        // just return for these conditions
1617
-        if (
1618
-            $this->checkout->admin_request
1619
-            || $this->checkout->action === 'redirect_form'
1620
-            || $this->checkout->action === 'update_checkout'
1621
-        ) {
1622
-            return;
1623
-        }
1624
-        // AJAX response
1625
-        $this->_handle_json_response();
1626
-        // redirect to next step or the Thank You page
1627
-        $this->_handle_html_redirects();
1628
-        // hmmm... must be something wrong, so let's just display the form again !
1629
-        $this->_display_spco_reg_form();
1630
-    }
1631
-
1632
-
1633
-
1634
-    /**
1635
-     *   _handle_json_response
1636
-     *
1637
-     * @access protected
1638
-     * @return void
1639
-     */
1640
-    protected function _handle_json_response()
1641
-    {
1642
-        // if this is an ajax request
1643
-        if (EE_Registry::instance()->REQ->ajax) {
1644
-            // DEBUG LOG
1645
-            //$this->checkout->log(
1646
-            //	__CLASS__, __FUNCTION__, __LINE__,
1647
-            //	array(
1648
-            //		'json_response_redirect_url' => $this->checkout->json_response->redirect_url(),
1649
-            //		'redirect'                   => $this->checkout->redirect,
1650
-            //		'continue_reg'               => $this->checkout->continue_reg,
1651
-            //	)
1652
-            //);
1653
-            $this->checkout->json_response->set_registration_time_limit(
1654
-                $this->checkout->get_registration_time_limit()
1655
-            );
1656
-            $this->checkout->json_response->set_payment_amount($this->checkout->amount_owing);
1657
-            // just send the ajax (
1658
-            $json_response = apply_filters(
1659
-                'FHEE__EE_Single_Page_Checkout__JSON_response',
1660
-                $this->checkout->json_response
1661
-            );
1662
-            echo $json_response;
1663
-            exit();
1664
-        }
1665
-    }
1666
-
1667
-
1668
-
1669
-    /**
1670
-     *   _handle_redirects
1671
-     *
1672
-     * @access protected
1673
-     * @return void
1674
-     */
1675
-    protected function _handle_html_redirects()
1676
-    {
1677
-        // going somewhere ?
1678
-        if ($this->checkout->redirect && ! empty($this->checkout->redirect_url)) {
1679
-            // store notices in a transient
1680
-            EE_Error::get_notices(false, true, true);
1681
-            // DEBUG LOG
1682
-            //$this->checkout->log(
1683
-            //	__CLASS__, __FUNCTION__, __LINE__,
1684
-            //	array(
1685
-            //		'headers_sent' => headers_sent(),
1686
-            //		'redirect_url'     => $this->checkout->redirect_url,
1687
-            //		'headers_list'    => headers_list(),
1688
-            //	)
1689
-            //);
1690
-            wp_safe_redirect($this->checkout->redirect_url);
1691
-            exit();
1692
-        }
1693
-    }
1694
-
1695
-
1696
-
1697
-    /**
1698
-     *   set_checkout_anchor
1699
-     *
1700
-     * @access public
1701
-     * @return void
1702
-     */
1703
-    public function set_checkout_anchor()
1704
-    {
1705
-        echo '<a id="checkout" style="float: left; margin-left: -999em;"></a>';
1706
-    }
20
+	/**
21
+	 * $_initialized - has the SPCO controller already been initialized ?
22
+	 *
23
+	 * @access private
24
+	 * @var bool $_initialized
25
+	 */
26
+	private static $_initialized = false;
27
+
28
+
29
+	/**
30
+	 * $_checkout_verified - is the EE_Checkout verified as correct for this request ?
31
+	 *
32
+	 * @access private
33
+	 * @var bool $_valid_checkout
34
+	 */
35
+	private static $_checkout_verified = true;
36
+
37
+	/**
38
+	 *    $_reg_steps_array - holds initial array of reg steps
39
+	 *
40
+	 * @access private
41
+	 * @var array $_reg_steps_array
42
+	 */
43
+	private static $_reg_steps_array = array();
44
+
45
+	/**
46
+	 *    $checkout - EE_Checkout object for handling the properties of the current checkout process
47
+	 *
48
+	 * @access public
49
+	 * @var EE_Checkout $checkout
50
+	 */
51
+	public $checkout;
52
+
53
+
54
+
55
+	/**
56
+	 * @return EED_Single_Page_Checkout
57
+	 */
58
+	public static function instance()
59
+	{
60
+		add_filter('EED_Single_Page_Checkout__SPCO_active', '__return_true');
61
+		return parent::get_instance(__CLASS__);
62
+	}
63
+
64
+
65
+
66
+	/**
67
+	 * @return EE_CART
68
+	 */
69
+	public function cart()
70
+	{
71
+		return $this->checkout->cart;
72
+	}
73
+
74
+
75
+
76
+	/**
77
+	 * @return EE_Transaction
78
+	 */
79
+	public function transaction()
80
+	{
81
+		return $this->checkout->transaction;
82
+	}
83
+
84
+
85
+
86
+	/**
87
+	 *    set_hooks - for hooking into EE Core, other modules, etc
88
+	 *
89
+	 * @access    public
90
+	 * @return    void
91
+	 * @throws \EE_Error
92
+	 */
93
+	public static function set_hooks()
94
+	{
95
+		EED_Single_Page_Checkout::set_definitions();
96
+	}
97
+
98
+
99
+
100
+	/**
101
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
102
+	 *
103
+	 * @access    public
104
+	 * @return    void
105
+	 * @throws \EE_Error
106
+	 */
107
+	public static function set_hooks_admin()
108
+	{
109
+		EED_Single_Page_Checkout::set_definitions();
110
+		if ( ! (defined('DOING_AJAX') && DOING_AJAX)) {
111
+			// hook into the top of pre_get_posts to set the reg step routing, which gives other modules or plugins a chance to modify the reg steps, but just before the routes get called
112
+			add_action('pre_get_posts', array('EED_Single_Page_Checkout', 'load_reg_steps'), 1);
113
+			return;
114
+		}
115
+		// going to start an output buffer in case anything gets accidentally output that might disrupt our JSON response
116
+		ob_start();
117
+		EED_Single_Page_Checkout::load_request_handler();
118
+		EED_Single_Page_Checkout::load_reg_steps();
119
+		// set ajax hooks
120
+		add_action('wp_ajax_process_reg_step', array('EED_Single_Page_Checkout', 'process_reg_step'));
121
+		add_action('wp_ajax_nopriv_process_reg_step', array('EED_Single_Page_Checkout', 'process_reg_step'));
122
+		add_action('wp_ajax_display_spco_reg_step', array('EED_Single_Page_Checkout', 'display_reg_step'));
123
+		add_action('wp_ajax_nopriv_display_spco_reg_step', array('EED_Single_Page_Checkout', 'display_reg_step'));
124
+		add_action('wp_ajax_update_reg_step', array('EED_Single_Page_Checkout', 'update_reg_step'));
125
+		add_action('wp_ajax_nopriv_update_reg_step', array('EED_Single_Page_Checkout', 'update_reg_step'));
126
+	}
127
+
128
+
129
+
130
+	/**
131
+	 *    process ajax request
132
+	 *
133
+	 * @param string $ajax_action
134
+	 * @throws \EE_Error
135
+	 */
136
+	public static function process_ajax_request($ajax_action)
137
+	{
138
+		EE_Registry::instance()->REQ->set('action', $ajax_action);
139
+		EED_Single_Page_Checkout::instance()->_initialize();
140
+	}
141
+
142
+
143
+
144
+	/**
145
+	 *    ajax display registration step
146
+	 *
147
+	 * @throws \EE_Error
148
+	 */
149
+	public static function display_reg_step()
150
+	{
151
+		EED_Single_Page_Checkout::process_ajax_request('display_spco_reg_step');
152
+	}
153
+
154
+
155
+
156
+	/**
157
+	 *    ajax process registration step
158
+	 *
159
+	 * @throws \EE_Error
160
+	 */
161
+	public static function process_reg_step()
162
+	{
163
+		EED_Single_Page_Checkout::process_ajax_request('process_reg_step');
164
+	}
165
+
166
+
167
+
168
+	/**
169
+	 *    ajax process registration step
170
+	 *
171
+	 * @throws \EE_Error
172
+	 */
173
+	public static function update_reg_step()
174
+	{
175
+		EED_Single_Page_Checkout::process_ajax_request('update_reg_step');
176
+	}
177
+
178
+
179
+
180
+	/**
181
+	 *   update_checkout
182
+	 *
183
+	 * @access public
184
+	 * @return void
185
+	 * @throws \EE_Error
186
+	 */
187
+	public static function update_checkout()
188
+	{
189
+		EED_Single_Page_Checkout::process_ajax_request('update_checkout');
190
+	}
191
+
192
+
193
+
194
+	/**
195
+	 *    load_request_handler
196
+	 *
197
+	 * @access    public
198
+	 * @return    void
199
+	 */
200
+	public static function load_request_handler()
201
+	{
202
+		// load core Request_Handler class
203
+		if ( ! isset(EE_Registry::instance()->REQ)) {
204
+			EE_Registry::instance()->load_core('Request_Handler');
205
+		}
206
+	}
207
+
208
+
209
+
210
+	/**
211
+	 *    set_definitions
212
+	 *
213
+	 * @access    public
214
+	 * @return    void
215
+	 * @throws \EE_Error
216
+	 */
217
+	public static function set_definitions()
218
+	{
219
+		define('SPCO_BASE_PATH', rtrim(str_replace(array('\\', '/'), DS, plugin_dir_path(__FILE__)), DS) . DS);
220
+		define('SPCO_CSS_URL', plugin_dir_url(__FILE__) . 'css' . DS);
221
+		define('SPCO_IMG_URL', plugin_dir_url(__FILE__) . 'img' . DS);
222
+		define('SPCO_JS_URL', plugin_dir_url(__FILE__) . 'js' . DS);
223
+		define('SPCO_INC_PATH', SPCO_BASE_PATH . 'inc' . DS);
224
+		define('SPCO_REG_STEPS_PATH', SPCO_BASE_PATH . 'reg_steps' . DS);
225
+		define('SPCO_TEMPLATES_PATH', SPCO_BASE_PATH . 'templates' . DS);
226
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(SPCO_BASE_PATH, true);
227
+		EE_Registry::$i18n_js_strings['registration_expiration_notice'] = sprintf(
228
+			__('%1$sWe\'re sorry, but you\'re registration time has expired.%2$s%4$sIf you still wish to complete your registration, please return to the %5$sEvent List%6$sEvent List%7$s and reselect your tickets if available. Please except our apologies for any inconvenience this may have caused.%8$s',
229
+				'event_espresso'),
230
+			'<h4 class="important-notice">',
231
+			'</h4>',
232
+			'<br />',
233
+			'<p>',
234
+			'<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
235
+			'">',
236
+			'</a>',
237
+			'</p>'
238
+		);
239
+	}
240
+
241
+
242
+
243
+	/**
244
+	 * load_reg_steps
245
+	 * loads and instantiates each reg step based on the EE_Registry::instance()->CFG->registration->reg_steps array
246
+	 *
247
+	 * @access    private
248
+	 * @throws EE_Error
249
+	 * @return void
250
+	 */
251
+	public static function load_reg_steps()
252
+	{
253
+		static $reg_steps_loaded = false;
254
+		if ($reg_steps_loaded) {
255
+			return;
256
+		}
257
+		// filter list of reg_steps
258
+		$reg_steps_to_load = (array)apply_filters(
259
+			'AHEE__SPCO__load_reg_steps__reg_steps_to_load',
260
+			EED_Single_Page_Checkout::get_reg_steps()
261
+		);
262
+		// sort by key (order)
263
+		ksort($reg_steps_to_load);
264
+		// loop through folders
265
+		foreach ($reg_steps_to_load as $order => $reg_step) {
266
+			// we need a
267
+			if (isset($reg_step['file_path'], $reg_step['class_name'], $reg_step['slug'])) {
268
+				// copy over to the reg_steps_array
269
+				EED_Single_Page_Checkout::$_reg_steps_array[$order] = $reg_step;
270
+				// register custom key route for each reg step
271
+				// ie: step=>"slug" - this is the entire reason we load the reg steps array now
272
+				EE_Config::register_route($reg_step['slug'], 'EED_Single_Page_Checkout', 'run', 'step');
273
+				// add AJAX or other hooks
274
+				if (isset($reg_step['has_hooks']) && $reg_step['has_hooks']) {
275
+					// setup autoloaders if necessary
276
+					if ( ! class_exists($reg_step['class_name'])) {
277
+						EEH_Autoloader::register_autoloaders_for_each_file_in_folder($reg_step['file_path'], true);
278
+					}
279
+					if (is_callable($reg_step['class_name'], 'set_hooks')) {
280
+						call_user_func(array($reg_step['class_name'], 'set_hooks'));
281
+					}
282
+				}
283
+			}
284
+		}
285
+		$reg_steps_loaded = true;
286
+	}
287
+
288
+
289
+
290
+	/**
291
+	 *    get_reg_steps
292
+	 *
293
+	 * @access    public
294
+	 * @return    array
295
+	 */
296
+	public static function get_reg_steps()
297
+	{
298
+		$reg_steps = EE_Registry::instance()->CFG->registration->reg_steps;
299
+		if (empty($reg_steps)) {
300
+			$reg_steps = array(
301
+				10  => array(
302
+					'file_path'  => SPCO_REG_STEPS_PATH . 'attendee_information',
303
+					'class_name' => 'EE_SPCO_Reg_Step_Attendee_Information',
304
+					'slug'       => 'attendee_information',
305
+					'has_hooks'  => false,
306
+				),
307
+				20  => array(
308
+					'file_path'  => SPCO_REG_STEPS_PATH . 'registration_confirmation',
309
+					'class_name' => 'EE_SPCO_Reg_Step_Registration_Confirmation',
310
+					'slug'       => 'registration_confirmation',
311
+					'has_hooks'  => false,
312
+				),
313
+				30  => array(
314
+					'file_path'  => SPCO_REG_STEPS_PATH . 'payment_options',
315
+					'class_name' => 'EE_SPCO_Reg_Step_Payment_Options',
316
+					'slug'       => 'payment_options',
317
+					'has_hooks'  => true,
318
+				),
319
+				999 => array(
320
+					'file_path'  => SPCO_REG_STEPS_PATH . 'finalize_registration',
321
+					'class_name' => 'EE_SPCO_Reg_Step_Finalize_Registration',
322
+					'slug'       => 'finalize_registration',
323
+					'has_hooks'  => false,
324
+				),
325
+			);
326
+		}
327
+		return $reg_steps;
328
+	}
329
+
330
+
331
+
332
+	/**
333
+	 *    registration_checkout_for_admin
334
+	 *
335
+	 * @access    public
336
+	 * @return    string
337
+	 * @throws \EE_Error
338
+	 */
339
+	public static function registration_checkout_for_admin()
340
+	{
341
+		EED_Single_Page_Checkout::load_reg_steps();
342
+		EE_Registry::instance()->REQ->set('step', 'attendee_information');
343
+		EE_Registry::instance()->REQ->set('action', 'display_spco_reg_step');
344
+		EE_Registry::instance()->REQ->set('process_form_submission', false);
345
+		EED_Single_Page_Checkout::instance()->_initialize();
346
+		EED_Single_Page_Checkout::instance()->_display_spco_reg_form();
347
+		return EE_Registry::instance()->REQ->get_output();
348
+	}
349
+
350
+
351
+
352
+	/**
353
+	 * process_registration_from_admin
354
+	 *
355
+	 * @access public
356
+	 * @return \EE_Transaction
357
+	 * @throws \EE_Error
358
+	 */
359
+	public static function process_registration_from_admin()
360
+	{
361
+		EED_Single_Page_Checkout::load_reg_steps();
362
+		EE_Registry::instance()->REQ->set('step', 'attendee_information');
363
+		EE_Registry::instance()->REQ->set('action', 'process_reg_step');
364
+		EE_Registry::instance()->REQ->set('process_form_submission', true);
365
+		EED_Single_Page_Checkout::instance()->_initialize();
366
+		if (EED_Single_Page_Checkout::instance()->checkout->current_step->completed()) {
367
+			$final_reg_step = end(EED_Single_Page_Checkout::instance()->checkout->reg_steps);
368
+			if ($final_reg_step instanceof EE_SPCO_Reg_Step_Finalize_Registration) {
369
+				EED_Single_Page_Checkout::instance()->checkout->set_reg_step_initiated($final_reg_step);
370
+				if ($final_reg_step->process_reg_step()) {
371
+					$final_reg_step->set_completed();
372
+					EED_Single_Page_Checkout::instance()->checkout->update_txn_reg_steps_array();
373
+					return EED_Single_Page_Checkout::instance()->checkout->transaction;
374
+				}
375
+			}
376
+		}
377
+		return null;
378
+	}
379
+
380
+
381
+
382
+	/**
383
+	 *    run
384
+	 *
385
+	 * @access    public
386
+	 * @param WP_Query $WP_Query
387
+	 * @return    void
388
+	 * @throws \EE_Error
389
+	 */
390
+	public function run($WP_Query)
391
+	{
392
+		if (
393
+			$WP_Query instanceof WP_Query
394
+			&& $WP_Query->is_main_query()
395
+			&& apply_filters('FHEE__EED_Single_Page_Checkout__run', true)
396
+			&& $this->_is_reg_checkout()
397
+		) {
398
+			$this->_initialize();
399
+		}
400
+	}
401
+
402
+
403
+
404
+	/**
405
+	 * determines whether current url matches reg page url
406
+	 *
407
+	 * @return bool
408
+	 */
409
+	protected function _is_reg_checkout()
410
+	{
411
+		// get current permalink for reg page without any extra query args
412
+		$reg_page_url = \get_permalink(EE_Config::instance()->core->reg_page_id);
413
+		// get request URI for current request, but without the scheme or host
414
+		$current_request_uri = \EEH_URL::filter_input_server_url('REQUEST_URI');
415
+		$current_request_uri = html_entity_decode($current_request_uri);
416
+		// get array of query args from the current request URI
417
+		$query_args = \EEH_URL::get_query_string($current_request_uri);
418
+		// grab page id if it is set
419
+		$page_id = isset($query_args['page_id']) ? absint($query_args['page_id']) : 0;
420
+		// and remove the page id from the query args (we will re-add it later)
421
+		unset($query_args['page_id']);
422
+		// now strip all query args from current request URI
423
+		$current_request_uri = remove_query_arg(array_flip($query_args), $current_request_uri);
424
+		// and re-add the page id if it was set
425
+		if ($page_id) {
426
+			$current_request_uri = add_query_arg('page_id', $page_id, $current_request_uri);
427
+		}
428
+		// remove slashes and ?
429
+		$current_request_uri = trim($current_request_uri, '?/');
430
+		// is current request URI part of the known full reg page URL ?
431
+		return ! empty($current_request_uri) && strpos($reg_page_url, $current_request_uri) !== false;
432
+	}
433
+
434
+
435
+
436
+	/**
437
+	 *    run
438
+	 *
439
+	 * @access    public
440
+	 * @param WP_Query $WP_Query
441
+	 * @return    void
442
+	 * @throws \EE_Error
443
+	 */
444
+	public static function init($WP_Query)
445
+	{
446
+		EED_Single_Page_Checkout::instance()->run($WP_Query);
447
+	}
448
+
449
+
450
+
451
+	/**
452
+	 *    _initialize - initial module setup
453
+	 *
454
+	 * @access    private
455
+	 * @throws EE_Error
456
+	 * @return    void
457
+	 */
458
+	private function _initialize()
459
+	{
460
+		// ensure SPCO doesn't run twice
461
+		if (EED_Single_Page_Checkout::$_initialized) {
462
+			return;
463
+		}
464
+		try {
465
+			$this->_verify_session();
466
+			// setup the EE_Checkout object
467
+			$this->checkout = $this->_initialize_checkout();
468
+			// filter checkout
469
+			$this->checkout = apply_filters('FHEE__EED_Single_Page_Checkout___initialize__checkout', $this->checkout);
470
+			// get the $_GET
471
+			$this->_get_request_vars();
472
+			if ($this->_block_bots()) {
473
+				return;
474
+			}
475
+			// filter continue_reg
476
+			$this->checkout->continue_reg = apply_filters('FHEE__EED_Single_Page_Checkout__init___continue_reg', true, $this->checkout);
477
+			// load the reg steps array
478
+			if ( ! $this->_load_and_instantiate_reg_steps()) {
479
+				EED_Single_Page_Checkout::$_initialized = true;
480
+				return;
481
+			}
482
+			// set the current step
483
+			$this->checkout->set_current_step($this->checkout->step);
484
+			// and the next step
485
+			$this->checkout->set_next_step();
486
+			// verify that everything has been setup correctly
487
+			if ( ! ($this->_verify_transaction_and_get_registrations() && $this->_final_verifications())) {
488
+				EED_Single_Page_Checkout::$_initialized = true;
489
+				return;
490
+			}
491
+			// lock the transaction
492
+			$this->checkout->transaction->lock();
493
+			// make sure all of our cached objects are added to their respective model entity mappers
494
+			$this->checkout->refresh_all_entities();
495
+			// set amount owing
496
+			$this->checkout->amount_owing = $this->checkout->transaction->remaining();
497
+			// initialize each reg step, which gives them the chance to potentially alter the process
498
+			$this->_initialize_reg_steps();
499
+			// DEBUG LOG
500
+			//$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
501
+			// get reg form
502
+			if( ! $this->_check_form_submission()) {
503
+				EED_Single_Page_Checkout::$_initialized = true;
504
+				return;
505
+			}
506
+			// checkout the action!!!
507
+			$this->_process_form_action();
508
+			// add some style and make it dance
509
+			$this->add_styles_and_scripts();
510
+			// kk... SPCO has successfully run
511
+			EED_Single_Page_Checkout::$_initialized = true;
512
+			// set no cache headers and constants
513
+			EE_System::do_not_cache();
514
+			// add anchor
515
+			add_action('loop_start', array($this, 'set_checkout_anchor'), 1);
516
+			// remove transaction lock
517
+			add_action('shutdown', array($this, 'unlock_transaction'), 1);
518
+		} catch (Exception $e) {
519
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
520
+		}
521
+	}
522
+
523
+
524
+
525
+	/**
526
+	 *    _verify_session
527
+	 * checks that the session is valid and not expired
528
+	 *
529
+	 * @access    private
530
+	 * @throws EE_Error
531
+	 */
532
+	private function _verify_session()
533
+	{
534
+		if ( ! EE_Registry::instance()->SSN instanceof EE_Session) {
535
+			throw new EE_Error(__('The EE_Session class could not be loaded.', 'event_espresso'));
536
+		}
537
+		// is session still valid ?
538
+		if (EE_Registry::instance()->SSN->expired() && EE_Registry::instance()->REQ->get('e_reg_url_link', '') === '') {
539
+			$this->checkout = new EE_Checkout();
540
+			EE_Registry::instance()->SSN->reset_cart();
541
+			EE_Registry::instance()->SSN->reset_checkout();
542
+			EE_Registry::instance()->SSN->reset_transaction();
543
+			EE_Error::add_attention(EE_Registry::$i18n_js_strings['registration_expiration_notice'], __FILE__,
544
+				__FUNCTION__, __LINE__);
545
+			EE_Registry::instance()->SSN->reset_expired();
546
+		}
547
+	}
548
+
549
+
550
+
551
+	/**
552
+	 *    _initialize_checkout
553
+	 * loads and instantiates EE_Checkout
554
+	 *
555
+	 * @access    private
556
+	 * @throws EE_Error
557
+	 * @return EE_Checkout
558
+	 */
559
+	private function _initialize_checkout()
560
+	{
561
+		// look in session for existing checkout
562
+		/** @type EE_Checkout $checkout */
563
+		$checkout = EE_Registry::instance()->SSN->checkout();
564
+		// verify
565
+		if ( ! $checkout instanceof EE_Checkout) {
566
+			// instantiate EE_Checkout object for handling the properties of the current checkout process
567
+			$checkout = EE_Registry::instance()->load_file(SPCO_INC_PATH, 'EE_Checkout', 'class', array(), false);
568
+		} else {
569
+			if ($checkout->current_step->is_final_step() && $checkout->exit_spco() === true) {
570
+				$this->unlock_transaction();
571
+				wp_safe_redirect($checkout->redirect_url);
572
+				exit();
573
+			}
574
+		}
575
+		$checkout = apply_filters('FHEE__EED_Single_Page_Checkout___initialize_checkout__checkout', $checkout);
576
+		// verify again
577
+		if ( ! $checkout instanceof EE_Checkout) {
578
+			throw new EE_Error(__('The EE_Checkout class could not be loaded.', 'event_espresso'));
579
+		}
580
+		// reset anything that needs a clean slate for each request
581
+		$checkout->reset_for_current_request();
582
+		return $checkout;
583
+	}
584
+
585
+
586
+
587
+	/**
588
+	 *    _get_request_vars
589
+	 *
590
+	 * @access    private
591
+	 * @return    void
592
+	 * @throws \EE_Error
593
+	 */
594
+	private function _get_request_vars()
595
+	{
596
+		// load classes
597
+		EED_Single_Page_Checkout::load_request_handler();
598
+		//make sure this request is marked as belonging to EE
599
+		EE_Registry::instance()->REQ->set_espresso_page(true);
600
+		// which step is being requested ?
601
+		$this->checkout->step = EE_Registry::instance()->REQ->get('step', $this->_get_first_step());
602
+		// which step is being edited ?
603
+		$this->checkout->edit_step = EE_Registry::instance()->REQ->get('edit_step', '');
604
+		// and what we're doing on the current step
605
+		$this->checkout->action = EE_Registry::instance()->REQ->get('action', 'display_spco_reg_step');
606
+		// timestamp
607
+		$this->checkout->uts = EE_Registry::instance()->REQ->get('uts', 0);
608
+		// returning to edit ?
609
+		$this->checkout->reg_url_link = EE_Registry::instance()->REQ->get('e_reg_url_link', '');
610
+		// or some other kind of revisit ?
611
+		$this->checkout->revisit = EE_Registry::instance()->REQ->get('revisit', false);
612
+		// and whether or not to generate a reg form for this request
613
+		$this->checkout->generate_reg_form = EE_Registry::instance()->REQ->get('generate_reg_form', true);        // TRUE 	FALSE
614
+		// and whether or not to process a reg form submission for this request
615
+		$this->checkout->process_form_submission = EE_Registry::instance()->REQ->get(
616
+			'process_form_submission',
617
+			$this->checkout->action === 'process_reg_step'
618
+		); // TRUE 	FALSE
619
+		$this->checkout->process_form_submission = $this->checkout->action !== 'display_spco_reg_step'
620
+			? $this->checkout->process_form_submission
621
+			: false;        // TRUE 	FALSE
622
+		// $this->_display_request_vars();
623
+	}
624
+
625
+
626
+
627
+	/**
628
+	 *  _display_request_vars
629
+	 *
630
+	 * @access    protected
631
+	 * @return    void
632
+	 */
633
+	protected function _display_request_vars()
634
+	{
635
+		if ( ! WP_DEBUG) {
636
+			return;
637
+		}
638
+		EEH_Debug_Tools::printr($_REQUEST, '$_REQUEST', __FILE__, __LINE__);
639
+		EEH_Debug_Tools::printr($this->checkout->step, '$this->checkout->step', __FILE__, __LINE__);
640
+		EEH_Debug_Tools::printr($this->checkout->edit_step, '$this->checkout->edit_step', __FILE__, __LINE__);
641
+		EEH_Debug_Tools::printr($this->checkout->action, '$this->checkout->action', __FILE__, __LINE__);
642
+		EEH_Debug_Tools::printr($this->checkout->reg_url_link, '$this->checkout->reg_url_link', __FILE__, __LINE__);
643
+		EEH_Debug_Tools::printr($this->checkout->revisit, '$this->checkout->revisit', __FILE__, __LINE__);
644
+		EEH_Debug_Tools::printr($this->checkout->generate_reg_form, '$this->checkout->generate_reg_form', __FILE__, __LINE__);
645
+		EEH_Debug_Tools::printr($this->checkout->process_form_submission, '$this->checkout->process_form_submission', __FILE__, __LINE__);
646
+	}
647
+
648
+
649
+
650
+	/**
651
+	 * _block_bots
652
+	 * checks that the incoming request has either of the following set:
653
+	 *  a uts (unix timestamp) which indicates that the request was redirected from the Ticket Selector
654
+	 *  a REG URL Link, which indicates that the request is a return visit to SPCO for a valid TXN
655
+	 * so if you're not coming from the Ticket Selector nor returning for a valid IP...
656
+	 * then where you coming from man?
657
+	 *
658
+	 * @return boolean
659
+	 */
660
+	private function _block_bots()
661
+	{
662
+		$invalid_checkout_access = \EED_Invalid_Checkout_Access::getInvalidCheckoutAccess();
663
+		if ($invalid_checkout_access->checkoutAccessIsInvalid($this->checkout)) {
664
+			return true;
665
+		}
666
+		return false;
667
+	}
668
+
669
+
670
+
671
+	/**
672
+	 *    _get_first_step
673
+	 *  gets slug for first step in $_reg_steps_array
674
+	 *
675
+	 * @access    private
676
+	 * @throws EE_Error
677
+	 * @return    array
678
+	 */
679
+	private function _get_first_step()
680
+	{
681
+		$first_step = reset(EED_Single_Page_Checkout::$_reg_steps_array);
682
+		return isset($first_step['slug']) ? $first_step['slug'] : 'attendee_information';
683
+	}
684
+
685
+
686
+
687
+	/**
688
+	 *    _load_and_instantiate_reg_steps
689
+	 *  instantiates each reg step based on the loaded reg_steps array
690
+	 *
691
+	 * @access    private
692
+	 * @throws EE_Error
693
+	 * @return    bool
694
+	 */
695
+	private function _load_and_instantiate_reg_steps()
696
+	{
697
+		// have reg_steps already been instantiated ?
698
+		if (
699
+			empty($this->checkout->reg_steps)
700
+			|| apply_filters('FHEE__Single_Page_Checkout__load_reg_steps__reload_reg_steps', false, $this->checkout)
701
+		) {
702
+			// if not, then loop through raw reg steps array
703
+			foreach (EED_Single_Page_Checkout::$_reg_steps_array as $order => $reg_step) {
704
+				if ( ! $this->_load_and_instantiate_reg_step($reg_step, $order)) {
705
+					return false;
706
+				}
707
+			}
708
+			EE_Registry::instance()->CFG->registration->skip_reg_confirmation = true;
709
+			EE_Registry::instance()->CFG->registration->reg_confirmation_last = true;
710
+			// skip the registration_confirmation page ?
711
+			if (EE_Registry::instance()->CFG->registration->skip_reg_confirmation) {
712
+				// just remove it from the reg steps array
713
+				$this->checkout->remove_reg_step('registration_confirmation', false);
714
+			} else if (
715
+				isset($this->checkout->reg_steps['registration_confirmation'])
716
+				&& EE_Registry::instance()->CFG->registration->reg_confirmation_last
717
+			) {
718
+				// set the order to something big like 100
719
+				$this->checkout->set_reg_step_order('registration_confirmation', 100);
720
+			}
721
+			// filter the array for good luck
722
+			$this->checkout->reg_steps = apply_filters(
723
+				'FHEE__Single_Page_Checkout__load_reg_steps__reg_steps',
724
+				$this->checkout->reg_steps
725
+			);
726
+			// finally re-sort based on the reg step class order properties
727
+			$this->checkout->sort_reg_steps();
728
+		} else {
729
+			foreach ($this->checkout->reg_steps as $reg_step) {
730
+				// set all current step stati to FALSE
731
+				$reg_step->set_is_current_step(false);
732
+			}
733
+		}
734
+		if (empty($this->checkout->reg_steps)) {
735
+			EE_Error::add_error(__('No Reg Steps were loaded..', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
736
+			return false;
737
+		}
738
+		// make reg step details available to JS
739
+		$this->checkout->set_reg_step_JSON_info();
740
+		return true;
741
+	}
742
+
743
+
744
+
745
+	/**
746
+	 *     _load_and_instantiate_reg_step
747
+	 *
748
+	 * @access    private
749
+	 * @param array $reg_step
750
+	 * @param int   $order
751
+	 * @return bool
752
+	 */
753
+	private function _load_and_instantiate_reg_step($reg_step = array(), $order = 0)
754
+	{
755
+		// we need a file_path, class_name, and slug to add a reg step
756
+		if (isset($reg_step['file_path'], $reg_step['class_name'], $reg_step['slug'])) {
757
+			// if editing a specific step, but this is NOT that step... (and it's not the 'finalize_registration' step)
758
+			if (
759
+				$this->checkout->reg_url_link
760
+				&& $this->checkout->step !== $reg_step['slug']
761
+				&& $reg_step['slug'] !== 'finalize_registration'
762
+			) {
763
+				return true;
764
+			}
765
+			// instantiate step class using file path and class name
766
+			$reg_step_obj = EE_Registry::instance()->load_file(
767
+				$reg_step['file_path'],
768
+				$reg_step['class_name'],
769
+				'class',
770
+				$this->checkout,
771
+				false
772
+			);
773
+			// did we gets the goods ?
774
+			if ($reg_step_obj instanceof EE_SPCO_Reg_Step) {
775
+				// set reg step order based on config
776
+				$reg_step_obj->set_order($order);
777
+				// add instantiated reg step object to the master reg steps array
778
+				$this->checkout->add_reg_step($reg_step_obj);
779
+			} else {
780
+				EE_Error::add_error(
781
+					__('The current step could not be set.', 'event_espresso'),
782
+					__FILE__, __FUNCTION__, __LINE__
783
+				);
784
+				return false;
785
+			}
786
+		} else {
787
+			if (WP_DEBUG) {
788
+				EE_Error::add_error(
789
+					sprintf(
790
+						__('A registration step could not be loaded. One or more of the following data points is invalid:%4$s%5$sFile Path: %1$s%6$s%5$sClass Name: %2$s%6$s%5$sSlug: %3$s%6$s%7$s', 'event_espresso'),
791
+						isset($reg_step['file_path']) ? $reg_step['file_path'] : '',
792
+						isset($reg_step['class_name']) ? $reg_step['class_name'] : '',
793
+						isset($reg_step['slug']) ? $reg_step['slug'] : '',
794
+						'<ul>',
795
+						'<li>',
796
+						'</li>',
797
+						'</ul>'
798
+					),
799
+					__FILE__, __FUNCTION__, __LINE__
800
+				);
801
+			}
802
+			return false;
803
+		}
804
+		return true;
805
+	}
806
+
807
+
808
+
809
+	/**
810
+	 * _verify_transaction_and_get_registrations
811
+	 *
812
+	 * @access private
813
+	 * @return bool
814
+	 */
815
+	private function _verify_transaction_and_get_registrations()
816
+	{
817
+		// was there already a valid transaction in the checkout from the session ?
818
+		if ( ! $this->checkout->transaction instanceof EE_Transaction) {
819
+			// get transaction from db or session
820
+			$this->checkout->transaction = $this->checkout->reg_url_link && ! is_admin()
821
+				? $this->_get_transaction_and_cart_for_previous_visit()
822
+				: $this->_get_cart_for_current_session_and_setup_new_transaction();
823
+			if ( ! $this->checkout->transaction instanceof EE_Transaction) {
824
+				EE_Error::add_error(
825
+					__('Your Registration and Transaction information could not be retrieved from the db.',
826
+						'event_espresso'),
827
+					__FILE__, __FUNCTION__, __LINE__
828
+				);
829
+				$this->checkout->transaction = EE_Transaction::new_instance();
830
+				// add some style and make it dance
831
+				$this->add_styles_and_scripts();
832
+				EED_Single_Page_Checkout::$_initialized = true;
833
+				return false;
834
+			}
835
+			// and the registrations for the transaction
836
+			$this->_get_registrations($this->checkout->transaction);
837
+		}
838
+		return true;
839
+	}
840
+
841
+
842
+
843
+	/**
844
+	 * _get_transaction_and_cart_for_previous_visit
845
+	 *
846
+	 * @access private
847
+	 * @return mixed EE_Transaction|NULL
848
+	 */
849
+	private function _get_transaction_and_cart_for_previous_visit()
850
+	{
851
+		/** @var $TXN_model EEM_Transaction */
852
+		$TXN_model = EE_Registry::instance()->load_model('Transaction');
853
+		// because the reg_url_link is present in the request, this is a return visit to SPCO, so we'll get the transaction data from the db
854
+		$transaction = $TXN_model->get_transaction_from_reg_url_link($this->checkout->reg_url_link);
855
+		// verify transaction
856
+		if ($transaction instanceof EE_Transaction) {
857
+			// and get the cart that was used for that transaction
858
+			$this->checkout->cart = $this->_get_cart_for_transaction($transaction);
859
+			return $transaction;
860
+		} else {
861
+			EE_Error::add_error(__('Your Registration and Transaction information could not be retrieved from the db.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
862
+			return null;
863
+		}
864
+	}
865
+
866
+
867
+
868
+	/**
869
+	 * _get_cart_for_transaction
870
+	 *
871
+	 * @access private
872
+	 * @param EE_Transaction $transaction
873
+	 * @return EE_Cart
874
+	 */
875
+	private function _get_cart_for_transaction($transaction)
876
+	{
877
+		return $this->checkout->get_cart_for_transaction($transaction);
878
+	}
879
+
880
+
881
+
882
+	/**
883
+	 * get_cart_for_transaction
884
+	 *
885
+	 * @access public
886
+	 * @param EE_Transaction $transaction
887
+	 * @return EE_Cart
888
+	 */
889
+	public function get_cart_for_transaction(EE_Transaction $transaction)
890
+	{
891
+		return $this->checkout->get_cart_for_transaction($transaction);
892
+	}
893
+
894
+
895
+
896
+	/**
897
+	 * _get_transaction_and_cart_for_current_session
898
+	 *    generates a new EE_Transaction object and adds it to the $_transaction property.
899
+	 *
900
+	 * @access private
901
+	 * @return EE_Transaction
902
+	 * @throws \EE_Error
903
+	 */
904
+	private function _get_cart_for_current_session_and_setup_new_transaction()
905
+	{
906
+		//  if there's no transaction, then this is the FIRST visit to SPCO
907
+		// so load up the cart ( passing nothing for the TXN because it doesn't exist yet )
908
+		$this->checkout->cart = $this->_get_cart_for_transaction(null);
909
+		// and then create a new transaction
910
+		$transaction = $this->_initialize_transaction();
911
+		// verify transaction
912
+		if ($transaction instanceof EE_Transaction) {
913
+			// save it so that we have an ID for other objects to use
914
+			$transaction->save();
915
+			// and save TXN data to the cart
916
+			$this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn($transaction->ID());
917
+		} else {
918
+			EE_Error::add_error(__('A Valid Transaction could not be initialized.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
919
+		}
920
+		return $transaction;
921
+	}
922
+
923
+
924
+
925
+	/**
926
+	 *    generates a new EE_Transaction object and adds it to the $_transaction property.
927
+	 *
928
+	 * @access private
929
+	 * @return mixed EE_Transaction|NULL
930
+	 */
931
+	private function _initialize_transaction()
932
+	{
933
+		try {
934
+			// ensure cart totals have been calculated
935
+			$this->checkout->cart->get_grand_total()->recalculate_total_including_taxes();
936
+			// grab the cart grand total
937
+			$cart_total = $this->checkout->cart->get_cart_grand_total();
938
+			// create new TXN
939
+			$transaction = EE_Transaction::new_instance(
940
+				array(
941
+					'TXN_reg_steps' => $this->checkout->initialize_txn_reg_steps_array(),
942
+					'TXN_total'     => $cart_total > 0 ? $cart_total : 0,
943
+					'TXN_paid'      => 0,
944
+					'STS_ID'        => EEM_Transaction::failed_status_code,
945
+				)
946
+			);
947
+			// save it so that we have an ID for other objects to use
948
+			$transaction->save();
949
+			// set cron job for following up on TXNs after their session has expired
950
+			EE_Cron_Tasks::schedule_expired_transaction_check(
951
+				EE_Registry::instance()->SSN->expiration() + 1,
952
+				$transaction->ID()
953
+			);
954
+			return $transaction;
955
+		} catch (Exception $e) {
956
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
957
+		}
958
+		return null;
959
+	}
960
+
961
+
962
+
963
+	/**
964
+	 * _get_registrations
965
+	 *
966
+	 * @access private
967
+	 * @param EE_Transaction $transaction
968
+	 * @return void
969
+	 * @throws \EventEspresso\core\exceptions\InvalidEntityException
970
+	 * @throws \EE_Error
971
+	 */
972
+	private function _get_registrations(EE_Transaction $transaction)
973
+	{
974
+		// first step: grab the registrants  { : o
975
+		$registrations = $transaction->registrations($this->checkout->reg_cache_where_params, true);
976
+		// verify registrations have been set
977
+		if (empty($registrations)) {
978
+			// if no cached registrations, then check the db
979
+			$registrations = $transaction->registrations($this->checkout->reg_cache_where_params, false);
980
+			// still nothing ? well as long as this isn't a revisit
981
+			if (empty($registrations) && ! $this->checkout->revisit) {
982
+				// generate new registrations from scratch
983
+				$registrations = $this->_initialize_registrations($transaction);
984
+			}
985
+		}
986
+		// sort by their original registration order
987
+		usort($registrations, array('EED_Single_Page_Checkout', 'sort_registrations_by_REG_count'));
988
+		// then loop thru the array
989
+		foreach ($registrations as $registration) {
990
+			// verify each registration
991
+			if ($registration instanceof EE_Registration) {
992
+				// we display all attendee info for the primary registrant
993
+				if ($this->checkout->reg_url_link === $registration->reg_url_link()
994
+					&& $registration->is_primary_registrant()
995
+				) {
996
+					$this->checkout->primary_revisit = true;
997
+					break;
998
+				} else if ($this->checkout->revisit
999
+						   && $this->checkout->reg_url_link !== $registration->reg_url_link()
1000
+				) {
1001
+					// but hide info if it doesn't belong to you
1002
+					$transaction->clear_cache('Registration', $registration->ID());
1003
+				}
1004
+				$this->checkout->set_reg_status_updated($registration->ID(), false);
1005
+			}
1006
+		}
1007
+	}
1008
+
1009
+
1010
+
1011
+	/**
1012
+	 *    adds related EE_Registration objects for each ticket in the cart to the current EE_Transaction object
1013
+	 *
1014
+	 * @access private
1015
+	 * @param EE_Transaction $transaction
1016
+	 * @return    array
1017
+	 * @throws \EventEspresso\core\exceptions\InvalidEntityException
1018
+	 * @throws \EE_Error
1019
+	 */
1020
+	private function _initialize_registrations(EE_Transaction $transaction)
1021
+	{
1022
+		$att_nmbr = 0;
1023
+		$registrations = array();
1024
+		if ($transaction instanceof EE_Transaction) {
1025
+			/** @type EE_Registration_Processor $registration_processor */
1026
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
1027
+			$this->checkout->total_ticket_count = $this->checkout->cart->all_ticket_quantity_count();
1028
+			// now let's add the cart items to the $transaction
1029
+			foreach ($this->checkout->cart->get_tickets() as $line_item) {
1030
+				//do the following for each ticket of this type they selected
1031
+				for ($x = 1; $x <= $line_item->quantity(); $x++) {
1032
+					$att_nmbr++;
1033
+					/** @var EventEspresso\core\services\commands\registration\CreateRegistrationCommand $CreateRegistrationCommand */
1034
+					$CreateRegistrationCommand = EE_Registry::instance()
1035
+															->create(
1036
+																'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
1037
+																array(
1038
+																	$transaction,
1039
+																	$line_item,
1040
+																	$att_nmbr,
1041
+																	$this->checkout->total_ticket_count,
1042
+																)
1043
+															);
1044
+					// override capabilities for frontend registrations
1045
+					if ( ! is_admin()) {
1046
+						$CreateRegistrationCommand->setCapCheck(
1047
+							new PublicCapabilities('', 'create_new_registration')
1048
+						);
1049
+					}
1050
+					$registration = EE_Registry::instance()->BUS->execute($CreateRegistrationCommand);
1051
+					if ( ! $registration instanceof EE_Registration) {
1052
+						throw new InvalidEntityException($registration, 'EE_Registration');
1053
+					}
1054
+					$registrations[ $registration->ID() ] = $registration;
1055
+				}
1056
+			}
1057
+			$registration_processor->fix_reg_final_price_rounding_issue($transaction);
1058
+		}
1059
+		return $registrations;
1060
+	}
1061
+
1062
+
1063
+
1064
+	/**
1065
+	 * sorts registrations by REG_count
1066
+	 *
1067
+	 * @access public
1068
+	 * @param EE_Registration $reg_A
1069
+	 * @param EE_Registration $reg_B
1070
+	 * @return int
1071
+	 */
1072
+	public static function sort_registrations_by_REG_count(EE_Registration $reg_A, EE_Registration $reg_B)
1073
+	{
1074
+		// this shouldn't ever happen within the same TXN, but oh well
1075
+		if ($reg_A->count() === $reg_B->count()) {
1076
+			return 0;
1077
+		}
1078
+		return ($reg_A->count() > $reg_B->count()) ? 1 : -1;
1079
+	}
1080
+
1081
+
1082
+
1083
+	/**
1084
+	 *    _final_verifications
1085
+	 * just makes sure that everything is set up correctly before proceeding
1086
+	 *
1087
+	 * @access    private
1088
+	 * @return    bool
1089
+	 * @throws \EE_Error
1090
+	 */
1091
+	private function _final_verifications()
1092
+	{
1093
+		// filter checkout
1094
+		$this->checkout = apply_filters('FHEE__EED_Single_Page_Checkout___final_verifications__checkout', $this->checkout);
1095
+		//verify that current step is still set correctly
1096
+		if ( ! $this->checkout->current_step instanceof EE_SPCO_Reg_Step) {
1097
+			EE_Error::add_error(
1098
+				__('We\'re sorry but the registration process can not proceed because one or more registration steps were not setup correctly. Please refresh the page and try again or contact support.', 'event_espresso'),
1099
+				__FILE__,
1100
+				__FUNCTION__,
1101
+				__LINE__
1102
+			);
1103
+			return false;
1104
+		}
1105
+		// if returning to SPCO, then verify that primary registrant is set
1106
+		if ( ! empty($this->checkout->reg_url_link)) {
1107
+			$valid_registrant = $this->checkout->transaction->primary_registration();
1108
+			if ( ! $valid_registrant instanceof EE_Registration) {
1109
+				EE_Error::add_error(
1110
+					__('We\'re sorry but there appears to be an error with the "reg_url_link" or the primary registrant for this transaction. Please refresh the page and try again or contact support.', 'event_espresso'),
1111
+					__FILE__,
1112
+					__FUNCTION__,
1113
+					__LINE__
1114
+				);
1115
+				return false;
1116
+			}
1117
+			$valid_registrant = null;
1118
+			foreach ($this->checkout->transaction->registrations($this->checkout->reg_cache_where_params) as $registration) {
1119
+				if (
1120
+					$registration instanceof EE_Registration
1121
+					&& $registration->reg_url_link() === $this->checkout->reg_url_link
1122
+				) {
1123
+					$valid_registrant = $registration;
1124
+				}
1125
+			}
1126
+			if ( ! $valid_registrant instanceof EE_Registration) {
1127
+				// hmmm... maybe we have the wrong session because the user is opening multiple tabs ?
1128
+				if (EED_Single_Page_Checkout::$_checkout_verified) {
1129
+					// clear the session, mark the checkout as unverified, and try again
1130
+					EE_Registry::instance()->SSN->clear_session();
1131
+					EED_Single_Page_Checkout::$_initialized = false;
1132
+					EED_Single_Page_Checkout::$_checkout_verified = false;
1133
+					$this->_initialize();
1134
+					EE_Error::reset_notices();
1135
+					return false;
1136
+				}
1137
+				EE_Error::add_error(
1138
+					__('We\'re sorry but there appears to be an error with the "reg_url_link" or the transaction itself. Please refresh the page and try again or contact support.', 'event_espresso'),
1139
+					__FILE__,
1140
+					__FUNCTION__,
1141
+					__LINE__
1142
+				);
1143
+				return false;
1144
+			}
1145
+		}
1146
+		// now that things have been kinda sufficiently verified,
1147
+		// let's add the checkout to the session so that's available other systems
1148
+		EE_Registry::instance()->SSN->set_checkout($this->checkout);
1149
+		return true;
1150
+	}
1151
+
1152
+
1153
+
1154
+	/**
1155
+	 *    _initialize_reg_steps
1156
+	 * first makes sure that EE_Transaction_Processor::set_reg_step_initiated() is called as required
1157
+	 * then loops thru all of the active reg steps and calls the initialize_reg_step() method
1158
+	 *
1159
+	 * @access    private
1160
+	 * @param bool $reinitializing
1161
+	 * @throws \EE_Error
1162
+	 */
1163
+	private function _initialize_reg_steps($reinitializing = false)
1164
+	{
1165
+		$this->checkout->set_reg_step_initiated($this->checkout->current_step);
1166
+		// loop thru all steps to call their individual "initialize" methods and set i18n strings for JS
1167
+		foreach ($this->checkout->reg_steps as $reg_step) {
1168
+			if ( ! $reg_step->initialize_reg_step()) {
1169
+				// if not initialized then maybe this step is being removed...
1170
+				if ( ! $reinitializing && $reg_step->is_current_step()) {
1171
+					// if it was the current step, then we need to start over here
1172
+					$this->_initialize_reg_steps(true);
1173
+					return;
1174
+				}
1175
+				continue;
1176
+			}
1177
+			// add css and JS for current step
1178
+			$reg_step->enqueue_styles_and_scripts();
1179
+			// i18n
1180
+			$reg_step->translate_js_strings();
1181
+			if ($reg_step->is_current_step()) {
1182
+				// the text that appears on the reg step form submit button
1183
+				$reg_step->set_submit_button_text();
1184
+			}
1185
+		}
1186
+		// dynamically creates hook point like: AHEE__Single_Page_Checkout___initialize_reg_step__attendee_information
1187
+		do_action("AHEE__Single_Page_Checkout___initialize_reg_step__{$this->checkout->current_step->slug()}", $this->checkout->current_step);
1188
+	}
1189
+
1190
+
1191
+
1192
+	/**
1193
+	 * _check_form_submission
1194
+	 *
1195
+	 * @access private
1196
+	 * @return boolean
1197
+	 */
1198
+	private function _check_form_submission()
1199
+	{
1200
+		//does this request require the reg form to be generated ?
1201
+		if ($this->checkout->generate_reg_form) {
1202
+			// ever heard that song by Blue Rodeo ?
1203
+			try {
1204
+				$this->checkout->current_step->reg_form = $this->checkout->current_step->generate_reg_form();
1205
+				// if not displaying a form, then check for form submission
1206
+				if (
1207
+					$this->checkout->process_form_submission
1208
+					&& $this->checkout->current_step->reg_form->was_submitted()
1209
+				) {
1210
+					// clear out any old data in case this step is being run again
1211
+					$this->checkout->current_step->set_valid_data(array());
1212
+					// capture submitted form data
1213
+					$this->checkout->current_step->reg_form->receive_form_submission(
1214
+						apply_filters('FHEE__Single_Page_Checkout___check_form_submission__request_params', EE_Registry::instance()->REQ->params(), $this->checkout)
1215
+					);
1216
+					// validate submitted form data
1217
+					if ( ! $this->checkout->continue_reg || ! $this->checkout->current_step->reg_form->is_valid()) {
1218
+						// thou shall not pass !!!
1219
+						$this->checkout->continue_reg = false;
1220
+						// any form validation errors?
1221
+						if ($this->checkout->current_step->reg_form->submission_error_message() !== '') {
1222
+							$submission_error_messages = array();
1223
+							// bad, bad, bad registrant
1224
+							foreach ($this->checkout->current_step->reg_form->get_validation_errors_accumulated() as $validation_error) {
1225
+								if ($validation_error instanceof EE_Validation_Error) {
1226
+									$submission_error_messages[] = sprintf(
1227
+										__('%s : %s', 'event_espresso'),
1228
+										$validation_error->get_form_section()->html_label_text(),
1229
+										$validation_error->getMessage()
1230
+									);
1231
+								}
1232
+							}
1233
+							EE_Error::add_error(implode('<br />', $submission_error_messages), __FILE__, __FUNCTION__, __LINE__);
1234
+						}
1235
+						// well not really... what will happen is we'll just get redirected back to redo the current step
1236
+						$this->go_to_next_step();
1237
+						return false;
1238
+					}
1239
+				}
1240
+			} catch (EE_Error $e) {
1241
+				$e->get_error();
1242
+			}
1243
+		}
1244
+		return true;
1245
+	}
1246
+
1247
+
1248
+
1249
+	/**
1250
+	 * _process_action
1251
+	 *
1252
+	 * @access private
1253
+	 * @return void
1254
+	 * @throws \EE_Error
1255
+	 */
1256
+	private function _process_form_action()
1257
+	{
1258
+		// what cha wanna do?
1259
+		switch ($this->checkout->action) {
1260
+			// AJAX next step reg form
1261
+			case 'display_spco_reg_step' :
1262
+				$this->checkout->redirect = false;
1263
+				if (EE_Registry::instance()->REQ->ajax) {
1264
+					$this->checkout->json_response->set_reg_step_html($this->checkout->current_step->display_reg_form());
1265
+				}
1266
+				break;
1267
+			default :
1268
+				// meh... do one of those other steps first
1269
+				if ( ! empty($this->checkout->action) && is_callable(array($this->checkout->current_step, $this->checkout->action))) {
1270
+					// dynamically creates hook point like: AHEE__Single_Page_Checkout__before_attendee_information__process_reg_step
1271
+					do_action("AHEE__Single_Page_Checkout__before_{$this->checkout->current_step->slug()}__{$this->checkout->action}", $this->checkout->current_step);
1272
+					// call action on current step
1273
+					if (call_user_func(array($this->checkout->current_step, $this->checkout->action))) {
1274
+						// good registrant, you get to proceed
1275
+						if (
1276
+							$this->checkout->current_step->success_message() !== ''
1277
+							&& apply_filters(
1278
+								'FHEE__Single_Page_Checkout___process_form_action__display_success',
1279
+								false
1280
+							)
1281
+						) {
1282
+							EE_Error::add_success(
1283
+								$this->checkout->current_step->success_message()
1284
+								. '<br />' . $this->checkout->next_step->_instructions()
1285
+							);
1286
+						}
1287
+						// pack it up, pack it in...
1288
+						$this->_setup_redirect();
1289
+					}
1290
+					// dynamically creates hook point like: AHEE__Single_Page_Checkout__after_payment_options__process_reg_step
1291
+					do_action("AHEE__Single_Page_Checkout__after_{$this->checkout->current_step->slug()}__{$this->checkout->action}", $this->checkout->current_step);
1292
+				} else {
1293
+					EE_Error::add_error(
1294
+						sprintf(
1295
+							__('The requested form action "%s" does not exist for the current "%s" registration step.', 'event_espresso'),
1296
+							$this->checkout->action,
1297
+							$this->checkout->current_step->name()
1298
+						),
1299
+						__FILE__,
1300
+						__FUNCTION__,
1301
+						__LINE__
1302
+					);
1303
+				}
1304
+			// end default
1305
+		}
1306
+		// store our progress so far
1307
+		$this->checkout->stash_transaction_and_checkout();
1308
+		// advance to the next step! If you pass GO, collect $200
1309
+		$this->go_to_next_step();
1310
+	}
1311
+
1312
+
1313
+
1314
+	/**
1315
+	 *        add_styles_and_scripts
1316
+	 *
1317
+	 * @access        public
1318
+	 * @return        void
1319
+	 */
1320
+	public function add_styles_and_scripts()
1321
+	{
1322
+		// i18n
1323
+		$this->translate_js_strings();
1324
+		if ($this->checkout->admin_request) {
1325
+			add_action('admin_enqueue_scripts', array($this, 'enqueue_styles_and_scripts'), 10);
1326
+		} else {
1327
+			add_action('wp_enqueue_scripts', array($this, 'enqueue_styles_and_scripts'), 10);
1328
+		}
1329
+	}
1330
+
1331
+
1332
+
1333
+	/**
1334
+	 *        translate_js_strings
1335
+	 *
1336
+	 * @access        public
1337
+	 * @return        void
1338
+	 */
1339
+	public function translate_js_strings()
1340
+	{
1341
+		EE_Registry::$i18n_js_strings['revisit'] = $this->checkout->revisit;
1342
+		EE_Registry::$i18n_js_strings['e_reg_url_link'] = $this->checkout->reg_url_link;
1343
+		EE_Registry::$i18n_js_strings['server_error'] = __('An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.', 'event_espresso');
1344
+		EE_Registry::$i18n_js_strings['invalid_json_response'] = __('An invalid response was returned from the server while attempting to process your request. Please refresh the page and try again or contact support.', 'event_espresso');
1345
+		EE_Registry::$i18n_js_strings['validation_error'] = __('There appears to be a problem with the form validation configuration! Please check the admin settings or contact support.', 'event_espresso');
1346
+		EE_Registry::$i18n_js_strings['invalid_payment_method'] = __('There appears to be a problem with the payment method configuration! Please refresh the page and try again or contact support.', 'event_espresso');
1347
+		EE_Registry::$i18n_js_strings['reg_step_error'] = __('This registration step could not be completed. Please refresh the page and try again.', 'event_espresso');
1348
+		EE_Registry::$i18n_js_strings['invalid_coupon'] = __('We\'re sorry but that coupon code does not appear to be valid. If this is incorrect, please contact the site administrator.', 'event_espresso');
1349
+		EE_Registry::$i18n_js_strings['process_registration'] = sprintf(
1350
+			__('Please wait while we process your registration.%sDo not refresh the page or navigate away while this is happening.%sThank you for your patience.', 'event_espresso'),
1351
+			'<br/>',
1352
+			'<br/>'
1353
+		);
1354
+		EE_Registry::$i18n_js_strings['language'] = get_bloginfo('language');
1355
+		EE_Registry::$i18n_js_strings['EESID'] = EE_Registry::instance()->SSN->id();
1356
+		EE_Registry::$i18n_js_strings['currency'] = EE_Registry::instance()->CFG->currency;
1357
+		EE_Registry::$i18n_js_strings['datepicker_yearRange'] = '-150:+20';
1358
+		EE_Registry::$i18n_js_strings['timer_years'] = __('years', 'event_espresso');
1359
+		EE_Registry::$i18n_js_strings['timer_months'] = __('months', 'event_espresso');
1360
+		EE_Registry::$i18n_js_strings['timer_weeks'] = __('weeks', 'event_espresso');
1361
+		EE_Registry::$i18n_js_strings['timer_days'] = __('days', 'event_espresso');
1362
+		EE_Registry::$i18n_js_strings['timer_hours'] = __('hours', 'event_espresso');
1363
+		EE_Registry::$i18n_js_strings['timer_minutes'] = __('minutes', 'event_espresso');
1364
+		EE_Registry::$i18n_js_strings['timer_seconds'] = __('seconds', 'event_espresso');
1365
+		EE_Registry::$i18n_js_strings['timer_year'] = __('year', 'event_espresso');
1366
+		EE_Registry::$i18n_js_strings['timer_month'] = __('month', 'event_espresso');
1367
+		EE_Registry::$i18n_js_strings['timer_week'] = __('week', 'event_espresso');
1368
+		EE_Registry::$i18n_js_strings['timer_day'] = __('day', 'event_espresso');
1369
+		EE_Registry::$i18n_js_strings['timer_hour'] = __('hour', 'event_espresso');
1370
+		EE_Registry::$i18n_js_strings['timer_minute'] = __('minute', 'event_espresso');
1371
+		EE_Registry::$i18n_js_strings['timer_second'] = __('second', 'event_espresso');
1372
+		EE_Registry::$i18n_js_strings['registration_expiration_notice'] = sprintf(
1373
+			__(
1374
+				'%1$sWe\'re sorry, but your registration time has expired.%2$s%3$s%4$sIf you still wish to complete your registration, please return to the %5$sEvent List%6$sEvent List%7$s and reselect your tickets if available. Please except our apologies for any inconvenience this may have caused.%8$s',
1375
+				'event_espresso'
1376
+			),
1377
+			'<h4 class="important-notice">',
1378
+			'</h4>',
1379
+			'<br />',
1380
+			'<p>',
1381
+			'<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
1382
+			'">',
1383
+			'</a>',
1384
+			'</p>'
1385
+		);
1386
+		EE_Registry::$i18n_js_strings['ajax_submit'] = apply_filters('FHEE__Single_Page_Checkout__translate_js_strings__ajax_submit', true);
1387
+		EE_Registry::$i18n_js_strings['session_extension'] = absint(
1388
+			apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS)
1389
+		);
1390
+		EE_Registry::$i18n_js_strings['session_expiration'] = gmdate(
1391
+			'M d, Y H:i:s', EE_Registry::instance()->SSN->expiration() + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1392
+		);
1393
+	}
1394
+
1395
+
1396
+
1397
+	/**
1398
+	 *    enqueue_styles_and_scripts
1399
+	 *
1400
+	 * @access        public
1401
+	 * @return        void
1402
+	 * @throws \EE_Error
1403
+	 */
1404
+	public function enqueue_styles_and_scripts()
1405
+	{
1406
+		// load css
1407
+		wp_register_style('single_page_checkout', SPCO_CSS_URL . 'single_page_checkout.css', array(), EVENT_ESPRESSO_VERSION);
1408
+		wp_enqueue_style('single_page_checkout');
1409
+		// load JS
1410
+		wp_register_script('jquery_plugin', EE_THIRD_PARTY_URL . 'jquery	.plugin.min.js', array('jquery'), '1.0.1', true);
1411
+		wp_register_script('jquery_countdown', EE_THIRD_PARTY_URL . 'jquery	.countdown.min.js', array('jquery_plugin'), '2.0.2', true);
1412
+		wp_register_script('single_page_checkout', SPCO_JS_URL . 'single_page_checkout.js', array('espresso_core', 'underscore', 'ee_form_section_validation', 'jquery_countdown'), EVENT_ESPRESSO_VERSION, true);
1413
+		$this->checkout->registration_form->enqueue_js();
1414
+		$this->checkout->current_step->reg_form->enqueue_js();
1415
+		wp_enqueue_script('single_page_checkout');
1416
+		/**
1417
+		 * global action hook for enqueueing styles and scripts with
1418
+		 * spco calls.
1419
+		 */
1420
+		do_action('AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts', $this);
1421
+		/**
1422
+		 * dynamic action hook for enqueueing styles and scripts with spco calls.
1423
+		 * The hook will end up being something like AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__attendee_information
1424
+		 */
1425
+		do_action('AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__' . $this->checkout->current_step->slug(), $this);
1426
+	}
1427
+
1428
+
1429
+
1430
+	/**
1431
+	 *    display the Registration Single Page Checkout Form
1432
+	 *
1433
+	 * @access    private
1434
+	 * @return    void
1435
+	 * @throws \EE_Error
1436
+	 */
1437
+	private function _display_spco_reg_form()
1438
+	{
1439
+		// if registering via the admin, just display the reg form for the current step
1440
+		if ($this->checkout->admin_request) {
1441
+			EE_Registry::instance()->REQ->add_output($this->checkout->current_step->display_reg_form());
1442
+		} else {
1443
+			// add powered by EE msg
1444
+			add_action('AHEE__SPCO__reg_form_footer', array('EED_Single_Page_Checkout', 'display_registration_footer'));
1445
+			$empty_cart = count($this->checkout->transaction->registrations($this->checkout->reg_cache_where_params)) < 1
1446
+				? true
1447
+				: false;
1448
+			EE_Registry::$i18n_js_strings['empty_cart'] = $empty_cart;
1449
+			$cookies_not_set_msg = '';
1450
+			if ($empty_cart && ! isset($_COOKIE['ee_cookie_test'])) {
1451
+				$cookies_not_set_msg = apply_filters(
1452
+					'FHEE__Single_Page_Checkout__display_spco_reg_form__cookies_not_set_msg',
1453
+					sprintf(
1454
+						__(
1455
+							'%1$s%3$sIt appears your browser is not currently set to accept Cookies%4$s%5$sIn order to register for events, you need to enable cookies.%7$sIf you require assistance, then click the following link to learn how to %8$senable cookies%9$s%6$s%2$s',
1456
+							'event_espresso'
1457
+						),
1458
+						'<div class="ee-attention">',
1459
+						'</div>',
1460
+						'<h6 class="important-notice">',
1461
+						'</h6>',
1462
+						'<p>',
1463
+						'</p>',
1464
+						'<br />',
1465
+						'<a href="http://www.whatarecookies.com/enable.asp" target="_blank">',
1466
+						'</a>'
1467
+					)
1468
+				);
1469
+			}
1470
+			$this->checkout->registration_form = new EE_Form_Section_Proper(
1471
+				array(
1472
+					'name'            => 'single-page-checkout',
1473
+					'html_id'         => 'ee-single-page-checkout-dv',
1474
+					'layout_strategy' =>
1475
+						new EE_Template_Layout(
1476
+							array(
1477
+								'layout_template_file' => SPCO_TEMPLATES_PATH . 'registration_page_wrapper.template.php',
1478
+								'template_args'        => array(
1479
+									'empty_cart'              => $empty_cart,
1480
+									'revisit'                 => $this->checkout->revisit,
1481
+									'reg_steps'               => $this->checkout->reg_steps,
1482
+									'next_step'               => $this->checkout->next_step instanceof EE_SPCO_Reg_Step
1483
+										? $this->checkout->next_step->slug()
1484
+										: '',
1485
+									'cancel_page_url'         => $this->checkout->cancel_page_url,
1486
+									'empty_msg'               => apply_filters(
1487
+										'FHEE__Single_Page_Checkout__display_spco_reg_form__empty_msg',
1488
+										sprintf(
1489
+											__('You need to %1$sReturn to Events list%2$sselect at least one event%3$s before you can proceed with the registration process.',
1490
+												'event_espresso'),
1491
+											'<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
1492
+											'">',
1493
+											'</a>'
1494
+										)
1495
+									),
1496
+									'cookies_not_set_msg'     => $cookies_not_set_msg,
1497
+									'registration_time_limit' => $this->checkout->get_registration_time_limit(),
1498
+									'session_expiration'      =>
1499
+										date('M d, Y H:i:s', EE_Registry::instance()->SSN->expiration() + (get_option('gmt_offset') * HOUR_IN_SECONDS)),
1500
+								),
1501
+							)
1502
+						),
1503
+				)
1504
+			);
1505
+			// load template and add to output sent that gets filtered into the_content()
1506
+			EE_Registry::instance()->REQ->add_output($this->checkout->registration_form->get_html());
1507
+		}
1508
+	}
1509
+
1510
+
1511
+
1512
+	/**
1513
+	 *    add_extra_finalize_registration_inputs
1514
+	 *
1515
+	 * @access    public
1516
+	 * @param $next_step
1517
+	 * @internal  param string $label
1518
+	 * @return void
1519
+	 */
1520
+	public function add_extra_finalize_registration_inputs($next_step)
1521
+	{
1522
+		if ($next_step === 'finalize_registration') {
1523
+			echo '<div id="spco-extra-finalize_registration-inputs-dv"></div>';
1524
+		}
1525
+	}
1526
+
1527
+
1528
+
1529
+	/**
1530
+	 *    display_registration_footer
1531
+	 *
1532
+	 * @access    public
1533
+	 * @return    string
1534
+	 */
1535
+	public static function display_registration_footer()
1536
+	{
1537
+		if (
1538
+		apply_filters(
1539
+			'FHEE__EE_Front__Controller__show_reg_footer',
1540
+			EE_Registry::instance()->CFG->admin->show_reg_footer
1541
+		)
1542
+		) {
1543
+			add_filter(
1544
+				'FHEE__EEH_Template__powered_by_event_espresso__url',
1545
+				function ($url) {
1546
+					return apply_filters('FHEE__EE_Front_Controller__registration_footer__url', $url);
1547
+				}
1548
+			);
1549
+			echo apply_filters(
1550
+				'FHEE__EE_Front_Controller__display_registration_footer',
1551
+				\EEH_Template::powered_by_event_espresso(
1552
+					'',
1553
+					'espresso-registration-footer-dv',
1554
+					array('utm_content' => 'registration_checkout')
1555
+				)
1556
+			);
1557
+		}
1558
+		return '';
1559
+	}
1560
+
1561
+
1562
+
1563
+	/**
1564
+	 *    unlock_transaction
1565
+	 *
1566
+	 * @access    public
1567
+	 * @return    void
1568
+	 * @throws \EE_Error
1569
+	 */
1570
+	public function unlock_transaction()
1571
+	{
1572
+		if ($this->checkout->transaction instanceof EE_Transaction) {
1573
+			$this->checkout->transaction->unlock();
1574
+		}
1575
+	}
1576
+
1577
+
1578
+
1579
+	/**
1580
+	 *        _setup_redirect
1581
+	 *
1582
+	 * @access    private
1583
+	 * @return void
1584
+	 */
1585
+	private function _setup_redirect()
1586
+	{
1587
+		if ($this->checkout->continue_reg && $this->checkout->next_step instanceof EE_SPCO_Reg_Step) {
1588
+			$this->checkout->redirect = true;
1589
+			if (empty($this->checkout->redirect_url)) {
1590
+				$this->checkout->redirect_url = $this->checkout->next_step->reg_step_url();
1591
+			}
1592
+			$this->checkout->redirect_url = apply_filters(
1593
+				'FHEE__EED_Single_Page_Checkout___setup_redirect__checkout_redirect_url',
1594
+				$this->checkout->redirect_url,
1595
+				$this->checkout
1596
+			);
1597
+		}
1598
+	}
1599
+
1600
+
1601
+
1602
+	/**
1603
+	 *   handle ajax message responses and redirects
1604
+	 *
1605
+	 * @access public
1606
+	 * @return void
1607
+	 * @throws \EE_Error
1608
+	 */
1609
+	public function go_to_next_step()
1610
+	{
1611
+		if (EE_Registry::instance()->REQ->ajax) {
1612
+			// capture contents of output buffer we started earlier in the request, and insert into JSON response
1613
+			$this->checkout->json_response->set_unexpected_errors(ob_get_clean());
1614
+		}
1615
+		$this->unlock_transaction();
1616
+		// just return for these conditions
1617
+		if (
1618
+			$this->checkout->admin_request
1619
+			|| $this->checkout->action === 'redirect_form'
1620
+			|| $this->checkout->action === 'update_checkout'
1621
+		) {
1622
+			return;
1623
+		}
1624
+		// AJAX response
1625
+		$this->_handle_json_response();
1626
+		// redirect to next step or the Thank You page
1627
+		$this->_handle_html_redirects();
1628
+		// hmmm... must be something wrong, so let's just display the form again !
1629
+		$this->_display_spco_reg_form();
1630
+	}
1631
+
1632
+
1633
+
1634
+	/**
1635
+	 *   _handle_json_response
1636
+	 *
1637
+	 * @access protected
1638
+	 * @return void
1639
+	 */
1640
+	protected function _handle_json_response()
1641
+	{
1642
+		// if this is an ajax request
1643
+		if (EE_Registry::instance()->REQ->ajax) {
1644
+			// DEBUG LOG
1645
+			//$this->checkout->log(
1646
+			//	__CLASS__, __FUNCTION__, __LINE__,
1647
+			//	array(
1648
+			//		'json_response_redirect_url' => $this->checkout->json_response->redirect_url(),
1649
+			//		'redirect'                   => $this->checkout->redirect,
1650
+			//		'continue_reg'               => $this->checkout->continue_reg,
1651
+			//	)
1652
+			//);
1653
+			$this->checkout->json_response->set_registration_time_limit(
1654
+				$this->checkout->get_registration_time_limit()
1655
+			);
1656
+			$this->checkout->json_response->set_payment_amount($this->checkout->amount_owing);
1657
+			// just send the ajax (
1658
+			$json_response = apply_filters(
1659
+				'FHEE__EE_Single_Page_Checkout__JSON_response',
1660
+				$this->checkout->json_response
1661
+			);
1662
+			echo $json_response;
1663
+			exit();
1664
+		}
1665
+	}
1666
+
1667
+
1668
+
1669
+	/**
1670
+	 *   _handle_redirects
1671
+	 *
1672
+	 * @access protected
1673
+	 * @return void
1674
+	 */
1675
+	protected function _handle_html_redirects()
1676
+	{
1677
+		// going somewhere ?
1678
+		if ($this->checkout->redirect && ! empty($this->checkout->redirect_url)) {
1679
+			// store notices in a transient
1680
+			EE_Error::get_notices(false, true, true);
1681
+			// DEBUG LOG
1682
+			//$this->checkout->log(
1683
+			//	__CLASS__, __FUNCTION__, __LINE__,
1684
+			//	array(
1685
+			//		'headers_sent' => headers_sent(),
1686
+			//		'redirect_url'     => $this->checkout->redirect_url,
1687
+			//		'headers_list'    => headers_list(),
1688
+			//	)
1689
+			//);
1690
+			wp_safe_redirect($this->checkout->redirect_url);
1691
+			exit();
1692
+		}
1693
+	}
1694
+
1695
+
1696
+
1697
+	/**
1698
+	 *   set_checkout_anchor
1699
+	 *
1700
+	 * @access public
1701
+	 * @return void
1702
+	 */
1703
+	public function set_checkout_anchor()
1704
+	{
1705
+		echo '<a id="checkout" style="float: left; margin-left: -999em;"></a>';
1706
+	}
1707 1707
 
1708 1708
 
1709 1709
 
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -216,13 +216,13 @@  discard block
 block discarded – undo
216 216
      */
217 217
     public static function set_definitions()
218 218
     {
219
-        define('SPCO_BASE_PATH', rtrim(str_replace(array('\\', '/'), DS, plugin_dir_path(__FILE__)), DS) . DS);
220
-        define('SPCO_CSS_URL', plugin_dir_url(__FILE__) . 'css' . DS);
221
-        define('SPCO_IMG_URL', plugin_dir_url(__FILE__) . 'img' . DS);
222
-        define('SPCO_JS_URL', plugin_dir_url(__FILE__) . 'js' . DS);
223
-        define('SPCO_INC_PATH', SPCO_BASE_PATH . 'inc' . DS);
224
-        define('SPCO_REG_STEPS_PATH', SPCO_BASE_PATH . 'reg_steps' . DS);
225
-        define('SPCO_TEMPLATES_PATH', SPCO_BASE_PATH . 'templates' . DS);
219
+        define('SPCO_BASE_PATH', rtrim(str_replace(array('\\', '/'), DS, plugin_dir_path(__FILE__)), DS).DS);
220
+        define('SPCO_CSS_URL', plugin_dir_url(__FILE__).'css'.DS);
221
+        define('SPCO_IMG_URL', plugin_dir_url(__FILE__).'img'.DS);
222
+        define('SPCO_JS_URL', plugin_dir_url(__FILE__).'js'.DS);
223
+        define('SPCO_INC_PATH', SPCO_BASE_PATH.'inc'.DS);
224
+        define('SPCO_REG_STEPS_PATH', SPCO_BASE_PATH.'reg_steps'.DS);
225
+        define('SPCO_TEMPLATES_PATH', SPCO_BASE_PATH.'templates'.DS);
226 226
         EEH_Autoloader::register_autoloaders_for_each_file_in_folder(SPCO_BASE_PATH, true);
227 227
         EE_Registry::$i18n_js_strings['registration_expiration_notice'] = sprintf(
228 228
             __('%1$sWe\'re sorry, but you\'re registration time has expired.%2$s%4$sIf you still wish to complete your registration, please return to the %5$sEvent List%6$sEvent List%7$s and reselect your tickets if available. Please except our apologies for any inconvenience this may have caused.%8$s',
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
             '</h4>',
232 232
             '<br />',
233 233
             '<p>',
234
-            '<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
234
+            '<a href="'.get_post_type_archive_link('espresso_events').'" title="',
235 235
             '">',
236 236
             '</a>',
237 237
             '</p>'
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
             return;
256 256
         }
257 257
         // filter list of reg_steps
258
-        $reg_steps_to_load = (array)apply_filters(
258
+        $reg_steps_to_load = (array) apply_filters(
259 259
             'AHEE__SPCO__load_reg_steps__reg_steps_to_load',
260 260
             EED_Single_Page_Checkout::get_reg_steps()
261 261
         );
@@ -299,25 +299,25 @@  discard block
 block discarded – undo
299 299
         if (empty($reg_steps)) {
300 300
             $reg_steps = array(
301 301
                 10  => array(
302
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'attendee_information',
302
+                    'file_path'  => SPCO_REG_STEPS_PATH.'attendee_information',
303 303
                     'class_name' => 'EE_SPCO_Reg_Step_Attendee_Information',
304 304
                     'slug'       => 'attendee_information',
305 305
                     'has_hooks'  => false,
306 306
                 ),
307 307
                 20  => array(
308
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'registration_confirmation',
308
+                    'file_path'  => SPCO_REG_STEPS_PATH.'registration_confirmation',
309 309
                     'class_name' => 'EE_SPCO_Reg_Step_Registration_Confirmation',
310 310
                     'slug'       => 'registration_confirmation',
311 311
                     'has_hooks'  => false,
312 312
                 ),
313 313
                 30  => array(
314
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'payment_options',
314
+                    'file_path'  => SPCO_REG_STEPS_PATH.'payment_options',
315 315
                     'class_name' => 'EE_SPCO_Reg_Step_Payment_Options',
316 316
                     'slug'       => 'payment_options',
317 317
                     'has_hooks'  => true,
318 318
                 ),
319 319
                 999 => array(
320
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'finalize_registration',
320
+                    'file_path'  => SPCO_REG_STEPS_PATH.'finalize_registration',
321 321
                     'class_name' => 'EE_SPCO_Reg_Step_Finalize_Registration',
322 322
                     'slug'       => 'finalize_registration',
323 323
                     'has_hooks'  => false,
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
             // DEBUG LOG
500 500
             //$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
501 501
             // get reg form
502
-            if( ! $this->_check_form_submission()) {
502
+            if ( ! $this->_check_form_submission()) {
503 503
                 EED_Single_Page_Checkout::$_initialized = true;
504 504
                 return;
505 505
             }
@@ -610,7 +610,7 @@  discard block
 block discarded – undo
610 610
         // or some other kind of revisit ?
611 611
         $this->checkout->revisit = EE_Registry::instance()->REQ->get('revisit', false);
612 612
         // and whether or not to generate a reg form for this request
613
-        $this->checkout->generate_reg_form = EE_Registry::instance()->REQ->get('generate_reg_form', true);        // TRUE 	FALSE
613
+        $this->checkout->generate_reg_form = EE_Registry::instance()->REQ->get('generate_reg_form', true); // TRUE 	FALSE
614 614
         // and whether or not to process a reg form submission for this request
615 615
         $this->checkout->process_form_submission = EE_Registry::instance()->REQ->get(
616 616
             'process_form_submission',
@@ -618,7 +618,7 @@  discard block
 block discarded – undo
618 618
         ); // TRUE 	FALSE
619 619
         $this->checkout->process_form_submission = $this->checkout->action !== 'display_spco_reg_step'
620 620
             ? $this->checkout->process_form_submission
621
-            : false;        // TRUE 	FALSE
621
+            : false; // TRUE 	FALSE
622 622
         // $this->_display_request_vars();
623 623
     }
624 624
 
@@ -1051,7 +1051,7 @@  discard block
 block discarded – undo
1051 1051
                     if ( ! $registration instanceof EE_Registration) {
1052 1052
                         throw new InvalidEntityException($registration, 'EE_Registration');
1053 1053
                     }
1054
-                    $registrations[ $registration->ID() ] = $registration;
1054
+                    $registrations[$registration->ID()] = $registration;
1055 1055
                 }
1056 1056
             }
1057 1057
             $registration_processor->fix_reg_final_price_rounding_issue($transaction);
@@ -1281,7 +1281,7 @@  discard block
 block discarded – undo
1281 1281
                         ) {
1282 1282
                             EE_Error::add_success(
1283 1283
                                 $this->checkout->current_step->success_message()
1284
-                                . '<br />' . $this->checkout->next_step->_instructions()
1284
+                                . '<br />'.$this->checkout->next_step->_instructions()
1285 1285
                             );
1286 1286
                         }
1287 1287
                         // pack it up, pack it in...
@@ -1378,7 +1378,7 @@  discard block
 block discarded – undo
1378 1378
             '</h4>',
1379 1379
             '<br />',
1380 1380
             '<p>',
1381
-            '<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
1381
+            '<a href="'.get_post_type_archive_link('espresso_events').'" title="',
1382 1382
             '">',
1383 1383
             '</a>',
1384 1384
             '</p>'
@@ -1404,12 +1404,12 @@  discard block
 block discarded – undo
1404 1404
     public function enqueue_styles_and_scripts()
1405 1405
     {
1406 1406
         // load css
1407
-        wp_register_style('single_page_checkout', SPCO_CSS_URL . 'single_page_checkout.css', array(), EVENT_ESPRESSO_VERSION);
1407
+        wp_register_style('single_page_checkout', SPCO_CSS_URL.'single_page_checkout.css', array(), EVENT_ESPRESSO_VERSION);
1408 1408
         wp_enqueue_style('single_page_checkout');
1409 1409
         // load JS
1410
-        wp_register_script('jquery_plugin', EE_THIRD_PARTY_URL . 'jquery	.plugin.min.js', array('jquery'), '1.0.1', true);
1411
-        wp_register_script('jquery_countdown', EE_THIRD_PARTY_URL . 'jquery	.countdown.min.js', array('jquery_plugin'), '2.0.2', true);
1412
-        wp_register_script('single_page_checkout', SPCO_JS_URL . 'single_page_checkout.js', array('espresso_core', 'underscore', 'ee_form_section_validation', 'jquery_countdown'), EVENT_ESPRESSO_VERSION, true);
1410
+        wp_register_script('jquery_plugin', EE_THIRD_PARTY_URL.'jquery	.plugin.min.js', array('jquery'), '1.0.1', true);
1411
+        wp_register_script('jquery_countdown', EE_THIRD_PARTY_URL.'jquery	.countdown.min.js', array('jquery_plugin'), '2.0.2', true);
1412
+        wp_register_script('single_page_checkout', SPCO_JS_URL.'single_page_checkout.js', array('espresso_core', 'underscore', 'ee_form_section_validation', 'jquery_countdown'), EVENT_ESPRESSO_VERSION, true);
1413 1413
         $this->checkout->registration_form->enqueue_js();
1414 1414
         $this->checkout->current_step->reg_form->enqueue_js();
1415 1415
         wp_enqueue_script('single_page_checkout');
@@ -1422,7 +1422,7 @@  discard block
 block discarded – undo
1422 1422
          * dynamic action hook for enqueueing styles and scripts with spco calls.
1423 1423
          * The hook will end up being something like AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__attendee_information
1424 1424
          */
1425
-        do_action('AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__' . $this->checkout->current_step->slug(), $this);
1425
+        do_action('AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__'.$this->checkout->current_step->slug(), $this);
1426 1426
     }
1427 1427
 
1428 1428
 
@@ -1474,7 +1474,7 @@  discard block
 block discarded – undo
1474 1474
                     'layout_strategy' =>
1475 1475
                         new EE_Template_Layout(
1476 1476
                             array(
1477
-                                'layout_template_file' => SPCO_TEMPLATES_PATH . 'registration_page_wrapper.template.php',
1477
+                                'layout_template_file' => SPCO_TEMPLATES_PATH.'registration_page_wrapper.template.php',
1478 1478
                                 'template_args'        => array(
1479 1479
                                     'empty_cart'              => $empty_cart,
1480 1480
                                     'revisit'                 => $this->checkout->revisit,
@@ -1488,7 +1488,7 @@  discard block
 block discarded – undo
1488 1488
                                         sprintf(
1489 1489
                                             __('You need to %1$sReturn to Events list%2$sselect at least one event%3$s before you can proceed with the registration process.',
1490 1490
                                                 'event_espresso'),
1491
-                                            '<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
1491
+                                            '<a href="'.get_post_type_archive_link('espresso_events').'" title="',
1492 1492
                                             '">',
1493 1493
                                             '</a>'
1494 1494
                                         )
@@ -1542,7 +1542,7 @@  discard block
 block discarded – undo
1542 1542
         ) {
1543 1543
             add_filter(
1544 1544
                 'FHEE__EEH_Template__powered_by_event_espresso__url',
1545
-                function ($url) {
1545
+                function($url) {
1546 1546
                     return apply_filters('FHEE__EE_Front_Controller__registration_footer__url', $url);
1547 1547
                 }
1548 1548
             );
Please login to merge, or discard this patch.