Completed
Branch FET/11118/delay-instantiating-... (72aa82)
by
unknown
114:16 queued 101:31
created
core/admin/EE_Admin.core.php 2 patches
Indentation   +896 added lines, -896 removed lines patch added patch discarded remove patch
@@ -22,454 +22,454 @@  discard block
 block discarded – undo
22 22
 final class EE_Admin implements InterminableInterface
23 23
 {
24 24
 
25
-    /**
26
-     * @var EE_Admin $_instance
27
-     */
28
-    private static $_instance;
29
-
30
-    /**
31
-     * @var PersistentAdminNoticeManager $persistent_admin_notice_manager
32
-     */
33
-    private $persistent_admin_notice_manager;
34
-
35
-    /**
36
-     * @singleton method used to instantiate class object
37
-     * @return EE_Admin
38
-     * @throws EE_Error
39
-     */
40
-    public static function instance()
41
-    {
42
-        // check if class object is instantiated
43
-        if (! self::$_instance instanceof EE_Admin) {
44
-            self::$_instance = new self();
45
-        }
46
-        return self::$_instance;
47
-    }
48
-
49
-
50
-    /**
51
-     * @return EE_Admin
52
-     * @throws EE_Error
53
-     */
54
-    public static function reset()
55
-    {
56
-        self::$_instance = null;
57
-        return self::instance();
58
-    }
59
-
60
-
61
-    /**
62
-     * class constructor
63
-     *
64
-     * @throws EE_Error
65
-     * @throws InvalidDataTypeException
66
-     * @throws InvalidInterfaceException
67
-     * @throws InvalidArgumentException
68
-     */
69
-    protected function __construct()
70
-    {
71
-        // define global EE_Admin constants
72
-        $this->_define_all_constants();
73
-        // set autoloaders for our admin page classes based on included path information
74
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_ADMIN);
75
-        // admin hooks
76
-        add_filter('plugin_action_links', array($this, 'filter_plugin_actions'), 10, 2);
77
-        // load EE_Request_Handler early
78
-        add_action('AHEE__EE_System__core_loaded_and_ready', array($this, 'get_request'));
79
-        add_action('AHEE__EE_System__initialize_last', array($this, 'init'));
80
-        add_action('AHEE__EE_Admin_Page__route_admin_request', array($this, 'route_admin_request'), 100, 2);
81
-        add_action('wp_loaded', array($this, 'wp_loaded'), 100);
82
-        add_action('admin_init', array($this, 'admin_init'), 100);
83
-        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'), 20);
84
-        add_action('admin_notices', array($this, 'display_admin_notices'), 10);
85
-        add_action('network_admin_notices', array($this, 'display_admin_notices'), 10);
86
-        add_filter('pre_update_option', array($this, 'check_for_invalid_datetime_formats'), 100, 2);
87
-        add_filter('admin_footer_text', array($this, 'espresso_admin_footer'));
88
-        //reset Environment config (we only do this on admin page loads);
89
-        EE_Registry::instance()->CFG->environment->recheck_values();
90
-        do_action('AHEE__EE_Admin__loaded');
91
-    }
92
-
93
-
94
-
95
-    /**
96
-     * _define_all_constants
97
-     * define constants that are set globally for all admin pages
98
-     *
99
-     * @return void
100
-     */
101
-    private function _define_all_constants()
102
-    {
103
-        if (! defined('EE_ADMIN_URL')) {
104
-            define('EE_ADMIN_URL', EE_PLUGIN_DIR_URL . 'core/admin/');
105
-            define('EE_ADMIN_PAGES_URL', EE_PLUGIN_DIR_URL . 'admin_pages/');
106
-            define('EE_ADMIN_TEMPLATE', EE_ADMIN . 'templates' . DS);
107
-            define('WP_ADMIN_PATH', ABSPATH . 'wp-admin/');
108
-            define('WP_AJAX_URL', admin_url('admin-ajax.php'));
109
-        }
110
-    }
111
-
112
-
113
-    /**
114
-     * filter_plugin_actions - adds links to the Plugins page listing
115
-     *
116
-     * @param    array  $links
117
-     * @param    string $plugin
118
-     * @return    array
119
-     */
120
-    public function filter_plugin_actions($links, $plugin)
121
-    {
122
-        // set $main_file in stone
123
-        static $main_file;
124
-        // if $main_file is not set yet
125
-        if (! $main_file) {
126
-            $main_file = plugin_basename(EVENT_ESPRESSO_MAIN_FILE);
127
-        }
128
-        if ($plugin === $main_file) {
129
-            // compare current plugin to this one
130
-            if (EE_Maintenance_Mode::instance()->level() === EE_Maintenance_Mode::level_2_complete_maintenance) {
131
-                $maintenance_link = '<a href="admin.php?page=espresso_maintenance_settings"'
132
-                                    . ' title="Event Espresso is in maintenance mode.  Click this link to learn why.">'
133
-                                    . esc_html__('Maintenance Mode Active', 'event_espresso')
134
-                                    . '</a>';
135
-                array_unshift($links, $maintenance_link);
136
-            } else {
137
-                $org_settings_link = '<a href="admin.php?page=espresso_general_settings">'
138
-                                     . esc_html__('Settings', 'event_espresso')
139
-                                     . '</a>';
140
-                $events_link       = '<a href="admin.php?page=espresso_events">'
141
-                                     . esc_html__('Events', 'event_espresso')
142
-                                     . '</a>';
143
-                // add before other links
144
-                array_unshift($links, $org_settings_link, $events_link);
145
-            }
146
-        }
147
-        return $links;
148
-    }
149
-
150
-
151
-    /**
152
-     * _get_request
153
-     *
154
-     * @return void
155
-     * @throws EE_Error
156
-     * @throws InvalidArgumentException
157
-     * @throws InvalidDataTypeException
158
-     * @throws InvalidInterfaceException
159
-     * @throws ReflectionException
160
-     */
161
-    public function get_request()
162
-    {
163
-        EE_Registry::instance()->load_core('Request_Handler');
164
-        EE_Registry::instance()->load_core('CPT_Strategy');
165
-    }
166
-
167
-
168
-
169
-    /**
170
-     * hide_admin_pages_except_maintenance_mode
171
-     *
172
-     * @param array $admin_page_folder_names
173
-     * @return array
174
-     */
175
-    public function hide_admin_pages_except_maintenance_mode($admin_page_folder_names = array())
176
-    {
177
-        return array(
178
-            'maintenance' => EE_ADMIN_PAGES . 'maintenance' . DS,
179
-            'about'       => EE_ADMIN_PAGES . 'about' . DS,
180
-            'support'     => EE_ADMIN_PAGES . 'support' . DS,
181
-        );
182
-    }
183
-
184
-
185
-
186
-    /**
187
-     * init- should fire after shortcode, module,  addon, other plugin (default priority), and even
188
-     * EE_Front_Controller's init phases have run
189
-     *
190
-     * @return void
191
-     * @throws EE_Error
192
-     * @throws InvalidArgumentException
193
-     * @throws InvalidDataTypeException
194
-     * @throws InvalidInterfaceException
195
-     * @throws ReflectionException
196
-     * @throws ServiceNotFoundException
197
-     */
198
-    public function init()
199
-    {
200
-        //only enable most of the EE_Admin IF we're not in full maintenance mode
201
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
202
-            //ok so we want to enable the entire admin
203
-            $this->persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
204
-                'EventEspresso\core\services\notifications\PersistentAdminNoticeManager',
205
-                array(
206
-                    EE_Admin_Page::add_query_args_and_nonce(
207
-                        array(
208
-                            'page'   => EE_Registry::instance()->REQ->get('page', ''),
209
-                            'action' => EE_Registry::instance()->REQ->get('action', ''),
210
-                        ),
211
-                        EE_ADMIN_URL
212
-                    ),
213
-                )
214
-            );
215
-            $this->maybeSetDatetimeWarningNotice();
216
-            //at a glance dashboard widget
217
-            add_filter('dashboard_glance_items', array($this, 'dashboard_glance_items'), 10);
218
-            //filter for get_edit_post_link used on comments for custom post types
219
-            add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 2);
220
-        }
221
-        // run the admin page factory but ONLY if we are doing an ee admin ajax request
222
-        if (! defined('DOING_AJAX') || EE_ADMIN_AJAX) {
223
-            try {
224
-                //this loads the controller for the admin pages which will setup routing etc
225
-                EE_Registry::instance()->load_core('Admin_Page_Loader');
226
-            } catch (EE_Error $e) {
227
-                $e->get_error();
228
-            }
229
-        }
230
-        add_filter('content_save_pre', array($this, 'its_eSpresso'), 10, 1);
231
-        //make sure our CPTs and custom taxonomy metaboxes get shown for first time users
232
-        add_action('admin_head', array($this, 'enable_hidden_ee_nav_menu_metaboxes'), 10);
233
-        add_action('admin_head', array($this, 'register_custom_nav_menu_boxes'), 10);
234
-        //exclude EE critical pages from all nav menus and wp_list_pages
235
-        add_filter('nav_menu_meta_box_object', array($this, 'remove_pages_from_nav_menu'), 10);
236
-    }
237
-
238
-
239
-    /**
240
-     *    get_persistent_admin_notices
241
-     *
242
-     * @access    public
243
-     * @return void
244
-     * @throws EE_Error
245
-     * @throws InvalidArgumentException
246
-     * @throws InvalidDataTypeException
247
-     * @throws InvalidInterfaceException
248
-     */
249
-    public function maybeSetDatetimeWarningNotice()
250
-    {
251
-        //add dismissable notice for datetime changes.  Only valid if site does not have a timezone_string set.
252
-        //@todo This needs to stay in core for a bit to catch anyone upgrading from a version without this to a version
253
-        //with this.  But after enough time (indeterminate at this point) we can just remove this notice.
254
-        //this was added with https://events.codebasehq.com/projects/event-espresso/tickets/10626
255
-        if (! get_option('timezone_string') && EEM_Event::instance()->count() > 0) {
256
-            new PersistentAdminNotice(
257
-                'datetime_fix_notice',
258
-                sprintf(
259
-                    esc_html__(
260
-                        '%1$sImportant announcement related to your install of Event Espresso%2$s: There are some changes made to your site that could affect how dates display for your events and other related items with dates and times.  Read more about it %3$shere%4$s. If your dates and times are displaying incorrectly (incorrect offset), you can fix it using the tool on %5$sthis page%4$s.',
261
-                        'event_espresso'
262
-                    ),
263
-                    '<strong>',
264
-                    '</strong>',
265
-                    '<a href="https://eventespresso.com/2017/08/important-upcoming-changes-dates-times">',
266
-                    '</a>',
267
-                    '<a href="' . EE_Admin_Page::add_query_args_and_nonce(
268
-                        array(
269
-                            'page' => 'espresso_maintenance_settings',
270
-                            'action' => 'datetime_tools'
271
-                        ),
272
-                        admin_url('admin.php')
273
-                    ) . '">'
274
-                ),
275
-                false,
276
-                'manage_options',
277
-                'datetime_fix_persistent_notice'
278
-            );
279
-        }
280
-    }
281
-
282
-
283
-
284
-    /**
285
-     * this simply hooks into the nav menu setup of pages metabox and makes sure that we remove EE critical pages from
286
-     * the list of options. the wp function "wp_nav_menu_item_post_type_meta_box" found in
287
-     * wp-admin/includes/nav-menu.php looks for the "_default_query" property on the post_type object and it uses that
288
-     * to override any queries found in the existing query for the given post type.  Note that _default_query is not a
289
-     * normal property on the post_type object.  It's found ONLY in this particular context.
290
-     *
291
-     * @param WP_Post $post_type WP post type object
292
-     * @return WP_Post
293
-     * @throws InvalidArgumentException
294
-     * @throws InvalidDataTypeException
295
-     * @throws InvalidInterfaceException
296
-     */
297
-    public function remove_pages_from_nav_menu($post_type)
298
-    {
299
-        //if this isn't the "pages" post type let's get out
300
-        if ($post_type->name !== 'page') {
301
-            return $post_type;
302
-        }
303
-        $critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
304
-        $post_type->_default_query = array(
305
-            'post__not_in' => $critical_pages,
306
-        );
307
-        return $post_type;
308
-    }
309
-
310
-
311
-
312
-    /**
313
-     * WP by default only shows three metaboxes in "nav-menus.php" for first times users.  We want to make sure our
314
-     * metaboxes get shown as well
315
-     *
316
-     * @return void
317
-     */
318
-    public function enable_hidden_ee_nav_menu_metaboxes()
319
-    {
320
-        global $wp_meta_boxes, $pagenow;
321
-        if (! is_array($wp_meta_boxes) || $pagenow !== 'nav-menus.php') {
322
-            return;
323
-        }
324
-        $user = wp_get_current_user();
325
-        //has this been done yet?
326
-        if (get_user_option('ee_nav_menu_initialized', $user->ID)) {
327
-            return;
328
-        }
329
-
330
-        $hidden_meta_boxes  = get_user_option('metaboxhidden_nav-menus', $user->ID);
331
-        $initial_meta_boxes = apply_filters(
332
-            'FHEE__EE_Admin__enable_hidden_ee_nav_menu_boxes__initial_meta_boxes',
333
-            array(
334
-                'nav-menu-theme-locations',
335
-                'add-page',
336
-                'add-custom-links',
337
-                'add-category',
338
-                'add-espresso_events',
339
-                'add-espresso_venues',
340
-                'add-espresso_event_categories',
341
-                'add-espresso_venue_categories',
342
-                'add-post-type-post',
343
-                'add-post-type-page',
344
-            )
345
-        );
346
-
347
-        if (is_array($hidden_meta_boxes)) {
348
-            foreach ($hidden_meta_boxes as $key => $meta_box_id) {
349
-                if (in_array($meta_box_id, $initial_meta_boxes, true)) {
350
-                    unset($hidden_meta_boxes[$key]);
351
-                }
352
-            }
353
-        }
354
-        update_user_option($user->ID, 'metaboxhidden_nav-menus', $hidden_meta_boxes, true);
355
-        update_user_option($user->ID, 'ee_nav_menu_initialized', 1, true);
356
-    }
357
-
358
-
359
-
360
-    /**
361
-     * This method simply registers custom nav menu boxes for "nav_menus.php route"
362
-     * Currently EE is using this to make sure there are menu options for our CPT archive page routes.
363
-     *
364
-     * @todo   modify this so its more dynamic and automatic for all ee CPTs and setups and can also be hooked into by
365
-     *         addons etc.
366
-     * @return void
367
-     */
368
-    public function register_custom_nav_menu_boxes()
369
-    {
370
-        add_meta_box(
371
-            'add-extra-nav-menu-pages',
372
-            esc_html__('Event Espresso Pages', 'event_espresso'),
373
-            array($this, 'ee_cpt_archive_pages'),
374
-            'nav-menus',
375
-            'side',
376
-            'core'
377
-        );
378
-    }
379
-
380
-
381
-
382
-    /**
383
-     * Use this to edit the post link for our cpts so that the edit link points to the correct page.
384
-     *
385
-     * @since   4.3.0
386
-     * @param string $link the original link generated by wp
387
-     * @param int    $id   post id
388
-     * @return string  the (maybe) modified link
389
-     */
390
-    public function modify_edit_post_link($link, $id)
391
-    {
392
-        if (! $post = get_post($id)) {
393
-            return $link;
394
-        }
395
-        if ($post->post_type === 'espresso_attendees') {
396
-            $query_args = array(
397
-                'action' => 'edit_attendee',
398
-                'post'   => $id,
399
-            );
400
-            return EEH_URL::add_query_args_and_nonce(
401
-                $query_args,
402
-                admin_url('admin.php?page=espresso_registrations')
403
-            );
404
-        }
405
-        return $link;
406
-    }
407
-
408
-
409
-
410
-    public function ee_cpt_archive_pages()
411
-    {
412
-        global $nav_menu_selected_id;
413
-        $db_fields   = false;
414
-        $walker      = new Walker_Nav_Menu_Checklist($db_fields);
415
-        $current_tab = 'event-archives';
416
-        $removed_args = array(
417
-            'action',
418
-            'customlink-tab',
419
-            'edit-menu-item',
420
-            'menu-item',
421
-            'page-tab',
422
-            '_wpnonce',
423
-        );
424
-        ?>
25
+	/**
26
+	 * @var EE_Admin $_instance
27
+	 */
28
+	private static $_instance;
29
+
30
+	/**
31
+	 * @var PersistentAdminNoticeManager $persistent_admin_notice_manager
32
+	 */
33
+	private $persistent_admin_notice_manager;
34
+
35
+	/**
36
+	 * @singleton method used to instantiate class object
37
+	 * @return EE_Admin
38
+	 * @throws EE_Error
39
+	 */
40
+	public static function instance()
41
+	{
42
+		// check if class object is instantiated
43
+		if (! self::$_instance instanceof EE_Admin) {
44
+			self::$_instance = new self();
45
+		}
46
+		return self::$_instance;
47
+	}
48
+
49
+
50
+	/**
51
+	 * @return EE_Admin
52
+	 * @throws EE_Error
53
+	 */
54
+	public static function reset()
55
+	{
56
+		self::$_instance = null;
57
+		return self::instance();
58
+	}
59
+
60
+
61
+	/**
62
+	 * class constructor
63
+	 *
64
+	 * @throws EE_Error
65
+	 * @throws InvalidDataTypeException
66
+	 * @throws InvalidInterfaceException
67
+	 * @throws InvalidArgumentException
68
+	 */
69
+	protected function __construct()
70
+	{
71
+		// define global EE_Admin constants
72
+		$this->_define_all_constants();
73
+		// set autoloaders for our admin page classes based on included path information
74
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_ADMIN);
75
+		// admin hooks
76
+		add_filter('plugin_action_links', array($this, 'filter_plugin_actions'), 10, 2);
77
+		// load EE_Request_Handler early
78
+		add_action('AHEE__EE_System__core_loaded_and_ready', array($this, 'get_request'));
79
+		add_action('AHEE__EE_System__initialize_last', array($this, 'init'));
80
+		add_action('AHEE__EE_Admin_Page__route_admin_request', array($this, 'route_admin_request'), 100, 2);
81
+		add_action('wp_loaded', array($this, 'wp_loaded'), 100);
82
+		add_action('admin_init', array($this, 'admin_init'), 100);
83
+		add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'), 20);
84
+		add_action('admin_notices', array($this, 'display_admin_notices'), 10);
85
+		add_action('network_admin_notices', array($this, 'display_admin_notices'), 10);
86
+		add_filter('pre_update_option', array($this, 'check_for_invalid_datetime_formats'), 100, 2);
87
+		add_filter('admin_footer_text', array($this, 'espresso_admin_footer'));
88
+		//reset Environment config (we only do this on admin page loads);
89
+		EE_Registry::instance()->CFG->environment->recheck_values();
90
+		do_action('AHEE__EE_Admin__loaded');
91
+	}
92
+
93
+
94
+
95
+	/**
96
+	 * _define_all_constants
97
+	 * define constants that are set globally for all admin pages
98
+	 *
99
+	 * @return void
100
+	 */
101
+	private function _define_all_constants()
102
+	{
103
+		if (! defined('EE_ADMIN_URL')) {
104
+			define('EE_ADMIN_URL', EE_PLUGIN_DIR_URL . 'core/admin/');
105
+			define('EE_ADMIN_PAGES_URL', EE_PLUGIN_DIR_URL . 'admin_pages/');
106
+			define('EE_ADMIN_TEMPLATE', EE_ADMIN . 'templates' . DS);
107
+			define('WP_ADMIN_PATH', ABSPATH . 'wp-admin/');
108
+			define('WP_AJAX_URL', admin_url('admin-ajax.php'));
109
+		}
110
+	}
111
+
112
+
113
+	/**
114
+	 * filter_plugin_actions - adds links to the Plugins page listing
115
+	 *
116
+	 * @param    array  $links
117
+	 * @param    string $plugin
118
+	 * @return    array
119
+	 */
120
+	public function filter_plugin_actions($links, $plugin)
121
+	{
122
+		// set $main_file in stone
123
+		static $main_file;
124
+		// if $main_file is not set yet
125
+		if (! $main_file) {
126
+			$main_file = plugin_basename(EVENT_ESPRESSO_MAIN_FILE);
127
+		}
128
+		if ($plugin === $main_file) {
129
+			// compare current plugin to this one
130
+			if (EE_Maintenance_Mode::instance()->level() === EE_Maintenance_Mode::level_2_complete_maintenance) {
131
+				$maintenance_link = '<a href="admin.php?page=espresso_maintenance_settings"'
132
+									. ' title="Event Espresso is in maintenance mode.  Click this link to learn why.">'
133
+									. esc_html__('Maintenance Mode Active', 'event_espresso')
134
+									. '</a>';
135
+				array_unshift($links, $maintenance_link);
136
+			} else {
137
+				$org_settings_link = '<a href="admin.php?page=espresso_general_settings">'
138
+									 . esc_html__('Settings', 'event_espresso')
139
+									 . '</a>';
140
+				$events_link       = '<a href="admin.php?page=espresso_events">'
141
+									 . esc_html__('Events', 'event_espresso')
142
+									 . '</a>';
143
+				// add before other links
144
+				array_unshift($links, $org_settings_link, $events_link);
145
+			}
146
+		}
147
+		return $links;
148
+	}
149
+
150
+
151
+	/**
152
+	 * _get_request
153
+	 *
154
+	 * @return void
155
+	 * @throws EE_Error
156
+	 * @throws InvalidArgumentException
157
+	 * @throws InvalidDataTypeException
158
+	 * @throws InvalidInterfaceException
159
+	 * @throws ReflectionException
160
+	 */
161
+	public function get_request()
162
+	{
163
+		EE_Registry::instance()->load_core('Request_Handler');
164
+		EE_Registry::instance()->load_core('CPT_Strategy');
165
+	}
166
+
167
+
168
+
169
+	/**
170
+	 * hide_admin_pages_except_maintenance_mode
171
+	 *
172
+	 * @param array $admin_page_folder_names
173
+	 * @return array
174
+	 */
175
+	public function hide_admin_pages_except_maintenance_mode($admin_page_folder_names = array())
176
+	{
177
+		return array(
178
+			'maintenance' => EE_ADMIN_PAGES . 'maintenance' . DS,
179
+			'about'       => EE_ADMIN_PAGES . 'about' . DS,
180
+			'support'     => EE_ADMIN_PAGES . 'support' . DS,
181
+		);
182
+	}
183
+
184
+
185
+
186
+	/**
187
+	 * init- should fire after shortcode, module,  addon, other plugin (default priority), and even
188
+	 * EE_Front_Controller's init phases have run
189
+	 *
190
+	 * @return void
191
+	 * @throws EE_Error
192
+	 * @throws InvalidArgumentException
193
+	 * @throws InvalidDataTypeException
194
+	 * @throws InvalidInterfaceException
195
+	 * @throws ReflectionException
196
+	 * @throws ServiceNotFoundException
197
+	 */
198
+	public function init()
199
+	{
200
+		//only enable most of the EE_Admin IF we're not in full maintenance mode
201
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
202
+			//ok so we want to enable the entire admin
203
+			$this->persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
204
+				'EventEspresso\core\services\notifications\PersistentAdminNoticeManager',
205
+				array(
206
+					EE_Admin_Page::add_query_args_and_nonce(
207
+						array(
208
+							'page'   => EE_Registry::instance()->REQ->get('page', ''),
209
+							'action' => EE_Registry::instance()->REQ->get('action', ''),
210
+						),
211
+						EE_ADMIN_URL
212
+					),
213
+				)
214
+			);
215
+			$this->maybeSetDatetimeWarningNotice();
216
+			//at a glance dashboard widget
217
+			add_filter('dashboard_glance_items', array($this, 'dashboard_glance_items'), 10);
218
+			//filter for get_edit_post_link used on comments for custom post types
219
+			add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 2);
220
+		}
221
+		// run the admin page factory but ONLY if we are doing an ee admin ajax request
222
+		if (! defined('DOING_AJAX') || EE_ADMIN_AJAX) {
223
+			try {
224
+				//this loads the controller for the admin pages which will setup routing etc
225
+				EE_Registry::instance()->load_core('Admin_Page_Loader');
226
+			} catch (EE_Error $e) {
227
+				$e->get_error();
228
+			}
229
+		}
230
+		add_filter('content_save_pre', array($this, 'its_eSpresso'), 10, 1);
231
+		//make sure our CPTs and custom taxonomy metaboxes get shown for first time users
232
+		add_action('admin_head', array($this, 'enable_hidden_ee_nav_menu_metaboxes'), 10);
233
+		add_action('admin_head', array($this, 'register_custom_nav_menu_boxes'), 10);
234
+		//exclude EE critical pages from all nav menus and wp_list_pages
235
+		add_filter('nav_menu_meta_box_object', array($this, 'remove_pages_from_nav_menu'), 10);
236
+	}
237
+
238
+
239
+	/**
240
+	 *    get_persistent_admin_notices
241
+	 *
242
+	 * @access    public
243
+	 * @return void
244
+	 * @throws EE_Error
245
+	 * @throws InvalidArgumentException
246
+	 * @throws InvalidDataTypeException
247
+	 * @throws InvalidInterfaceException
248
+	 */
249
+	public function maybeSetDatetimeWarningNotice()
250
+	{
251
+		//add dismissable notice for datetime changes.  Only valid if site does not have a timezone_string set.
252
+		//@todo This needs to stay in core for a bit to catch anyone upgrading from a version without this to a version
253
+		//with this.  But after enough time (indeterminate at this point) we can just remove this notice.
254
+		//this was added with https://events.codebasehq.com/projects/event-espresso/tickets/10626
255
+		if (! get_option('timezone_string') && EEM_Event::instance()->count() > 0) {
256
+			new PersistentAdminNotice(
257
+				'datetime_fix_notice',
258
+				sprintf(
259
+					esc_html__(
260
+						'%1$sImportant announcement related to your install of Event Espresso%2$s: There are some changes made to your site that could affect how dates display for your events and other related items with dates and times.  Read more about it %3$shere%4$s. If your dates and times are displaying incorrectly (incorrect offset), you can fix it using the tool on %5$sthis page%4$s.',
261
+						'event_espresso'
262
+					),
263
+					'<strong>',
264
+					'</strong>',
265
+					'<a href="https://eventespresso.com/2017/08/important-upcoming-changes-dates-times">',
266
+					'</a>',
267
+					'<a href="' . EE_Admin_Page::add_query_args_and_nonce(
268
+						array(
269
+							'page' => 'espresso_maintenance_settings',
270
+							'action' => 'datetime_tools'
271
+						),
272
+						admin_url('admin.php')
273
+					) . '">'
274
+				),
275
+				false,
276
+				'manage_options',
277
+				'datetime_fix_persistent_notice'
278
+			);
279
+		}
280
+	}
281
+
282
+
283
+
284
+	/**
285
+	 * this simply hooks into the nav menu setup of pages metabox and makes sure that we remove EE critical pages from
286
+	 * the list of options. the wp function "wp_nav_menu_item_post_type_meta_box" found in
287
+	 * wp-admin/includes/nav-menu.php looks for the "_default_query" property on the post_type object and it uses that
288
+	 * to override any queries found in the existing query for the given post type.  Note that _default_query is not a
289
+	 * normal property on the post_type object.  It's found ONLY in this particular context.
290
+	 *
291
+	 * @param WP_Post $post_type WP post type object
292
+	 * @return WP_Post
293
+	 * @throws InvalidArgumentException
294
+	 * @throws InvalidDataTypeException
295
+	 * @throws InvalidInterfaceException
296
+	 */
297
+	public function remove_pages_from_nav_menu($post_type)
298
+	{
299
+		//if this isn't the "pages" post type let's get out
300
+		if ($post_type->name !== 'page') {
301
+			return $post_type;
302
+		}
303
+		$critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
304
+		$post_type->_default_query = array(
305
+			'post__not_in' => $critical_pages,
306
+		);
307
+		return $post_type;
308
+	}
309
+
310
+
311
+
312
+	/**
313
+	 * WP by default only shows three metaboxes in "nav-menus.php" for first times users.  We want to make sure our
314
+	 * metaboxes get shown as well
315
+	 *
316
+	 * @return void
317
+	 */
318
+	public function enable_hidden_ee_nav_menu_metaboxes()
319
+	{
320
+		global $wp_meta_boxes, $pagenow;
321
+		if (! is_array($wp_meta_boxes) || $pagenow !== 'nav-menus.php') {
322
+			return;
323
+		}
324
+		$user = wp_get_current_user();
325
+		//has this been done yet?
326
+		if (get_user_option('ee_nav_menu_initialized', $user->ID)) {
327
+			return;
328
+		}
329
+
330
+		$hidden_meta_boxes  = get_user_option('metaboxhidden_nav-menus', $user->ID);
331
+		$initial_meta_boxes = apply_filters(
332
+			'FHEE__EE_Admin__enable_hidden_ee_nav_menu_boxes__initial_meta_boxes',
333
+			array(
334
+				'nav-menu-theme-locations',
335
+				'add-page',
336
+				'add-custom-links',
337
+				'add-category',
338
+				'add-espresso_events',
339
+				'add-espresso_venues',
340
+				'add-espresso_event_categories',
341
+				'add-espresso_venue_categories',
342
+				'add-post-type-post',
343
+				'add-post-type-page',
344
+			)
345
+		);
346
+
347
+		if (is_array($hidden_meta_boxes)) {
348
+			foreach ($hidden_meta_boxes as $key => $meta_box_id) {
349
+				if (in_array($meta_box_id, $initial_meta_boxes, true)) {
350
+					unset($hidden_meta_boxes[$key]);
351
+				}
352
+			}
353
+		}
354
+		update_user_option($user->ID, 'metaboxhidden_nav-menus', $hidden_meta_boxes, true);
355
+		update_user_option($user->ID, 'ee_nav_menu_initialized', 1, true);
356
+	}
357
+
358
+
359
+
360
+	/**
361
+	 * This method simply registers custom nav menu boxes for "nav_menus.php route"
362
+	 * Currently EE is using this to make sure there are menu options for our CPT archive page routes.
363
+	 *
364
+	 * @todo   modify this so its more dynamic and automatic for all ee CPTs and setups and can also be hooked into by
365
+	 *         addons etc.
366
+	 * @return void
367
+	 */
368
+	public function register_custom_nav_menu_boxes()
369
+	{
370
+		add_meta_box(
371
+			'add-extra-nav-menu-pages',
372
+			esc_html__('Event Espresso Pages', 'event_espresso'),
373
+			array($this, 'ee_cpt_archive_pages'),
374
+			'nav-menus',
375
+			'side',
376
+			'core'
377
+		);
378
+	}
379
+
380
+
381
+
382
+	/**
383
+	 * Use this to edit the post link for our cpts so that the edit link points to the correct page.
384
+	 *
385
+	 * @since   4.3.0
386
+	 * @param string $link the original link generated by wp
387
+	 * @param int    $id   post id
388
+	 * @return string  the (maybe) modified link
389
+	 */
390
+	public function modify_edit_post_link($link, $id)
391
+	{
392
+		if (! $post = get_post($id)) {
393
+			return $link;
394
+		}
395
+		if ($post->post_type === 'espresso_attendees') {
396
+			$query_args = array(
397
+				'action' => 'edit_attendee',
398
+				'post'   => $id,
399
+			);
400
+			return EEH_URL::add_query_args_and_nonce(
401
+				$query_args,
402
+				admin_url('admin.php?page=espresso_registrations')
403
+			);
404
+		}
405
+		return $link;
406
+	}
407
+
408
+
409
+
410
+	public function ee_cpt_archive_pages()
411
+	{
412
+		global $nav_menu_selected_id;
413
+		$db_fields   = false;
414
+		$walker      = new Walker_Nav_Menu_Checklist($db_fields);
415
+		$current_tab = 'event-archives';
416
+		$removed_args = array(
417
+			'action',
418
+			'customlink-tab',
419
+			'edit-menu-item',
420
+			'menu-item',
421
+			'page-tab',
422
+			'_wpnonce',
423
+		);
424
+		?>
425 425
         <div id="posttype-extra-nav-menu-pages" class="posttypediv">
426 426
             <ul id="posttype-extra-nav-menu-pages-tabs" class="posttype-tabs add-menu-item-tabs">
427 427
                 <li <?php echo('event-archives' === $current_tab ? ' class="tabs"' : ''); ?>>
428 428
                     <a class="nav-tab-link" data-type="tabs-panel-posttype-extra-nav-menu-pages-event-archives"
429 429
                        href="<?php if ($nav_menu_selected_id) {
430
-                            echo esc_url(
431
-                                add_query_arg(
432
-                                    'extra-nav-menu-pages-tab',
433
-                                    'event-archives',
434
-                                    remove_query_arg($removed_args)
435
-                                )
436
-                            );
437
-                       } ?>#tabs-panel-posttype-extra-nav-menu-pages-event-archives">
430
+							echo esc_url(
431
+								add_query_arg(
432
+									'extra-nav-menu-pages-tab',
433
+									'event-archives',
434
+									remove_query_arg($removed_args)
435
+								)
436
+							);
437
+					   } ?>#tabs-panel-posttype-extra-nav-menu-pages-event-archives">
438 438
                         <?php _e('Event Archive Pages', 'event_espresso'); ?>
439 439
                     </a>
440 440
                 </li>
441 441
             </ul><!-- .posttype-tabs -->
442 442
 
443 443
             <div id="tabs-panel-posttype-extra-nav-menu-pages-event-archives" class="tabs-panel <?php
444
-                echo('event-archives' === $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive');
445
-                ?>">
444
+				echo('event-archives' === $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive');
445
+				?>">
446 446
                     <ul id="extra-nav-menu-pageschecklist-event-archives" class="categorychecklist form-no-clear">
447 447
                         <?php
448
-                        $pages          = $this->_get_extra_nav_menu_pages_items();
449
-                        $args['walker'] = $walker;
450
-                        echo walk_nav_menu_tree(
451
-                            array_map(
452
-                                array($this, '_setup_extra_nav_menu_pages_items'),
453
-                                $pages
454
-                            ),
455
-                            0,
456
-                            (object) $args
457
-                        );
458
-                        ?>
448
+						$pages          = $this->_get_extra_nav_menu_pages_items();
449
+						$args['walker'] = $walker;
450
+						echo walk_nav_menu_tree(
451
+							array_map(
452
+								array($this, '_setup_extra_nav_menu_pages_items'),
453
+								$pages
454
+							),
455
+							0,
456
+							(object) $args
457
+						);
458
+						?>
459 459
                     </ul>
460 460
                 </div><!-- /.tabs-panel -->
461 461
 
462 462
                 <p class="button-controls">
463 463
                 <span class="list-controls">
464 464
                     <a href="<?php
465
-                    echo esc_url(add_query_arg(
466
-                        array(
467
-                            'extra-nav-menu-pages-tab' => 'event-archives',
468
-                            'selectall'                => 1,
469
-                        ),
470
-                        remove_query_arg($removed_args)
471
-                    ));
472
-                    ?>#posttype-extra-nav-menu-pages>" class="select-all"><?php _e('Select All'); ?></a>
465
+					echo esc_url(add_query_arg(
466
+						array(
467
+							'extra-nav-menu-pages-tab' => 'event-archives',
468
+							'selectall'                => 1,
469
+						),
470
+						remove_query_arg($removed_args)
471
+					));
472
+					?>#posttype-extra-nav-menu-pages>" class="select-all"><?php _e('Select All'); ?></a>
473 473
                 </span>
474 474
                 <span class="add-to-menu">
475 475
                     <input type="submit"<?php wp_nav_menu_disabled_check($nav_menu_selected_id); ?>
@@ -482,471 +482,471 @@  discard block
 block discarded – undo
482 482
 
483 483
         </div><!-- /.posttypediv -->
484 484
         <?php
485
-    }
486
-
487
-
488
-    /**
489
-     * Returns an array of event archive nav items.
490
-     *
491
-     * @todo  for now this method is just in place so when it gets abstracted further we can substitute in whatever
492
-     *        method we use for getting the extra nav menu items
493
-     * @return array
494
-     */
495
-    private function _get_extra_nav_menu_pages_items()
496
-    {
497
-        $menuitems[] = array(
498
-            'title'       => esc_html__('Event List', 'event_espresso'),
499
-            'url'         => get_post_type_archive_link('espresso_events'),
500
-            'description' => esc_html__('Archive page for all events.', 'event_espresso'),
501
-        );
502
-        return apply_filters('FHEE__EE_Admin__get_extra_nav_menu_pages_items', $menuitems);
503
-    }
504
-
505
-
506
-    /**
507
-     * Setup nav menu walker item for usage in the event archive nav menu metabox.  It receives a menu_item array with
508
-     * the properties and converts it to the menu item object.
509
-     *
510
-     * @see wp_setup_nav_menu_item() in wp-includes/nav-menu.php
511
-     * @param $menu_item_values
512
-     * @return stdClass
513
-     */
514
-    private function _setup_extra_nav_menu_pages_items($menu_item_values)
515
-    {
516
-        $menu_item = new stdClass();
517
-        $keys      = array(
518
-            'ID'               => 0,
519
-            'db_id'            => 0,
520
-            'menu_item_parent' => 0,
521
-            'object_id'        => -1,
522
-            'post_parent'      => 0,
523
-            'type'             => 'custom',
524
-            'object'           => '',
525
-            'type_label'       => esc_html__('Extra Nav Menu Item', 'event_espresso'),
526
-            'title'            => '',
527
-            'url'              => '',
528
-            'target'           => '',
529
-            'attr_title'       => '',
530
-            'description'      => '',
531
-            'classes'          => array(),
532
-            'xfn'              => '',
533
-        );
534
-
535
-        foreach ($keys as $key => $value) {
536
-            $menu_item->{$key} = isset($menu_item_values[$key]) ? $menu_item_values[$key] : $value;
537
-        }
538
-        return $menu_item;
539
-    }
540
-
541
-
542
-    /**
543
-     * This is the action hook for the AHEE__EE_Admin_Page__route_admin_request hook that fires off right before an
544
-     * EE_Admin_Page route is called.
545
-     *
546
-     * @return void
547
-     */
548
-    public function route_admin_request()
549
-    {
550
-    }
551
-
552
-
553
-    /**
554
-     * wp_loaded should fire on the WordPress wp_loaded hook.  This fires on a VERY late priority.
555
-     *
556
-     * @return void
557
-     */
558
-    public function wp_loaded()
559
-    {
560
-    }
561
-
562
-
563
-    /**
564
-     * admin_init
565
-     *
566
-     * @return void
567
-     * @throws EE_Error
568
-     * @throws InvalidArgumentException
569
-     * @throws InvalidDataTypeException
570
-     * @throws InvalidInterfaceException
571
-     * @throws ReflectionException
572
-     */
573
-    public function admin_init()
574
-    {
575
-
576
-        /**
577
-         * our cpt models must be instantiated on WordPress post processing routes (wp-admin/post.php),
578
-         * so any hooking into core WP routes is taken care of.  So in this next few lines of code:
579
-         * - check if doing post processing.
580
-         * - check if doing post processing of one of EE CPTs
581
-         * - instantiate the corresponding EE CPT model for the post_type being processed.
582
-         */
583
-        if (isset($_POST['action'], $_POST['post_type']) && $_POST['action'] === 'editpost') {
584
-            EE_Registry::instance()->load_core('Register_CPTs');
585
-            EE_Register_CPTs::instantiate_cpt_models($_POST['post_type']);
586
-        }
587
-
588
-
589
-        /**
590
-         * This code excludes EE critical pages anywhere `wp_dropdown_pages` is used to create a dropdown for selecting
591
-         * critical pages.  The only place critical pages need included in a generated dropdown is on the "Critical
592
-         * Pages" tab in the EE General Settings Admin page.
593
-         * This is for user-proofing.
594
-         */
595
-        add_filter('wp_dropdown_pages', array($this, 'modify_dropdown_pages'));
596
-    }
597
-
598
-
599
-    /**
600
-     * Callback for wp_dropdown_pages hook to remove ee critical pages from the dropdown selection.
601
-     *
602
-     * @param string $output Current output.
603
-     * @return string
604
-     * @throws InvalidArgumentException
605
-     * @throws InvalidDataTypeException
606
-     * @throws InvalidInterfaceException
607
-     */
608
-    public function modify_dropdown_pages($output)
609
-    {
610
-        //get critical pages
611
-        $critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
612
-
613
-        //split current output by line break for easier parsing.
614
-        $split_output = explode("\n", $output);
615
-
616
-        //loop through to remove any critical pages from the array.
617
-        foreach ($critical_pages as $page_id) {
618
-            $needle = 'value="' . $page_id . '"';
619
-            foreach ($split_output as $key => $haystack) {
620
-                if (strpos($haystack, $needle) !== false) {
621
-                    unset($split_output[$key]);
622
-                }
623
-            }
624
-        }
625
-        //replace output with the new contents
626
-        return implode("\n", $split_output);
627
-    }
628
-
629
-
630
-    /**
631
-     * enqueue all admin scripts that need loaded for admin pages
632
-     *
633
-     * @return void
634
-     */
635
-    public function enqueue_admin_scripts()
636
-    {
637
-        // this javascript is loaded on every admin page to catch any injections ee needs to add to wp run js.
638
-        // Note: the intention of this script is to only do TARGETED injections.  I.E, only injecting on certain script
639
-        // calls.
640
-        wp_enqueue_script(
641
-            'ee-inject-wp',
642
-            EE_ADMIN_URL . 'assets/ee-cpt-wp-injects.js',
643
-            array('jquery'),
644
-            EVENT_ESPRESSO_VERSION,
645
-            true
646
-        );
647
-        // register cookie script for future dependencies
648
-        wp_register_script(
649
-            'jquery-cookie',
650
-            EE_THIRD_PARTY_URL . 'joyride/jquery.cookie.js',
651
-            array('jquery'),
652
-            '2.1',
653
-            true
654
-        );
655
-        //joyride is turned OFF by default, but prior to the admin_enqueue_scripts hook, can be turned back on again
656
-        // via: add_filter('FHEE_load_joyride', '__return_true' );
657
-        if (apply_filters('FHEE_load_joyride', false)) {
658
-            //joyride style
659
-            wp_register_style('joyride-css', EE_THIRD_PARTY_URL . 'joyride/joyride-2.1.css', array(), '2.1');
660
-            wp_register_style(
661
-                'ee-joyride-css',
662
-                EE_GLOBAL_ASSETS_URL . 'css/ee-joyride-styles.css',
663
-                array('joyride-css'),
664
-                EVENT_ESPRESSO_VERSION
665
-            );
666
-            wp_register_script(
667
-                'joyride-modernizr',
668
-                EE_THIRD_PARTY_URL . 'joyride/modernizr.mq.js',
669
-                array(),
670
-                '2.1',
671
-                true
672
-            );
673
-            //joyride JS
674
-            wp_register_script(
675
-                'jquery-joyride',
676
-                EE_THIRD_PARTY_URL . 'joyride/jquery.joyride-2.1.js',
677
-                array('jquery-cookie', 'joyride-modernizr'),
678
-                '2.1',
679
-                true
680
-            );
681
-            // wanna go for a joyride?
682
-            wp_enqueue_style('ee-joyride-css');
683
-            wp_enqueue_script('jquery-joyride');
684
-        }
685
-    }
686
-
687
-
688
-    /**
689
-     * display_admin_notices
690
-     *
691
-     * @return void
692
-     */
693
-    public function display_admin_notices()
694
-    {
695
-        echo EE_Error::get_notices();
696
-    }
697
-
698
-
699
-
700
-    /**
701
-     * @param array $elements
702
-     * @return array
703
-     * @throws EE_Error
704
-     * @throws InvalidArgumentException
705
-     * @throws InvalidDataTypeException
706
-     * @throws InvalidInterfaceException
707
-     */
708
-    public function dashboard_glance_items($elements)
709
-    {
710
-        $elements                        = is_array($elements) ? $elements : array($elements);
711
-        $events                          = EEM_Event::instance()->count();
712
-        $items['events']['url']          = EE_Admin_Page::add_query_args_and_nonce(
713
-            array('page' => 'espresso_events'),
714
-            admin_url('admin.php')
715
-        );
716
-        $items['events']['text']         = sprintf(_n('%s Event', '%s Events', $events), number_format_i18n($events));
717
-        $items['events']['title']        = esc_html__('Click to view all Events', 'event_espresso');
718
-        $registrations                   = EEM_Registration::instance()->count(
719
-            array(
720
-                array(
721
-                    'STS_ID' => array('!=', EEM_Registration::status_id_incomplete),
722
-                ),
723
-            )
724
-        );
725
-        $items['registrations']['url']   = EE_Admin_Page::add_query_args_and_nonce(
726
-            array('page' => 'espresso_registrations'),
727
-            admin_url('admin.php')
728
-        );
729
-        $items['registrations']['text']  = sprintf(
730
-            _n('%s Registration', '%s Registrations', $registrations),
731
-            number_format_i18n($registrations)
732
-        );
733
-        $items['registrations']['title'] = esc_html__('Click to view all registrations', 'event_espresso');
734
-
735
-        $items = (array)apply_filters('FHEE__EE_Admin__dashboard_glance_items__items', $items);
736
-
737
-        foreach ($items as $type => $item_properties) {
738
-            $elements[] = sprintf(
739
-                '<a class="ee-dashboard-link-' . $type . '" href="%s" title="%s">%s</a>',
740
-                $item_properties['url'],
741
-                $item_properties['title'],
742
-                $item_properties['text']
743
-            );
744
-        }
745
-        return $elements;
746
-    }
747
-
748
-
749
-    /**
750
-     * check_for_invalid_datetime_formats
751
-     * if an admin changes their date or time format settings on the WP General Settings admin page, verify that
752
-     * their selected format can be parsed by PHP
753
-     *
754
-     * @param    $value
755
-     * @param    $option
756
-     * @throws EE_Error
757
-     * @return    string
758
-     */
759
-    public function check_for_invalid_datetime_formats($value, $option)
760
-    {
761
-        // check for date_format or time_format
762
-        switch ($option) {
763
-            case 'date_format':
764
-                $date_time_format = $value . ' ' . get_option('time_format');
765
-                break;
766
-            case 'time_format':
767
-                $date_time_format = get_option('date_format') . ' ' . $value;
768
-                break;
769
-            default:
770
-                $date_time_format = false;
771
-        }
772
-        // do we have a date_time format to check ?
773
-        if ($date_time_format) {
774
-            $error_msg = EEH_DTT_Helper::validate_format_string($date_time_format);
775
-
776
-            if (is_array($error_msg)) {
777
-                $msg = '<p>'
778
-                       . sprintf(
779
-                           esc_html__(
780
-                               'The following date time "%s" ( %s ) is difficult to be properly parsed by PHP for the following reasons:',
781
-                               'event_espresso'
782
-                           ),
783
-                           date($date_time_format),
784
-                           $date_time_format
785
-                       )
786
-                       . '</p><p><ul>';
787
-
788
-
789
-                foreach ($error_msg as $error) {
790
-                    $msg .= '<li>' . $error . '</li>';
791
-                }
792
-
793
-                $msg .= '</ul></p><p>'
794
-                        . sprintf(
795
-                            esc_html__(
796
-                                '%sPlease note that your date and time formats have been reset to "F j, Y" and "g:i a" respectively.%s',
797
-                                'event_espresso'
798
-                            ),
799
-                            '<span style="color:#D54E21;">',
800
-                            '</span>'
801
-                        )
802
-                        . '</p>';
803
-
804
-                // trigger WP settings error
805
-                add_settings_error(
806
-                    'date_format',
807
-                    'date_format',
808
-                    $msg
809
-                );
810
-
811
-                // set format to something valid
812
-                switch ($option) {
813
-                    case 'date_format':
814
-                        $value = 'F j, Y';
815
-                        break;
816
-                    case 'time_format':
817
-                        $value = 'g:i a';
818
-                        break;
819
-                }
820
-            }
821
-        }
822
-        return $value;
823
-    }
824
-
825
-
826
-    /**
827
-     * its_eSpresso - converts the less commonly used spelling of "Expresso" to "Espresso"
828
-     *
829
-     * @param $content
830
-     * @return    string
831
-     */
832
-    public function its_eSpresso($content)
833
-    {
834
-        return str_replace('[EXPRESSO_', '[ESPRESSO_', $content);
835
-    }
836
-
837
-
838
-    /**
839
-     * espresso_admin_footer
840
-     *
841
-     * @return    string
842
-     */
843
-    public function espresso_admin_footer()
844
-    {
845
-        return \EEH_Template::powered_by_event_espresso('aln-cntr', '', array('utm_content' => 'admin_footer'));
846
-    }
847
-
848
-
849
-    /**
850
-     * static method for registering ee admin page.
851
-     * This method is deprecated in favor of the new location in EE_Register_Admin_Page::register.
852
-     *
853
-     * @since      4.3.0
854
-     * @deprecated 4.3.0    Use EE_Register_Admin_Page::register() instead
855
-     * @see        EE_Register_Admin_Page::register()
856
-     * @param       $page_basename
857
-     * @param       $page_path
858
-     * @param array $config
859
-     * @return void
860
-     * @throws EE_Error
861
-     */
862
-    public static function register_ee_admin_page($page_basename, $page_path, $config = array())
863
-    {
864
-        EE_Error::doing_it_wrong(
865
-            __METHOD__,
866
-            sprintf(
867
-                esc_html__(
868
-                    'Usage is deprecated.  Use EE_Register_Admin_Page::register() for registering the %s admin page.',
869
-                    'event_espresso'
870
-                ),
871
-                $page_basename
872
-            ),
873
-            '4.3'
874
-        );
875
-        if (class_exists('EE_Register_Admin_Page')) {
876
-            $config['page_path'] = $page_path;
877
-        }
878
-        EE_Register_Admin_Page::register($page_basename, $config);
879
-    }
880
-
881
-
882
-    /**
883
-     * @deprecated 4.8.41
884
-     * @param  int      $post_ID
885
-     * @param  \WP_Post $post
886
-     * @return void
887
-     */
888
-    public static function parse_post_content_on_save($post_ID, $post)
889
-    {
890
-        EE_Error::doing_it_wrong(
891
-            __METHOD__,
892
-            esc_html__('Usage is deprecated', 'event_espresso'),
893
-            '4.8.41'
894
-        );
895
-    }
896
-
897
-
898
-    /**
899
-     * @deprecated 4.8.41
900
-     * @param  $option
901
-     * @param  $old_value
902
-     * @param  $value
903
-     * @return void
904
-     */
905
-    public function reset_page_for_posts_on_change($option, $old_value, $value)
906
-    {
907
-        EE_Error::doing_it_wrong(
908
-            __METHOD__,
909
-            esc_html__('Usage is deprecated', 'event_espresso'),
910
-            '4.8.41'
911
-        );
912
-    }
913
-
914
-
915
-
916
-    /**
917
-     * @deprecated 4.9.27
918
-     * @return void
919
-     */
920
-    public function get_persistent_admin_notices()
921
-    {
922
-        EE_Error::doing_it_wrong(
923
-            __METHOD__,
924
-            sprintf(
925
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
926
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
927
-            ),
928
-            '4.9.27'
929
-        );
930
-    }
931
-
932
-
933
-
934
-    /**
935
-     * @deprecated 4.9.27
936
-     * @throws InvalidInterfaceException
937
-     * @throws InvalidDataTypeException
938
-     * @throws DomainException
939
-     */
940
-    public function dismiss_ee_nag_notice_callback()
941
-    {
942
-        EE_Error::doing_it_wrong(
943
-            __METHOD__,
944
-            sprintf(
945
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
946
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
947
-            ),
948
-            '4.9.27'
949
-        );
950
-        $this->persistent_admin_notice_manager->dismissNotice();
951
-    }
485
+	}
486
+
487
+
488
+	/**
489
+	 * Returns an array of event archive nav items.
490
+	 *
491
+	 * @todo  for now this method is just in place so when it gets abstracted further we can substitute in whatever
492
+	 *        method we use for getting the extra nav menu items
493
+	 * @return array
494
+	 */
495
+	private function _get_extra_nav_menu_pages_items()
496
+	{
497
+		$menuitems[] = array(
498
+			'title'       => esc_html__('Event List', 'event_espresso'),
499
+			'url'         => get_post_type_archive_link('espresso_events'),
500
+			'description' => esc_html__('Archive page for all events.', 'event_espresso'),
501
+		);
502
+		return apply_filters('FHEE__EE_Admin__get_extra_nav_menu_pages_items', $menuitems);
503
+	}
504
+
505
+
506
+	/**
507
+	 * Setup nav menu walker item for usage in the event archive nav menu metabox.  It receives a menu_item array with
508
+	 * the properties and converts it to the menu item object.
509
+	 *
510
+	 * @see wp_setup_nav_menu_item() in wp-includes/nav-menu.php
511
+	 * @param $menu_item_values
512
+	 * @return stdClass
513
+	 */
514
+	private function _setup_extra_nav_menu_pages_items($menu_item_values)
515
+	{
516
+		$menu_item = new stdClass();
517
+		$keys      = array(
518
+			'ID'               => 0,
519
+			'db_id'            => 0,
520
+			'menu_item_parent' => 0,
521
+			'object_id'        => -1,
522
+			'post_parent'      => 0,
523
+			'type'             => 'custom',
524
+			'object'           => '',
525
+			'type_label'       => esc_html__('Extra Nav Menu Item', 'event_espresso'),
526
+			'title'            => '',
527
+			'url'              => '',
528
+			'target'           => '',
529
+			'attr_title'       => '',
530
+			'description'      => '',
531
+			'classes'          => array(),
532
+			'xfn'              => '',
533
+		);
534
+
535
+		foreach ($keys as $key => $value) {
536
+			$menu_item->{$key} = isset($menu_item_values[$key]) ? $menu_item_values[$key] : $value;
537
+		}
538
+		return $menu_item;
539
+	}
540
+
541
+
542
+	/**
543
+	 * This is the action hook for the AHEE__EE_Admin_Page__route_admin_request hook that fires off right before an
544
+	 * EE_Admin_Page route is called.
545
+	 *
546
+	 * @return void
547
+	 */
548
+	public function route_admin_request()
549
+	{
550
+	}
551
+
552
+
553
+	/**
554
+	 * wp_loaded should fire on the WordPress wp_loaded hook.  This fires on a VERY late priority.
555
+	 *
556
+	 * @return void
557
+	 */
558
+	public function wp_loaded()
559
+	{
560
+	}
561
+
562
+
563
+	/**
564
+	 * admin_init
565
+	 *
566
+	 * @return void
567
+	 * @throws EE_Error
568
+	 * @throws InvalidArgumentException
569
+	 * @throws InvalidDataTypeException
570
+	 * @throws InvalidInterfaceException
571
+	 * @throws ReflectionException
572
+	 */
573
+	public function admin_init()
574
+	{
575
+
576
+		/**
577
+		 * our cpt models must be instantiated on WordPress post processing routes (wp-admin/post.php),
578
+		 * so any hooking into core WP routes is taken care of.  So in this next few lines of code:
579
+		 * - check if doing post processing.
580
+		 * - check if doing post processing of one of EE CPTs
581
+		 * - instantiate the corresponding EE CPT model for the post_type being processed.
582
+		 */
583
+		if (isset($_POST['action'], $_POST['post_type']) && $_POST['action'] === 'editpost') {
584
+			EE_Registry::instance()->load_core('Register_CPTs');
585
+			EE_Register_CPTs::instantiate_cpt_models($_POST['post_type']);
586
+		}
587
+
588
+
589
+		/**
590
+		 * This code excludes EE critical pages anywhere `wp_dropdown_pages` is used to create a dropdown for selecting
591
+		 * critical pages.  The only place critical pages need included in a generated dropdown is on the "Critical
592
+		 * Pages" tab in the EE General Settings Admin page.
593
+		 * This is for user-proofing.
594
+		 */
595
+		add_filter('wp_dropdown_pages', array($this, 'modify_dropdown_pages'));
596
+	}
597
+
598
+
599
+	/**
600
+	 * Callback for wp_dropdown_pages hook to remove ee critical pages from the dropdown selection.
601
+	 *
602
+	 * @param string $output Current output.
603
+	 * @return string
604
+	 * @throws InvalidArgumentException
605
+	 * @throws InvalidDataTypeException
606
+	 * @throws InvalidInterfaceException
607
+	 */
608
+	public function modify_dropdown_pages($output)
609
+	{
610
+		//get critical pages
611
+		$critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
612
+
613
+		//split current output by line break for easier parsing.
614
+		$split_output = explode("\n", $output);
615
+
616
+		//loop through to remove any critical pages from the array.
617
+		foreach ($critical_pages as $page_id) {
618
+			$needle = 'value="' . $page_id . '"';
619
+			foreach ($split_output as $key => $haystack) {
620
+				if (strpos($haystack, $needle) !== false) {
621
+					unset($split_output[$key]);
622
+				}
623
+			}
624
+		}
625
+		//replace output with the new contents
626
+		return implode("\n", $split_output);
627
+	}
628
+
629
+
630
+	/**
631
+	 * enqueue all admin scripts that need loaded for admin pages
632
+	 *
633
+	 * @return void
634
+	 */
635
+	public function enqueue_admin_scripts()
636
+	{
637
+		// this javascript is loaded on every admin page to catch any injections ee needs to add to wp run js.
638
+		// Note: the intention of this script is to only do TARGETED injections.  I.E, only injecting on certain script
639
+		// calls.
640
+		wp_enqueue_script(
641
+			'ee-inject-wp',
642
+			EE_ADMIN_URL . 'assets/ee-cpt-wp-injects.js',
643
+			array('jquery'),
644
+			EVENT_ESPRESSO_VERSION,
645
+			true
646
+		);
647
+		// register cookie script for future dependencies
648
+		wp_register_script(
649
+			'jquery-cookie',
650
+			EE_THIRD_PARTY_URL . 'joyride/jquery.cookie.js',
651
+			array('jquery'),
652
+			'2.1',
653
+			true
654
+		);
655
+		//joyride is turned OFF by default, but prior to the admin_enqueue_scripts hook, can be turned back on again
656
+		// via: add_filter('FHEE_load_joyride', '__return_true' );
657
+		if (apply_filters('FHEE_load_joyride', false)) {
658
+			//joyride style
659
+			wp_register_style('joyride-css', EE_THIRD_PARTY_URL . 'joyride/joyride-2.1.css', array(), '2.1');
660
+			wp_register_style(
661
+				'ee-joyride-css',
662
+				EE_GLOBAL_ASSETS_URL . 'css/ee-joyride-styles.css',
663
+				array('joyride-css'),
664
+				EVENT_ESPRESSO_VERSION
665
+			);
666
+			wp_register_script(
667
+				'joyride-modernizr',
668
+				EE_THIRD_PARTY_URL . 'joyride/modernizr.mq.js',
669
+				array(),
670
+				'2.1',
671
+				true
672
+			);
673
+			//joyride JS
674
+			wp_register_script(
675
+				'jquery-joyride',
676
+				EE_THIRD_PARTY_URL . 'joyride/jquery.joyride-2.1.js',
677
+				array('jquery-cookie', 'joyride-modernizr'),
678
+				'2.1',
679
+				true
680
+			);
681
+			// wanna go for a joyride?
682
+			wp_enqueue_style('ee-joyride-css');
683
+			wp_enqueue_script('jquery-joyride');
684
+		}
685
+	}
686
+
687
+
688
+	/**
689
+	 * display_admin_notices
690
+	 *
691
+	 * @return void
692
+	 */
693
+	public function display_admin_notices()
694
+	{
695
+		echo EE_Error::get_notices();
696
+	}
697
+
698
+
699
+
700
+	/**
701
+	 * @param array $elements
702
+	 * @return array
703
+	 * @throws EE_Error
704
+	 * @throws InvalidArgumentException
705
+	 * @throws InvalidDataTypeException
706
+	 * @throws InvalidInterfaceException
707
+	 */
708
+	public function dashboard_glance_items($elements)
709
+	{
710
+		$elements                        = is_array($elements) ? $elements : array($elements);
711
+		$events                          = EEM_Event::instance()->count();
712
+		$items['events']['url']          = EE_Admin_Page::add_query_args_and_nonce(
713
+			array('page' => 'espresso_events'),
714
+			admin_url('admin.php')
715
+		);
716
+		$items['events']['text']         = sprintf(_n('%s Event', '%s Events', $events), number_format_i18n($events));
717
+		$items['events']['title']        = esc_html__('Click to view all Events', 'event_espresso');
718
+		$registrations                   = EEM_Registration::instance()->count(
719
+			array(
720
+				array(
721
+					'STS_ID' => array('!=', EEM_Registration::status_id_incomplete),
722
+				),
723
+			)
724
+		);
725
+		$items['registrations']['url']   = EE_Admin_Page::add_query_args_and_nonce(
726
+			array('page' => 'espresso_registrations'),
727
+			admin_url('admin.php')
728
+		);
729
+		$items['registrations']['text']  = sprintf(
730
+			_n('%s Registration', '%s Registrations', $registrations),
731
+			number_format_i18n($registrations)
732
+		);
733
+		$items['registrations']['title'] = esc_html__('Click to view all registrations', 'event_espresso');
734
+
735
+		$items = (array)apply_filters('FHEE__EE_Admin__dashboard_glance_items__items', $items);
736
+
737
+		foreach ($items as $type => $item_properties) {
738
+			$elements[] = sprintf(
739
+				'<a class="ee-dashboard-link-' . $type . '" href="%s" title="%s">%s</a>',
740
+				$item_properties['url'],
741
+				$item_properties['title'],
742
+				$item_properties['text']
743
+			);
744
+		}
745
+		return $elements;
746
+	}
747
+
748
+
749
+	/**
750
+	 * check_for_invalid_datetime_formats
751
+	 * if an admin changes their date or time format settings on the WP General Settings admin page, verify that
752
+	 * their selected format can be parsed by PHP
753
+	 *
754
+	 * @param    $value
755
+	 * @param    $option
756
+	 * @throws EE_Error
757
+	 * @return    string
758
+	 */
759
+	public function check_for_invalid_datetime_formats($value, $option)
760
+	{
761
+		// check for date_format or time_format
762
+		switch ($option) {
763
+			case 'date_format':
764
+				$date_time_format = $value . ' ' . get_option('time_format');
765
+				break;
766
+			case 'time_format':
767
+				$date_time_format = get_option('date_format') . ' ' . $value;
768
+				break;
769
+			default:
770
+				$date_time_format = false;
771
+		}
772
+		// do we have a date_time format to check ?
773
+		if ($date_time_format) {
774
+			$error_msg = EEH_DTT_Helper::validate_format_string($date_time_format);
775
+
776
+			if (is_array($error_msg)) {
777
+				$msg = '<p>'
778
+					   . sprintf(
779
+						   esc_html__(
780
+							   'The following date time "%s" ( %s ) is difficult to be properly parsed by PHP for the following reasons:',
781
+							   'event_espresso'
782
+						   ),
783
+						   date($date_time_format),
784
+						   $date_time_format
785
+					   )
786
+					   . '</p><p><ul>';
787
+
788
+
789
+				foreach ($error_msg as $error) {
790
+					$msg .= '<li>' . $error . '</li>';
791
+				}
792
+
793
+				$msg .= '</ul></p><p>'
794
+						. sprintf(
795
+							esc_html__(
796
+								'%sPlease note that your date and time formats have been reset to "F j, Y" and "g:i a" respectively.%s',
797
+								'event_espresso'
798
+							),
799
+							'<span style="color:#D54E21;">',
800
+							'</span>'
801
+						)
802
+						. '</p>';
803
+
804
+				// trigger WP settings error
805
+				add_settings_error(
806
+					'date_format',
807
+					'date_format',
808
+					$msg
809
+				);
810
+
811
+				// set format to something valid
812
+				switch ($option) {
813
+					case 'date_format':
814
+						$value = 'F j, Y';
815
+						break;
816
+					case 'time_format':
817
+						$value = 'g:i a';
818
+						break;
819
+				}
820
+			}
821
+		}
822
+		return $value;
823
+	}
824
+
825
+
826
+	/**
827
+	 * its_eSpresso - converts the less commonly used spelling of "Expresso" to "Espresso"
828
+	 *
829
+	 * @param $content
830
+	 * @return    string
831
+	 */
832
+	public function its_eSpresso($content)
833
+	{
834
+		return str_replace('[EXPRESSO_', '[ESPRESSO_', $content);
835
+	}
836
+
837
+
838
+	/**
839
+	 * espresso_admin_footer
840
+	 *
841
+	 * @return    string
842
+	 */
843
+	public function espresso_admin_footer()
844
+	{
845
+		return \EEH_Template::powered_by_event_espresso('aln-cntr', '', array('utm_content' => 'admin_footer'));
846
+	}
847
+
848
+
849
+	/**
850
+	 * static method for registering ee admin page.
851
+	 * This method is deprecated in favor of the new location in EE_Register_Admin_Page::register.
852
+	 *
853
+	 * @since      4.3.0
854
+	 * @deprecated 4.3.0    Use EE_Register_Admin_Page::register() instead
855
+	 * @see        EE_Register_Admin_Page::register()
856
+	 * @param       $page_basename
857
+	 * @param       $page_path
858
+	 * @param array $config
859
+	 * @return void
860
+	 * @throws EE_Error
861
+	 */
862
+	public static function register_ee_admin_page($page_basename, $page_path, $config = array())
863
+	{
864
+		EE_Error::doing_it_wrong(
865
+			__METHOD__,
866
+			sprintf(
867
+				esc_html__(
868
+					'Usage is deprecated.  Use EE_Register_Admin_Page::register() for registering the %s admin page.',
869
+					'event_espresso'
870
+				),
871
+				$page_basename
872
+			),
873
+			'4.3'
874
+		);
875
+		if (class_exists('EE_Register_Admin_Page')) {
876
+			$config['page_path'] = $page_path;
877
+		}
878
+		EE_Register_Admin_Page::register($page_basename, $config);
879
+	}
880
+
881
+
882
+	/**
883
+	 * @deprecated 4.8.41
884
+	 * @param  int      $post_ID
885
+	 * @param  \WP_Post $post
886
+	 * @return void
887
+	 */
888
+	public static function parse_post_content_on_save($post_ID, $post)
889
+	{
890
+		EE_Error::doing_it_wrong(
891
+			__METHOD__,
892
+			esc_html__('Usage is deprecated', 'event_espresso'),
893
+			'4.8.41'
894
+		);
895
+	}
896
+
897
+
898
+	/**
899
+	 * @deprecated 4.8.41
900
+	 * @param  $option
901
+	 * @param  $old_value
902
+	 * @param  $value
903
+	 * @return void
904
+	 */
905
+	public function reset_page_for_posts_on_change($option, $old_value, $value)
906
+	{
907
+		EE_Error::doing_it_wrong(
908
+			__METHOD__,
909
+			esc_html__('Usage is deprecated', 'event_espresso'),
910
+			'4.8.41'
911
+		);
912
+	}
913
+
914
+
915
+
916
+	/**
917
+	 * @deprecated 4.9.27
918
+	 * @return void
919
+	 */
920
+	public function get_persistent_admin_notices()
921
+	{
922
+		EE_Error::doing_it_wrong(
923
+			__METHOD__,
924
+			sprintf(
925
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
926
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
927
+			),
928
+			'4.9.27'
929
+		);
930
+	}
931
+
932
+
933
+
934
+	/**
935
+	 * @deprecated 4.9.27
936
+	 * @throws InvalidInterfaceException
937
+	 * @throws InvalidDataTypeException
938
+	 * @throws DomainException
939
+	 */
940
+	public function dismiss_ee_nag_notice_callback()
941
+	{
942
+		EE_Error::doing_it_wrong(
943
+			__METHOD__,
944
+			sprintf(
945
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
946
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
947
+			),
948
+			'4.9.27'
949
+		);
950
+		$this->persistent_admin_notice_manager->dismissNotice();
951
+	}
952 952
 }
Please login to merge, or discard this patch.
Spacing   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
     public static function instance()
41 41
     {
42 42
         // check if class object is instantiated
43
-        if (! self::$_instance instanceof EE_Admin) {
43
+        if ( ! self::$_instance instanceof EE_Admin) {
44 44
             self::$_instance = new self();
45 45
         }
46 46
         return self::$_instance;
@@ -100,11 +100,11 @@  discard block
 block discarded – undo
100 100
      */
101 101
     private function _define_all_constants()
102 102
     {
103
-        if (! defined('EE_ADMIN_URL')) {
104
-            define('EE_ADMIN_URL', EE_PLUGIN_DIR_URL . 'core/admin/');
105
-            define('EE_ADMIN_PAGES_URL', EE_PLUGIN_DIR_URL . 'admin_pages/');
106
-            define('EE_ADMIN_TEMPLATE', EE_ADMIN . 'templates' . DS);
107
-            define('WP_ADMIN_PATH', ABSPATH . 'wp-admin/');
103
+        if ( ! defined('EE_ADMIN_URL')) {
104
+            define('EE_ADMIN_URL', EE_PLUGIN_DIR_URL.'core/admin/');
105
+            define('EE_ADMIN_PAGES_URL', EE_PLUGIN_DIR_URL.'admin_pages/');
106
+            define('EE_ADMIN_TEMPLATE', EE_ADMIN.'templates'.DS);
107
+            define('WP_ADMIN_PATH', ABSPATH.'wp-admin/');
108 108
             define('WP_AJAX_URL', admin_url('admin-ajax.php'));
109 109
         }
110 110
     }
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
         // set $main_file in stone
123 123
         static $main_file;
124 124
         // if $main_file is not set yet
125
-        if (! $main_file) {
125
+        if ( ! $main_file) {
126 126
             $main_file = plugin_basename(EVENT_ESPRESSO_MAIN_FILE);
127 127
         }
128 128
         if ($plugin === $main_file) {
@@ -175,9 +175,9 @@  discard block
 block discarded – undo
175 175
     public function hide_admin_pages_except_maintenance_mode($admin_page_folder_names = array())
176 176
     {
177 177
         return array(
178
-            'maintenance' => EE_ADMIN_PAGES . 'maintenance' . DS,
179
-            'about'       => EE_ADMIN_PAGES . 'about' . DS,
180
-            'support'     => EE_ADMIN_PAGES . 'support' . DS,
178
+            'maintenance' => EE_ADMIN_PAGES.'maintenance'.DS,
179
+            'about'       => EE_ADMIN_PAGES.'about'.DS,
180
+            'support'     => EE_ADMIN_PAGES.'support'.DS,
181 181
         );
182 182
     }
183 183
 
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
             add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 2);
220 220
         }
221 221
         // run the admin page factory but ONLY if we are doing an ee admin ajax request
222
-        if (! defined('DOING_AJAX') || EE_ADMIN_AJAX) {
222
+        if ( ! defined('DOING_AJAX') || EE_ADMIN_AJAX) {
223 223
             try {
224 224
                 //this loads the controller for the admin pages which will setup routing etc
225 225
                 EE_Registry::instance()->load_core('Admin_Page_Loader');
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
         //@todo This needs to stay in core for a bit to catch anyone upgrading from a version without this to a version
253 253
         //with this.  But after enough time (indeterminate at this point) we can just remove this notice.
254 254
         //this was added with https://events.codebasehq.com/projects/event-espresso/tickets/10626
255
-        if (! get_option('timezone_string') && EEM_Event::instance()->count() > 0) {
255
+        if ( ! get_option('timezone_string') && EEM_Event::instance()->count() > 0) {
256 256
             new PersistentAdminNotice(
257 257
                 'datetime_fix_notice',
258 258
                 sprintf(
@@ -264,13 +264,13 @@  discard block
 block discarded – undo
264 264
                     '</strong>',
265 265
                     '<a href="https://eventespresso.com/2017/08/important-upcoming-changes-dates-times">',
266 266
                     '</a>',
267
-                    '<a href="' . EE_Admin_Page::add_query_args_and_nonce(
267
+                    '<a href="'.EE_Admin_Page::add_query_args_and_nonce(
268 268
                         array(
269 269
                             'page' => 'espresso_maintenance_settings',
270 270
                             'action' => 'datetime_tools'
271 271
                         ),
272 272
                         admin_url('admin.php')
273
-                    ) . '">'
273
+                    ).'">'
274 274
                 ),
275 275
                 false,
276 276
                 'manage_options',
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
     public function enable_hidden_ee_nav_menu_metaboxes()
319 319
     {
320 320
         global $wp_meta_boxes, $pagenow;
321
-        if (! is_array($wp_meta_boxes) || $pagenow !== 'nav-menus.php') {
321
+        if ( ! is_array($wp_meta_boxes) || $pagenow !== 'nav-menus.php') {
322 322
             return;
323 323
         }
324 324
         $user = wp_get_current_user();
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
      */
390 390
     public function modify_edit_post_link($link, $id)
391 391
     {
392
-        if (! $post = get_post($id)) {
392
+        if ( ! $post = get_post($id)) {
393 393
             return $link;
394 394
         }
395 395
         if ($post->post_type === 'espresso_attendees') {
@@ -615,7 +615,7 @@  discard block
 block discarded – undo
615 615
 
616 616
         //loop through to remove any critical pages from the array.
617 617
         foreach ($critical_pages as $page_id) {
618
-            $needle = 'value="' . $page_id . '"';
618
+            $needle = 'value="'.$page_id.'"';
619 619
             foreach ($split_output as $key => $haystack) {
620 620
                 if (strpos($haystack, $needle) !== false) {
621 621
                     unset($split_output[$key]);
@@ -639,7 +639,7 @@  discard block
 block discarded – undo
639 639
         // calls.
640 640
         wp_enqueue_script(
641 641
             'ee-inject-wp',
642
-            EE_ADMIN_URL . 'assets/ee-cpt-wp-injects.js',
642
+            EE_ADMIN_URL.'assets/ee-cpt-wp-injects.js',
643 643
             array('jquery'),
644 644
             EVENT_ESPRESSO_VERSION,
645 645
             true
@@ -647,7 +647,7 @@  discard block
 block discarded – undo
647 647
         // register cookie script for future dependencies
648 648
         wp_register_script(
649 649
             'jquery-cookie',
650
-            EE_THIRD_PARTY_URL . 'joyride/jquery.cookie.js',
650
+            EE_THIRD_PARTY_URL.'joyride/jquery.cookie.js',
651 651
             array('jquery'),
652 652
             '2.1',
653 653
             true
@@ -656,16 +656,16 @@  discard block
 block discarded – undo
656 656
         // via: add_filter('FHEE_load_joyride', '__return_true' );
657 657
         if (apply_filters('FHEE_load_joyride', false)) {
658 658
             //joyride style
659
-            wp_register_style('joyride-css', EE_THIRD_PARTY_URL . 'joyride/joyride-2.1.css', array(), '2.1');
659
+            wp_register_style('joyride-css', EE_THIRD_PARTY_URL.'joyride/joyride-2.1.css', array(), '2.1');
660 660
             wp_register_style(
661 661
                 'ee-joyride-css',
662
-                EE_GLOBAL_ASSETS_URL . 'css/ee-joyride-styles.css',
662
+                EE_GLOBAL_ASSETS_URL.'css/ee-joyride-styles.css',
663 663
                 array('joyride-css'),
664 664
                 EVENT_ESPRESSO_VERSION
665 665
             );
666 666
             wp_register_script(
667 667
                 'joyride-modernizr',
668
-                EE_THIRD_PARTY_URL . 'joyride/modernizr.mq.js',
668
+                EE_THIRD_PARTY_URL.'joyride/modernizr.mq.js',
669 669
                 array(),
670 670
                 '2.1',
671 671
                 true
@@ -673,7 +673,7 @@  discard block
 block discarded – undo
673 673
             //joyride JS
674 674
             wp_register_script(
675 675
                 'jquery-joyride',
676
-                EE_THIRD_PARTY_URL . 'joyride/jquery.joyride-2.1.js',
676
+                EE_THIRD_PARTY_URL.'joyride/jquery.joyride-2.1.js',
677 677
                 array('jquery-cookie', 'joyride-modernizr'),
678 678
                 '2.1',
679 679
                 true
@@ -722,21 +722,21 @@  discard block
 block discarded – undo
722 722
                 ),
723 723
             )
724 724
         );
725
-        $items['registrations']['url']   = EE_Admin_Page::add_query_args_and_nonce(
725
+        $items['registrations']['url'] = EE_Admin_Page::add_query_args_and_nonce(
726 726
             array('page' => 'espresso_registrations'),
727 727
             admin_url('admin.php')
728 728
         );
729
-        $items['registrations']['text']  = sprintf(
729
+        $items['registrations']['text'] = sprintf(
730 730
             _n('%s Registration', '%s Registrations', $registrations),
731 731
             number_format_i18n($registrations)
732 732
         );
733 733
         $items['registrations']['title'] = esc_html__('Click to view all registrations', 'event_espresso');
734 734
 
735
-        $items = (array)apply_filters('FHEE__EE_Admin__dashboard_glance_items__items', $items);
735
+        $items = (array) apply_filters('FHEE__EE_Admin__dashboard_glance_items__items', $items);
736 736
 
737 737
         foreach ($items as $type => $item_properties) {
738 738
             $elements[] = sprintf(
739
-                '<a class="ee-dashboard-link-' . $type . '" href="%s" title="%s">%s</a>',
739
+                '<a class="ee-dashboard-link-'.$type.'" href="%s" title="%s">%s</a>',
740 740
                 $item_properties['url'],
741 741
                 $item_properties['title'],
742 742
                 $item_properties['text']
@@ -761,10 +761,10 @@  discard block
 block discarded – undo
761 761
         // check for date_format or time_format
762 762
         switch ($option) {
763 763
             case 'date_format':
764
-                $date_time_format = $value . ' ' . get_option('time_format');
764
+                $date_time_format = $value.' '.get_option('time_format');
765 765
                 break;
766 766
             case 'time_format':
767
-                $date_time_format = get_option('date_format') . ' ' . $value;
767
+                $date_time_format = get_option('date_format').' '.$value;
768 768
                 break;
769 769
             default:
770 770
                 $date_time_format = false;
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
 
788 788
 
789 789
                 foreach ($error_msg as $error) {
790
-                    $msg .= '<li>' . $error . '</li>';
790
+                    $msg .= '<li>'.$error.'</li>';
791 791
                 }
792 792
 
793 793
                 $msg .= '</ul></p><p>'
Please login to merge, or discard this patch.
core/EE_Session.core.php 3 patches
Doc Comments   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -484,7 +484,7 @@  discard block
 block discarded – undo
484 484
      *
485 485
      * @access    public
486 486
      * @param    array $data
487
-     * @return    TRUE on success, FALSE on fail
487
+     * @return    boolean on success, FALSE on fail
488 488
      */
489 489
     public function set_session_data($data)
490 490
     {
@@ -511,7 +511,7 @@  discard block
 block discarded – undo
511 511
     /**
512 512
      * @initiate session
513 513
      * @access   private
514
-     * @return TRUE on success, FALSE on fail
514
+     * @return boolean on success, FALSE on fail
515 515
      * @throws EE_Error
516 516
      * @throws InvalidArgumentException
517 517
      * @throws InvalidDataTypeException
@@ -746,7 +746,7 @@  discard block
 block discarded – undo
746 746
      * @update session data  prior to saving to the db
747 747
      * @access public
748 748
      * @param bool $new_session
749
-     * @return TRUE on success, FALSE on fail
749
+     * @return boolean on success, FALSE on fail
750 750
      * @throws EE_Error
751 751
      * @throws InvalidArgumentException
752 752
      * @throws InvalidDataTypeException
@@ -847,7 +847,7 @@  discard block
 block discarded – undo
847 847
      * _save_session_to_db
848 848
      *
849 849
      * @param bool $clear_session
850
-     * @return string
850
+     * @return boolean
851 851
      * @throws EE_Error
852 852
      * @throws InvalidArgumentException
853 853
      * @throws InvalidDataTypeException
@@ -1008,7 +1008,7 @@  discard block
 block discarded – undo
1008 1008
      * @access public
1009 1009
      * @param array|mixed $data_to_reset
1010 1010
      * @param bool        $show_all_notices
1011
-     * @return TRUE on success, FALSE on fail
1011
+     * @return boolean on success, FALSE on fail
1012 1012
      */
1013 1013
     public function reset_data($data_to_reset = array(), $show_all_notices = false)
1014 1014
     {
Please login to merge, or discard this patch.
Indentation   +1204 added lines, -1204 removed lines patch added patch discarded remove patch
@@ -20,1210 +20,1210 @@  discard block
 block discarded – undo
20 20
 class EE_Session implements SessionIdentifierInterface
21 21
 {
22 22
 
23
-    const session_id_prefix    = 'ee_ssn_';
24
-
25
-    const hash_check_prefix    = 'ee_shc_';
26
-
27
-    const OPTION_NAME_SETTINGS = 'ee_session_settings';
28
-
29
-    /**
30
-     * instance of the EE_Session object
31
-     *
32
-     * @var EE_Session
33
-     */
34
-    private static $_instance;
35
-
36
-    /**
37
-     * @var CacheStorageInterface $cache_storage
38
-     */
39
-    protected $cache_storage;
40
-
41
-    /**
42
-     * EE_Encryption object
43
-     *
44
-     * @var EE_Encryption
45
-     */
46
-    protected $encryption;
47
-
48
-    /**
49
-     * the session id
50
-     *
51
-     * @var string
52
-     */
53
-    private $_sid;
54
-
55
-    /**
56
-     * session id salt
57
-     *
58
-     * @var string
59
-     */
60
-    private $_sid_salt;
61
-
62
-    /**
63
-     * session data
64
-     *
65
-     * @var array
66
-     */
67
-    private $_session_data = array();
68
-
69
-    /**
70
-     * how long an EE session lasts
71
-     * default session lifespan of 2 hours (for not so instant IPNs)
72
-     *
73
-     * @var int
74
-     */
75
-    private $_lifespan;
76
-
77
-    /**
78
-     * session expiration time as Unix timestamp in GMT
79
-     *
80
-     * @var int
81
-     */
82
-    private $_expiration;
83
-
84
-    /**
85
-     * whether or not session has expired at some point
86
-     *
87
-     * @var boolean
88
-     */
89
-    private $_expired = false;
90
-
91
-    /**
92
-     * current time as Unix timestamp in GMT
93
-     *
94
-     * @var int
95
-     */
96
-    private $_time;
97
-
98
-    /**
99
-     * whether to encrypt session data
100
-     *
101
-     * @var bool
102
-     */
103
-    private $_use_encryption;
104
-
105
-    /**
106
-     * well... according to the server...
107
-     *
108
-     * @var null
109
-     */
110
-    private $_user_agent;
111
-
112
-    /**
113
-     * do you really trust the server ?
114
-     *
115
-     * @var null
116
-     */
117
-    private $_ip_address;
118
-
119
-    /**
120
-     * current WP user_id
121
-     *
122
-     * @var null
123
-     */
124
-    private $_wp_user_id;
125
-
126
-    /**
127
-     * array for defining default session vars
128
-     *
129
-     * @var array
130
-     */
131
-    private $_default_session_vars = array(
132
-        'id'            => null,
133
-        'user_id'       => null,
134
-        'ip_address'    => null,
135
-        'user_agent'    => null,
136
-        'init_access'   => null,
137
-        'last_access'   => null,
138
-        'expiration'    => null,
139
-        'pages_visited' => array(),
140
-    );
141
-
142
-    /**
143
-     * timestamp for when last garbage collection cycle was performed
144
-     *
145
-     * @var int $_last_gc
146
-     */
147
-    private $_last_gc;
148
-
149
-
150
-
151
-    /**
152
-     * @singleton method used to instantiate class object
153
-     * @param CacheStorageInterface $cache_storage
154
-     * @param EE_Encryption         $encryption
155
-     * @return EE_Session
156
-     * @throws InvalidArgumentException
157
-     * @throws InvalidDataTypeException
158
-     * @throws InvalidInterfaceException
159
-     */
160
-    public static function instance(
161
-        CacheStorageInterface $cache_storage = null,
162
-        EE_Encryption $encryption = null
163
-    ) {
164
-        // check if class object is instantiated
165
-        // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
166
-        // add_filter( 'FHEE_load_EE_Session', '__return_false' );
167
-        if (! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
168
-            self::$_instance = new self($cache_storage, $encryption);
169
-        }
170
-        return self::$_instance;
171
-    }
172
-
173
-
174
-
175
-    /**
176
-     * protected constructor to prevent direct creation
177
-     *
178
-     * @param CacheStorageInterface $cache_storage
179
-     * @param EE_Encryption         $encryption
180
-     * @throws InvalidArgumentException
181
-     * @throws InvalidDataTypeException
182
-     * @throws InvalidInterfaceException
183
-     */
184
-    protected function __construct(CacheStorageInterface $cache_storage, EE_Encryption $encryption = null)
185
-    {
186
-
187
-        // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
188
-        if (! apply_filters('FHEE_load_EE_Session', true)) {
189
-            return;
190
-        }
191
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
192
-        if (! defined('ESPRESSO_SESSION')) {
193
-            define('ESPRESSO_SESSION', true);
194
-        }
195
-        // default session lifespan in seconds
196
-        $this->_lifespan = apply_filters(
197
-                               'FHEE__EE_Session__construct___lifespan',
198
-                               60 * MINUTE_IN_SECONDS
199
-                           ) + 1;
200
-        /*
23
+	const session_id_prefix    = 'ee_ssn_';
24
+
25
+	const hash_check_prefix    = 'ee_shc_';
26
+
27
+	const OPTION_NAME_SETTINGS = 'ee_session_settings';
28
+
29
+	/**
30
+	 * instance of the EE_Session object
31
+	 *
32
+	 * @var EE_Session
33
+	 */
34
+	private static $_instance;
35
+
36
+	/**
37
+	 * @var CacheStorageInterface $cache_storage
38
+	 */
39
+	protected $cache_storage;
40
+
41
+	/**
42
+	 * EE_Encryption object
43
+	 *
44
+	 * @var EE_Encryption
45
+	 */
46
+	protected $encryption;
47
+
48
+	/**
49
+	 * the session id
50
+	 *
51
+	 * @var string
52
+	 */
53
+	private $_sid;
54
+
55
+	/**
56
+	 * session id salt
57
+	 *
58
+	 * @var string
59
+	 */
60
+	private $_sid_salt;
61
+
62
+	/**
63
+	 * session data
64
+	 *
65
+	 * @var array
66
+	 */
67
+	private $_session_data = array();
68
+
69
+	/**
70
+	 * how long an EE session lasts
71
+	 * default session lifespan of 2 hours (for not so instant IPNs)
72
+	 *
73
+	 * @var int
74
+	 */
75
+	private $_lifespan;
76
+
77
+	/**
78
+	 * session expiration time as Unix timestamp in GMT
79
+	 *
80
+	 * @var int
81
+	 */
82
+	private $_expiration;
83
+
84
+	/**
85
+	 * whether or not session has expired at some point
86
+	 *
87
+	 * @var boolean
88
+	 */
89
+	private $_expired = false;
90
+
91
+	/**
92
+	 * current time as Unix timestamp in GMT
93
+	 *
94
+	 * @var int
95
+	 */
96
+	private $_time;
97
+
98
+	/**
99
+	 * whether to encrypt session data
100
+	 *
101
+	 * @var bool
102
+	 */
103
+	private $_use_encryption;
104
+
105
+	/**
106
+	 * well... according to the server...
107
+	 *
108
+	 * @var null
109
+	 */
110
+	private $_user_agent;
111
+
112
+	/**
113
+	 * do you really trust the server ?
114
+	 *
115
+	 * @var null
116
+	 */
117
+	private $_ip_address;
118
+
119
+	/**
120
+	 * current WP user_id
121
+	 *
122
+	 * @var null
123
+	 */
124
+	private $_wp_user_id;
125
+
126
+	/**
127
+	 * array for defining default session vars
128
+	 *
129
+	 * @var array
130
+	 */
131
+	private $_default_session_vars = array(
132
+		'id'            => null,
133
+		'user_id'       => null,
134
+		'ip_address'    => null,
135
+		'user_agent'    => null,
136
+		'init_access'   => null,
137
+		'last_access'   => null,
138
+		'expiration'    => null,
139
+		'pages_visited' => array(),
140
+	);
141
+
142
+	/**
143
+	 * timestamp for when last garbage collection cycle was performed
144
+	 *
145
+	 * @var int $_last_gc
146
+	 */
147
+	private $_last_gc;
148
+
149
+
150
+
151
+	/**
152
+	 * @singleton method used to instantiate class object
153
+	 * @param CacheStorageInterface $cache_storage
154
+	 * @param EE_Encryption         $encryption
155
+	 * @return EE_Session
156
+	 * @throws InvalidArgumentException
157
+	 * @throws InvalidDataTypeException
158
+	 * @throws InvalidInterfaceException
159
+	 */
160
+	public static function instance(
161
+		CacheStorageInterface $cache_storage = null,
162
+		EE_Encryption $encryption = null
163
+	) {
164
+		// check if class object is instantiated
165
+		// session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
166
+		// add_filter( 'FHEE_load_EE_Session', '__return_false' );
167
+		if (! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
168
+			self::$_instance = new self($cache_storage, $encryption);
169
+		}
170
+		return self::$_instance;
171
+	}
172
+
173
+
174
+
175
+	/**
176
+	 * protected constructor to prevent direct creation
177
+	 *
178
+	 * @param CacheStorageInterface $cache_storage
179
+	 * @param EE_Encryption         $encryption
180
+	 * @throws InvalidArgumentException
181
+	 * @throws InvalidDataTypeException
182
+	 * @throws InvalidInterfaceException
183
+	 */
184
+	protected function __construct(CacheStorageInterface $cache_storage, EE_Encryption $encryption = null)
185
+	{
186
+
187
+		// session loading is turned ON by default, but prior to the init hook, can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
188
+		if (! apply_filters('FHEE_load_EE_Session', true)) {
189
+			return;
190
+		}
191
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
192
+		if (! defined('ESPRESSO_SESSION')) {
193
+			define('ESPRESSO_SESSION', true);
194
+		}
195
+		// default session lifespan in seconds
196
+		$this->_lifespan = apply_filters(
197
+							   'FHEE__EE_Session__construct___lifespan',
198
+							   60 * MINUTE_IN_SECONDS
199
+						   ) + 1;
200
+		/*
201 201
          * do something like the following to adjust the session lifespan:
202 202
          * 		public static function session_lifespan() {
203 203
          * 			return 15 * MINUTE_IN_SECONDS;
204 204
          * 		}
205 205
          */
206
-        // retrieve session options from db
207
-        $session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
208
-        if (! empty($session_settings)) {
209
-            // cycle though existing session options
210
-            foreach ($session_settings as $var_name => $session_setting) {
211
-                // set values for class properties
212
-                $var_name          = '_' . $var_name;
213
-                $this->{$var_name} = $session_setting;
214
-            }
215
-        }
216
-        $this->cache_storage = $cache_storage;
217
-        // are we using encryption?
218
-        $this->_use_encryption = $encryption instanceof EE_Encryption
219
-                                 && EE_Registry::instance()->CFG->admin->encode_session_data();
220
-        // \EEH_Debug_Tools::printr($this->_use_encryption, '$this->_use_encryption', __FILE__, __LINE__);
221
-        // encrypt data via: $this->encryption->encrypt();
222
-        $this->encryption = $encryption;
223
-        // filter hook allows outside functions/classes/plugins to change default empty cart
224
-        $extra_default_session_vars = apply_filters('FHEE__EE_Session__construct__extra_default_session_vars', array());
225
-        array_merge($this->_default_session_vars, $extra_default_session_vars);
226
-        // apply default session vars
227
-        $this->_set_defaults();
228
-        add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
229
-        // check request for 'clear_session' param
230
-        add_action('AHEE__EE_Request_Handler__construct__complete', array($this, 'wp_loaded'));
231
-        // once everything is all said and done,
232
-        add_action('shutdown', array($this, 'update'), 100);
233
-        add_action('shutdown', array($this, 'garbageCollection'), 1000);
234
-        $this->configure_garbage_collection_filters();
235
-    }
236
-
237
-
238
-
239
-    /**
240
-     * @return void
241
-     * @throws EE_Error
242
-     * @throws InvalidArgumentException
243
-     * @throws InvalidDataTypeException
244
-     * @throws InvalidInterfaceException
245
-     * @throws InvalidSessionDataException
246
-     */
247
-    public function open_session()
248
-    {
249
-        // check for existing session and retrieve it from db
250
-        if (! $this->_espresso_session()) {
251
-            // or just start a new one
252
-            $this->_create_espresso_session();
253
-        }
254
-    }
255
-
256
-
257
-
258
-    /**
259
-     * @return bool
260
-     */
261
-    public function expired()
262
-    {
263
-        return $this->_expired;
264
-    }
265
-
266
-
267
-
268
-    /**
269
-     * @return void
270
-     */
271
-    public function reset_expired()
272
-    {
273
-        $this->_expired = false;
274
-    }
275
-
276
-
277
-    /**
278
-     * @return int
279
-     */
280
-    public function expiration()
281
-    {
282
-        return $this->_expiration;
283
-    }
284
-
285
-
286
-
287
-    /**
288
-     * @return int
289
-     */
290
-    public function extension()
291
-    {
292
-        return apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS);
293
-    }
294
-
295
-
296
-
297
-    /**
298
-     * @param int $time number of seconds to add to session expiration
299
-     */
300
-    public function extend_expiration($time = 0)
301
-    {
302
-        $time              = $time ? $time : $this->extension();
303
-        $this->_expiration += absint($time);
304
-    }
305
-
306
-
307
-
308
-    /**
309
-     * @return int
310
-     */
311
-    public function lifespan()
312
-    {
313
-        return $this->_lifespan;
314
-    }
315
-
316
-
317
-
318
-    /**
319
-     * This just sets some defaults for the _session data property
320
-     *
321
-     * @access private
322
-     * @return void
323
-     */
324
-    private function _set_defaults()
325
-    {
326
-        // set some defaults
327
-        foreach ($this->_default_session_vars as $key => $default_var) {
328
-            if (is_array($default_var)) {
329
-                $this->_session_data[ $key ] = array();
330
-            } else {
331
-                $this->_session_data[ $key ] = '';
332
-            }
333
-        }
334
-    }
206
+		// retrieve session options from db
207
+		$session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
208
+		if (! empty($session_settings)) {
209
+			// cycle though existing session options
210
+			foreach ($session_settings as $var_name => $session_setting) {
211
+				// set values for class properties
212
+				$var_name          = '_' . $var_name;
213
+				$this->{$var_name} = $session_setting;
214
+			}
215
+		}
216
+		$this->cache_storage = $cache_storage;
217
+		// are we using encryption?
218
+		$this->_use_encryption = $encryption instanceof EE_Encryption
219
+								 && EE_Registry::instance()->CFG->admin->encode_session_data();
220
+		// \EEH_Debug_Tools::printr($this->_use_encryption, '$this->_use_encryption', __FILE__, __LINE__);
221
+		// encrypt data via: $this->encryption->encrypt();
222
+		$this->encryption = $encryption;
223
+		// filter hook allows outside functions/classes/plugins to change default empty cart
224
+		$extra_default_session_vars = apply_filters('FHEE__EE_Session__construct__extra_default_session_vars', array());
225
+		array_merge($this->_default_session_vars, $extra_default_session_vars);
226
+		// apply default session vars
227
+		$this->_set_defaults();
228
+		add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
229
+		// check request for 'clear_session' param
230
+		add_action('AHEE__EE_Request_Handler__construct__complete', array($this, 'wp_loaded'));
231
+		// once everything is all said and done,
232
+		add_action('shutdown', array($this, 'update'), 100);
233
+		add_action('shutdown', array($this, 'garbageCollection'), 1000);
234
+		$this->configure_garbage_collection_filters();
235
+	}
236
+
237
+
238
+
239
+	/**
240
+	 * @return void
241
+	 * @throws EE_Error
242
+	 * @throws InvalidArgumentException
243
+	 * @throws InvalidDataTypeException
244
+	 * @throws InvalidInterfaceException
245
+	 * @throws InvalidSessionDataException
246
+	 */
247
+	public function open_session()
248
+	{
249
+		// check for existing session and retrieve it from db
250
+		if (! $this->_espresso_session()) {
251
+			// or just start a new one
252
+			$this->_create_espresso_session();
253
+		}
254
+	}
255
+
256
+
257
+
258
+	/**
259
+	 * @return bool
260
+	 */
261
+	public function expired()
262
+	{
263
+		return $this->_expired;
264
+	}
265
+
266
+
267
+
268
+	/**
269
+	 * @return void
270
+	 */
271
+	public function reset_expired()
272
+	{
273
+		$this->_expired = false;
274
+	}
275
+
276
+
277
+	/**
278
+	 * @return int
279
+	 */
280
+	public function expiration()
281
+	{
282
+		return $this->_expiration;
283
+	}
284
+
285
+
286
+
287
+	/**
288
+	 * @return int
289
+	 */
290
+	public function extension()
291
+	{
292
+		return apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS);
293
+	}
294
+
295
+
296
+
297
+	/**
298
+	 * @param int $time number of seconds to add to session expiration
299
+	 */
300
+	public function extend_expiration($time = 0)
301
+	{
302
+		$time              = $time ? $time : $this->extension();
303
+		$this->_expiration += absint($time);
304
+	}
305
+
306
+
307
+
308
+	/**
309
+	 * @return int
310
+	 */
311
+	public function lifespan()
312
+	{
313
+		return $this->_lifespan;
314
+	}
315
+
316
+
317
+
318
+	/**
319
+	 * This just sets some defaults for the _session data property
320
+	 *
321
+	 * @access private
322
+	 * @return void
323
+	 */
324
+	private function _set_defaults()
325
+	{
326
+		// set some defaults
327
+		foreach ($this->_default_session_vars as $key => $default_var) {
328
+			if (is_array($default_var)) {
329
+				$this->_session_data[ $key ] = array();
330
+			} else {
331
+				$this->_session_data[ $key ] = '';
332
+			}
333
+		}
334
+	}
335 335
 
336 336
 
337
-
338
-    /**
339
-     * @retrieve  session data
340
-     * @access    public
341
-     * @return    string
342
-     */
343
-    public function id()
344
-    {
345
-        return $this->_sid;
346
-    }
337
+
338
+	/**
339
+	 * @retrieve  session data
340
+	 * @access    public
341
+	 * @return    string
342
+	 */
343
+	public function id()
344
+	{
345
+		return $this->_sid;
346
+	}
347 347
 
348 348
 
349 349
 
350
-    /**
351
-     * @param \EE_Cart $cart
352
-     * @return bool
353
-     */
354
-    public function set_cart(EE_Cart $cart)
355
-    {
356
-        $this->_session_data['cart'] = $cart;
357
-        return true;
358
-    }
350
+	/**
351
+	 * @param \EE_Cart $cart
352
+	 * @return bool
353
+	 */
354
+	public function set_cart(EE_Cart $cart)
355
+	{
356
+		$this->_session_data['cart'] = $cart;
357
+		return true;
358
+	}
359 359
 
360 360
 
361 361
 
362
-    /**
363
-     * reset_cart
364
-     */
365
-    public function reset_cart()
366
-    {
367
-        do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
368
-        $this->_session_data['cart'] = null;
369
-    }
370
-
371
-
372
-
373
-    /**
374
-     * @return \EE_Cart
375
-     */
376
-    public function cart()
377
-    {
378
-        return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
379
-            ? $this->_session_data['cart']
380
-            : null;
381
-    }
382
-
383
-
384
-
385
-    /**
386
-     * @param \EE_Checkout $checkout
387
-     * @return bool
388
-     */
389
-    public function set_checkout(EE_Checkout $checkout)
390
-    {
391
-        $this->_session_data['checkout'] = $checkout;
392
-        return true;
393
-    }
394
-
395
-
396
-
397
-    /**
398
-     * reset_checkout
399
-     */
400
-    public function reset_checkout()
401
-    {
402
-        do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
403
-        $this->_session_data['checkout'] = null;
404
-    }
405
-
406
-
407
-
408
-    /**
409
-     * @return \EE_Checkout
410
-     */
411
-    public function checkout()
412
-    {
413
-        return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
414
-            ? $this->_session_data['checkout']
415
-            : null;
416
-    }
417
-
418
-
419
-
420
-    /**
421
-     * @param \EE_Transaction $transaction
422
-     * @return bool
423
-     * @throws EE_Error
424
-     */
425
-    public function set_transaction(EE_Transaction $transaction)
426
-    {
427
-        // first remove the session from the transaction before we save the transaction in the session
428
-        $transaction->set_txn_session_data(null);
429
-        $this->_session_data['transaction'] = $transaction;
430
-        return true;
431
-    }
432
-
433
-
434
-
435
-    /**
436
-     * reset_transaction
437
-     */
438
-    public function reset_transaction()
439
-    {
440
-        do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
441
-        $this->_session_data['transaction'] = null;
442
-    }
443
-
444
-
445
-
446
-    /**
447
-     * @return \EE_Transaction
448
-     */
449
-    public function transaction()
450
-    {
451
-        return isset($this->_session_data['transaction'])
452
-               && $this->_session_data['transaction'] instanceof EE_Transaction
453
-            ? $this->_session_data['transaction']
454
-            : null;
455
-    }
456
-
457
-
458
-
459
-    /**
460
-     * retrieve session data
461
-     *
462
-     * @access    public
463
-     * @param null $key
464
-     * @param bool $reset_cache
465
-     * @return    array
466
-     */
467
-    public function get_session_data($key = null, $reset_cache = false)
468
-    {
469
-        if ($reset_cache) {
470
-            $this->reset_cart();
471
-            $this->reset_checkout();
472
-            $this->reset_transaction();
473
-        }
474
-        if (! empty($key)) {
475
-            return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
476
-        }
477
-        return $this->_session_data;
478
-    }
479
-
480
-
481
-
482
-    /**
483
-     * set session data
484
-     *
485
-     * @access    public
486
-     * @param    array $data
487
-     * @return    TRUE on success, FALSE on fail
488
-     */
489
-    public function set_session_data($data)
490
-    {
491
-
492
-        // nothing ??? bad data ??? go home!
493
-        if (empty($data) || ! is_array($data)) {
494
-            EE_Error::add_error(__('No session data or invalid session data was provided.', 'event_espresso'), __FILE__,
495
-                __FUNCTION__, __LINE__);
496
-            return false;
497
-        }
498
-        foreach ($data as $key => $value) {
499
-            if (isset($this->_default_session_vars[ $key ])) {
500
-                EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.',
501
-                    'event_espresso'), $key), __FILE__, __FUNCTION__, __LINE__);
502
-                return false;
503
-            }
504
-            $this->_session_data[ $key ] = $value;
505
-        }
506
-        return true;
507
-    }
508
-
509
-
510
-
511
-    /**
512
-     * @initiate session
513
-     * @access   private
514
-     * @return TRUE on success, FALSE on fail
515
-     * @throws EE_Error
516
-     * @throws InvalidArgumentException
517
-     * @throws InvalidDataTypeException
518
-     * @throws InvalidInterfaceException
519
-     * @throws InvalidSessionDataException
520
-     */
521
-    private function _espresso_session()
522
-    {
523
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
524
-        // check that session has started
525
-        if (session_id() === '') {
526
-            //starts a new session if one doesn't already exist, or re-initiates an existing one
527
-            session_start();
528
-        }
529
-        // get our modified session ID
530
-        $this->_sid = $this->_generate_session_id();
531
-        // and the visitors IP
532
-        $this->_ip_address = $this->_visitor_ip();
533
-        // set the "user agent"
534
-        $this->_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? esc_attr($_SERVER['HTTP_USER_AGENT']) : false;
535
-        // now let's retrieve what's in the db
536
-        $session_data = $this->_retrieve_session_data();
537
-        if (! empty($session_data)) {
538
-            // get the current time in UTC
539
-            $this->_time = $this->_time !== null ? $this->_time : time();
540
-            // and reset the session expiration
541
-            $this->_expiration = isset($session_data['expiration'])
542
-                ? $session_data['expiration']
543
-                : $this->_time + $this->_lifespan;
544
-        } else {
545
-            // set initial site access time and the session expiration
546
-            $this->_set_init_access_and_expiration();
547
-            // set referer
548
-            $this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
549
-                ? esc_attr($_SERVER['HTTP_REFERER'])
550
-                : '';
551
-            // no previous session = go back and create one (on top of the data above)
552
-            return false;
553
-        }
554
-        // now the user agent
555
-        if ($session_data['user_agent'] !== $this->_user_agent) {
556
-            return false;
557
-        }
558
-        // wait a minute... how old are you?
559
-        if ($this->_time > $this->_expiration) {
560
-            // yer too old fer me!
561
-            $this->_expired = true;
562
-            // wipe out everything that isn't a default session datum
563
-            $this->clear_session(__CLASS__, __FUNCTION__);
564
-        }
565
-        // make event espresso session data available to plugin
566
-        $this->_session_data = array_merge($this->_session_data, $session_data);
567
-        return true;
568
-    }
569
-
570
-
571
-
572
-    /**
573
-     * _get_session_data
574
-     * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup
575
-     * databases
576
-     *
577
-     * @return array
578
-     * @throws EE_Error
579
-     * @throws InvalidArgumentException
580
-     * @throws InvalidSessionDataException
581
-     * @throws InvalidDataTypeException
582
-     * @throws InvalidInterfaceException
583
-     */
584
-    protected function _retrieve_session_data()
585
-    {
586
-        $ssn_key = EE_Session::session_id_prefix . $this->_sid;
587
-        try {
588
-            // we're using WP's Transient API to store session data using the PHP session ID as the option name
589
-            $session_data = $this->cache_storage->get($ssn_key, false);
590
-            if (empty($session_data)) {
591
-                return array();
592
-            }
593
-            if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
594
-                $hash_check = $this->cache_storage->get(
595
-                    EE_Session::hash_check_prefix . $this->_sid,
596
-                    false
597
-                );
598
-                if ($hash_check && $hash_check !== md5($session_data)) {
599
-                    EE_Error::add_error(
600
-                        sprintf(
601
-                            __(
602
-                                'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
603
-                                'event_espresso'
604
-                            ),
605
-                            EE_Session::session_id_prefix . $this->_sid
606
-                        ),
607
-                        __FILE__, __FUNCTION__, __LINE__
608
-                    );
609
-                }
610
-            }
611
-        } catch (Exception $e) {
612
-            // let's just eat that error for now and attempt to correct any corrupted data
613
-            global $wpdb;
614
-            $row          = $wpdb->get_row(
615
-                $wpdb->prepare(
616
-                    "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
617
-                    '_transient_' . $ssn_key
618
-                )
619
-            );
620
-            $session_data = is_object($row) ? $row->option_value : null;
621
-            if ($session_data) {
622
-                $session_data = preg_replace_callback(
623
-                    '!s:(d+):"(.*?)";!',
624
-                    function ($match)
625
-                    {
626
-                        return $match[1] === strlen($match[2])
627
-                            ? $match[0]
628
-                            : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
629
-                    },
630
-                    $session_data
631
-                );
632
-            }
633
-            $session_data = maybe_unserialize($session_data);
634
-        }
635
-        // in case the data is encoded... try to decode it
636
-        $session_data = $this->encryption instanceof EE_Encryption
637
-            ? $this->encryption->base64_string_decode($session_data)
638
-            : $session_data;
639
-        if (! is_array($session_data)) {
640
-            try {
641
-                $session_data = maybe_unserialize($session_data);
642
-            } catch (Exception $e) {
643
-                $msg = esc_html__(
644
-                    'An error occurred while attempting to unserialize the session data.',
645
-                    'event_espresso'
646
-                );
647
-                $msg .= WP_DEBUG
648
-                    ? '<br><pre>'
649
-                      . print_r($session_data, true)
650
-                      . '</pre><br>'
651
-                      . $this->find_serialize_error($session_data)
652
-                    : '';
653
-                $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
654
-                throw new InvalidSessionDataException($msg, 0, $e);
655
-            }
656
-        }
657
-        // just a check to make sure the session array is indeed an array
658
-        if (! is_array($session_data)) {
659
-            // no?!?! then something is wrong
660
-            $msg = esc_html__(
661
-                'The session data is missing, invalid, or corrupted.',
662
-                'event_espresso'
663
-            );
664
-            $msg .= WP_DEBUG
665
-                ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
666
-                : '';
667
-            $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
668
-            throw new InvalidSessionDataException($msg);
669
-        }
670
-        if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
671
-            $session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
672
-                $session_data['transaction']
673
-            );
674
-        }
675
-        return $session_data;
676
-    }
677
-
678
-
679
-
680
-    /**
681
-     * _generate_session_id
682
-     * Retrieves the PHP session id either directly from the PHP session,
683
-     * or from the $_REQUEST array if it was passed in from an AJAX request.
684
-     * The session id is then salted and hashed (mmm sounds tasty)
685
-     * so that it can be safely used as a $_REQUEST param
686
-     *
687
-     * @return string
688
-     */
689
-    protected function _generate_session_id()
690
-    {
691
-        // check if the SID was passed explicitly, otherwise get from session, then add salt and hash it to reduce length
692
-        if (isset($_REQUEST['EESID'])) {
693
-            $session_id = sanitize_text_field($_REQUEST['EESID']);
694
-        } else {
695
-            $session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
696
-        }
697
-        return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
698
-    }
699
-
700
-
701
-
702
-    /**
703
-     * _get_sid_salt
704
-     *
705
-     * @return string
706
-     */
707
-    protected function _get_sid_salt()
708
-    {
709
-        // was session id salt already saved to db ?
710
-        if (empty($this->_sid_salt)) {
711
-            // no?  then maybe use WP defined constant
712
-            if (defined('AUTH_SALT')) {
713
-                $this->_sid_salt = AUTH_SALT;
714
-            }
715
-            // if salt doesn't exist or is too short
716
-            if (strlen($this->_sid_salt) < 32) {
717
-                // create a new one
718
-                $this->_sid_salt = wp_generate_password(64);
719
-            }
720
-            // and save it as a permanent session setting
721
-            $this->updateSessionSettings(array('sid_salt' => $this->_sid_salt));
722
-        }
723
-        return $this->_sid_salt;
724
-    }
725
-
726
-
727
-
728
-    /**
729
-     * _set_init_access_and_expiration
730
-     *
731
-     * @return void
732
-     */
733
-    protected function _set_init_access_and_expiration()
734
-    {
735
-        $this->_time       = time();
736
-        $this->_expiration = $this->_time + $this->_lifespan;
737
-        // set initial site access time
738
-        $this->_session_data['init_access'] = $this->_time;
739
-        // and the session expiration
740
-        $this->_session_data['expiration'] = $this->_expiration;
741
-    }
742
-
743
-
744
-
745
-    /**
746
-     * @update session data  prior to saving to the db
747
-     * @access public
748
-     * @param bool $new_session
749
-     * @return TRUE on success, FALSE on fail
750
-     * @throws EE_Error
751
-     * @throws InvalidArgumentException
752
-     * @throws InvalidDataTypeException
753
-     * @throws InvalidInterfaceException
754
-     */
755
-    public function update($new_session = false)
756
-    {
757
-        $this->_session_data = $this->_session_data !== null
758
-                               && is_array($this->_session_data)
759
-                               && isset($this->_session_data['id'])
760
-            ? $this->_session_data
761
-            : array();
762
-        if (empty($this->_session_data)) {
763
-            $this->_set_defaults();
764
-        }
765
-        $session_data = array();
766
-        foreach ($this->_session_data as $key => $value) {
767
-
768
-            switch ($key) {
769
-
770
-                case 'id' :
771
-                    // session ID
772
-                    $session_data['id'] = $this->_sid;
773
-                    break;
774
-                case 'ip_address' :
775
-                    // visitor ip address
776
-                    $session_data['ip_address'] = $this->_visitor_ip();
777
-                    break;
778
-                case 'user_agent' :
779
-                    // visitor user_agent
780
-                    $session_data['user_agent'] = $this->_user_agent;
781
-                    break;
782
-                case 'init_access' :
783
-                    $session_data['init_access'] = absint($value);
784
-                    break;
785
-                case 'last_access' :
786
-                    // current access time
787
-                    $session_data['last_access'] = $this->_time;
788
-                    break;
789
-                case 'expiration' :
790
-                    // when the session expires
791
-                    $session_data['expiration'] = ! empty($this->_expiration)
792
-                        ? $this->_expiration
793
-                        : $session_data['init_access'] + $this->_lifespan;
794
-                    break;
795
-                case 'user_id' :
796
-                    // current user if logged in
797
-                    $session_data['user_id'] = $this->_wp_user_id();
798
-                    break;
799
-                case 'pages_visited' :
800
-                    $page_visit = $this->_get_page_visit();
801
-                    if ($page_visit) {
802
-                        // set pages visited where the first will be the http referrer
803
-                        $this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
804
-                        // we'll only save the last 10 page visits.
805
-                        $session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
806
-                    }
807
-                    break;
808
-                default :
809
-                    // carry any other data over
810
-                    $session_data[ $key ] = $this->_session_data[ $key ];
811
-            }
812
-        }
813
-        $this->_session_data = $session_data;
814
-        // creating a new session does not require saving to the db just yet
815
-        if (! $new_session) {
816
-            // ready? let's save
817
-            if ($this->_save_session_to_db()) {
818
-                return true;
819
-            }
820
-            return false;
821
-        }
822
-        // meh, why not?
823
-        return true;
824
-    }
825
-
826
-
827
-
828
-    /**
829
-     * @create session data array
830
-     * @access public
831
-     * @return bool
832
-     * @throws EE_Error
833
-     * @throws InvalidArgumentException
834
-     * @throws InvalidDataTypeException
835
-     * @throws InvalidInterfaceException
836
-     */
837
-    private function _create_espresso_session()
838
-    {
839
-        do_action('AHEE_log', __CLASS__, __FUNCTION__, '');
840
-        // use the update function for now with $new_session arg set to TRUE
841
-        return $this->update(true) ? true : false;
842
-    }
843
-
844
-
845
-
846
-    /**
847
-     * _save_session_to_db
848
-     *
849
-     * @param bool $clear_session
850
-     * @return string
851
-     * @throws EE_Error
852
-     * @throws InvalidArgumentException
853
-     * @throws InvalidDataTypeException
854
-     * @throws InvalidInterfaceException
855
-     */
856
-    private function _save_session_to_db($clear_session = false)
857
-    {
858
-        // unless we're deleting the session data, don't save anything if there isn't a cart
859
-        if (! $clear_session && ! $this->cart() instanceof EE_Cart) {
860
-            return false;
861
-        }
862
-        $transaction = $this->transaction();
863
-        if ($transaction instanceof EE_Transaction) {
864
-            if (! $transaction->ID()) {
865
-                $transaction->save();
866
-            }
867
-            $this->_session_data['transaction'] = $transaction->ID();
868
-        }
869
-        // then serialize all of our session data
870
-        $session_data = serialize($this->_session_data);
871
-        // do we need to also encode it to avoid corrupted data when saved to the db?
872
-        $session_data = $this->_use_encryption
873
-            ? $this->encryption->base64_string_encode($session_data)
874
-            : $session_data;
875
-        // maybe save hash check
876
-        if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
877
-            $this->cache_storage->add(
878
-                EE_Session::hash_check_prefix . $this->_sid,
879
-                md5($session_data),
880
-                $this->_lifespan
881
-            );
882
-        }
883
-        // we're using the Transient API for storing session data,
884
-        return $this->cache_storage->add(
885
-            EE_Session::session_id_prefix . $this->_sid,
886
-            $session_data,
887
-            $this->_lifespan
888
-        );
889
-    }
890
-
891
-
892
-
893
-    /**
894
-     * _visitor_ip
895
-     *    attempt to get IP address of current visitor from server
896
-     * plz see: http://stackoverflow.com/a/2031935/1475279
897
-     *
898
-     * @access public
899
-     * @return string
900
-     */
901
-    private function _visitor_ip()
902
-    {
903
-        $visitor_ip  = '0.0.0.0';
904
-        $server_keys = array(
905
-            'HTTP_CLIENT_IP',
906
-            'HTTP_X_FORWARDED_FOR',
907
-            'HTTP_X_FORWARDED',
908
-            'HTTP_X_CLUSTER_CLIENT_IP',
909
-            'HTTP_FORWARDED_FOR',
910
-            'HTTP_FORWARDED',
911
-            'REMOTE_ADDR',
912
-        );
913
-        foreach ($server_keys as $key) {
914
-            if (isset($_SERVER[ $key ])) {
915
-                foreach (array_map('trim', explode(',', $_SERVER[ $key ])) as $ip) {
916
-                    if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
917
-                        $visitor_ip = $ip;
918
-                    }
919
-                }
920
-            }
921
-        }
922
-        return $visitor_ip;
923
-    }
924
-
925
-
926
-
927
-    /**
928
-     * @get    the full page request the visitor is accessing
929
-     * @access public
930
-     * @return string
931
-     */
932
-    public function _get_page_visit()
933
-    {
934
-        $page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
935
-        // check for request url
936
-        if (isset($_SERVER['REQUEST_URI'])) {
937
-            $http_host   = '';
938
-            $page_id     = '?';
939
-            $e_reg       = '';
940
-            $request_uri = esc_url($_SERVER['REQUEST_URI']);
941
-            $ru_bits     = explode('?', $request_uri);
942
-            $request_uri = $ru_bits[0];
943
-            // check for and grab host as well
944
-            if (isset($_SERVER['HTTP_HOST'])) {
945
-                $http_host = esc_url($_SERVER['HTTP_HOST']);
946
-            }
947
-            // check for page_id in SERVER REQUEST
948
-            if (isset($_REQUEST['page_id'])) {
949
-                // rebuild $e_reg without any of the extra parameters
950
-                $page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
951
-            }
952
-            // check for $e_reg in SERVER REQUEST
953
-            if (isset($_REQUEST['ee'])) {
954
-                // rebuild $e_reg without any of the extra parameters
955
-                $e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
956
-            }
957
-            $page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
958
-        }
959
-        return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
960
-    }
961
-
962
-
963
-
964
-    /**
965
-     * @the    current wp user id
966
-     * @access public
967
-     * @return int
968
-     */
969
-    public function _wp_user_id()
970
-    {
971
-        // if I need to explain the following lines of code, then you shouldn't be looking at this!
972
-        $this->_wp_user_id = get_current_user_id();
973
-        return $this->_wp_user_id;
974
-    }
975
-
976
-
977
-
978
-    /**
979
-     * Clear EE_Session data
980
-     *
981
-     * @access public
982
-     * @param string $class
983
-     * @param string $function
984
-     * @return void
985
-     * @throws EE_Error
986
-     * @throws InvalidArgumentException
987
-     * @throws InvalidDataTypeException
988
-     * @throws InvalidInterfaceException
989
-     */
990
-    public function clear_session($class = '', $function = '')
991
-    {
992
-        //echo '<h3 style="color:#999;line-height:.9em;"><span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/><span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b></h3>';
993
-        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
994
-        $this->reset_cart();
995
-        $this->reset_checkout();
996
-        $this->reset_transaction();
997
-        // wipe out everything that isn't a default session datum
998
-        $this->reset_data(array_keys($this->_session_data));
999
-        // reset initial site access time and the session expiration
1000
-        $this->_set_init_access_and_expiration();
1001
-        $this->_save_session_to_db(true);
1002
-    }
1003
-
1004
-
1005
-
1006
-    /**
1007
-     * @resets all non-default session vars
1008
-     * @access public
1009
-     * @param array|mixed $data_to_reset
1010
-     * @param bool        $show_all_notices
1011
-     * @return TRUE on success, FALSE on fail
1012
-     */
1013
-    public function reset_data($data_to_reset = array(), $show_all_notices = false)
1014
-    {
1015
-        // if $data_to_reset is not in an array, then put it in one
1016
-        if (! is_array($data_to_reset)) {
1017
-            $data_to_reset = array($data_to_reset);
1018
-        }
1019
-        // nothing ??? go home!
1020
-        if (empty($data_to_reset)) {
1021
-            EE_Error::add_error(__('No session data could be reset, because no session var name was provided.',
1022
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1023
-            return false;
1024
-        }
1025
-        $return_value = true;
1026
-        // since $data_to_reset is an array, cycle through the values
1027
-        foreach ($data_to_reset as $reset) {
1028
-
1029
-            // first check to make sure it is a valid session var
1030
-            if (isset($this->_session_data[ $reset ])) {
1031
-                // then check to make sure it is not a default var
1032
-                if (! array_key_exists($reset, $this->_default_session_vars)) {
1033
-                    // remove session var
1034
-                    unset($this->_session_data[ $reset ]);
1035
-                    if ($show_all_notices) {
1036
-                        EE_Error::add_success(sprintf(__('The session variable %s was removed.', 'event_espresso'),
1037
-                            $reset), __FILE__, __FUNCTION__, __LINE__);
1038
-                    }
1039
-                } else {
1040
-                    // yeeeeeeeeerrrrrrrrrrr OUT !!!!
1041
-                    if ($show_all_notices) {
1042
-                        EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.',
1043
-                            'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
1044
-                    }
1045
-                    $return_value = false;
1046
-                }
1047
-            } elseif ($show_all_notices) {
1048
-                // oops! that session var does not exist!
1049
-                EE_Error::add_error(sprintf(__('The session item provided, %s, is invalid or does not exist.',
1050
-                    'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
1051
-                $return_value = false;
1052
-            }
1053
-        } // end of foreach
1054
-        return $return_value;
1055
-    }
1056
-
1057
-
1058
-
1059
-    /**
1060
-     *   wp_loaded
1061
-     *
1062
-     * @access public
1063
-     * @throws EE_Error
1064
-     * @throws InvalidDataTypeException
1065
-     * @throws InvalidInterfaceException
1066
-     * @throws InvalidArgumentException
1067
-     */
1068
-    public function wp_loaded()
1069
-    {
1070
-        if (
1071
-            EE_Registry::instance()->REQ instanceof EE_Request_Handler
1072
-            && EE_Registry::instance()->REQ->is_set('clear_session')
1073
-        ) {
1074
-            $this->clear_session(__CLASS__, __FUNCTION__);
1075
-        }
1076
-    }
1077
-
1078
-
1079
-
1080
-    /**
1081
-     * Used to reset the entire object (for tests).
1082
-     *
1083
-     * @since 4.3.0
1084
-     * @throws EE_Error
1085
-     * @throws InvalidDataTypeException
1086
-     * @throws InvalidInterfaceException
1087
-     * @throws InvalidArgumentException
1088
-     */
1089
-    public function reset_instance()
1090
-    {
1091
-        $this->clear_session();
1092
-        self::$_instance = null;
1093
-    }
1094
-
1095
-
1096
-
1097
-    public function configure_garbage_collection_filters()
1098
-    {
1099
-        // run old filter we had for controlling session cleanup
1100
-        $expired_session_transient_delete_query_limit = absint(
1101
-            apply_filters(
1102
-                'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1103
-                50
1104
-            )
1105
-        );
1106
-        // is there a value? or one that is different than the default 50 records?
1107
-        if ($expired_session_transient_delete_query_limit === 0) {
1108
-            // hook into TransientCacheStorage in case Session cleanup was turned off
1109
-            add_filter('FHEE__TransientCacheStorage__transient_cleanup_schedule', '__return_zero');
1110
-        } elseif ($expired_session_transient_delete_query_limit !== 50) {
1111
-            // or use that for the new transient cleanup query limit
1112
-            add_filter(
1113
-                'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1114
-                function () use ($expired_session_transient_delete_query_limit)
1115
-                {
1116
-                    return $expired_session_transient_delete_query_limit;
1117
-                }
1118
-            );
1119
-        }
1120
-    }
1121
-
1122
-
1123
-
1124
-    /**
1125
-     * @see http://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset/21389439#10152996
1126
-     * @param $data1
1127
-     * @return string
1128
-     */
1129
-    private function find_serialize_error($data1)
1130
-    {
1131
-        $error = '<pre>';
1132
-        $data2 = preg_replace_callback(
1133
-            '!s:(\d+):"(.*?)";!',
1134
-            function ($match)
1135
-            {
1136
-                return ($match[1] === strlen($match[2]))
1137
-                    ? $match[0]
1138
-                    : 's:'
1139
-                      . strlen($match[2])
1140
-                      . ':"'
1141
-                      . $match[2]
1142
-                      . '";';
1143
-            },
1144
-            $data1
1145
-        );
1146
-        $max   = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1147
-        $error .= $data1 . PHP_EOL;
1148
-        $error .= $data2 . PHP_EOL;
1149
-        for ($i = 0; $i < $max; $i++) {
1150
-            if (@$data1[ $i ] !== @$data2[ $i ]) {
1151
-                $error  .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1152
-                $error  .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1153
-                $error  .= "\t-> Line Number = $i" . PHP_EOL;
1154
-                $start  = ($i - 20);
1155
-                $start  = ($start < 0) ? 0 : $start;
1156
-                $length = 40;
1157
-                $point  = $max - $i;
1158
-                if ($point < 20) {
1159
-                    $rlength = 1;
1160
-                    $rpoint  = -$point;
1161
-                } else {
1162
-                    $rpoint  = $length - 20;
1163
-                    $rlength = 1;
1164
-                }
1165
-                $error .= "\t-> Section Data1  = ";
1166
-                $error .= substr_replace(
1167
-                    substr($data1, $start, $length),
1168
-                    "<b style=\"color:green\">{$data1[ $i ]}</b>",
1169
-                    $rpoint,
1170
-                    $rlength
1171
-                );
1172
-                $error .= PHP_EOL;
1173
-                $error .= "\t-> Section Data2  = ";
1174
-                $error .= substr_replace(
1175
-                    substr($data2, $start, $length),
1176
-                    "<b style=\"color:red\">{$data2[ $i ]}</b>",
1177
-                    $rpoint,
1178
-                    $rlength
1179
-                );
1180
-                $error .= PHP_EOL;
1181
-            }
1182
-        }
1183
-        $error .= '</pre>';
1184
-        return $error;
1185
-    }
1186
-
1187
-
1188
-    /**
1189
-     * Saves an  array of settings used for configuring aspects of session behaviour
1190
-     *
1191
-     * @param array $updated_settings
1192
-     */
1193
-    private function updateSessionSettings(array $updated_settings = array())
1194
-    {
1195
-        // add existing settings, but only if not included in incoming $updated_settings array
1196
-        $updated_settings += get_option(EE_Session::OPTION_NAME_SETTINGS, array());
1197
-        update_option(EE_Session::OPTION_NAME_SETTINGS, $updated_settings);
1198
-    }
1199
-
1200
-
1201
-    /**
1202
-     * garbage_collection
1203
-     */
1204
-    public function garbageCollection()
1205
-    {
1206
-        // only perform during regular requests if last garbage collection was over an hour ago
1207
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1208
-            $this->_last_gc = time();
1209
-            $this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1210
-            /** @type WPDB $wpdb */
1211
-            global $wpdb;
1212
-            // filter the query limit. Set to 0 to turn off garbage collection
1213
-            $expired_session_transient_delete_query_limit = absint(
1214
-                apply_filters(
1215
-                    'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1216
-                    50
1217
-                )
1218
-            );
1219
-            // non-zero LIMIT means take out the trash
1220
-            if ($expired_session_transient_delete_query_limit) {
1221
-                $session_key    = str_replace('_', '\_', EE_Session::session_id_prefix);
1222
-                $hash_check_key = str_replace('_', '\_', EE_Session::hash_check_prefix);
1223
-                // since transient expiration timestamps are set in the future, we can compare against NOW
1224
-                // but we only want to pick up any trash that's been around for more than a day
1225
-                $expiration = time() - DAY_IN_SECONDS;
1226
-                $SQL        = "
362
+	/**
363
+	 * reset_cart
364
+	 */
365
+	public function reset_cart()
366
+	{
367
+		do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
368
+		$this->_session_data['cart'] = null;
369
+	}
370
+
371
+
372
+
373
+	/**
374
+	 * @return \EE_Cart
375
+	 */
376
+	public function cart()
377
+	{
378
+		return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
379
+			? $this->_session_data['cart']
380
+			: null;
381
+	}
382
+
383
+
384
+
385
+	/**
386
+	 * @param \EE_Checkout $checkout
387
+	 * @return bool
388
+	 */
389
+	public function set_checkout(EE_Checkout $checkout)
390
+	{
391
+		$this->_session_data['checkout'] = $checkout;
392
+		return true;
393
+	}
394
+
395
+
396
+
397
+	/**
398
+	 * reset_checkout
399
+	 */
400
+	public function reset_checkout()
401
+	{
402
+		do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
403
+		$this->_session_data['checkout'] = null;
404
+	}
405
+
406
+
407
+
408
+	/**
409
+	 * @return \EE_Checkout
410
+	 */
411
+	public function checkout()
412
+	{
413
+		return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
414
+			? $this->_session_data['checkout']
415
+			: null;
416
+	}
417
+
418
+
419
+
420
+	/**
421
+	 * @param \EE_Transaction $transaction
422
+	 * @return bool
423
+	 * @throws EE_Error
424
+	 */
425
+	public function set_transaction(EE_Transaction $transaction)
426
+	{
427
+		// first remove the session from the transaction before we save the transaction in the session
428
+		$transaction->set_txn_session_data(null);
429
+		$this->_session_data['transaction'] = $transaction;
430
+		return true;
431
+	}
432
+
433
+
434
+
435
+	/**
436
+	 * reset_transaction
437
+	 */
438
+	public function reset_transaction()
439
+	{
440
+		do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
441
+		$this->_session_data['transaction'] = null;
442
+	}
443
+
444
+
445
+
446
+	/**
447
+	 * @return \EE_Transaction
448
+	 */
449
+	public function transaction()
450
+	{
451
+		return isset($this->_session_data['transaction'])
452
+			   && $this->_session_data['transaction'] instanceof EE_Transaction
453
+			? $this->_session_data['transaction']
454
+			: null;
455
+	}
456
+
457
+
458
+
459
+	/**
460
+	 * retrieve session data
461
+	 *
462
+	 * @access    public
463
+	 * @param null $key
464
+	 * @param bool $reset_cache
465
+	 * @return    array
466
+	 */
467
+	public function get_session_data($key = null, $reset_cache = false)
468
+	{
469
+		if ($reset_cache) {
470
+			$this->reset_cart();
471
+			$this->reset_checkout();
472
+			$this->reset_transaction();
473
+		}
474
+		if (! empty($key)) {
475
+			return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
476
+		}
477
+		return $this->_session_data;
478
+	}
479
+
480
+
481
+
482
+	/**
483
+	 * set session data
484
+	 *
485
+	 * @access    public
486
+	 * @param    array $data
487
+	 * @return    TRUE on success, FALSE on fail
488
+	 */
489
+	public function set_session_data($data)
490
+	{
491
+
492
+		// nothing ??? bad data ??? go home!
493
+		if (empty($data) || ! is_array($data)) {
494
+			EE_Error::add_error(__('No session data or invalid session data was provided.', 'event_espresso'), __FILE__,
495
+				__FUNCTION__, __LINE__);
496
+			return false;
497
+		}
498
+		foreach ($data as $key => $value) {
499
+			if (isset($this->_default_session_vars[ $key ])) {
500
+				EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.',
501
+					'event_espresso'), $key), __FILE__, __FUNCTION__, __LINE__);
502
+				return false;
503
+			}
504
+			$this->_session_data[ $key ] = $value;
505
+		}
506
+		return true;
507
+	}
508
+
509
+
510
+
511
+	/**
512
+	 * @initiate session
513
+	 * @access   private
514
+	 * @return TRUE on success, FALSE on fail
515
+	 * @throws EE_Error
516
+	 * @throws InvalidArgumentException
517
+	 * @throws InvalidDataTypeException
518
+	 * @throws InvalidInterfaceException
519
+	 * @throws InvalidSessionDataException
520
+	 */
521
+	private function _espresso_session()
522
+	{
523
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
524
+		// check that session has started
525
+		if (session_id() === '') {
526
+			//starts a new session if one doesn't already exist, or re-initiates an existing one
527
+			session_start();
528
+		}
529
+		// get our modified session ID
530
+		$this->_sid = $this->_generate_session_id();
531
+		// and the visitors IP
532
+		$this->_ip_address = $this->_visitor_ip();
533
+		// set the "user agent"
534
+		$this->_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? esc_attr($_SERVER['HTTP_USER_AGENT']) : false;
535
+		// now let's retrieve what's in the db
536
+		$session_data = $this->_retrieve_session_data();
537
+		if (! empty($session_data)) {
538
+			// get the current time in UTC
539
+			$this->_time = $this->_time !== null ? $this->_time : time();
540
+			// and reset the session expiration
541
+			$this->_expiration = isset($session_data['expiration'])
542
+				? $session_data['expiration']
543
+				: $this->_time + $this->_lifespan;
544
+		} else {
545
+			// set initial site access time and the session expiration
546
+			$this->_set_init_access_and_expiration();
547
+			// set referer
548
+			$this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
549
+				? esc_attr($_SERVER['HTTP_REFERER'])
550
+				: '';
551
+			// no previous session = go back and create one (on top of the data above)
552
+			return false;
553
+		}
554
+		// now the user agent
555
+		if ($session_data['user_agent'] !== $this->_user_agent) {
556
+			return false;
557
+		}
558
+		// wait a minute... how old are you?
559
+		if ($this->_time > $this->_expiration) {
560
+			// yer too old fer me!
561
+			$this->_expired = true;
562
+			// wipe out everything that isn't a default session datum
563
+			$this->clear_session(__CLASS__, __FUNCTION__);
564
+		}
565
+		// make event espresso session data available to plugin
566
+		$this->_session_data = array_merge($this->_session_data, $session_data);
567
+		return true;
568
+	}
569
+
570
+
571
+
572
+	/**
573
+	 * _get_session_data
574
+	 * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup
575
+	 * databases
576
+	 *
577
+	 * @return array
578
+	 * @throws EE_Error
579
+	 * @throws InvalidArgumentException
580
+	 * @throws InvalidSessionDataException
581
+	 * @throws InvalidDataTypeException
582
+	 * @throws InvalidInterfaceException
583
+	 */
584
+	protected function _retrieve_session_data()
585
+	{
586
+		$ssn_key = EE_Session::session_id_prefix . $this->_sid;
587
+		try {
588
+			// we're using WP's Transient API to store session data using the PHP session ID as the option name
589
+			$session_data = $this->cache_storage->get($ssn_key, false);
590
+			if (empty($session_data)) {
591
+				return array();
592
+			}
593
+			if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
594
+				$hash_check = $this->cache_storage->get(
595
+					EE_Session::hash_check_prefix . $this->_sid,
596
+					false
597
+				);
598
+				if ($hash_check && $hash_check !== md5($session_data)) {
599
+					EE_Error::add_error(
600
+						sprintf(
601
+							__(
602
+								'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
603
+								'event_espresso'
604
+							),
605
+							EE_Session::session_id_prefix . $this->_sid
606
+						),
607
+						__FILE__, __FUNCTION__, __LINE__
608
+					);
609
+				}
610
+			}
611
+		} catch (Exception $e) {
612
+			// let's just eat that error for now and attempt to correct any corrupted data
613
+			global $wpdb;
614
+			$row          = $wpdb->get_row(
615
+				$wpdb->prepare(
616
+					"SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
617
+					'_transient_' . $ssn_key
618
+				)
619
+			);
620
+			$session_data = is_object($row) ? $row->option_value : null;
621
+			if ($session_data) {
622
+				$session_data = preg_replace_callback(
623
+					'!s:(d+):"(.*?)";!',
624
+					function ($match)
625
+					{
626
+						return $match[1] === strlen($match[2])
627
+							? $match[0]
628
+							: 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
629
+					},
630
+					$session_data
631
+				);
632
+			}
633
+			$session_data = maybe_unserialize($session_data);
634
+		}
635
+		// in case the data is encoded... try to decode it
636
+		$session_data = $this->encryption instanceof EE_Encryption
637
+			? $this->encryption->base64_string_decode($session_data)
638
+			: $session_data;
639
+		if (! is_array($session_data)) {
640
+			try {
641
+				$session_data = maybe_unserialize($session_data);
642
+			} catch (Exception $e) {
643
+				$msg = esc_html__(
644
+					'An error occurred while attempting to unserialize the session data.',
645
+					'event_espresso'
646
+				);
647
+				$msg .= WP_DEBUG
648
+					? '<br><pre>'
649
+					  . print_r($session_data, true)
650
+					  . '</pre><br>'
651
+					  . $this->find_serialize_error($session_data)
652
+					: '';
653
+				$this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
654
+				throw new InvalidSessionDataException($msg, 0, $e);
655
+			}
656
+		}
657
+		// just a check to make sure the session array is indeed an array
658
+		if (! is_array($session_data)) {
659
+			// no?!?! then something is wrong
660
+			$msg = esc_html__(
661
+				'The session data is missing, invalid, or corrupted.',
662
+				'event_espresso'
663
+			);
664
+			$msg .= WP_DEBUG
665
+				? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
666
+				: '';
667
+			$this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
668
+			throw new InvalidSessionDataException($msg);
669
+		}
670
+		if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
671
+			$session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
672
+				$session_data['transaction']
673
+			);
674
+		}
675
+		return $session_data;
676
+	}
677
+
678
+
679
+
680
+	/**
681
+	 * _generate_session_id
682
+	 * Retrieves the PHP session id either directly from the PHP session,
683
+	 * or from the $_REQUEST array if it was passed in from an AJAX request.
684
+	 * The session id is then salted and hashed (mmm sounds tasty)
685
+	 * so that it can be safely used as a $_REQUEST param
686
+	 *
687
+	 * @return string
688
+	 */
689
+	protected function _generate_session_id()
690
+	{
691
+		// check if the SID was passed explicitly, otherwise get from session, then add salt and hash it to reduce length
692
+		if (isset($_REQUEST['EESID'])) {
693
+			$session_id = sanitize_text_field($_REQUEST['EESID']);
694
+		} else {
695
+			$session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
696
+		}
697
+		return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
698
+	}
699
+
700
+
701
+
702
+	/**
703
+	 * _get_sid_salt
704
+	 *
705
+	 * @return string
706
+	 */
707
+	protected function _get_sid_salt()
708
+	{
709
+		// was session id salt already saved to db ?
710
+		if (empty($this->_sid_salt)) {
711
+			// no?  then maybe use WP defined constant
712
+			if (defined('AUTH_SALT')) {
713
+				$this->_sid_salt = AUTH_SALT;
714
+			}
715
+			// if salt doesn't exist or is too short
716
+			if (strlen($this->_sid_salt) < 32) {
717
+				// create a new one
718
+				$this->_sid_salt = wp_generate_password(64);
719
+			}
720
+			// and save it as a permanent session setting
721
+			$this->updateSessionSettings(array('sid_salt' => $this->_sid_salt));
722
+		}
723
+		return $this->_sid_salt;
724
+	}
725
+
726
+
727
+
728
+	/**
729
+	 * _set_init_access_and_expiration
730
+	 *
731
+	 * @return void
732
+	 */
733
+	protected function _set_init_access_and_expiration()
734
+	{
735
+		$this->_time       = time();
736
+		$this->_expiration = $this->_time + $this->_lifespan;
737
+		// set initial site access time
738
+		$this->_session_data['init_access'] = $this->_time;
739
+		// and the session expiration
740
+		$this->_session_data['expiration'] = $this->_expiration;
741
+	}
742
+
743
+
744
+
745
+	/**
746
+	 * @update session data  prior to saving to the db
747
+	 * @access public
748
+	 * @param bool $new_session
749
+	 * @return TRUE on success, FALSE on fail
750
+	 * @throws EE_Error
751
+	 * @throws InvalidArgumentException
752
+	 * @throws InvalidDataTypeException
753
+	 * @throws InvalidInterfaceException
754
+	 */
755
+	public function update($new_session = false)
756
+	{
757
+		$this->_session_data = $this->_session_data !== null
758
+							   && is_array($this->_session_data)
759
+							   && isset($this->_session_data['id'])
760
+			? $this->_session_data
761
+			: array();
762
+		if (empty($this->_session_data)) {
763
+			$this->_set_defaults();
764
+		}
765
+		$session_data = array();
766
+		foreach ($this->_session_data as $key => $value) {
767
+
768
+			switch ($key) {
769
+
770
+				case 'id' :
771
+					// session ID
772
+					$session_data['id'] = $this->_sid;
773
+					break;
774
+				case 'ip_address' :
775
+					// visitor ip address
776
+					$session_data['ip_address'] = $this->_visitor_ip();
777
+					break;
778
+				case 'user_agent' :
779
+					// visitor user_agent
780
+					$session_data['user_agent'] = $this->_user_agent;
781
+					break;
782
+				case 'init_access' :
783
+					$session_data['init_access'] = absint($value);
784
+					break;
785
+				case 'last_access' :
786
+					// current access time
787
+					$session_data['last_access'] = $this->_time;
788
+					break;
789
+				case 'expiration' :
790
+					// when the session expires
791
+					$session_data['expiration'] = ! empty($this->_expiration)
792
+						? $this->_expiration
793
+						: $session_data['init_access'] + $this->_lifespan;
794
+					break;
795
+				case 'user_id' :
796
+					// current user if logged in
797
+					$session_data['user_id'] = $this->_wp_user_id();
798
+					break;
799
+				case 'pages_visited' :
800
+					$page_visit = $this->_get_page_visit();
801
+					if ($page_visit) {
802
+						// set pages visited where the first will be the http referrer
803
+						$this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
804
+						// we'll only save the last 10 page visits.
805
+						$session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
806
+					}
807
+					break;
808
+				default :
809
+					// carry any other data over
810
+					$session_data[ $key ] = $this->_session_data[ $key ];
811
+			}
812
+		}
813
+		$this->_session_data = $session_data;
814
+		// creating a new session does not require saving to the db just yet
815
+		if (! $new_session) {
816
+			// ready? let's save
817
+			if ($this->_save_session_to_db()) {
818
+				return true;
819
+			}
820
+			return false;
821
+		}
822
+		// meh, why not?
823
+		return true;
824
+	}
825
+
826
+
827
+
828
+	/**
829
+	 * @create session data array
830
+	 * @access public
831
+	 * @return bool
832
+	 * @throws EE_Error
833
+	 * @throws InvalidArgumentException
834
+	 * @throws InvalidDataTypeException
835
+	 * @throws InvalidInterfaceException
836
+	 */
837
+	private function _create_espresso_session()
838
+	{
839
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, '');
840
+		// use the update function for now with $new_session arg set to TRUE
841
+		return $this->update(true) ? true : false;
842
+	}
843
+
844
+
845
+
846
+	/**
847
+	 * _save_session_to_db
848
+	 *
849
+	 * @param bool $clear_session
850
+	 * @return string
851
+	 * @throws EE_Error
852
+	 * @throws InvalidArgumentException
853
+	 * @throws InvalidDataTypeException
854
+	 * @throws InvalidInterfaceException
855
+	 */
856
+	private function _save_session_to_db($clear_session = false)
857
+	{
858
+		// unless we're deleting the session data, don't save anything if there isn't a cart
859
+		if (! $clear_session && ! $this->cart() instanceof EE_Cart) {
860
+			return false;
861
+		}
862
+		$transaction = $this->transaction();
863
+		if ($transaction instanceof EE_Transaction) {
864
+			if (! $transaction->ID()) {
865
+				$transaction->save();
866
+			}
867
+			$this->_session_data['transaction'] = $transaction->ID();
868
+		}
869
+		// then serialize all of our session data
870
+		$session_data = serialize($this->_session_data);
871
+		// do we need to also encode it to avoid corrupted data when saved to the db?
872
+		$session_data = $this->_use_encryption
873
+			? $this->encryption->base64_string_encode($session_data)
874
+			: $session_data;
875
+		// maybe save hash check
876
+		if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
877
+			$this->cache_storage->add(
878
+				EE_Session::hash_check_prefix . $this->_sid,
879
+				md5($session_data),
880
+				$this->_lifespan
881
+			);
882
+		}
883
+		// we're using the Transient API for storing session data,
884
+		return $this->cache_storage->add(
885
+			EE_Session::session_id_prefix . $this->_sid,
886
+			$session_data,
887
+			$this->_lifespan
888
+		);
889
+	}
890
+
891
+
892
+
893
+	/**
894
+	 * _visitor_ip
895
+	 *    attempt to get IP address of current visitor from server
896
+	 * plz see: http://stackoverflow.com/a/2031935/1475279
897
+	 *
898
+	 * @access public
899
+	 * @return string
900
+	 */
901
+	private function _visitor_ip()
902
+	{
903
+		$visitor_ip  = '0.0.0.0';
904
+		$server_keys = array(
905
+			'HTTP_CLIENT_IP',
906
+			'HTTP_X_FORWARDED_FOR',
907
+			'HTTP_X_FORWARDED',
908
+			'HTTP_X_CLUSTER_CLIENT_IP',
909
+			'HTTP_FORWARDED_FOR',
910
+			'HTTP_FORWARDED',
911
+			'REMOTE_ADDR',
912
+		);
913
+		foreach ($server_keys as $key) {
914
+			if (isset($_SERVER[ $key ])) {
915
+				foreach (array_map('trim', explode(',', $_SERVER[ $key ])) as $ip) {
916
+					if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
917
+						$visitor_ip = $ip;
918
+					}
919
+				}
920
+			}
921
+		}
922
+		return $visitor_ip;
923
+	}
924
+
925
+
926
+
927
+	/**
928
+	 * @get    the full page request the visitor is accessing
929
+	 * @access public
930
+	 * @return string
931
+	 */
932
+	public function _get_page_visit()
933
+	{
934
+		$page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
935
+		// check for request url
936
+		if (isset($_SERVER['REQUEST_URI'])) {
937
+			$http_host   = '';
938
+			$page_id     = '?';
939
+			$e_reg       = '';
940
+			$request_uri = esc_url($_SERVER['REQUEST_URI']);
941
+			$ru_bits     = explode('?', $request_uri);
942
+			$request_uri = $ru_bits[0];
943
+			// check for and grab host as well
944
+			if (isset($_SERVER['HTTP_HOST'])) {
945
+				$http_host = esc_url($_SERVER['HTTP_HOST']);
946
+			}
947
+			// check for page_id in SERVER REQUEST
948
+			if (isset($_REQUEST['page_id'])) {
949
+				// rebuild $e_reg without any of the extra parameters
950
+				$page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
951
+			}
952
+			// check for $e_reg in SERVER REQUEST
953
+			if (isset($_REQUEST['ee'])) {
954
+				// rebuild $e_reg without any of the extra parameters
955
+				$e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
956
+			}
957
+			$page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
958
+		}
959
+		return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
960
+	}
961
+
962
+
963
+
964
+	/**
965
+	 * @the    current wp user id
966
+	 * @access public
967
+	 * @return int
968
+	 */
969
+	public function _wp_user_id()
970
+	{
971
+		// if I need to explain the following lines of code, then you shouldn't be looking at this!
972
+		$this->_wp_user_id = get_current_user_id();
973
+		return $this->_wp_user_id;
974
+	}
975
+
976
+
977
+
978
+	/**
979
+	 * Clear EE_Session data
980
+	 *
981
+	 * @access public
982
+	 * @param string $class
983
+	 * @param string $function
984
+	 * @return void
985
+	 * @throws EE_Error
986
+	 * @throws InvalidArgumentException
987
+	 * @throws InvalidDataTypeException
988
+	 * @throws InvalidInterfaceException
989
+	 */
990
+	public function clear_session($class = '', $function = '')
991
+	{
992
+		//echo '<h3 style="color:#999;line-height:.9em;"><span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/><span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b></h3>';
993
+		do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
994
+		$this->reset_cart();
995
+		$this->reset_checkout();
996
+		$this->reset_transaction();
997
+		// wipe out everything that isn't a default session datum
998
+		$this->reset_data(array_keys($this->_session_data));
999
+		// reset initial site access time and the session expiration
1000
+		$this->_set_init_access_and_expiration();
1001
+		$this->_save_session_to_db(true);
1002
+	}
1003
+
1004
+
1005
+
1006
+	/**
1007
+	 * @resets all non-default session vars
1008
+	 * @access public
1009
+	 * @param array|mixed $data_to_reset
1010
+	 * @param bool        $show_all_notices
1011
+	 * @return TRUE on success, FALSE on fail
1012
+	 */
1013
+	public function reset_data($data_to_reset = array(), $show_all_notices = false)
1014
+	{
1015
+		// if $data_to_reset is not in an array, then put it in one
1016
+		if (! is_array($data_to_reset)) {
1017
+			$data_to_reset = array($data_to_reset);
1018
+		}
1019
+		// nothing ??? go home!
1020
+		if (empty($data_to_reset)) {
1021
+			EE_Error::add_error(__('No session data could be reset, because no session var name was provided.',
1022
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1023
+			return false;
1024
+		}
1025
+		$return_value = true;
1026
+		// since $data_to_reset is an array, cycle through the values
1027
+		foreach ($data_to_reset as $reset) {
1028
+
1029
+			// first check to make sure it is a valid session var
1030
+			if (isset($this->_session_data[ $reset ])) {
1031
+				// then check to make sure it is not a default var
1032
+				if (! array_key_exists($reset, $this->_default_session_vars)) {
1033
+					// remove session var
1034
+					unset($this->_session_data[ $reset ]);
1035
+					if ($show_all_notices) {
1036
+						EE_Error::add_success(sprintf(__('The session variable %s was removed.', 'event_espresso'),
1037
+							$reset), __FILE__, __FUNCTION__, __LINE__);
1038
+					}
1039
+				} else {
1040
+					// yeeeeeeeeerrrrrrrrrrr OUT !!!!
1041
+					if ($show_all_notices) {
1042
+						EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.',
1043
+							'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
1044
+					}
1045
+					$return_value = false;
1046
+				}
1047
+			} elseif ($show_all_notices) {
1048
+				// oops! that session var does not exist!
1049
+				EE_Error::add_error(sprintf(__('The session item provided, %s, is invalid or does not exist.',
1050
+					'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
1051
+				$return_value = false;
1052
+			}
1053
+		} // end of foreach
1054
+		return $return_value;
1055
+	}
1056
+
1057
+
1058
+
1059
+	/**
1060
+	 *   wp_loaded
1061
+	 *
1062
+	 * @access public
1063
+	 * @throws EE_Error
1064
+	 * @throws InvalidDataTypeException
1065
+	 * @throws InvalidInterfaceException
1066
+	 * @throws InvalidArgumentException
1067
+	 */
1068
+	public function wp_loaded()
1069
+	{
1070
+		if (
1071
+			EE_Registry::instance()->REQ instanceof EE_Request_Handler
1072
+			&& EE_Registry::instance()->REQ->is_set('clear_session')
1073
+		) {
1074
+			$this->clear_session(__CLASS__, __FUNCTION__);
1075
+		}
1076
+	}
1077
+
1078
+
1079
+
1080
+	/**
1081
+	 * Used to reset the entire object (for tests).
1082
+	 *
1083
+	 * @since 4.3.0
1084
+	 * @throws EE_Error
1085
+	 * @throws InvalidDataTypeException
1086
+	 * @throws InvalidInterfaceException
1087
+	 * @throws InvalidArgumentException
1088
+	 */
1089
+	public function reset_instance()
1090
+	{
1091
+		$this->clear_session();
1092
+		self::$_instance = null;
1093
+	}
1094
+
1095
+
1096
+
1097
+	public function configure_garbage_collection_filters()
1098
+	{
1099
+		// run old filter we had for controlling session cleanup
1100
+		$expired_session_transient_delete_query_limit = absint(
1101
+			apply_filters(
1102
+				'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1103
+				50
1104
+			)
1105
+		);
1106
+		// is there a value? or one that is different than the default 50 records?
1107
+		if ($expired_session_transient_delete_query_limit === 0) {
1108
+			// hook into TransientCacheStorage in case Session cleanup was turned off
1109
+			add_filter('FHEE__TransientCacheStorage__transient_cleanup_schedule', '__return_zero');
1110
+		} elseif ($expired_session_transient_delete_query_limit !== 50) {
1111
+			// or use that for the new transient cleanup query limit
1112
+			add_filter(
1113
+				'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1114
+				function () use ($expired_session_transient_delete_query_limit)
1115
+				{
1116
+					return $expired_session_transient_delete_query_limit;
1117
+				}
1118
+			);
1119
+		}
1120
+	}
1121
+
1122
+
1123
+
1124
+	/**
1125
+	 * @see http://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset/21389439#10152996
1126
+	 * @param $data1
1127
+	 * @return string
1128
+	 */
1129
+	private function find_serialize_error($data1)
1130
+	{
1131
+		$error = '<pre>';
1132
+		$data2 = preg_replace_callback(
1133
+			'!s:(\d+):"(.*?)";!',
1134
+			function ($match)
1135
+			{
1136
+				return ($match[1] === strlen($match[2]))
1137
+					? $match[0]
1138
+					: 's:'
1139
+					  . strlen($match[2])
1140
+					  . ':"'
1141
+					  . $match[2]
1142
+					  . '";';
1143
+			},
1144
+			$data1
1145
+		);
1146
+		$max   = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1147
+		$error .= $data1 . PHP_EOL;
1148
+		$error .= $data2 . PHP_EOL;
1149
+		for ($i = 0; $i < $max; $i++) {
1150
+			if (@$data1[ $i ] !== @$data2[ $i ]) {
1151
+				$error  .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1152
+				$error  .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1153
+				$error  .= "\t-> Line Number = $i" . PHP_EOL;
1154
+				$start  = ($i - 20);
1155
+				$start  = ($start < 0) ? 0 : $start;
1156
+				$length = 40;
1157
+				$point  = $max - $i;
1158
+				if ($point < 20) {
1159
+					$rlength = 1;
1160
+					$rpoint  = -$point;
1161
+				} else {
1162
+					$rpoint  = $length - 20;
1163
+					$rlength = 1;
1164
+				}
1165
+				$error .= "\t-> Section Data1  = ";
1166
+				$error .= substr_replace(
1167
+					substr($data1, $start, $length),
1168
+					"<b style=\"color:green\">{$data1[ $i ]}</b>",
1169
+					$rpoint,
1170
+					$rlength
1171
+				);
1172
+				$error .= PHP_EOL;
1173
+				$error .= "\t-> Section Data2  = ";
1174
+				$error .= substr_replace(
1175
+					substr($data2, $start, $length),
1176
+					"<b style=\"color:red\">{$data2[ $i ]}</b>",
1177
+					$rpoint,
1178
+					$rlength
1179
+				);
1180
+				$error .= PHP_EOL;
1181
+			}
1182
+		}
1183
+		$error .= '</pre>';
1184
+		return $error;
1185
+	}
1186
+
1187
+
1188
+	/**
1189
+	 * Saves an  array of settings used for configuring aspects of session behaviour
1190
+	 *
1191
+	 * @param array $updated_settings
1192
+	 */
1193
+	private function updateSessionSettings(array $updated_settings = array())
1194
+	{
1195
+		// add existing settings, but only if not included in incoming $updated_settings array
1196
+		$updated_settings += get_option(EE_Session::OPTION_NAME_SETTINGS, array());
1197
+		update_option(EE_Session::OPTION_NAME_SETTINGS, $updated_settings);
1198
+	}
1199
+
1200
+
1201
+	/**
1202
+	 * garbage_collection
1203
+	 */
1204
+	public function garbageCollection()
1205
+	{
1206
+		// only perform during regular requests if last garbage collection was over an hour ago
1207
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1208
+			$this->_last_gc = time();
1209
+			$this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1210
+			/** @type WPDB $wpdb */
1211
+			global $wpdb;
1212
+			// filter the query limit. Set to 0 to turn off garbage collection
1213
+			$expired_session_transient_delete_query_limit = absint(
1214
+				apply_filters(
1215
+					'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1216
+					50
1217
+				)
1218
+			);
1219
+			// non-zero LIMIT means take out the trash
1220
+			if ($expired_session_transient_delete_query_limit) {
1221
+				$session_key    = str_replace('_', '\_', EE_Session::session_id_prefix);
1222
+				$hash_check_key = str_replace('_', '\_', EE_Session::hash_check_prefix);
1223
+				// since transient expiration timestamps are set in the future, we can compare against NOW
1224
+				// but we only want to pick up any trash that's been around for more than a day
1225
+				$expiration = time() - DAY_IN_SECONDS;
1226
+				$SQL        = "
1227 1227
                     SELECT option_name
1228 1228
                     FROM {$wpdb->options}
1229 1229
                     WHERE
@@ -1232,19 +1232,19 @@  discard block
 block discarded – undo
1232 1232
                     AND option_value < {$expiration}
1233 1233
                     LIMIT {$expired_session_transient_delete_query_limit}
1234 1234
                 ";
1235
-                // produces something like:
1236
-                // SELECT option_name FROM wp_options
1237
-                // WHERE ( option_name LIKE '\_transient\_timeout\_ee\_ssn\_%'
1238
-                // OR option_name LIKE '\_transient\_timeout\_ee\_shc\_%' )
1239
-                // AND option_value < 1508368198 LIMIT 50
1240
-                $expired_sessions = $wpdb->get_col($SQL);
1241
-                // valid results?
1242
-                if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1243
-                    $this->cache_storage->deleteMany($expired_sessions, true);
1244
-                }
1245
-            }
1246
-        }
1247
-    }
1235
+				// produces something like:
1236
+				// SELECT option_name FROM wp_options
1237
+				// WHERE ( option_name LIKE '\_transient\_timeout\_ee\_ssn\_%'
1238
+				// OR option_name LIKE '\_transient\_timeout\_ee\_shc\_%' )
1239
+				// AND option_value < 1508368198 LIMIT 50
1240
+				$expired_sessions = $wpdb->get_col($SQL);
1241
+				// valid results?
1242
+				if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1243
+					$this->cache_storage->deleteMany($expired_sessions, true);
1244
+				}
1245
+			}
1246
+		}
1247
+	}
1248 1248
 
1249 1249
 
1250 1250
 
Please login to merge, or discard this patch.
Spacing   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
         // check if class object is instantiated
165 165
         // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
166 166
         // add_filter( 'FHEE_load_EE_Session', '__return_false' );
167
-        if (! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
167
+        if ( ! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
168 168
             self::$_instance = new self($cache_storage, $encryption);
169 169
         }
170 170
         return self::$_instance;
@@ -185,11 +185,11 @@  discard block
 block discarded – undo
185 185
     {
186 186
 
187 187
         // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
188
-        if (! apply_filters('FHEE_load_EE_Session', true)) {
188
+        if ( ! apply_filters('FHEE_load_EE_Session', true)) {
189 189
             return;
190 190
         }
191 191
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
192
-        if (! defined('ESPRESSO_SESSION')) {
192
+        if ( ! defined('ESPRESSO_SESSION')) {
193 193
             define('ESPRESSO_SESSION', true);
194 194
         }
195 195
         // default session lifespan in seconds
@@ -205,11 +205,11 @@  discard block
 block discarded – undo
205 205
          */
206 206
         // retrieve session options from db
207 207
         $session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
208
-        if (! empty($session_settings)) {
208
+        if ( ! empty($session_settings)) {
209 209
             // cycle though existing session options
210 210
             foreach ($session_settings as $var_name => $session_setting) {
211 211
                 // set values for class properties
212
-                $var_name          = '_' . $var_name;
212
+                $var_name          = '_'.$var_name;
213 213
                 $this->{$var_name} = $session_setting;
214 214
             }
215 215
         }
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
     public function open_session()
248 248
     {
249 249
         // check for existing session and retrieve it from db
250
-        if (! $this->_espresso_session()) {
250
+        if ( ! $this->_espresso_session()) {
251 251
             // or just start a new one
252 252
             $this->_create_espresso_session();
253 253
         }
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
      */
300 300
     public function extend_expiration($time = 0)
301 301
     {
302
-        $time              = $time ? $time : $this->extension();
302
+        $time = $time ? $time : $this->extension();
303 303
         $this->_expiration += absint($time);
304 304
     }
305 305
 
@@ -326,9 +326,9 @@  discard block
 block discarded – undo
326 326
         // set some defaults
327 327
         foreach ($this->_default_session_vars as $key => $default_var) {
328 328
             if (is_array($default_var)) {
329
-                $this->_session_data[ $key ] = array();
329
+                $this->_session_data[$key] = array();
330 330
             } else {
331
-                $this->_session_data[ $key ] = '';
331
+                $this->_session_data[$key] = '';
332 332
             }
333 333
         }
334 334
     }
@@ -471,8 +471,8 @@  discard block
 block discarded – undo
471 471
             $this->reset_checkout();
472 472
             $this->reset_transaction();
473 473
         }
474
-        if (! empty($key)) {
475
-            return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
474
+        if ( ! empty($key)) {
475
+            return isset($this->_session_data[$key]) ? $this->_session_data[$key] : null;
476 476
         }
477 477
         return $this->_session_data;
478 478
     }
@@ -496,12 +496,12 @@  discard block
 block discarded – undo
496 496
             return false;
497 497
         }
498 498
         foreach ($data as $key => $value) {
499
-            if (isset($this->_default_session_vars[ $key ])) {
499
+            if (isset($this->_default_session_vars[$key])) {
500 500
                 EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.',
501 501
                     'event_espresso'), $key), __FILE__, __FUNCTION__, __LINE__);
502 502
                 return false;
503 503
             }
504
-            $this->_session_data[ $key ] = $value;
504
+            $this->_session_data[$key] = $value;
505 505
         }
506 506
         return true;
507 507
     }
@@ -534,7 +534,7 @@  discard block
 block discarded – undo
534 534
         $this->_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? esc_attr($_SERVER['HTTP_USER_AGENT']) : false;
535 535
         // now let's retrieve what's in the db
536 536
         $session_data = $this->_retrieve_session_data();
537
-        if (! empty($session_data)) {
537
+        if ( ! empty($session_data)) {
538 538
             // get the current time in UTC
539 539
             $this->_time = $this->_time !== null ? $this->_time : time();
540 540
             // and reset the session expiration
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
             // set initial site access time and the session expiration
546 546
             $this->_set_init_access_and_expiration();
547 547
             // set referer
548
-            $this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
548
+            $this->_session_data['pages_visited'][$this->_session_data['init_access']] = isset($_SERVER['HTTP_REFERER'])
549 549
                 ? esc_attr($_SERVER['HTTP_REFERER'])
550 550
                 : '';
551 551
             // no previous session = go back and create one (on top of the data above)
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
      */
584 584
     protected function _retrieve_session_data()
585 585
     {
586
-        $ssn_key = EE_Session::session_id_prefix . $this->_sid;
586
+        $ssn_key = EE_Session::session_id_prefix.$this->_sid;
587 587
         try {
588 588
             // we're using WP's Transient API to store session data using the PHP session ID as the option name
589 589
             $session_data = $this->cache_storage->get($ssn_key, false);
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
             }
593 593
             if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
594 594
                 $hash_check = $this->cache_storage->get(
595
-                    EE_Session::hash_check_prefix . $this->_sid,
595
+                    EE_Session::hash_check_prefix.$this->_sid,
596 596
                     false
597 597
                 );
598 598
                 if ($hash_check && $hash_check !== md5($session_data)) {
@@ -602,7 +602,7 @@  discard block
 block discarded – undo
602 602
                                 'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
603 603
                                 'event_espresso'
604 604
                             ),
605
-                            EE_Session::session_id_prefix . $this->_sid
605
+                            EE_Session::session_id_prefix.$this->_sid
606 606
                         ),
607 607
                         __FILE__, __FUNCTION__, __LINE__
608 608
                     );
@@ -611,21 +611,21 @@  discard block
 block discarded – undo
611 611
         } catch (Exception $e) {
612 612
             // let's just eat that error for now and attempt to correct any corrupted data
613 613
             global $wpdb;
614
-            $row          = $wpdb->get_row(
614
+            $row = $wpdb->get_row(
615 615
                 $wpdb->prepare(
616 616
                     "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
617
-                    '_transient_' . $ssn_key
617
+                    '_transient_'.$ssn_key
618 618
                 )
619 619
             );
620 620
             $session_data = is_object($row) ? $row->option_value : null;
621 621
             if ($session_data) {
622 622
                 $session_data = preg_replace_callback(
623 623
                     '!s:(d+):"(.*?)";!',
624
-                    function ($match)
624
+                    function($match)
625 625
                     {
626 626
                         return $match[1] === strlen($match[2])
627 627
                             ? $match[0]
628
-                            : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
628
+                            : 's:'.strlen($match[2]).':"'.$match[2].'";';
629 629
                     },
630 630
                     $session_data
631 631
                 );
@@ -636,7 +636,7 @@  discard block
 block discarded – undo
636 636
         $session_data = $this->encryption instanceof EE_Encryption
637 637
             ? $this->encryption->base64_string_decode($session_data)
638 638
             : $session_data;
639
-        if (! is_array($session_data)) {
639
+        if ( ! is_array($session_data)) {
640 640
             try {
641 641
                 $session_data = maybe_unserialize($session_data);
642 642
             } catch (Exception $e) {
@@ -650,21 +650,21 @@  discard block
 block discarded – undo
650 650
                       . '</pre><br>'
651 651
                       . $this->find_serialize_error($session_data)
652 652
                     : '';
653
-                $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
653
+                $this->cache_storage->delete(EE_Session::session_id_prefix.$this->_sid);
654 654
                 throw new InvalidSessionDataException($msg, 0, $e);
655 655
             }
656 656
         }
657 657
         // just a check to make sure the session array is indeed an array
658
-        if (! is_array($session_data)) {
658
+        if ( ! is_array($session_data)) {
659 659
             // no?!?! then something is wrong
660 660
             $msg = esc_html__(
661 661
                 'The session data is missing, invalid, or corrupted.',
662 662
                 'event_espresso'
663 663
             );
664 664
             $msg .= WP_DEBUG
665
-                ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
665
+                ? '<br><pre>'.print_r($session_data, true).'</pre><br>'.$this->find_serialize_error($session_data)
666 666
                 : '';
667
-            $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
667
+            $this->cache_storage->delete(EE_Session::session_id_prefix.$this->_sid);
668 668
             throw new InvalidSessionDataException($msg);
669 669
         }
670 670
         if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
@@ -692,7 +692,7 @@  discard block
 block discarded – undo
692 692
         if (isset($_REQUEST['EESID'])) {
693 693
             $session_id = sanitize_text_field($_REQUEST['EESID']);
694 694
         } else {
695
-            $session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
695
+            $session_id = md5(session_id().get_current_blog_id().$this->_get_sid_salt());
696 696
         }
697 697
         return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
698 698
     }
@@ -800,19 +800,19 @@  discard block
 block discarded – undo
800 800
                     $page_visit = $this->_get_page_visit();
801 801
                     if ($page_visit) {
802 802
                         // set pages visited where the first will be the http referrer
803
-                        $this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
803
+                        $this->_session_data['pages_visited'][$this->_time] = $page_visit;
804 804
                         // we'll only save the last 10 page visits.
805 805
                         $session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
806 806
                     }
807 807
                     break;
808 808
                 default :
809 809
                     // carry any other data over
810
-                    $session_data[ $key ] = $this->_session_data[ $key ];
810
+                    $session_data[$key] = $this->_session_data[$key];
811 811
             }
812 812
         }
813 813
         $this->_session_data = $session_data;
814 814
         // creating a new session does not require saving to the db just yet
815
-        if (! $new_session) {
815
+        if ( ! $new_session) {
816 816
             // ready? let's save
817 817
             if ($this->_save_session_to_db()) {
818 818
                 return true;
@@ -856,12 +856,12 @@  discard block
 block discarded – undo
856 856
     private function _save_session_to_db($clear_session = false)
857 857
     {
858 858
         // unless we're deleting the session data, don't save anything if there isn't a cart
859
-        if (! $clear_session && ! $this->cart() instanceof EE_Cart) {
859
+        if ( ! $clear_session && ! $this->cart() instanceof EE_Cart) {
860 860
             return false;
861 861
         }
862 862
         $transaction = $this->transaction();
863 863
         if ($transaction instanceof EE_Transaction) {
864
-            if (! $transaction->ID()) {
864
+            if ( ! $transaction->ID()) {
865 865
                 $transaction->save();
866 866
             }
867 867
             $this->_session_data['transaction'] = $transaction->ID();
@@ -875,14 +875,14 @@  discard block
 block discarded – undo
875 875
         // maybe save hash check
876 876
         if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
877 877
             $this->cache_storage->add(
878
-                EE_Session::hash_check_prefix . $this->_sid,
878
+                EE_Session::hash_check_prefix.$this->_sid,
879 879
                 md5($session_data),
880 880
                 $this->_lifespan
881 881
             );
882 882
         }
883 883
         // we're using the Transient API for storing session data,
884 884
         return $this->cache_storage->add(
885
-            EE_Session::session_id_prefix . $this->_sid,
885
+            EE_Session::session_id_prefix.$this->_sid,
886 886
             $session_data,
887 887
             $this->_lifespan
888 888
         );
@@ -911,8 +911,8 @@  discard block
 block discarded – undo
911 911
             'REMOTE_ADDR',
912 912
         );
913 913
         foreach ($server_keys as $key) {
914
-            if (isset($_SERVER[ $key ])) {
915
-                foreach (array_map('trim', explode(',', $_SERVER[ $key ])) as $ip) {
914
+            if (isset($_SERVER[$key])) {
915
+                foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip) {
916 916
                     if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
917 917
                         $visitor_ip = $ip;
918 918
                     }
@@ -931,7 +931,7 @@  discard block
 block discarded – undo
931 931
      */
932 932
     public function _get_page_visit()
933 933
     {
934
-        $page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
934
+        $page_visit = home_url('/').'wp-admin/admin-ajax.php';
935 935
         // check for request url
936 936
         if (isset($_SERVER['REQUEST_URI'])) {
937 937
             $http_host   = '';
@@ -947,14 +947,14 @@  discard block
 block discarded – undo
947 947
             // check for page_id in SERVER REQUEST
948 948
             if (isset($_REQUEST['page_id'])) {
949 949
                 // rebuild $e_reg without any of the extra parameters
950
-                $page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
950
+                $page_id = '?page_id='.esc_attr($_REQUEST['page_id']).'&amp;';
951 951
             }
952 952
             // check for $e_reg in SERVER REQUEST
953 953
             if (isset($_REQUEST['ee'])) {
954 954
                 // rebuild $e_reg without any of the extra parameters
955
-                $e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
955
+                $e_reg = 'ee='.esc_attr($_REQUEST['ee']);
956 956
             }
957
-            $page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
957
+            $page_visit = rtrim($http_host.$request_uri.$page_id.$e_reg, '?');
958 958
         }
959 959
         return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
960 960
     }
@@ -990,7 +990,7 @@  discard block
 block discarded – undo
990 990
     public function clear_session($class = '', $function = '')
991 991
     {
992 992
         //echo '<h3 style="color:#999;line-height:.9em;"><span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/><span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b></h3>';
993
-        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
993
+        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : '.$class.'::'.$function.'()');
994 994
         $this->reset_cart();
995 995
         $this->reset_checkout();
996 996
         $this->reset_transaction();
@@ -1013,7 +1013,7 @@  discard block
 block discarded – undo
1013 1013
     public function reset_data($data_to_reset = array(), $show_all_notices = false)
1014 1014
     {
1015 1015
         // if $data_to_reset is not in an array, then put it in one
1016
-        if (! is_array($data_to_reset)) {
1016
+        if ( ! is_array($data_to_reset)) {
1017 1017
             $data_to_reset = array($data_to_reset);
1018 1018
         }
1019 1019
         // nothing ??? go home!
@@ -1027,11 +1027,11 @@  discard block
 block discarded – undo
1027 1027
         foreach ($data_to_reset as $reset) {
1028 1028
 
1029 1029
             // first check to make sure it is a valid session var
1030
-            if (isset($this->_session_data[ $reset ])) {
1030
+            if (isset($this->_session_data[$reset])) {
1031 1031
                 // then check to make sure it is not a default var
1032
-                if (! array_key_exists($reset, $this->_default_session_vars)) {
1032
+                if ( ! array_key_exists($reset, $this->_default_session_vars)) {
1033 1033
                     // remove session var
1034
-                    unset($this->_session_data[ $reset ]);
1034
+                    unset($this->_session_data[$reset]);
1035 1035
                     if ($show_all_notices) {
1036 1036
                         EE_Error::add_success(sprintf(__('The session variable %s was removed.', 'event_espresso'),
1037 1037
                             $reset), __FILE__, __FUNCTION__, __LINE__);
@@ -1111,7 +1111,7 @@  discard block
 block discarded – undo
1111 1111
             // or use that for the new transient cleanup query limit
1112 1112
             add_filter(
1113 1113
                 'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1114
-                function () use ($expired_session_transient_delete_query_limit)
1114
+                function() use ($expired_session_transient_delete_query_limit)
1115 1115
                 {
1116 1116
                     return $expired_session_transient_delete_query_limit;
1117 1117
                 }
@@ -1131,7 +1131,7 @@  discard block
 block discarded – undo
1131 1131
         $error = '<pre>';
1132 1132
         $data2 = preg_replace_callback(
1133 1133
             '!s:(\d+):"(.*?)";!',
1134
-            function ($match)
1134
+            function($match)
1135 1135
             {
1136 1136
                 return ($match[1] === strlen($match[2]))
1137 1137
                     ? $match[0]
@@ -1143,14 +1143,14 @@  discard block
 block discarded – undo
1143 1143
             },
1144 1144
             $data1
1145 1145
         );
1146
-        $max   = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1147
-        $error .= $data1 . PHP_EOL;
1148
-        $error .= $data2 . PHP_EOL;
1146
+        $max = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1147
+        $error .= $data1.PHP_EOL;
1148
+        $error .= $data2.PHP_EOL;
1149 1149
         for ($i = 0; $i < $max; $i++) {
1150
-            if (@$data1[ $i ] !== @$data2[ $i ]) {
1151
-                $error  .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1152
-                $error  .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1153
-                $error  .= "\t-> Line Number = $i" . PHP_EOL;
1150
+            if (@$data1[$i] !== @$data2[$i]) {
1151
+                $error  .= 'Difference '.@$data1[$i].' != '.@$data2[$i].PHP_EOL;
1152
+                $error  .= "\t-> ORD number ".ord(@$data1[$i]).' != '.ord(@$data2[$i]).PHP_EOL;
1153
+                $error  .= "\t-> Line Number = $i".PHP_EOL;
1154 1154
                 $start  = ($i - 20);
1155 1155
                 $start  = ($start < 0) ? 0 : $start;
1156 1156
                 $length = 40;
@@ -1165,7 +1165,7 @@  discard block
 block discarded – undo
1165 1165
                 $error .= "\t-> Section Data1  = ";
1166 1166
                 $error .= substr_replace(
1167 1167
                     substr($data1, $start, $length),
1168
-                    "<b style=\"color:green\">{$data1[ $i ]}</b>",
1168
+                    "<b style=\"color:green\">{$data1[$i]}</b>",
1169 1169
                     $rpoint,
1170 1170
                     $rlength
1171 1171
                 );
@@ -1173,7 +1173,7 @@  discard block
 block discarded – undo
1173 1173
                 $error .= "\t-> Section Data2  = ";
1174 1174
                 $error .= substr_replace(
1175 1175
                     substr($data2, $start, $length),
1176
-                    "<b style=\"color:red\">{$data2[ $i ]}</b>",
1176
+                    "<b style=\"color:red\">{$data2[$i]}</b>",
1177 1177
                     $rpoint,
1178 1178
                     $rlength
1179 1179
                 );
@@ -1204,7 +1204,7 @@  discard block
 block discarded – undo
1204 1204
     public function garbageCollection()
1205 1205
     {
1206 1206
         // only perform during regular requests if last garbage collection was over an hour ago
1207
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1207
+        if ( ! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1208 1208
             $this->_last_gc = time();
1209 1209
             $this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1210 1210
             /** @type WPDB $wpdb */
@@ -1239,7 +1239,7 @@  discard block
 block discarded – undo
1239 1239
                 // AND option_value < 1508368198 LIMIT 50
1240 1240
                 $expired_sessions = $wpdb->get_col($SQL);
1241 1241
                 // valid results?
1242
-                if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1242
+                if ( ! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1243 1243
                     $this->cache_storage->deleteMany($expired_sessions, true);
1244 1244
                 }
1245 1245
             }
Please login to merge, or discard this patch.
admin_pages/registration_form/Registration_Form_Admin_Page.core.php 2 patches
Indentation   +640 added lines, -640 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
 /**
@@ -28,596 +28,596 @@  discard block
 block discarded – undo
28 28
 class Registration_Form_Admin_Page extends EE_Admin_Page
29 29
 {
30 30
 
31
-    /**
32
-     * _question
33
-     * holds the specific question object for the question details screen
34
-     *
35
-     * @var EE_Question $_question
36
-     */
37
-    protected $_question;
38
-
39
-    /**
40
-     * _question_group
41
-     * holds the specific question group object for the question group details screen
42
-     *
43
-     * @var EE_Question_Group $_question_group
44
-     */
45
-    protected $_question_group;
46
-
47
-    /**
48
-     *_question_model EEM_Question model instance (for queries)
49
-     *
50
-     * @var EEM_Question $_question_model ;
51
-     */
52
-    protected $_question_model;
53
-
54
-    /**
55
-     * _question_group_model EEM_Question_group instance (for queries)
56
-     *
57
-     * @var EEM_Question_Group $_question_group_model
58
-     */
59
-    protected $_question_group_model;
60
-
61
-
62
-    /**
63
-     * @Constructor
64
-     * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
65
-     * @access public
66
-     */
67
-    public function __construct($routing = true)
68
-    {
69
-        require_once(EE_MODELS . 'EEM_Question.model.php');
70
-        require_once(EE_MODELS . 'EEM_Question_Group.model.php');
71
-        $this->_question_model       = EEM_Question::instance();
72
-        $this->_question_group_model = EEM_Question_Group::instance();
73
-        parent::__construct($routing);
74
-    }
75
-
76
-
77
-    protected function _init_page_props()
78
-    {
79
-        $this->page_slug        = REGISTRATION_FORM_PG_SLUG;
80
-        $this->page_label       = esc_html__('Registration Form', 'event_espresso');
81
-        $this->_admin_base_url  = REGISTRATION_FORM_ADMIN_URL;
82
-        $this->_admin_base_path = REGISTRATION_FORM_ADMIN;
83
-    }
84
-
85
-
86
-    protected function _ajax_hooks()
87
-    {
88
-    }
89
-
90
-
91
-    protected function _define_page_props()
92
-    {
93
-        $this->_admin_page_title = esc_html__('Registration Form', 'event_espresso');
94
-        $this->_labels           = array(
95
-            'buttons' => array(
96
-                'edit_question' => esc_html__('Edit Question', 'event_espresso'),
97
-            ),
98
-        );
99
-    }
100
-
101
-
102
-    /**
103
-     *_set_page_routes
104
-     */
105
-    protected function _set_page_routes()
106
-    {
107
-        $qst_id             = ! empty($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0;
108
-        $this->_page_routes = array(
109
-            'default' => array(
110
-                'func'       => '_questions_overview_list_table',
111
-                'capability' => 'ee_read_questions',
112
-            ),
113
-
114
-            'edit_question' => array(
115
-                'func'       => '_edit_question',
116
-                'capability' => 'ee_edit_question',
117
-                'obj_id'     => $qst_id,
118
-                'args'       => array('edit'),
119
-            ),
120
-
121
-            'question_groups' => array(
122
-                'func'       => '_questions_groups_preview',
123
-                'capability' => 'ee_read_question_groups',
124
-            ),
125
-
126
-            'update_question' => array(
127
-                'func'       => '_insert_or_update_question',
128
-                'args'       => array('new_question' => false),
129
-                'capability' => 'ee_edit_question',
130
-                'obj_id'     => $qst_id,
131
-                'noheader'   => true,
132
-            ),
133
-        );
134
-    }
135
-
136
-
137
-    protected function _set_page_config()
138
-    {
139
-        $this->_page_config = array(
140
-            'default' => array(
141
-                'nav'           => array(
142
-                    'label' => esc_html__('Questions', 'event_espresso'),
143
-                    'order' => 10,
144
-                ),
145
-                'list_table'    => 'Registration_Form_Questions_Admin_List_Table',
146
-                'metaboxes'     => $this->_default_espresso_metaboxes,
147
-                'help_tabs'     => array(
148
-                    'registration_form_questions_overview_help_tab'                           => array(
149
-                        'title'    => esc_html__('Questions Overview', 'event_espresso'),
150
-                        'filename' => 'registration_form_questions_overview',
151
-                    ),
152
-                    'registration_form_questions_overview_table_column_headings_help_tab'     => array(
153
-                        'title'    => esc_html__('Questions Overview Table Column Headings', 'event_espresso'),
154
-                        'filename' => 'registration_form_questions_overview_table_column_headings',
155
-                    ),
156
-                    'registration_form_questions_overview_views_bulk_actions_search_help_tab' => array(
157
-                        'title'    => esc_html__('Question Overview Views & Bulk Actions & Search', 'event_espresso'),
158
-                        'filename' => 'registration_form_questions_overview_views_bulk_actions_search',
159
-                    ),
160
-                ),
161
-                'help_tour'     => array('Registration_Form_Questions_Overview_Help_Tour'),
162
-                'require_nonce' => false,
163
-                'qtips'         => array(
164
-                    'EE_Registration_Form_Tips',
165
-                )/**/
166
-            ),
167
-
168
-            'question_groups' => array(
169
-                'nav'           => array(
170
-                    'label' => esc_html__('Question Groups', 'event_espresso'),
171
-                    'order' => 20,
172
-                ),
173
-                'metaboxes'     => $this->_default_espresso_metaboxes,
174
-                'help_tabs'     => array(
175
-                    'registration_form_question_groups_help_tab' => array(
176
-                        'title'    => esc_html__('Question Groups', 'event_espresso'),
177
-                        'filename' => 'registration_form_question_groups',
178
-                    ),
179
-                ),
180
-                'help_tour'     => array('Registration_Form_Question_Groups_Help_Tour'),
181
-                'require_nonce' => false,
182
-            ),
183
-
184
-            'edit_question' => array(
185
-                'nav'           => array(
186
-                    'label'      => esc_html__('Edit Question', 'event_espresso'),
187
-                    'order'      => 15,
188
-                    'persistent' => false,
189
-                    'url'        => isset($this->_req_data['question_id']) ? add_query_arg(array('question_id' => $this->_req_data['question_id']),
190
-                        $this->_current_page_view_url) : $this->_admin_base_url,
191
-                ),
192
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
193
-                'help_tabs'     => array(
194
-                    'registration_form_edit_question_group_help_tab' => array(
195
-                        'title'    => esc_html__('Edit Question', 'event_espresso'),
196
-                        'filename' => 'registration_form_edit_question',
197
-                    ),
198
-                ),
199
-                'help_tour'     => array('Registration_Form_Edit_Question_Help_Tour'),
200
-                'require_nonce' => false,
201
-            ),
202
-        );
203
-    }
204
-
205
-
206
-    protected function _add_screen_options()
207
-    {
208
-        //todo
209
-    }
210
-
211
-    protected function _add_screen_options_default()
212
-    {
213
-        $page_title              = $this->_admin_page_title;
214
-        $this->_admin_page_title = esc_html__('Questions', 'event_espresso');
215
-        $this->_per_page_screen_option();
216
-        $this->_admin_page_title = $page_title;
217
-    }
218
-
219
-    protected function _add_screen_options_question_groups()
220
-    {
221
-        $page_title              = $this->_admin_page_title;
222
-        $this->_admin_page_title = esc_html__('Question Groups', 'event_espresso');
223
-        $this->_per_page_screen_option();
224
-        $this->_admin_page_title = $page_title;
225
-    }
226
-
227
-    //none of the below group are currently used for Event Categories
228
-    protected function _add_feature_pointers()
229
-    {
230
-    }
231
-
232
-    public function load_scripts_styles()
233
-    {
234
-        wp_register_style('espresso_registration',
235
-            REGISTRATION_FORM_ASSETS_URL . 'espresso_registration_form_admin.css', array(), EVENT_ESPRESSO_VERSION);
236
-        wp_enqueue_style('espresso_registration');
237
-    }
238
-
239
-    public function admin_init()
240
-    {
241
-    }
242
-
243
-    public function admin_notices()
244
-    {
245
-    }
246
-
247
-    public function admin_footer_scripts()
248
-    {
249
-    }
250
-
251
-
252
-    public function load_scripts_styles_default()
253
-    {
254
-    }
255
-
256
-
257
-    public function load_scripts_styles_add_question()
258
-    {
259
-        $this->load_scripts_styles_forms();
260
-        wp_register_script('espresso_registration_form_single',
261
-            REGISTRATION_FORM_ASSETS_URL . 'espresso_registration_form_admin.js', array('jquery-ui-sortable'),
262
-            EVENT_ESPRESSO_VERSION, true);
263
-        wp_enqueue_script('espresso_registration_form_single');
264
-    }
265
-
266
-    public function load_scripts_styles_edit_question()
267
-    {
268
-        $this->load_scripts_styles_forms();
269
-        wp_register_script('espresso_registration_form_single',
270
-            REGISTRATION_FORM_ASSETS_URL . 'espresso_registration_form_admin.js', array('jquery-ui-sortable'),
271
-            EVENT_ESPRESSO_VERSION, true);
272
-        wp_enqueue_script('espresso_registration_form_single');
273
-    }
274
-
275
-
276
-    public function recaptcha_info_help_tab()
277
-    {
278
-        $template = REGISTRATION_FORM_TEMPLATE_PATH . 'recaptcha_info_help_tab.template.php';
279
-        EEH_Template::display_template($template, array());
280
-    }
281
-
282
-
283
-    public function load_scripts_styles_forms()
284
-    {
285
-        //styles
286
-        wp_enqueue_style('espresso-ui-theme');
287
-        //scripts
288
-        wp_enqueue_script('ee_admin_js');
289
-    }
290
-
291
-
292
-    protected function _set_list_table_views_default()
293
-    {
294
-        $this->_views = array(
295
-            'all' => array(
296
-                'slug'  => 'all',
297
-                'label' => esc_html__('View All Questions', 'event_espresso'),
298
-                'count' => 0,
31
+	/**
32
+	 * _question
33
+	 * holds the specific question object for the question details screen
34
+	 *
35
+	 * @var EE_Question $_question
36
+	 */
37
+	protected $_question;
38
+
39
+	/**
40
+	 * _question_group
41
+	 * holds the specific question group object for the question group details screen
42
+	 *
43
+	 * @var EE_Question_Group $_question_group
44
+	 */
45
+	protected $_question_group;
46
+
47
+	/**
48
+	 *_question_model EEM_Question model instance (for queries)
49
+	 *
50
+	 * @var EEM_Question $_question_model ;
51
+	 */
52
+	protected $_question_model;
53
+
54
+	/**
55
+	 * _question_group_model EEM_Question_group instance (for queries)
56
+	 *
57
+	 * @var EEM_Question_Group $_question_group_model
58
+	 */
59
+	protected $_question_group_model;
60
+
61
+
62
+	/**
63
+	 * @Constructor
64
+	 * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
65
+	 * @access public
66
+	 */
67
+	public function __construct($routing = true)
68
+	{
69
+		require_once(EE_MODELS . 'EEM_Question.model.php');
70
+		require_once(EE_MODELS . 'EEM_Question_Group.model.php');
71
+		$this->_question_model       = EEM_Question::instance();
72
+		$this->_question_group_model = EEM_Question_Group::instance();
73
+		parent::__construct($routing);
74
+	}
75
+
76
+
77
+	protected function _init_page_props()
78
+	{
79
+		$this->page_slug        = REGISTRATION_FORM_PG_SLUG;
80
+		$this->page_label       = esc_html__('Registration Form', 'event_espresso');
81
+		$this->_admin_base_url  = REGISTRATION_FORM_ADMIN_URL;
82
+		$this->_admin_base_path = REGISTRATION_FORM_ADMIN;
83
+	}
84
+
85
+
86
+	protected function _ajax_hooks()
87
+	{
88
+	}
89
+
90
+
91
+	protected function _define_page_props()
92
+	{
93
+		$this->_admin_page_title = esc_html__('Registration Form', 'event_espresso');
94
+		$this->_labels           = array(
95
+			'buttons' => array(
96
+				'edit_question' => esc_html__('Edit Question', 'event_espresso'),
97
+			),
98
+		);
99
+	}
100
+
101
+
102
+	/**
103
+	 *_set_page_routes
104
+	 */
105
+	protected function _set_page_routes()
106
+	{
107
+		$qst_id             = ! empty($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0;
108
+		$this->_page_routes = array(
109
+			'default' => array(
110
+				'func'       => '_questions_overview_list_table',
111
+				'capability' => 'ee_read_questions',
112
+			),
113
+
114
+			'edit_question' => array(
115
+				'func'       => '_edit_question',
116
+				'capability' => 'ee_edit_question',
117
+				'obj_id'     => $qst_id,
118
+				'args'       => array('edit'),
119
+			),
120
+
121
+			'question_groups' => array(
122
+				'func'       => '_questions_groups_preview',
123
+				'capability' => 'ee_read_question_groups',
124
+			),
125
+
126
+			'update_question' => array(
127
+				'func'       => '_insert_or_update_question',
128
+				'args'       => array('new_question' => false),
129
+				'capability' => 'ee_edit_question',
130
+				'obj_id'     => $qst_id,
131
+				'noheader'   => true,
132
+			),
133
+		);
134
+	}
135
+
136
+
137
+	protected function _set_page_config()
138
+	{
139
+		$this->_page_config = array(
140
+			'default' => array(
141
+				'nav'           => array(
142
+					'label' => esc_html__('Questions', 'event_espresso'),
143
+					'order' => 10,
144
+				),
145
+				'list_table'    => 'Registration_Form_Questions_Admin_List_Table',
146
+				'metaboxes'     => $this->_default_espresso_metaboxes,
147
+				'help_tabs'     => array(
148
+					'registration_form_questions_overview_help_tab'                           => array(
149
+						'title'    => esc_html__('Questions Overview', 'event_espresso'),
150
+						'filename' => 'registration_form_questions_overview',
151
+					),
152
+					'registration_form_questions_overview_table_column_headings_help_tab'     => array(
153
+						'title'    => esc_html__('Questions Overview Table Column Headings', 'event_espresso'),
154
+						'filename' => 'registration_form_questions_overview_table_column_headings',
155
+					),
156
+					'registration_form_questions_overview_views_bulk_actions_search_help_tab' => array(
157
+						'title'    => esc_html__('Question Overview Views & Bulk Actions & Search', 'event_espresso'),
158
+						'filename' => 'registration_form_questions_overview_views_bulk_actions_search',
159
+					),
160
+				),
161
+				'help_tour'     => array('Registration_Form_Questions_Overview_Help_Tour'),
162
+				'require_nonce' => false,
163
+				'qtips'         => array(
164
+					'EE_Registration_Form_Tips',
165
+				)/**/
166
+			),
167
+
168
+			'question_groups' => array(
169
+				'nav'           => array(
170
+					'label' => esc_html__('Question Groups', 'event_espresso'),
171
+					'order' => 20,
172
+				),
173
+				'metaboxes'     => $this->_default_espresso_metaboxes,
174
+				'help_tabs'     => array(
175
+					'registration_form_question_groups_help_tab' => array(
176
+						'title'    => esc_html__('Question Groups', 'event_espresso'),
177
+						'filename' => 'registration_form_question_groups',
178
+					),
179
+				),
180
+				'help_tour'     => array('Registration_Form_Question_Groups_Help_Tour'),
181
+				'require_nonce' => false,
182
+			),
183
+
184
+			'edit_question' => array(
185
+				'nav'           => array(
186
+					'label'      => esc_html__('Edit Question', 'event_espresso'),
187
+					'order'      => 15,
188
+					'persistent' => false,
189
+					'url'        => isset($this->_req_data['question_id']) ? add_query_arg(array('question_id' => $this->_req_data['question_id']),
190
+						$this->_current_page_view_url) : $this->_admin_base_url,
191
+				),
192
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
193
+				'help_tabs'     => array(
194
+					'registration_form_edit_question_group_help_tab' => array(
195
+						'title'    => esc_html__('Edit Question', 'event_espresso'),
196
+						'filename' => 'registration_form_edit_question',
197
+					),
198
+				),
199
+				'help_tour'     => array('Registration_Form_Edit_Question_Help_Tour'),
200
+				'require_nonce' => false,
201
+			),
202
+		);
203
+	}
204
+
205
+
206
+	protected function _add_screen_options()
207
+	{
208
+		//todo
209
+	}
210
+
211
+	protected function _add_screen_options_default()
212
+	{
213
+		$page_title              = $this->_admin_page_title;
214
+		$this->_admin_page_title = esc_html__('Questions', 'event_espresso');
215
+		$this->_per_page_screen_option();
216
+		$this->_admin_page_title = $page_title;
217
+	}
218
+
219
+	protected function _add_screen_options_question_groups()
220
+	{
221
+		$page_title              = $this->_admin_page_title;
222
+		$this->_admin_page_title = esc_html__('Question Groups', 'event_espresso');
223
+		$this->_per_page_screen_option();
224
+		$this->_admin_page_title = $page_title;
225
+	}
226
+
227
+	//none of the below group are currently used for Event Categories
228
+	protected function _add_feature_pointers()
229
+	{
230
+	}
231
+
232
+	public function load_scripts_styles()
233
+	{
234
+		wp_register_style('espresso_registration',
235
+			REGISTRATION_FORM_ASSETS_URL . 'espresso_registration_form_admin.css', array(), EVENT_ESPRESSO_VERSION);
236
+		wp_enqueue_style('espresso_registration');
237
+	}
238
+
239
+	public function admin_init()
240
+	{
241
+	}
242
+
243
+	public function admin_notices()
244
+	{
245
+	}
246
+
247
+	public function admin_footer_scripts()
248
+	{
249
+	}
250
+
251
+
252
+	public function load_scripts_styles_default()
253
+	{
254
+	}
255
+
256
+
257
+	public function load_scripts_styles_add_question()
258
+	{
259
+		$this->load_scripts_styles_forms();
260
+		wp_register_script('espresso_registration_form_single',
261
+			REGISTRATION_FORM_ASSETS_URL . 'espresso_registration_form_admin.js', array('jquery-ui-sortable'),
262
+			EVENT_ESPRESSO_VERSION, true);
263
+		wp_enqueue_script('espresso_registration_form_single');
264
+	}
265
+
266
+	public function load_scripts_styles_edit_question()
267
+	{
268
+		$this->load_scripts_styles_forms();
269
+		wp_register_script('espresso_registration_form_single',
270
+			REGISTRATION_FORM_ASSETS_URL . 'espresso_registration_form_admin.js', array('jquery-ui-sortable'),
271
+			EVENT_ESPRESSO_VERSION, true);
272
+		wp_enqueue_script('espresso_registration_form_single');
273
+	}
274
+
275
+
276
+	public function recaptcha_info_help_tab()
277
+	{
278
+		$template = REGISTRATION_FORM_TEMPLATE_PATH . 'recaptcha_info_help_tab.template.php';
279
+		EEH_Template::display_template($template, array());
280
+	}
281
+
282
+
283
+	public function load_scripts_styles_forms()
284
+	{
285
+		//styles
286
+		wp_enqueue_style('espresso-ui-theme');
287
+		//scripts
288
+		wp_enqueue_script('ee_admin_js');
289
+	}
290
+
291
+
292
+	protected function _set_list_table_views_default()
293
+	{
294
+		$this->_views = array(
295
+			'all' => array(
296
+				'slug'  => 'all',
297
+				'label' => esc_html__('View All Questions', 'event_espresso'),
298
+				'count' => 0,
299 299
 //				'bulk_action' => array(
300 300
 //					'trash_questions' => esc_html__('Trash', 'event_espresso'),
301 301
 //					)
302
-            ),
303
-        );
304
-
305
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_questions',
306
-            'espresso_registration_form_trash_questions')
307
-        ) {
308
-            $this->_views['trash'] = array(
309
-                'slug'  => 'trash',
310
-                'label' => esc_html__('Trash', 'event_espresso'),
311
-                'count' => 0,
302
+			),
303
+		);
304
+
305
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_questions',
306
+			'espresso_registration_form_trash_questions')
307
+		) {
308
+			$this->_views['trash'] = array(
309
+				'slug'  => 'trash',
310
+				'label' => esc_html__('Trash', 'event_espresso'),
311
+				'count' => 0,
312 312
 //				'bulk_action' => array(
313 313
 //					'delete_questions' => esc_html__('Delete Permanently', 'event_espresso'),
314 314
 //					'restore_questions' => esc_html__('Restore', 'event_espresso'),
315
-            );
316
-        }
317
-    }
318
-
319
-    /**
320
-     * This just previews the question groups tab that comes in caffeinated.
321
-     *
322
-     * @return string html
323
-     */
324
-    protected function _questions_groups_preview()
325
-    {
326
-        $this->_admin_page_title              = esc_html__('Question Groups (Preview)', 'event_espresso');
327
-        $this->_template_args['preview_img']  = '<img src="' . REGISTRATION_FORM_ASSETS_URL . 'caf_reg_form_preview.jpg" alt="' . esc_attr__('Preview Question Groups Overview List Table screenshot',
328
-                'event_espresso') . '" />';
329
-        $this->_template_args['preview_text'] = '<strong>' . esc_html__('Question Groups is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Question Groups feature you are able to create new question groups, edit existing question groups, and create and edit new questions and add them to question groups.',
330
-                'event_espresso') . '</strong>';
331
-        $this->display_admin_caf_preview_page('question_groups_tab');
332
-    }
333
-
334
-
335
-    /**
336
-     * Extracts the question field's values from the POST request to update or insert them
337
-     *
338
-     * @param \EEM_Base $model
339
-     * @return array where each key is the name of a model's field/db column, and each value is its value.
340
-     */
341
-    protected function _set_column_values_for(EEM_Base $model)
342
-    {
343
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
344
-        $set_column_values = array();
345
-
346
-        //some initial checks for proper values.
347
-        //if QST_admin_only, then no matter what QST_required is we disable.
348
-        if (! empty($this->_req_data['QST_admin_only'])) {
349
-            $this->_req_data['QST_required'] = 0;
350
-        }
351
-        foreach ($model->field_settings() as $fieldName => $settings) {
352
-            // basically if QSG_identifier is empty or not set
353
-            if ($fieldName === 'QSG_identifier' && (isset($this->_req_data['QSG_identifier']) && empty($this->_req_data['QSG_identifier']))) {
354
-                $QSG_name                      = isset($this->_req_data['QSG_name']) ? $this->_req_data['QSG_name'] : '';
355
-                $set_column_values[$fieldName] = sanitize_title($QSG_name) . '-' . uniqid('', true);
315
+			);
316
+		}
317
+	}
318
+
319
+	/**
320
+	 * This just previews the question groups tab that comes in caffeinated.
321
+	 *
322
+	 * @return string html
323
+	 */
324
+	protected function _questions_groups_preview()
325
+	{
326
+		$this->_admin_page_title              = esc_html__('Question Groups (Preview)', 'event_espresso');
327
+		$this->_template_args['preview_img']  = '<img src="' . REGISTRATION_FORM_ASSETS_URL . 'caf_reg_form_preview.jpg" alt="' . esc_attr__('Preview Question Groups Overview List Table screenshot',
328
+				'event_espresso') . '" />';
329
+		$this->_template_args['preview_text'] = '<strong>' . esc_html__('Question Groups is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Question Groups feature you are able to create new question groups, edit existing question groups, and create and edit new questions and add them to question groups.',
330
+				'event_espresso') . '</strong>';
331
+		$this->display_admin_caf_preview_page('question_groups_tab');
332
+	}
333
+
334
+
335
+	/**
336
+	 * Extracts the question field's values from the POST request to update or insert them
337
+	 *
338
+	 * @param \EEM_Base $model
339
+	 * @return array where each key is the name of a model's field/db column, and each value is its value.
340
+	 */
341
+	protected function _set_column_values_for(EEM_Base $model)
342
+	{
343
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
344
+		$set_column_values = array();
345
+
346
+		//some initial checks for proper values.
347
+		//if QST_admin_only, then no matter what QST_required is we disable.
348
+		if (! empty($this->_req_data['QST_admin_only'])) {
349
+			$this->_req_data['QST_required'] = 0;
350
+		}
351
+		foreach ($model->field_settings() as $fieldName => $settings) {
352
+			// basically if QSG_identifier is empty or not set
353
+			if ($fieldName === 'QSG_identifier' && (isset($this->_req_data['QSG_identifier']) && empty($this->_req_data['QSG_identifier']))) {
354
+				$QSG_name                      = isset($this->_req_data['QSG_name']) ? $this->_req_data['QSG_name'] : '';
355
+				$set_column_values[$fieldName] = sanitize_title($QSG_name) . '-' . uniqid('', true);
356 356
 //				dd($set_column_values);
357
-            } //if the admin label is blank, use a slug version of the question text
358
-            else if ($fieldName === 'QST_admin_label' && (isset($this->_req_data['QST_admin_label']) && empty($this->_req_data['QST_admin_label']))) {
359
-                $QST_text                      = isset($this->_req_data['QST_display_text']) ? $this->_req_data['QST_display_text'] : '';
360
-                $set_column_values[$fieldName] = sanitize_title(wp_trim_words($QST_text, 10));
361
-            } else if ($fieldName === 'QST_admin_only' && (! isset($this->_req_data['QST_admin_only']))) {
362
-                $set_column_values[$fieldName] = 0;
363
-            } else if ($fieldName === 'QST_max') {
364
-                $qst_system = EEM_Question::instance()->get_var(
365
-                    array(
366
-                        array(
367
-                            'QST_ID' => isset($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0,
368
-                        ),
369
-                    ),
370
-                    'QST_system');
371
-                $max_max    = EEM_Question::instance()->absolute_max_for_system_question($qst_system);
372
-                if (empty($this->_req_data['QST_max']) ||
373
-                    $this->_req_data['QST_max'] > $max_max
374
-                ) {
375
-                    $set_column_values[$fieldName] = $max_max;
376
-                }
377
-            }
378
-
379
-
380
-            //only add a property to the array if it's not null (otherwise the model should just use the default value)
381
-            if (
382
-                ! isset($set_column_values[$fieldName]) &&
383
-                isset($this->_req_data[$fieldName])
384
-            ) {
385
-                $set_column_values[$fieldName] = $this->_req_data[$fieldName];
386
-            }
387
-
388
-        }
389
-        return $set_column_values;//validation fo this data to be performed by the model before insertion.
390
-    }
391
-
392
-
393
-    /**
394
-     *_questions_overview_list_table
395
-     */
396
-    protected function _questions_overview_list_table()
397
-    {
398
-        $this->_search_btn_label = esc_html__('Questions', 'event_espresso');
399
-        $this->display_admin_list_table_page_with_sidebar();
400
-    }
401
-
402
-
403
-    /**
404
-     * _edit_question
405
-     */
406
-    protected function _edit_question()
407
-    {
408
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
409
-        $ID = isset($this->_req_data['QST_ID']) && ! empty($this->_req_data['QST_ID']) ? absint($this->_req_data['QST_ID']) : false;
410
-
411
-        switch ($this->_req_action) {
412
-            case 'add_question' :
413
-                $this->_admin_page_title = esc_html__('Add Question', 'event_espresso');
414
-                break;
415
-            case 'edit_question' :
416
-                $this->_admin_page_title = esc_html__('Edit Question', 'event_espresso');
417
-                break;
418
-            default :
419
-                $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
420
-        }
421
-
422
-        // add PRC_ID to title if editing
423
-        $this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
424
-        if ($ID) {
425
-            $question                 = $this->_question_model->get_one_by_ID($ID);
426
-            $additional_hidden_fields = array('QST_ID' => array('type' => 'hidden', 'value' => $ID));
427
-            $this->_set_add_edit_form_tags('update_question', $additional_hidden_fields);
428
-        } else {
429
-            $question = EE_Question::new_instance();
430
-            $question->set_order_to_latest();
431
-            $this->_set_add_edit_form_tags('insert_question');
432
-        }
433
-        if( $question->system_ID() === EEM_Attendee::system_question_phone ){
434
-            $question_types = array_intersect_key(
435
-                EEM_Question::instance()->allowed_question_types(),
436
-                array_flip(
437
-                    array(
438
-                        EEM_Question::QST_type_text,
439
-                        EEM_Question::QST_type_us_phone
440
-                    )
441
-                )
442
-            );
443
-        } else {
444
-            $question_types = $question->has_answers() ? $this->_question_model->question_types_in_same_category($question->type()) : $this->_question_model->allowed_question_types();
445
-        }
446
-        $this->_template_args['QST_ID']                     = $ID;
447
-        $this->_template_args['question']                   = $question;
448
-        $this->_template_args['question_types']             = $question_types;
449
-        $this->_template_args['max_max']                    = EEM_Question::instance()->absolute_max_for_system_question(
450
-            $question->system_ID()
451
-        );
452
-        $this->_template_args['question_type_descriptions'] = $this->_get_question_type_descriptions();
453
-        $this->_set_publish_post_box_vars('id', $ID);
454
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
455
-            REGISTRATION_FORM_TEMPLATE_PATH . 'questions_main_meta_box.template.php',
456
-            $this->_template_args, true
457
-        );
458
-
459
-        // the details template wrapper
460
-        $this->display_admin_page_with_sidebar();
461
-    }
462
-
463
-
464
-    /**
465
-     * @return string
466
-     */
467
-    protected function _get_question_type_descriptions()
468
-    {
469
-        EE_Registry::instance()->load_helper('HTML');
470
-        $descriptions               = '';
471
-        $question_type_descriptions = EEM_Question::instance()->question_descriptions();
472
-        foreach ($question_type_descriptions as $type => $question_type_description) {
473
-            if ($type == 'HTML_TEXTAREA') {
474
-                $html = new EE_Simple_HTML_Validation_Strategy();
475
-                $question_type_description .= sprintf(
476
-                    esc_html__('%1$s(allowed tags: %2$s)', 'event_espresso'),
477
-                    '<br/>',
478
-                    $html->get_list_of_allowed_tags()
479
-                );
480
-            }
481
-            $descriptions .= EEH_HTML::p(
482
-                $question_type_description,
483
-                'question_type_description-' . $type,
484
-                'question_type_description description',
485
-                'display:none;'
486
-            );
487
-        }
488
-        return $descriptions;
489
-    }
490
-
491
-
492
-    /**
493
-     * @param bool|true $new_question
494
-     * @throws \EE_Error
495
-     */
496
-    protected function _insert_or_update_question($new_question = true)
497
-    {
498
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
499
-        $set_column_values = $this->_set_column_values_for($this->_question_model);
500
-        if ($new_question) {
501
-            $question = EE_Question::new_instance($set_column_values);
502
-            $action_desc = 'added';
503
-        } else {
504
-            $question     = EEM_Question::instance()->get_one_by_ID(absint($this->_req_data['QST_ID']));
505
-            foreach($set_column_values as $field => $new_value) {
506
-                $question->set($field, $new_value);
507
-            }
508
-            $action_desc = 'updated';
509
-        }
510
-        $success = $question->save();
511
-        $ID = $question->ID();
512
-        if ($ID && $question->should_have_question_options()) {
513
-            //save the related options
514
-            //trash removed options, save old ones
515
-            //get list of all options
516
-            $options  = $question->options();
517
-            if (! empty($options)) {
518
-                foreach ($options as $option_ID => $option) {
519
-                    $option_req_index = $this->_get_option_req_data_index($option_ID);
520
-                    if ($option_req_index !== false) {
521
-                        $option->save($this->_req_data['question_options'][$option_req_index]);
522
-                    } else {
523
-                        //not found, remove it
524
-                        $option->delete();
525
-                    }
526
-                }
527
-            }
528
-            //save new related options
529
-            foreach ($this->_req_data['question_options'] as $index => $option_req_data) {
530
-                //skip $index that is from our sample
531
-                if ( $index === 'xxcountxx' ) {
532
-                    continue;
533
-                }
534
-                //note we allow saving blank options.
535
-                if (empty($option_req_data['QSO_ID'])
536
-                ) {//no ID! save it!
537
-                    $new_option = EE_Question_Option::new_instance(array(
538
-                        'QSO_value' => $option_req_data['QSO_value'],
539
-                        'QSO_desc'  => $option_req_data['QSO_desc'],
540
-                        'QSO_order' => $option_req_data['QSO_order'],
541
-                        'QST_ID'    => $question->ID(),
542
-                    ));
543
-                    $new_option->save();
544
-                }
545
-            }
546
-        }
547
-        $query_args = array('action' => 'edit_question', 'QST_ID' => $ID);
548
-        if ($success !== false) {
549
-            $msg = $new_question ? sprintf(esc_html__('The %s has been created', 'event_espresso'),
550
-                $this->_question_model->item_name()) : sprintf(esc_html__('The %s has been updated', 'event_espresso'),
551
-                $this->_question_model->item_name());
552
-            EE_Error::add_success($msg);
553
-        }
554
-
555
-        $this->_redirect_after_action(false, '', $action_desc, $query_args, true);
556
-    }
557
-
558
-
559
-    /**
560
-     * Upon saving a question, there should be an array of 'question_options'. This array is index numerically, but not
561
-     * by ID
562
-     * (this is done because new question options don't have an ID, but we may want to add multiple simultaneously).
563
-     * So, this function gets the index in that request data array called question_options. Returns FALSE if not found.
564
-     *
565
-     * @param int $ID of the question option to find
566
-     * @return int index in question_options array if successful, FALSE if unsuccessful
567
-     */
568
-    protected function _get_option_req_data_index($ID)
569
-    {
570
-        $req_data_for_question_options = $this->_req_data['question_options'];
571
-        foreach ($req_data_for_question_options as $num => $option_data) {
572
-            if (array_key_exists('QSO_ID', $option_data) && (int)$option_data['QSO_ID'] === $ID) {
573
-                return $num;
574
-            }
575
-        }
576
-        return false;
577
-    }
578
-
579
-
580
-
581
-
582
-    /***********/
583
-    /* QUERIES */
584
-    /**
585
-     * For internal use in getting all the query parameters
586
-     * (because it's pretty well the same between question, question groups,
587
-     * and for both when searching for trashed and untrashed ones)
588
-     *
589
-     * @param EEM_Base $model either EEM_Question or EEM_Question_Group
590
-     * @param int      $per_page
591
-     * @param int      $current_page
592
-     * @return array lik EEM_Base::get_all's $query_params parameter
593
-     */
594
-    protected function get_query_params($model, $per_page = 10, $current_page = 10)
595
-    {
596
-        $query_params             = array();
597
-        $offset                   = ($current_page - 1) * $per_page;
598
-        $query_params['limit']    = array($offset, $per_page);
599
-        $order                    = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'ASC';
600
-        $orderby_field            = $model instanceof EEM_Question ? 'QST_ID' : 'QSG_order';
601
-        $field_to_order_by        = empty($this->_req_data['orderby']) ? $orderby_field : $this->_req_data['orderby'];
602
-        $query_params['order_by'] = array($field_to_order_by => $order);
603
-        $search_string            = array_key_exists('s', $this->_req_data) ? $this->_req_data['s'] : null;
604
-        if (! empty($search_string)) {
605
-            if ($model instanceof EEM_Question_Group) {
606
-                $query_params[0] = array(
607
-                    'OR' => array(
608
-                        'QSG_name' => array('LIKE', "%$search_string%"),
609
-                        'QSG_desc' => array('LIKE', "%$search_string%"),
610
-                    ),
611
-                );
612
-            } else {
613
-                $query_params[0] = array(
614
-                    'QST_display_text' => array('LIKE', "%$search_string%"),
615
-                );
616
-            }
617
-        }
618
-
619
-        //capability checks (just leaving this commented out for reference because it illustrates some complicated query params that could be useful when fully implemented)
620
-        /*if ( $model instanceof EEM_Question_Group ) {
357
+			} //if the admin label is blank, use a slug version of the question text
358
+			else if ($fieldName === 'QST_admin_label' && (isset($this->_req_data['QST_admin_label']) && empty($this->_req_data['QST_admin_label']))) {
359
+				$QST_text                      = isset($this->_req_data['QST_display_text']) ? $this->_req_data['QST_display_text'] : '';
360
+				$set_column_values[$fieldName] = sanitize_title(wp_trim_words($QST_text, 10));
361
+			} else if ($fieldName === 'QST_admin_only' && (! isset($this->_req_data['QST_admin_only']))) {
362
+				$set_column_values[$fieldName] = 0;
363
+			} else if ($fieldName === 'QST_max') {
364
+				$qst_system = EEM_Question::instance()->get_var(
365
+					array(
366
+						array(
367
+							'QST_ID' => isset($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0,
368
+						),
369
+					),
370
+					'QST_system');
371
+				$max_max    = EEM_Question::instance()->absolute_max_for_system_question($qst_system);
372
+				if (empty($this->_req_data['QST_max']) ||
373
+					$this->_req_data['QST_max'] > $max_max
374
+				) {
375
+					$set_column_values[$fieldName] = $max_max;
376
+				}
377
+			}
378
+
379
+
380
+			//only add a property to the array if it's not null (otherwise the model should just use the default value)
381
+			if (
382
+				! isset($set_column_values[$fieldName]) &&
383
+				isset($this->_req_data[$fieldName])
384
+			) {
385
+				$set_column_values[$fieldName] = $this->_req_data[$fieldName];
386
+			}
387
+
388
+		}
389
+		return $set_column_values;//validation fo this data to be performed by the model before insertion.
390
+	}
391
+
392
+
393
+	/**
394
+	 *_questions_overview_list_table
395
+	 */
396
+	protected function _questions_overview_list_table()
397
+	{
398
+		$this->_search_btn_label = esc_html__('Questions', 'event_espresso');
399
+		$this->display_admin_list_table_page_with_sidebar();
400
+	}
401
+
402
+
403
+	/**
404
+	 * _edit_question
405
+	 */
406
+	protected function _edit_question()
407
+	{
408
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
409
+		$ID = isset($this->_req_data['QST_ID']) && ! empty($this->_req_data['QST_ID']) ? absint($this->_req_data['QST_ID']) : false;
410
+
411
+		switch ($this->_req_action) {
412
+			case 'add_question' :
413
+				$this->_admin_page_title = esc_html__('Add Question', 'event_espresso');
414
+				break;
415
+			case 'edit_question' :
416
+				$this->_admin_page_title = esc_html__('Edit Question', 'event_espresso');
417
+				break;
418
+			default :
419
+				$this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
420
+		}
421
+
422
+		// add PRC_ID to title if editing
423
+		$this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
424
+		if ($ID) {
425
+			$question                 = $this->_question_model->get_one_by_ID($ID);
426
+			$additional_hidden_fields = array('QST_ID' => array('type' => 'hidden', 'value' => $ID));
427
+			$this->_set_add_edit_form_tags('update_question', $additional_hidden_fields);
428
+		} else {
429
+			$question = EE_Question::new_instance();
430
+			$question->set_order_to_latest();
431
+			$this->_set_add_edit_form_tags('insert_question');
432
+		}
433
+		if( $question->system_ID() === EEM_Attendee::system_question_phone ){
434
+			$question_types = array_intersect_key(
435
+				EEM_Question::instance()->allowed_question_types(),
436
+				array_flip(
437
+					array(
438
+						EEM_Question::QST_type_text,
439
+						EEM_Question::QST_type_us_phone
440
+					)
441
+				)
442
+			);
443
+		} else {
444
+			$question_types = $question->has_answers() ? $this->_question_model->question_types_in_same_category($question->type()) : $this->_question_model->allowed_question_types();
445
+		}
446
+		$this->_template_args['QST_ID']                     = $ID;
447
+		$this->_template_args['question']                   = $question;
448
+		$this->_template_args['question_types']             = $question_types;
449
+		$this->_template_args['max_max']                    = EEM_Question::instance()->absolute_max_for_system_question(
450
+			$question->system_ID()
451
+		);
452
+		$this->_template_args['question_type_descriptions'] = $this->_get_question_type_descriptions();
453
+		$this->_set_publish_post_box_vars('id', $ID);
454
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
455
+			REGISTRATION_FORM_TEMPLATE_PATH . 'questions_main_meta_box.template.php',
456
+			$this->_template_args, true
457
+		);
458
+
459
+		// the details template wrapper
460
+		$this->display_admin_page_with_sidebar();
461
+	}
462
+
463
+
464
+	/**
465
+	 * @return string
466
+	 */
467
+	protected function _get_question_type_descriptions()
468
+	{
469
+		EE_Registry::instance()->load_helper('HTML');
470
+		$descriptions               = '';
471
+		$question_type_descriptions = EEM_Question::instance()->question_descriptions();
472
+		foreach ($question_type_descriptions as $type => $question_type_description) {
473
+			if ($type == 'HTML_TEXTAREA') {
474
+				$html = new EE_Simple_HTML_Validation_Strategy();
475
+				$question_type_description .= sprintf(
476
+					esc_html__('%1$s(allowed tags: %2$s)', 'event_espresso'),
477
+					'<br/>',
478
+					$html->get_list_of_allowed_tags()
479
+				);
480
+			}
481
+			$descriptions .= EEH_HTML::p(
482
+				$question_type_description,
483
+				'question_type_description-' . $type,
484
+				'question_type_description description',
485
+				'display:none;'
486
+			);
487
+		}
488
+		return $descriptions;
489
+	}
490
+
491
+
492
+	/**
493
+	 * @param bool|true $new_question
494
+	 * @throws \EE_Error
495
+	 */
496
+	protected function _insert_or_update_question($new_question = true)
497
+	{
498
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
499
+		$set_column_values = $this->_set_column_values_for($this->_question_model);
500
+		if ($new_question) {
501
+			$question = EE_Question::new_instance($set_column_values);
502
+			$action_desc = 'added';
503
+		} else {
504
+			$question     = EEM_Question::instance()->get_one_by_ID(absint($this->_req_data['QST_ID']));
505
+			foreach($set_column_values as $field => $new_value) {
506
+				$question->set($field, $new_value);
507
+			}
508
+			$action_desc = 'updated';
509
+		}
510
+		$success = $question->save();
511
+		$ID = $question->ID();
512
+		if ($ID && $question->should_have_question_options()) {
513
+			//save the related options
514
+			//trash removed options, save old ones
515
+			//get list of all options
516
+			$options  = $question->options();
517
+			if (! empty($options)) {
518
+				foreach ($options as $option_ID => $option) {
519
+					$option_req_index = $this->_get_option_req_data_index($option_ID);
520
+					if ($option_req_index !== false) {
521
+						$option->save($this->_req_data['question_options'][$option_req_index]);
522
+					} else {
523
+						//not found, remove it
524
+						$option->delete();
525
+					}
526
+				}
527
+			}
528
+			//save new related options
529
+			foreach ($this->_req_data['question_options'] as $index => $option_req_data) {
530
+				//skip $index that is from our sample
531
+				if ( $index === 'xxcountxx' ) {
532
+					continue;
533
+				}
534
+				//note we allow saving blank options.
535
+				if (empty($option_req_data['QSO_ID'])
536
+				) {//no ID! save it!
537
+					$new_option = EE_Question_Option::new_instance(array(
538
+						'QSO_value' => $option_req_data['QSO_value'],
539
+						'QSO_desc'  => $option_req_data['QSO_desc'],
540
+						'QSO_order' => $option_req_data['QSO_order'],
541
+						'QST_ID'    => $question->ID(),
542
+					));
543
+					$new_option->save();
544
+				}
545
+			}
546
+		}
547
+		$query_args = array('action' => 'edit_question', 'QST_ID' => $ID);
548
+		if ($success !== false) {
549
+			$msg = $new_question ? sprintf(esc_html__('The %s has been created', 'event_espresso'),
550
+				$this->_question_model->item_name()) : sprintf(esc_html__('The %s has been updated', 'event_espresso'),
551
+				$this->_question_model->item_name());
552
+			EE_Error::add_success($msg);
553
+		}
554
+
555
+		$this->_redirect_after_action(false, '', $action_desc, $query_args, true);
556
+	}
557
+
558
+
559
+	/**
560
+	 * Upon saving a question, there should be an array of 'question_options'. This array is index numerically, but not
561
+	 * by ID
562
+	 * (this is done because new question options don't have an ID, but we may want to add multiple simultaneously).
563
+	 * So, this function gets the index in that request data array called question_options. Returns FALSE if not found.
564
+	 *
565
+	 * @param int $ID of the question option to find
566
+	 * @return int index in question_options array if successful, FALSE if unsuccessful
567
+	 */
568
+	protected function _get_option_req_data_index($ID)
569
+	{
570
+		$req_data_for_question_options = $this->_req_data['question_options'];
571
+		foreach ($req_data_for_question_options as $num => $option_data) {
572
+			if (array_key_exists('QSO_ID', $option_data) && (int)$option_data['QSO_ID'] === $ID) {
573
+				return $num;
574
+			}
575
+		}
576
+		return false;
577
+	}
578
+
579
+
580
+
581
+
582
+	/***********/
583
+	/* QUERIES */
584
+	/**
585
+	 * For internal use in getting all the query parameters
586
+	 * (because it's pretty well the same between question, question groups,
587
+	 * and for both when searching for trashed and untrashed ones)
588
+	 *
589
+	 * @param EEM_Base $model either EEM_Question or EEM_Question_Group
590
+	 * @param int      $per_page
591
+	 * @param int      $current_page
592
+	 * @return array lik EEM_Base::get_all's $query_params parameter
593
+	 */
594
+	protected function get_query_params($model, $per_page = 10, $current_page = 10)
595
+	{
596
+		$query_params             = array();
597
+		$offset                   = ($current_page - 1) * $per_page;
598
+		$query_params['limit']    = array($offset, $per_page);
599
+		$order                    = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'ASC';
600
+		$orderby_field            = $model instanceof EEM_Question ? 'QST_ID' : 'QSG_order';
601
+		$field_to_order_by        = empty($this->_req_data['orderby']) ? $orderby_field : $this->_req_data['orderby'];
602
+		$query_params['order_by'] = array($field_to_order_by => $order);
603
+		$search_string            = array_key_exists('s', $this->_req_data) ? $this->_req_data['s'] : null;
604
+		if (! empty($search_string)) {
605
+			if ($model instanceof EEM_Question_Group) {
606
+				$query_params[0] = array(
607
+					'OR' => array(
608
+						'QSG_name' => array('LIKE', "%$search_string%"),
609
+						'QSG_desc' => array('LIKE', "%$search_string%"),
610
+					),
611
+				);
612
+			} else {
613
+				$query_params[0] = array(
614
+					'QST_display_text' => array('LIKE', "%$search_string%"),
615
+				);
616
+			}
617
+		}
618
+
619
+		//capability checks (just leaving this commented out for reference because it illustrates some complicated query params that could be useful when fully implemented)
620
+		/*if ( $model instanceof EEM_Question_Group ) {
621 621
             if ( ! EE_Registry::instance()->CAP->current_user_can( 'edit_others_question_groups', 'espresso_registration_form_edit_question_group' ) ) {
622 622
                 $query_params[0] = array(
623 623
                     'AND' => array(
@@ -647,62 +647,62 @@  discard block
 block discarded – undo
647 647
             }
648 648
         }/**/
649 649
 
650
-        return $query_params;
651
-
652
-    }
653
-
654
-
655
-    /**
656
-     * @param int        $per_page
657
-     * @param int        $current_page
658
-     * @param bool|false $count
659
-     * @return \EE_Soft_Delete_Base_Class[]|int
660
-     */
661
-    public function get_questions($per_page = 10, $current_page = 1, $count = false)
662
-    {
663
-        $QST          = EEM_Question::instance();
664
-        $query_params = $this->get_query_params($QST, $per_page, $current_page);
665
-        if ($count) {
666
-            $where   = isset($query_params[0]) ? array($query_params[0]) : array();
667
-            $results = $QST->count($where);
668
-        } else {
669
-            $results = $QST->get_all($query_params);
670
-        }
671
-        return $results;
672
-
673
-    }
674
-
675
-
676
-    /**
677
-     * @param            $per_page
678
-     * @param int        $current_page
679
-     * @param bool|false $count
680
-     * @return \EE_Soft_Delete_Base_Class[]|int
681
-     */
682
-    public function get_trashed_questions($per_page, $current_page = 1, $count = false)
683
-    {
684
-        $query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
685
-        $where        = isset($query_params[0]) ? array($query_params[0]) : array();
686
-        $questions    = $count ? EEM_Question::instance()->count_deleted($where) : EEM_Question::instance()->get_all_deleted($query_params);
687
-        return $questions;
688
-    }
689
-
690
-
691
-    /**
692
-     * @param            $per_page
693
-     * @param int        $current_page
694
-     * @param bool|false $count
695
-     * @return \EE_Soft_Delete_Base_Class[]
696
-     */
697
-    public function get_question_groups($per_page, $current_page = 1, $count = false)
698
-    {
699
-        /** @type EEM_Question_Group $questionGroupModel */
700
-        $questionGroupModel = EEM_Question_Group::instance();
701
-        //note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
702
-        return $questionGroupModel->get_all(
703
-            $this->get_query_params($questionGroupModel, $per_page, $current_page)
704
-        );
705
-    }
650
+		return $query_params;
651
+
652
+	}
653
+
654
+
655
+	/**
656
+	 * @param int        $per_page
657
+	 * @param int        $current_page
658
+	 * @param bool|false $count
659
+	 * @return \EE_Soft_Delete_Base_Class[]|int
660
+	 */
661
+	public function get_questions($per_page = 10, $current_page = 1, $count = false)
662
+	{
663
+		$QST          = EEM_Question::instance();
664
+		$query_params = $this->get_query_params($QST, $per_page, $current_page);
665
+		if ($count) {
666
+			$where   = isset($query_params[0]) ? array($query_params[0]) : array();
667
+			$results = $QST->count($where);
668
+		} else {
669
+			$results = $QST->get_all($query_params);
670
+		}
671
+		return $results;
672
+
673
+	}
674
+
675
+
676
+	/**
677
+	 * @param            $per_page
678
+	 * @param int        $current_page
679
+	 * @param bool|false $count
680
+	 * @return \EE_Soft_Delete_Base_Class[]|int
681
+	 */
682
+	public function get_trashed_questions($per_page, $current_page = 1, $count = false)
683
+	{
684
+		$query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
685
+		$where        = isset($query_params[0]) ? array($query_params[0]) : array();
686
+		$questions    = $count ? EEM_Question::instance()->count_deleted($where) : EEM_Question::instance()->get_all_deleted($query_params);
687
+		return $questions;
688
+	}
689
+
690
+
691
+	/**
692
+	 * @param            $per_page
693
+	 * @param int        $current_page
694
+	 * @param bool|false $count
695
+	 * @return \EE_Soft_Delete_Base_Class[]
696
+	 */
697
+	public function get_question_groups($per_page, $current_page = 1, $count = false)
698
+	{
699
+		/** @type EEM_Question_Group $questionGroupModel */
700
+		$questionGroupModel = EEM_Question_Group::instance();
701
+		//note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
702
+		return $questionGroupModel->get_all(
703
+			$this->get_query_params($questionGroupModel, $per_page, $current_page)
704
+		);
705
+	}
706 706
 
707 707
 
708 708
 } //ends Registration_Form_Admin_Page class
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 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
 
@@ -66,8 +66,8 @@  discard block
 block discarded – undo
66 66
      */
67 67
     public function __construct($routing = true)
68 68
     {
69
-        require_once(EE_MODELS . 'EEM_Question.model.php');
70
-        require_once(EE_MODELS . 'EEM_Question_Group.model.php');
69
+        require_once(EE_MODELS.'EEM_Question.model.php');
70
+        require_once(EE_MODELS.'EEM_Question_Group.model.php');
71 71
         $this->_question_model       = EEM_Question::instance();
72 72
         $this->_question_group_model = EEM_Question_Group::instance();
73 73
         parent::__construct($routing);
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
     public function load_scripts_styles()
233 233
     {
234 234
         wp_register_style('espresso_registration',
235
-            REGISTRATION_FORM_ASSETS_URL . 'espresso_registration_form_admin.css', array(), EVENT_ESPRESSO_VERSION);
235
+            REGISTRATION_FORM_ASSETS_URL.'espresso_registration_form_admin.css', array(), EVENT_ESPRESSO_VERSION);
236 236
         wp_enqueue_style('espresso_registration');
237 237
     }
238 238
 
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
     {
259 259
         $this->load_scripts_styles_forms();
260 260
         wp_register_script('espresso_registration_form_single',
261
-            REGISTRATION_FORM_ASSETS_URL . 'espresso_registration_form_admin.js', array('jquery-ui-sortable'),
261
+            REGISTRATION_FORM_ASSETS_URL.'espresso_registration_form_admin.js', array('jquery-ui-sortable'),
262 262
             EVENT_ESPRESSO_VERSION, true);
263 263
         wp_enqueue_script('espresso_registration_form_single');
264 264
     }
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
     {
268 268
         $this->load_scripts_styles_forms();
269 269
         wp_register_script('espresso_registration_form_single',
270
-            REGISTRATION_FORM_ASSETS_URL . 'espresso_registration_form_admin.js', array('jquery-ui-sortable'),
270
+            REGISTRATION_FORM_ASSETS_URL.'espresso_registration_form_admin.js', array('jquery-ui-sortable'),
271 271
             EVENT_ESPRESSO_VERSION, true);
272 272
         wp_enqueue_script('espresso_registration_form_single');
273 273
     }
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 
276 276
     public function recaptcha_info_help_tab()
277 277
     {
278
-        $template = REGISTRATION_FORM_TEMPLATE_PATH . 'recaptcha_info_help_tab.template.php';
278
+        $template = REGISTRATION_FORM_TEMPLATE_PATH.'recaptcha_info_help_tab.template.php';
279 279
         EEH_Template::display_template($template, array());
280 280
     }
281 281
 
@@ -324,10 +324,10 @@  discard block
 block discarded – undo
324 324
     protected function _questions_groups_preview()
325 325
     {
326 326
         $this->_admin_page_title              = esc_html__('Question Groups (Preview)', 'event_espresso');
327
-        $this->_template_args['preview_img']  = '<img src="' . REGISTRATION_FORM_ASSETS_URL . 'caf_reg_form_preview.jpg" alt="' . esc_attr__('Preview Question Groups Overview List Table screenshot',
328
-                'event_espresso') . '" />';
329
-        $this->_template_args['preview_text'] = '<strong>' . esc_html__('Question Groups is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Question Groups feature you are able to create new question groups, edit existing question groups, and create and edit new questions and add them to question groups.',
330
-                'event_espresso') . '</strong>';
327
+        $this->_template_args['preview_img']  = '<img src="'.REGISTRATION_FORM_ASSETS_URL.'caf_reg_form_preview.jpg" alt="'.esc_attr__('Preview Question Groups Overview List Table screenshot',
328
+                'event_espresso').'" />';
329
+        $this->_template_args['preview_text'] = '<strong>'.esc_html__('Question Groups is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Question Groups feature you are able to create new question groups, edit existing question groups, and create and edit new questions and add them to question groups.',
330
+                'event_espresso').'</strong>';
331 331
         $this->display_admin_caf_preview_page('question_groups_tab');
332 332
     }
333 333
 
@@ -345,20 +345,20 @@  discard block
 block discarded – undo
345 345
 
346 346
         //some initial checks for proper values.
347 347
         //if QST_admin_only, then no matter what QST_required is we disable.
348
-        if (! empty($this->_req_data['QST_admin_only'])) {
348
+        if ( ! empty($this->_req_data['QST_admin_only'])) {
349 349
             $this->_req_data['QST_required'] = 0;
350 350
         }
351 351
         foreach ($model->field_settings() as $fieldName => $settings) {
352 352
             // basically if QSG_identifier is empty or not set
353 353
             if ($fieldName === 'QSG_identifier' && (isset($this->_req_data['QSG_identifier']) && empty($this->_req_data['QSG_identifier']))) {
354 354
                 $QSG_name                      = isset($this->_req_data['QSG_name']) ? $this->_req_data['QSG_name'] : '';
355
-                $set_column_values[$fieldName] = sanitize_title($QSG_name) . '-' . uniqid('', true);
355
+                $set_column_values[$fieldName] = sanitize_title($QSG_name).'-'.uniqid('', true);
356 356
 //				dd($set_column_values);
357 357
             } //if the admin label is blank, use a slug version of the question text
358 358
             else if ($fieldName === 'QST_admin_label' && (isset($this->_req_data['QST_admin_label']) && empty($this->_req_data['QST_admin_label']))) {
359 359
                 $QST_text                      = isset($this->_req_data['QST_display_text']) ? $this->_req_data['QST_display_text'] : '';
360 360
                 $set_column_values[$fieldName] = sanitize_title(wp_trim_words($QST_text, 10));
361
-            } else if ($fieldName === 'QST_admin_only' && (! isset($this->_req_data['QST_admin_only']))) {
361
+            } else if ($fieldName === 'QST_admin_only' && ( ! isset($this->_req_data['QST_admin_only']))) {
362 362
                 $set_column_values[$fieldName] = 0;
363 363
             } else if ($fieldName === 'QST_max') {
364 364
                 $qst_system = EEM_Question::instance()->get_var(
@@ -368,7 +368,7 @@  discard block
 block discarded – undo
368 368
                         ),
369 369
                     ),
370 370
                     'QST_system');
371
-                $max_max    = EEM_Question::instance()->absolute_max_for_system_question($qst_system);
371
+                $max_max = EEM_Question::instance()->absolute_max_for_system_question($qst_system);
372 372
                 if (empty($this->_req_data['QST_max']) ||
373 373
                     $this->_req_data['QST_max'] > $max_max
374 374
                 ) {
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
             }
387 387
 
388 388
         }
389
-        return $set_column_values;//validation fo this data to be performed by the model before insertion.
389
+        return $set_column_values; //validation fo this data to be performed by the model before insertion.
390 390
     }
391 391
 
392 392
 
@@ -420,7 +420,7 @@  discard block
 block discarded – undo
420 420
         }
421 421
 
422 422
         // add PRC_ID to title if editing
423
-        $this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
423
+        $this->_admin_page_title = $ID ? $this->_admin_page_title.' # '.$ID : $this->_admin_page_title;
424 424
         if ($ID) {
425 425
             $question                 = $this->_question_model->get_one_by_ID($ID);
426 426
             $additional_hidden_fields = array('QST_ID' => array('type' => 'hidden', 'value' => $ID));
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
             $question->set_order_to_latest();
431 431
             $this->_set_add_edit_form_tags('insert_question');
432 432
         }
433
-        if( $question->system_ID() === EEM_Attendee::system_question_phone ){
433
+        if ($question->system_ID() === EEM_Attendee::system_question_phone) {
434 434
             $question_types = array_intersect_key(
435 435
                 EEM_Question::instance()->allowed_question_types(),
436 436
                 array_flip(
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
         $this->_template_args['question_type_descriptions'] = $this->_get_question_type_descriptions();
453 453
         $this->_set_publish_post_box_vars('id', $ID);
454 454
         $this->_template_args['admin_page_content'] = EEH_Template::display_template(
455
-            REGISTRATION_FORM_TEMPLATE_PATH . 'questions_main_meta_box.template.php',
455
+            REGISTRATION_FORM_TEMPLATE_PATH.'questions_main_meta_box.template.php',
456 456
             $this->_template_args, true
457 457
         );
458 458
 
@@ -480,7 +480,7 @@  discard block
 block discarded – undo
480 480
             }
481 481
             $descriptions .= EEH_HTML::p(
482 482
                 $question_type_description,
483
-                'question_type_description-' . $type,
483
+                'question_type_description-'.$type,
484 484
                 'question_type_description description',
485 485
                 'display:none;'
486 486
             );
@@ -501,8 +501,8 @@  discard block
 block discarded – undo
501 501
             $question = EE_Question::new_instance($set_column_values);
502 502
             $action_desc = 'added';
503 503
         } else {
504
-            $question     = EEM_Question::instance()->get_one_by_ID(absint($this->_req_data['QST_ID']));
505
-            foreach($set_column_values as $field => $new_value) {
504
+            $question = EEM_Question::instance()->get_one_by_ID(absint($this->_req_data['QST_ID']));
505
+            foreach ($set_column_values as $field => $new_value) {
506 506
                 $question->set($field, $new_value);
507 507
             }
508 508
             $action_desc = 'updated';
@@ -513,8 +513,8 @@  discard block
 block discarded – undo
513 513
             //save the related options
514 514
             //trash removed options, save old ones
515 515
             //get list of all options
516
-            $options  = $question->options();
517
-            if (! empty($options)) {
516
+            $options = $question->options();
517
+            if ( ! empty($options)) {
518 518
                 foreach ($options as $option_ID => $option) {
519 519
                     $option_req_index = $this->_get_option_req_data_index($option_ID);
520 520
                     if ($option_req_index !== false) {
@@ -528,7 +528,7 @@  discard block
 block discarded – undo
528 528
             //save new related options
529 529
             foreach ($this->_req_data['question_options'] as $index => $option_req_data) {
530 530
                 //skip $index that is from our sample
531
-                if ( $index === 'xxcountxx' ) {
531
+                if ($index === 'xxcountxx') {
532 532
                     continue;
533 533
                 }
534 534
                 //note we allow saving blank options.
@@ -569,7 +569,7 @@  discard block
 block discarded – undo
569 569
     {
570 570
         $req_data_for_question_options = $this->_req_data['question_options'];
571 571
         foreach ($req_data_for_question_options as $num => $option_data) {
572
-            if (array_key_exists('QSO_ID', $option_data) && (int)$option_data['QSO_ID'] === $ID) {
572
+            if (array_key_exists('QSO_ID', $option_data) && (int) $option_data['QSO_ID'] === $ID) {
573 573
                 return $num;
574 574
             }
575 575
         }
@@ -601,7 +601,7 @@  discard block
 block discarded – undo
601 601
         $field_to_order_by        = empty($this->_req_data['orderby']) ? $orderby_field : $this->_req_data['orderby'];
602 602
         $query_params['order_by'] = array($field_to_order_by => $order);
603 603
         $search_string            = array_key_exists('s', $this->_req_data) ? $this->_req_data['s'] : null;
604
-        if (! empty($search_string)) {
604
+        if ( ! empty($search_string)) {
605 605
             if ($model instanceof EEM_Question_Group) {
606 606
                 $query_params[0] = array(
607 607
                     'OR' => array(
Please login to merge, or discard this patch.
modules/messages/EED_Messages.module.php 2 patches
Indentation   +1239 added lines, -1239 removed lines patch added patch discarded remove patch
@@ -18,1254 +18,1254 @@
 block discarded – undo
18 18
 class EED_Messages extends EED_Module
19 19
 {
20 20
 
21
-    /**
22
-     * This holds the EE_messages controller
23
-     *
24
-     * @deprecated 4.9.0
25
-     * @var EE_messages $_EEMSG
26
-     */
27
-    protected static $_EEMSG;
28
-
29
-    /**
30
-     * @type EE_Message_Resource_Manager $_message_resource_manager
31
-     */
32
-    protected static $_message_resource_manager;
33
-
34
-    /**
35
-     * This holds the EE_Messages_Processor business class.
36
-     *
37
-     * @type EE_Messages_Processor
38
-     */
39
-    protected static $_MSG_PROCESSOR;
40
-
41
-    /**
42
-     * holds all the paths for various messages components.
43
-     * Utilized by autoloader registry
44
-     *
45
-     * @var array
46
-     */
47
-    protected static $_MSG_PATHS;
48
-
49
-
50
-    /**
51
-     * This will hold an array of messages template packs that are registered in the messages system.
52
-     * Format is:
53
-     * array(
54
-     *    'template_pack_dbref' => EE_Messages_Template_Pack (instance)
55
-     * )
56
-     *
57
-     * @var EE_Messages_Template_Pack[]
58
-     */
59
-    protected static $_TMP_PACKS = array();
60
-
61
-
62
-    /**
63
-     * @return EED_Messages
64
-     */
65
-    public static function instance()
66
-    {
67
-        return parent::get_instance(__CLASS__);
68
-    }
69
-
70
-
71
-    /**
72
-     *  set_hooks - for hooking into EE Core, other modules, etc
73
-     *
74
-     * @since 4.5.0
75
-     * @return    void
76
-     */
77
-    public static function set_hooks()
78
-    {
79
-        //actions
80
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
81
-        add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
82
-            array('EED_Messages', 'maybe_registration'), 10, 2);
83
-        //filters
84
-        add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
85
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
86
-        add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
87
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
88
-        //register routes
89
-        self::_register_routes();
90
-    }
91
-
92
-    /**
93
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
94
-     *
95
-     * @access    public
96
-     * @return    void
97
-     */
98
-    public static function set_hooks_admin()
99
-    {
100
-        //actions
101
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
102
-        add_action('AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
103
-            array('EED_Messages', 'payment_reminder'), 10);
104
-        add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
105
-            array('EED_Messages', 'maybe_registration'), 10, 3);
106
-        add_action('AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
107
-            array('EED_Messages', 'send_newsletter_message'), 10, 2);
108
-        add_action('AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
109
-            array('EED_Messages', 'cancelled_registration'), 10);
110
-        add_action('AHEE__EE_Admin_Page___process_admin_payment_notification',
111
-            array('EED_Messages', 'process_admin_payment'), 10, 1);
112
-        //filters
113
-        add_filter('FHEE__EE_Admin_Page___process_resend_registration__success',
114
-            array('EED_Messages', 'process_resend'), 10, 2);
115
-        add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
116
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
117
-        add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
118
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
119
-    }
120
-
121
-
122
-    /**
123
-     * All the message triggers done by route go in here.
124
-     *
125
-     * @since 4.5.0
126
-     * @return void
127
-     */
128
-    protected static function _register_routes()
129
-    {
130
-        EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
131
-        EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
132
-        EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
133
-        EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
134
-        do_action('AHEE__EED_Messages___register_routes');
135
-    }
136
-
137
-
138
-    /**
139
-     * This is called when a browser display trigger is executed.
140
-     * The browser display trigger is typically used when a already generated message is displayed directly in the
141
-     * browser.
142
-     *
143
-     * @since 4.9.0
144
-     * @param WP $WP
145
-     * @throws EE_Error
146
-     * @throws InvalidArgumentException
147
-     * @throws ReflectionException
148
-     * @throws InvalidDataTypeException
149
-     * @throws InvalidInterfaceException
150
-     */
151
-    public function browser_trigger($WP)
152
-    {
153
-        //ensure controller is loaded
154
-        self::_load_controller();
155
-        $token = EE_Registry::instance()->REQ->get('token');
156
-        try {
157
-            $mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
158
-            self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
159
-        } catch (EE_Error $e) {
160
-            $error_msg = __('Please note that a system message failed to send due to a technical issue.',
161
-                'event_espresso');
162
-            // add specific message for developers if WP_DEBUG in on
163
-            $error_msg .= '||' . $e->getMessage();
164
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
165
-        }
166
-    }
167
-
168
-
169
-    /**
170
-     * This is called when a browser error trigger is executed.
171
-     * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
172
-     * message and display it.
173
-     *
174
-     * @since 4.9.0
175
-     * @param $WP
176
-     * @throws EE_Error
177
-     * @throws InvalidArgumentException
178
-     * @throws InvalidDataTypeException
179
-     * @throws InvalidInterfaceException
180
-     */
181
-    public function browser_error_trigger($WP)
182
-    {
183
-        $token = EE_Registry::instance()->REQ->get('token');
184
-        if ($token) {
185
-            $message = EEM_Message::instance()->get_one_by_token($token);
186
-            if ($message instanceof EE_Message) {
187
-                header('HTTP/1.1 200 OK');
188
-                $error_msg = nl2br($message->error_message());
189
-                ?>
21
+	/**
22
+	 * This holds the EE_messages controller
23
+	 *
24
+	 * @deprecated 4.9.0
25
+	 * @var EE_messages $_EEMSG
26
+	 */
27
+	protected static $_EEMSG;
28
+
29
+	/**
30
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
31
+	 */
32
+	protected static $_message_resource_manager;
33
+
34
+	/**
35
+	 * This holds the EE_Messages_Processor business class.
36
+	 *
37
+	 * @type EE_Messages_Processor
38
+	 */
39
+	protected static $_MSG_PROCESSOR;
40
+
41
+	/**
42
+	 * holds all the paths for various messages components.
43
+	 * Utilized by autoloader registry
44
+	 *
45
+	 * @var array
46
+	 */
47
+	protected static $_MSG_PATHS;
48
+
49
+
50
+	/**
51
+	 * This will hold an array of messages template packs that are registered in the messages system.
52
+	 * Format is:
53
+	 * array(
54
+	 *    'template_pack_dbref' => EE_Messages_Template_Pack (instance)
55
+	 * )
56
+	 *
57
+	 * @var EE_Messages_Template_Pack[]
58
+	 */
59
+	protected static $_TMP_PACKS = array();
60
+
61
+
62
+	/**
63
+	 * @return EED_Messages
64
+	 */
65
+	public static function instance()
66
+	{
67
+		return parent::get_instance(__CLASS__);
68
+	}
69
+
70
+
71
+	/**
72
+	 *  set_hooks - for hooking into EE Core, other modules, etc
73
+	 *
74
+	 * @since 4.5.0
75
+	 * @return    void
76
+	 */
77
+	public static function set_hooks()
78
+	{
79
+		//actions
80
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
81
+		add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
82
+			array('EED_Messages', 'maybe_registration'), 10, 2);
83
+		//filters
84
+		add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
85
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
86
+		add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
87
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
88
+		//register routes
89
+		self::_register_routes();
90
+	}
91
+
92
+	/**
93
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
94
+	 *
95
+	 * @access    public
96
+	 * @return    void
97
+	 */
98
+	public static function set_hooks_admin()
99
+	{
100
+		//actions
101
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
102
+		add_action('AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
103
+			array('EED_Messages', 'payment_reminder'), 10);
104
+		add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
105
+			array('EED_Messages', 'maybe_registration'), 10, 3);
106
+		add_action('AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
107
+			array('EED_Messages', 'send_newsletter_message'), 10, 2);
108
+		add_action('AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
109
+			array('EED_Messages', 'cancelled_registration'), 10);
110
+		add_action('AHEE__EE_Admin_Page___process_admin_payment_notification',
111
+			array('EED_Messages', 'process_admin_payment'), 10, 1);
112
+		//filters
113
+		add_filter('FHEE__EE_Admin_Page___process_resend_registration__success',
114
+			array('EED_Messages', 'process_resend'), 10, 2);
115
+		add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
116
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
117
+		add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
118
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
119
+	}
120
+
121
+
122
+	/**
123
+	 * All the message triggers done by route go in here.
124
+	 *
125
+	 * @since 4.5.0
126
+	 * @return void
127
+	 */
128
+	protected static function _register_routes()
129
+	{
130
+		EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
131
+		EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
132
+		EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
133
+		EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
134
+		do_action('AHEE__EED_Messages___register_routes');
135
+	}
136
+
137
+
138
+	/**
139
+	 * This is called when a browser display trigger is executed.
140
+	 * The browser display trigger is typically used when a already generated message is displayed directly in the
141
+	 * browser.
142
+	 *
143
+	 * @since 4.9.0
144
+	 * @param WP $WP
145
+	 * @throws EE_Error
146
+	 * @throws InvalidArgumentException
147
+	 * @throws ReflectionException
148
+	 * @throws InvalidDataTypeException
149
+	 * @throws InvalidInterfaceException
150
+	 */
151
+	public function browser_trigger($WP)
152
+	{
153
+		//ensure controller is loaded
154
+		self::_load_controller();
155
+		$token = EE_Registry::instance()->REQ->get('token');
156
+		try {
157
+			$mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
158
+			self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
159
+		} catch (EE_Error $e) {
160
+			$error_msg = __('Please note that a system message failed to send due to a technical issue.',
161
+				'event_espresso');
162
+			// add specific message for developers if WP_DEBUG in on
163
+			$error_msg .= '||' . $e->getMessage();
164
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
165
+		}
166
+	}
167
+
168
+
169
+	/**
170
+	 * This is called when a browser error trigger is executed.
171
+	 * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
172
+	 * message and display it.
173
+	 *
174
+	 * @since 4.9.0
175
+	 * @param $WP
176
+	 * @throws EE_Error
177
+	 * @throws InvalidArgumentException
178
+	 * @throws InvalidDataTypeException
179
+	 * @throws InvalidInterfaceException
180
+	 */
181
+	public function browser_error_trigger($WP)
182
+	{
183
+		$token = EE_Registry::instance()->REQ->get('token');
184
+		if ($token) {
185
+			$message = EEM_Message::instance()->get_one_by_token($token);
186
+			if ($message instanceof EE_Message) {
187
+				header('HTTP/1.1 200 OK');
188
+				$error_msg = nl2br($message->error_message());
189
+				?>
190 190
                 <!DOCTYPE html>
191 191
                 <html>
192 192
                 <head></head>
193 193
                 <body>
194 194
                 <?php echo empty($error_msg)
195
-                    ? esc_html__('Unfortunately, we were unable to capture the error message for this message.',
196
-                        'event_espresso')
197
-                    : wp_kses(
198
-                        $error_msg,
199
-                        array(
200
-                            'a'      => array(
201
-                                'href'  => array(),
202
-                                'title' => array(),
203
-                            ),
204
-                            'span'   => array(),
205
-                            'div'    => array(),
206
-                            'p'      => array(),
207
-                            'strong' => array(),
208
-                            'em'     => array(),
209
-                            'br'     => array(),
210
-                        )
211
-                    ); ?>
195
+					? esc_html__('Unfortunately, we were unable to capture the error message for this message.',
196
+						'event_espresso')
197
+					: wp_kses(
198
+						$error_msg,
199
+						array(
200
+							'a'      => array(
201
+								'href'  => array(),
202
+								'title' => array(),
203
+							),
204
+							'span'   => array(),
205
+							'div'    => array(),
206
+							'p'      => array(),
207
+							'strong' => array(),
208
+							'em'     => array(),
209
+							'br'     => array(),
210
+						)
211
+					); ?>
212 212
                 </body>
213 213
                 </html>
214 214
                 <?php
215
-                exit;
216
-            }
217
-        }
218
-        return;
219
-    }
220
-
221
-
222
-    /**
223
-     *  This runs when the msg_url_trigger route has initiated.
224
-     *
225
-     * @since 4.5.0
226
-     * @param WP $WP
227
-     * @throws EE_Error
228
-     * @throws InvalidArgumentException
229
-     * @throws ReflectionException
230
-     * @throws InvalidDataTypeException
231
-     * @throws InvalidInterfaceException
232
-     */
233
-    public function run($WP)
234
-    {
235
-        //ensure controller is loaded
236
-        self::_load_controller();
237
-        // attempt to process message
238
-        try {
239
-            /** @type EE_Message_To_Generate_From_Request $message_to_generate */
240
-            $message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
241
-            self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
242
-        } catch (EE_Error $e) {
243
-            $error_msg = __('Please note that a system message failed to send due to a technical issue.',
244
-                'event_espresso');
245
-            // add specific message for developers if WP_DEBUG in on
246
-            $error_msg .= '||' . $e->getMessage();
247
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
248
-        }
249
-    }
250
-
251
-
252
-    /**
253
-     * This is triggered by the 'msg_cron_trigger' route.
254
-     *
255
-     * @param WP $WP
256
-     */
257
-    public function execute_batch_request($WP)
258
-    {
259
-        $this->run_cron();
260
-        header('HTTP/1.1 200 OK');
261
-        exit();
262
-    }
263
-
264
-
265
-    /**
266
-     * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
267
-     * request.
268
-     */
269
-    public function run_cron()
270
-    {
271
-        self::_load_controller();
272
-        //get required vars
273
-        $cron_type     = EE_Registry::instance()->REQ->get('type');
274
-        $transient_key = EE_Registry::instance()->REQ->get('key');
275
-
276
-        //now let's verify transient, if not valid exit immediately
277
-        if (! get_transient($transient_key)) {
278
-            /**
279
-             * trigger error so this gets in the error logs.  This is important because it happens on a non-user
280
-             * request.
281
-             */
282
-            trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
283
-        }
284
-
285
-        //if made it here, lets' delete the transient to keep the db clean
286
-        delete_transient($transient_key);
287
-
288
-        if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
289
-
290
-            $method = 'batch_' . $cron_type . '_from_queue';
291
-            if (method_exists(self::$_MSG_PROCESSOR, $method)) {
292
-                self::$_MSG_PROCESSOR->$method();
293
-            } else {
294
-                //no matching task
295
-                /**
296
-                 * trigger error so this gets in the error logs.  This is important because it happens on a non user
297
-                 * request.
298
-                 */
299
-                trigger_error(esc_attr(sprintf(__('There is no task corresponding to this route %s', 'event_espresso'),
300
-                    $cron_type)));
301
-            }
302
-        }
303
-
304
-        do_action('FHEE__EED_Messages__run_cron__end');
305
-    }
306
-
307
-
308
-    /**
309
-     * This is used to retrieve the template pack for the given name.
310
-     * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
311
-     * the default template pack is returned.
312
-     *
313
-     * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
314
-     * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
315
-     *                                   in generating the Pack class name).
316
-     * @return EE_Messages_Template_Pack
317
-     * @throws EE_Error
318
-     * @throws InvalidArgumentException
319
-     * @throws ReflectionException
320
-     * @throws InvalidDataTypeException
321
-     * @throws InvalidInterfaceException
322
-     */
323
-    public static function get_template_pack($template_pack_name)
324
-    {
325
-        EE_Registry::instance()->load_helper('MSG_Template');
326
-        return EEH_MSG_Template::get_template_pack($template_pack_name);
327
-    }
328
-
329
-
330
-    /**
331
-     * Retrieves an array of all template packs.
332
-     * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
333
-     *
334
-     * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
335
-     * @return EE_Messages_Template_Pack[]
336
-     * @throws EE_Error
337
-     * @throws InvalidArgumentException
338
-     * @throws ReflectionException
339
-     * @throws InvalidDataTypeException
340
-     * @throws InvalidInterfaceException
341
-     */
342
-    public static function get_template_packs()
343
-    {
344
-        EE_Registry::instance()->load_helper('MSG_Template');
345
-
346
-        //for backward compat, let's make sure this returns in the same format as originally.
347
-        $template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
348
-        $template_pack_collection->rewind();
349
-        $template_packs = array();
350
-        while ($template_pack_collection->valid()) {
351
-            $template_packs[$template_pack_collection->current()->dbref] = $template_pack_collection->current();
352
-            $template_pack_collection->next();
353
-        }
354
-        return $template_packs;
355
-    }
356
-
357
-
358
-    /**
359
-     * This simply makes sure the autoloaders are registered for the EE_messages system.
360
-     *
361
-     * @since 4.5.0
362
-     * @return void
363
-     * @throws EE_Error
364
-     */
365
-    public static function set_autoloaders()
366
-    {
367
-        if (empty(self::$_MSG_PATHS)) {
368
-            self::_set_messages_paths();
369
-            foreach (self::$_MSG_PATHS as $path) {
370
-                EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
371
-            }
372
-            // add aliases
373
-            EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
374
-            EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
375
-        }
376
-    }
377
-
378
-
379
-    /**
380
-     * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
381
-     * for use by the Messages Autoloaders
382
-     *
383
-     * @since 4.5.0
384
-     * @return void.
385
-     */
386
-    protected static function _set_messages_paths()
387
-    {
388
-        $dir_ref = array(
389
-            'messages/message_type',
390
-            'messages/messenger',
391
-            'messages/defaults',
392
-            'messages/defaults/email',
393
-            'messages/data_class',
394
-            'messages/validators',
395
-            'messages/validators/email',
396
-            'messages/validators/html',
397
-            'shortcodes',
398
-        );
399
-        $paths   = array();
400
-        foreach ($dir_ref as $index => $dir) {
401
-            $paths[$index] = EE_LIBRARIES . $dir;
402
-        }
403
-        self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
404
-    }
405
-
406
-
407
-    /**
408
-     * Takes care of loading dependencies
409
-     *
410
-     * @since 4.5.0
411
-     * @return void
412
-     * @throws EE_Error
413
-     * @throws InvalidArgumentException
414
-     * @throws ReflectionException
415
-     * @throws InvalidDataTypeException
416
-     * @throws InvalidInterfaceException
417
-     */
418
-    protected static function _load_controller()
419
-    {
420
-        if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
421
-            EE_Registry::instance()->load_core('Request_Handler');
422
-            self::set_autoloaders();
423
-            self::$_EEMSG                    = EE_Registry::instance()->load_lib('messages');
424
-            self::$_MSG_PROCESSOR            = EE_Registry::instance()->load_lib('Messages_Processor');
425
-            self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
426
-        }
427
-    }
428
-
429
-
430
-    /**
431
-     * @param EE_Transaction $transaction
432
-     * @throws EE_Error
433
-     * @throws InvalidArgumentException
434
-     * @throws InvalidDataTypeException
435
-     * @throws InvalidInterfaceException
436
-     * @throws ReflectionException
437
-     */
438
-    public static function payment_reminder(EE_Transaction $transaction)
439
-    {
440
-        self::_load_controller();
441
-        $data = array($transaction, null);
442
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
443
-    }
444
-
445
-
446
-    /**
447
-     * Any messages triggers for after successful gateway payments should go in here.
448
-     *
449
-     * @param EE_Transaction $transaction object
450
-     * @param EE_Payment|null     $payment     object
451
-     * @return void
452
-     * @throws EE_Error
453
-     * @throws InvalidArgumentException
454
-     * @throws ReflectionException
455
-     * @throws InvalidDataTypeException
456
-     * @throws InvalidInterfaceException
457
-     */
458
-    public static function payment(EE_Transaction $transaction, EE_Payment $payment = null)
459
-    {
460
-        //if there's no payment object, then we cannot do a payment type message!
461
-        if (! $payment instanceof EE_Payment) {
462
-            return;
463
-        }
464
-        self::_load_controller();
465
-        $data = array($transaction, $payment);
466
-        EE_Registry::instance()->load_helper('MSG_Template');
467
-        $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
468
-        //if payment amount is less than 0 then switch to payment_refund message type.
469
-        $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
470
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
471
-    }
472
-
473
-
474
-    /**
475
-     * @param EE_Transaction $transaction
476
-     * @throws EE_Error
477
-     * @throws InvalidArgumentException
478
-     * @throws InvalidDataTypeException
479
-     * @throws InvalidInterfaceException
480
-     * @throws ReflectionException
481
-     */
482
-    public static function cancelled_registration(EE_Transaction $transaction)
483
-    {
484
-        self::_load_controller();
485
-        $data = array($transaction, null);
486
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
487
-    }
488
-
489
-
490
-
491
-    /**
492
-     * Trigger for Registration messages
493
-     * Note that what registration message type is sent depends on what the reg status is for the registrations on the
494
-     * incoming transaction.
495
-     *
496
-     * @param EE_Registration $registration
497
-     * @param array           $extra_details
498
-     * @return void
499
-     * @throws EE_Error
500
-     * @throws InvalidArgumentException
501
-     * @throws InvalidDataTypeException
502
-     * @throws InvalidInterfaceException
503
-     * @throws ReflectionException
504
-     * @throws EntityNotFoundException
505
-     */
506
-    public static function maybe_registration(EE_Registration $registration, $extra_details = array())
507
-    {
508
-
509
-        if (! self::_verify_registration_notification_send($registration, $extra_details)) {
510
-            //no messages please
511
-            return;
512
-        }
513
-
514
-        // get all non-trashed registrations so we make sure we send messages for the right status.
515
-        $all_registrations = $registration->transaction()->registrations(
516
-            array(
517
-                array('REG_deleted' => false),
518
-                'order_by' => array(
519
-                    'Event.EVT_name'     => 'ASC',
520
-                    'Attendee.ATT_lname' => 'ASC',
521
-                    'Attendee.ATT_fname' => 'ASC'
522
-                )
523
-            )
524
-        );
525
-        //cached array of statuses so we only trigger messages once per status.
526
-        $statuses_sent = array();
527
-        self::_load_controller();
528
-        $mtgs = array();
529
-
530
-        //loop through registrations and trigger messages once per status.
531
-        foreach ($all_registrations as $reg) {
532
-
533
-            //already triggered?
534
-            if (in_array($reg->status_ID(), $statuses_sent)) {
535
-                continue;
536
-            }
537
-
538
-            $message_type    = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
539
-            $mtgs            = array_merge(
540
-                    $mtgs,
541
-                    self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
542
-                            $message_type,
543
-                            array($registration->transaction(), null, $reg->status_ID())
544
-                    )
545
-            );
546
-            $statuses_sent[] = $reg->status_ID();
547
-        }
548
-
549
-        if (count($statuses_sent) > 1) {
550
-            $mtgs = array_merge(
551
-                $mtgs,
552
-                self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
553
-                    'registration_summary',
554
-                    array($registration->transaction(), null)
555
-                )
556
-            );
557
-        }
558
-
559
-        //batch queue and initiate request
560
-        self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
561
-        self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
562
-    }
563
-
564
-
565
-    /**
566
-     * This is a helper method used to very whether a registration notification should be sent or
567
-     * not.  Prevents duplicate notifications going out for registration context notifications.
568
-     *
569
-     * @param EE_Registration $registration  [description]
570
-     * @param array           $extra_details [description]
571
-     * @return bool          true = send away, false = nope halt the presses.
572
-     */
573
-    protected static function _verify_registration_notification_send(
574
-        EE_Registration $registration,
575
-        $extra_details = array()
576
-    ) {
577
-        //self::log(
578
-        //	__CLASS__, __FUNCTION__, __LINE__,
579
-        //	$registration->transaction(),
580
-        //	array( '$extra_details' => $extra_details )
581
-        //);
582
-        // currently only using this to send messages for the primary registrant
583
-        if (! $registration->is_primary_registrant()) {
584
-            return false;
585
-        }
586
-        // first we check if we're in admin and not doing front ajax
587
-        if (is_admin() && ! EE_FRONT_AJAX) {
588
-            //make sure appropriate admin params are set for sending messages
589
-            if (empty($_REQUEST['txn_reg_status_change']['send_notifications']) || ! absint($_REQUEST['txn_reg_status_change']['send_notifications'])) {
590
-                //no messages sent please.
591
-                return false;
592
-            }
593
-        } else {
594
-            // frontend request (either regular or via AJAX)
595
-            // TXN is NOT finalized ?
596
-            if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
597
-                return false;
598
-            }
599
-            // return visit but nothing changed ???
600
-            if (
601
-                isset($extra_details['revisit'], $extra_details['status_updates']) &&
602
-                $extra_details['revisit'] && ! $extra_details['status_updates']
603
-            ) {
604
-                return false;
605
-            }
606
-            // NOT sending messages && reg status is something other than "Not-Approved"
607
-            if (
608
-                ! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
609
-                $registration->status_ID() !== EEM_Registration::status_id_not_approved
610
-            ) {
611
-                return false;
612
-            }
613
-        }
614
-        // release the kraken
615
-        return true;
616
-    }
617
-
618
-
619
-    /**
620
-     * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
621
-     * status id.
622
-     *
623
-     * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
624
-     *                    or EEH_MSG_Template::convert_reg_status_to_message_type
625
-     * @param string $reg_status
626
-     * @return array
627
-     * @throws EE_Error
628
-     * @throws InvalidArgumentException
629
-     * @throws ReflectionException
630
-     * @throws InvalidDataTypeException
631
-     * @throws InvalidInterfaceException
632
-     */
633
-    protected static function _get_reg_status_array($reg_status = '')
634
-    {
635
-        EE_Registry::instance()->load_helper('MSG_Template');
636
-        return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
637
-            ? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
638
-            : EEH_MSG_Template::reg_status_to_message_type_array();
639
-    }
640
-
641
-
642
-    /**
643
-     * Simply returns the payment message type for the given payment status.
644
-     *
645
-     * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
646
-     *                   or EEH_MSG_Template::convert_payment_status_to_message_type
647
-     * @param string $payment_status The payment status being matched.
648
-     * @return bool|string The payment message type slug matching the status or false if no match.
649
-     * @throws EE_Error
650
-     * @throws InvalidArgumentException
651
-     * @throws ReflectionException
652
-     * @throws InvalidDataTypeException
653
-     * @throws InvalidInterfaceException
654
-     */
655
-    protected static function _get_payment_message_type($payment_status)
656
-    {
657
-        EE_Registry::instance()->load_helper('MSG_Template');
658
-        return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
659
-            ? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
660
-            : false;
661
-    }
662
-
663
-
664
-    /**
665
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
666
-     *
667
-     * @access public
668
-     * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
669
-     * @return bool success/fail
670
-     * @throws EE_Error
671
-     * @throws InvalidArgumentException
672
-     * @throws InvalidDataTypeException
673
-     * @throws InvalidInterfaceException
674
-     * @throws ReflectionException
675
-     */
676
-    public static function process_resend($req_data)
677
-    {
678
-        self::_load_controller();
679
-
680
-        //if $msgID in this request then skip to the new resend_message
681
-        if (EE_Registry::instance()->REQ->get('MSG_ID')) {
682
-            return self::resend_message();
683
-        }
684
-
685
-        //make sure any incoming request data is set on the REQ so that it gets picked up later.
686
-        $req_data = (array)$req_data;
687
-        foreach ($req_data as $request_key => $request_value) {
688
-            EE_Registry::instance()->REQ->set($request_key, $request_value);
689
-        }
690
-
691
-        if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request()) {
692
-            return false;
693
-        }
694
-
695
-        try {
696
-            self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
697
-            self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
698
-        } catch (EE_Error $e) {
699
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
700
-            return false;
701
-        }
702
-        EE_Error::add_success(
703
-            __('Messages have been successfully queued for generation and sending.', 'event_espresso')
704
-        );
705
-        return true; //everything got queued.
706
-    }
707
-
708
-
709
-    /**
710
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
711
-     *
712
-     * @return bool
713
-     * @throws EE_Error
714
-     * @throws InvalidArgumentException
715
-     * @throws InvalidDataTypeException
716
-     * @throws InvalidInterfaceException
717
-     * @throws ReflectionException
718
-     */
719
-    public static function resend_message()
720
-    {
721
-        self::_load_controller();
722
-
723
-        $msgID = EE_Registry::instance()->REQ->get('MSG_ID');
724
-        if (! $msgID) {
725
-            EE_Error::add_error(__('Something went wrong because there is no "MSG_ID" value in the request',
726
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
727
-            return false;
728
-        }
729
-
730
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array)$msgID);
731
-
732
-        //setup success message.
733
-        $count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
734
-        EE_Error::add_success(sprintf(
735
-            _n(
736
-                'There was %d message queued for resending.',
737
-                'There were %d messages queued for resending.',
738
-                $count_ready_for_resend,
739
-                'event_espresso'
740
-            ),
741
-            $count_ready_for_resend
742
-        ));
743
-        return true;
744
-    }
745
-
746
-
747
-    /**
748
-     * Message triggers for manual payment applied by admin
749
-     *
750
-     * @param  EE_Payment $payment EE_payment object
751
-     * @return bool success/fail
752
-     * @throws EE_Error
753
-     * @throws InvalidArgumentException
754
-     * @throws ReflectionException
755
-     * @throws InvalidDataTypeException
756
-     * @throws InvalidInterfaceException
757
-     */
758
-    public static function process_admin_payment(EE_Payment $payment)
759
-    {
760
-        EE_Registry::instance()->load_helper('MSG_Template');
761
-        //we need to get the transaction object
762
-        $transaction = $payment->transaction();
763
-        if ($transaction instanceof EE_Transaction) {
764
-            $data         = array($transaction, $payment);
765
-            $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
766
-
767
-            //if payment amount is less than 0 then switch to payment_refund message type.
768
-            $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
769
-
770
-            //if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
771
-            $message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved ? false : $message_type;
772
-
773
-            self::_load_controller();
774
-
775
-            self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
776
-
777
-            //get count of queued for generation
778
-            $count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(array(
779
-                EEM_Message::status_incomplete,
780
-                EEM_Message::status_idle,
781
-            ));
782
-
783
-            if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
784
-                add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
785
-                return true;
786
-            } else {
787
-                $count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::instance()->stati_indicating_failed_sending());
788
-                /**
789
-                 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
790
-                 * IMMEDIATE generation.
791
-                 */
792
-                if ($count_failed > 0) {
793
-                    EE_Error::add_error(sprintf(
794
-                        _n(
795
-                            'The payment notification generation failed.',
796
-                            '%d payment notifications failed being sent.',
797
-                            $count_failed,
798
-                            'event_espresso'
799
-                        ),
800
-                        $count_failed
801
-                    ), __FILE__, __FUNCTION__, __LINE__);
802
-
803
-                    return false;
804
-                } else {
805
-                    add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
806
-                    return true;
807
-                }
808
-            }
809
-        } else {
810
-            EE_Error::add_error(
811
-                'Unable to generate the payment notification because the given value for the transaction is invalid.',
812
-                'event_espresso'
813
-            );
814
-            return false;
815
-        }
816
-    }
817
-
818
-
819
-    /**
820
-     * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
821
-     *
822
-     * @since   4.3.0
823
-     * @param  EE_Registration[] $registrations an array of EE_Registration objects
824
-     * @param  int               $grp_id        a specific message template group id.
825
-     * @return void
826
-     * @throws EE_Error
827
-     * @throws InvalidArgumentException
828
-     * @throws InvalidDataTypeException
829
-     * @throws InvalidInterfaceException
830
-     * @throws ReflectionException
831
-     */
832
-    public static function send_newsletter_message($registrations, $grp_id)
833
-    {
834
-        //make sure mtp is id and set it in the EE_Request Handler later messages setup.
835
-        EE_Registry::instance()->REQ->set('GRP_ID', (int)$grp_id);
836
-        self::_load_controller();
837
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
838
-    }
839
-
840
-
841
-    /**
842
-     * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
843
-     *
844
-     * @since   4.3.0
845
-     * @param    string          $registration_message_trigger_url
846
-     * @param    EE_Registration $registration
847
-     * @param string             $messenger
848
-     * @param string             $message_type
849
-     * @return string
850
-     * @throws EE_Error
851
-     * @throws InvalidArgumentException
852
-     * @throws InvalidDataTypeException
853
-     * @throws InvalidInterfaceException
854
-     */
855
-    public static function registration_message_trigger_url(
856
-        $registration_message_trigger_url,
857
-        EE_Registration $registration,
858
-        $messenger = 'html',
859
-        $message_type = 'invoice'
860
-    ) {
861
-        // whitelist $messenger
862
-        switch ($messenger) {
863
-            case 'pdf' :
864
-                $sending_messenger    = 'pdf';
865
-                $generating_messenger = 'html';
866
-                break;
867
-            case 'html' :
868
-            default :
869
-                $sending_messenger    = 'html';
870
-                $generating_messenger = 'html';
871
-                break;
872
-        }
873
-        // whitelist $message_type
874
-        switch ($message_type) {
875
-            case 'receipt' :
876
-                $message_type = 'receipt';
877
-                break;
878
-            case 'invoice' :
879
-            default :
880
-                $message_type = 'invoice';
881
-                break;
882
-        }
883
-        // verify that both the messenger AND the message type are active
884
-        if (EEH_MSG_Template::is_messenger_active($sending_messenger) && EEH_MSG_Template::is_mt_active($message_type)) {
885
-            //need to get the correct message template group for this (i.e. is there a custom invoice for the event this registration is registered for?)
886
-            $template_query_params = array(
887
-                'MTP_is_active'    => true,
888
-                'MTP_messenger'    => $generating_messenger,
889
-                'MTP_message_type' => $message_type,
890
-                'Event.EVT_ID'     => $registration->event_ID(),
891
-            );
892
-            //get the message template group.
893
-            $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
894
-            //if we don't have an EE_Message_Template_Group then return
895
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
896
-                // remove EVT_ID from query params so that global templates get picked up
897
-                unset($template_query_params['Event.EVT_ID']);
898
-                //get global template as the fallback
899
-                $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
900
-            }
901
-            //if we don't have an EE_Message_Template_Group then return
902
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
903
-                return '';
904
-            }
905
-            // generate the URL
906
-            $registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
907
-                $sending_messenger,
908
-                $generating_messenger,
909
-                'purchaser',
910
-                $message_type,
911
-                $registration,
912
-                $msg_template_group->ID(),
913
-                $registration->transaction_ID()
914
-            );
915
-
916
-        }
917
-        return $registration_message_trigger_url;
918
-    }
919
-
920
-
921
-    /**
922
-     * Use to generate and return a message preview!
923
-     *
924
-     * @param  string $type      This should correspond with a valid message type
925
-     * @param  string $context   This should correspond with a valid context for the message type
926
-     * @param  string $messenger This should correspond with a valid messenger.
927
-     * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
928
-     *                           preview
929
-     * @return bool|string The body of the message or if send is requested, sends.
930
-     * @throws EE_Error
931
-     * @throws InvalidArgumentException
932
-     * @throws InvalidDataTypeException
933
-     * @throws InvalidInterfaceException
934
-     * @throws ReflectionException
935
-     */
936
-    public static function preview_message($type, $context, $messenger, $send = false)
937
-    {
938
-        self::_load_controller();
939
-        $mtg                     = new EE_Message_To_Generate(
940
-            $messenger,
941
-            $type,
942
-            array(),
943
-            $context,
944
-            true
945
-        );
946
-        $generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
947
-        if ($generated_preview_queue instanceof EE_Messages_Queue) {
948
-            //loop through all content for the preview and remove any persisted records.
949
-            $content = '';
950
-            foreach ($generated_preview_queue->get_message_repository() as $message) {
951
-                $content = $message->content();
952
-                if ($message->ID() > 0 && $message->STS_ID() !== EEM_Message::status_failed) {
953
-                    $message->delete();
954
-                }
955
-            }
956
-            return $content;
957
-        } else {
958
-            return $generated_preview_queue;
959
-        }
960
-    }
961
-
962
-
963
-    /**
964
-     * This is a method that allows for sending a message using a messenger matching the string given and the provided
965
-     * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
966
-     * content found in the EE_Message objects in the queue.
967
-     *
968
-     * @since 4.9.0
969
-     * @param string            $messenger            a string matching a valid active messenger in the system
970
-     * @param string            $message_type         Although it seems contrary to the name of the method, a message
971
-     *                                                type name is still required to send along the message type to the
972
-     *                                                messenger because this is used for determining what specific
973
-     *                                                variations might be loaded for the generated message.
974
-     * @param EE_Messages_Queue $queue
975
-     * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
976
-     *                                                aggregate EE_Message object.
977
-     * @return bool success or fail.
978
-     * @throws EE_Error
979
-     * @throws InvalidArgumentException
980
-     * @throws ReflectionException
981
-     * @throws InvalidDataTypeException
982
-     * @throws InvalidInterfaceException
983
-     */
984
-    public static function send_message_with_messenger_only(
985
-        $messenger,
986
-        $message_type,
987
-        EE_Messages_Queue $queue,
988
-        $custom_subject = ''
989
-    ) {
990
-        self::_load_controller();
991
-        /** @type EE_Message_To_Generate_From_Queue $message_to_generate */
992
-        $message_to_generate = EE_Registry::instance()->load_lib(
993
-            'Message_To_Generate_From_Queue',
994
-            array(
995
-                $messenger,
996
-                $message_type,
997
-                $queue,
998
-                $custom_subject,
999
-            )
1000
-        );
1001
-        return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
1002
-    }
1003
-
1004
-
1005
-    /**
1006
-     * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
1007
-     *
1008
-     * @since 4.9.0
1009
-     * @param array $message_ids An array of message ids
1010
-     * @return bool|EE_Messages_Queue false if nothing was generated, EE_Messages_Queue containing generated
1011
-     *                           messages.
1012
-     * @throws EE_Error
1013
-     * @throws InvalidArgumentException
1014
-     * @throws InvalidDataTypeException
1015
-     * @throws InvalidInterfaceException
1016
-     * @throws ReflectionException
1017
-     */
1018
-    public static function generate_now($message_ids)
1019
-    {
1020
-        self::_load_controller();
1021
-        $messages        = EEM_Message::instance()->get_all(
1022
-            array(
1023
-                0 => array(
1024
-                    'MSG_ID' => array('IN', $message_ids),
1025
-                    'STS_ID' => EEM_Message::status_incomplete,
1026
-                ),
1027
-            )
1028
-        );
1029
-        $generated_queue = false;
1030
-        if ($messages) {
1031
-            $generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
1032
-        }
1033
-
1034
-        if (! $generated_queue instanceof EE_Messages_Queue) {
1035
-            EE_Error::add_error(
1036
-                __('The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
1037
-                    'event_espresso'),
1038
-                __FILE__, __FUNCTION__, __LINE__
1039
-            );
1040
-        }
1041
-        return $generated_queue;
1042
-    }
1043
-
1044
-
1045
-    /**
1046
-     * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
1047
-     * EEM_Message::status_idle
1048
-     *
1049
-     * @since 4.9.0
1050
-     * @param $message_ids
1051
-     * @return bool|EE_Messages_Queue false if no messages sent.
1052
-     * @throws EE_Error
1053
-     * @throws InvalidArgumentException
1054
-     * @throws InvalidDataTypeException
1055
-     * @throws InvalidInterfaceException
1056
-     * @throws ReflectionException
1057
-     */
1058
-    public static function send_now($message_ids)
1059
-    {
1060
-        self::_load_controller();
1061
-        $messages   = EEM_Message::instance()->get_all(
1062
-            array(
1063
-                0 => array(
1064
-                    'MSG_ID' => array('IN', $message_ids),
1065
-                    'STS_ID' => array(
1066
-                        'IN',
1067
-                        array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
1068
-                    ),
1069
-                ),
1070
-            )
1071
-        );
1072
-        $sent_queue = false;
1073
-        if ($messages) {
1074
-            $sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
1075
-        }
1076
-
1077
-        if (! $sent_queue instanceof EE_Messages_Queue) {
1078
-            EE_Error::add_error(
1079
-                __('The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
1080
-                    'event_espresso'),
1081
-                __FILE__, __FUNCTION__, __LINE__
1082
-            );
1083
-        } else {
1084
-            //can count how many sent by using the messages in the queue
1085
-            $sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
1086
-            if ($sent_count > 0) {
1087
-                EE_Error::add_success(
1088
-                    sprintf(
1089
-                        _n(
1090
-                            'There was %d message successfully sent.',
1091
-                            'There were %d messages successfully sent.',
1092
-                            $sent_count,
1093
-                            'event_espresso'
1094
-                        ),
1095
-                        $sent_count
1096
-                    )
1097
-                );
1098
-            } else {
1099
-                EE_Error::overwrite_errors();
1100
-                EE_Error::add_error(
1101
-                    __('No message was sent because of problems with sending. Either all the messages you selected were not a sendable message, they were ALREADY sent on a different scheduled task, or there was an error.
215
+				exit;
216
+			}
217
+		}
218
+		return;
219
+	}
220
+
221
+
222
+	/**
223
+	 *  This runs when the msg_url_trigger route has initiated.
224
+	 *
225
+	 * @since 4.5.0
226
+	 * @param WP $WP
227
+	 * @throws EE_Error
228
+	 * @throws InvalidArgumentException
229
+	 * @throws ReflectionException
230
+	 * @throws InvalidDataTypeException
231
+	 * @throws InvalidInterfaceException
232
+	 */
233
+	public function run($WP)
234
+	{
235
+		//ensure controller is loaded
236
+		self::_load_controller();
237
+		// attempt to process message
238
+		try {
239
+			/** @type EE_Message_To_Generate_From_Request $message_to_generate */
240
+			$message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
241
+			self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
242
+		} catch (EE_Error $e) {
243
+			$error_msg = __('Please note that a system message failed to send due to a technical issue.',
244
+				'event_espresso');
245
+			// add specific message for developers if WP_DEBUG in on
246
+			$error_msg .= '||' . $e->getMessage();
247
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
248
+		}
249
+	}
250
+
251
+
252
+	/**
253
+	 * This is triggered by the 'msg_cron_trigger' route.
254
+	 *
255
+	 * @param WP $WP
256
+	 */
257
+	public function execute_batch_request($WP)
258
+	{
259
+		$this->run_cron();
260
+		header('HTTP/1.1 200 OK');
261
+		exit();
262
+	}
263
+
264
+
265
+	/**
266
+	 * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
267
+	 * request.
268
+	 */
269
+	public function run_cron()
270
+	{
271
+		self::_load_controller();
272
+		//get required vars
273
+		$cron_type     = EE_Registry::instance()->REQ->get('type');
274
+		$transient_key = EE_Registry::instance()->REQ->get('key');
275
+
276
+		//now let's verify transient, if not valid exit immediately
277
+		if (! get_transient($transient_key)) {
278
+			/**
279
+			 * trigger error so this gets in the error logs.  This is important because it happens on a non-user
280
+			 * request.
281
+			 */
282
+			trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
283
+		}
284
+
285
+		//if made it here, lets' delete the transient to keep the db clean
286
+		delete_transient($transient_key);
287
+
288
+		if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
289
+
290
+			$method = 'batch_' . $cron_type . '_from_queue';
291
+			if (method_exists(self::$_MSG_PROCESSOR, $method)) {
292
+				self::$_MSG_PROCESSOR->$method();
293
+			} else {
294
+				//no matching task
295
+				/**
296
+				 * trigger error so this gets in the error logs.  This is important because it happens on a non user
297
+				 * request.
298
+				 */
299
+				trigger_error(esc_attr(sprintf(__('There is no task corresponding to this route %s', 'event_espresso'),
300
+					$cron_type)));
301
+			}
302
+		}
303
+
304
+		do_action('FHEE__EED_Messages__run_cron__end');
305
+	}
306
+
307
+
308
+	/**
309
+	 * This is used to retrieve the template pack for the given name.
310
+	 * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
311
+	 * the default template pack is returned.
312
+	 *
313
+	 * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
314
+	 * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
315
+	 *                                   in generating the Pack class name).
316
+	 * @return EE_Messages_Template_Pack
317
+	 * @throws EE_Error
318
+	 * @throws InvalidArgumentException
319
+	 * @throws ReflectionException
320
+	 * @throws InvalidDataTypeException
321
+	 * @throws InvalidInterfaceException
322
+	 */
323
+	public static function get_template_pack($template_pack_name)
324
+	{
325
+		EE_Registry::instance()->load_helper('MSG_Template');
326
+		return EEH_MSG_Template::get_template_pack($template_pack_name);
327
+	}
328
+
329
+
330
+	/**
331
+	 * Retrieves an array of all template packs.
332
+	 * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
333
+	 *
334
+	 * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
335
+	 * @return EE_Messages_Template_Pack[]
336
+	 * @throws EE_Error
337
+	 * @throws InvalidArgumentException
338
+	 * @throws ReflectionException
339
+	 * @throws InvalidDataTypeException
340
+	 * @throws InvalidInterfaceException
341
+	 */
342
+	public static function get_template_packs()
343
+	{
344
+		EE_Registry::instance()->load_helper('MSG_Template');
345
+
346
+		//for backward compat, let's make sure this returns in the same format as originally.
347
+		$template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
348
+		$template_pack_collection->rewind();
349
+		$template_packs = array();
350
+		while ($template_pack_collection->valid()) {
351
+			$template_packs[$template_pack_collection->current()->dbref] = $template_pack_collection->current();
352
+			$template_pack_collection->next();
353
+		}
354
+		return $template_packs;
355
+	}
356
+
357
+
358
+	/**
359
+	 * This simply makes sure the autoloaders are registered for the EE_messages system.
360
+	 *
361
+	 * @since 4.5.0
362
+	 * @return void
363
+	 * @throws EE_Error
364
+	 */
365
+	public static function set_autoloaders()
366
+	{
367
+		if (empty(self::$_MSG_PATHS)) {
368
+			self::_set_messages_paths();
369
+			foreach (self::$_MSG_PATHS as $path) {
370
+				EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
371
+			}
372
+			// add aliases
373
+			EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
374
+			EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
375
+		}
376
+	}
377
+
378
+
379
+	/**
380
+	 * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
381
+	 * for use by the Messages Autoloaders
382
+	 *
383
+	 * @since 4.5.0
384
+	 * @return void.
385
+	 */
386
+	protected static function _set_messages_paths()
387
+	{
388
+		$dir_ref = array(
389
+			'messages/message_type',
390
+			'messages/messenger',
391
+			'messages/defaults',
392
+			'messages/defaults/email',
393
+			'messages/data_class',
394
+			'messages/validators',
395
+			'messages/validators/email',
396
+			'messages/validators/html',
397
+			'shortcodes',
398
+		);
399
+		$paths   = array();
400
+		foreach ($dir_ref as $index => $dir) {
401
+			$paths[$index] = EE_LIBRARIES . $dir;
402
+		}
403
+		self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
404
+	}
405
+
406
+
407
+	/**
408
+	 * Takes care of loading dependencies
409
+	 *
410
+	 * @since 4.5.0
411
+	 * @return void
412
+	 * @throws EE_Error
413
+	 * @throws InvalidArgumentException
414
+	 * @throws ReflectionException
415
+	 * @throws InvalidDataTypeException
416
+	 * @throws InvalidInterfaceException
417
+	 */
418
+	protected static function _load_controller()
419
+	{
420
+		if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
421
+			EE_Registry::instance()->load_core('Request_Handler');
422
+			self::set_autoloaders();
423
+			self::$_EEMSG                    = EE_Registry::instance()->load_lib('messages');
424
+			self::$_MSG_PROCESSOR            = EE_Registry::instance()->load_lib('Messages_Processor');
425
+			self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
426
+		}
427
+	}
428
+
429
+
430
+	/**
431
+	 * @param EE_Transaction $transaction
432
+	 * @throws EE_Error
433
+	 * @throws InvalidArgumentException
434
+	 * @throws InvalidDataTypeException
435
+	 * @throws InvalidInterfaceException
436
+	 * @throws ReflectionException
437
+	 */
438
+	public static function payment_reminder(EE_Transaction $transaction)
439
+	{
440
+		self::_load_controller();
441
+		$data = array($transaction, null);
442
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
443
+	}
444
+
445
+
446
+	/**
447
+	 * Any messages triggers for after successful gateway payments should go in here.
448
+	 *
449
+	 * @param EE_Transaction $transaction object
450
+	 * @param EE_Payment|null     $payment     object
451
+	 * @return void
452
+	 * @throws EE_Error
453
+	 * @throws InvalidArgumentException
454
+	 * @throws ReflectionException
455
+	 * @throws InvalidDataTypeException
456
+	 * @throws InvalidInterfaceException
457
+	 */
458
+	public static function payment(EE_Transaction $transaction, EE_Payment $payment = null)
459
+	{
460
+		//if there's no payment object, then we cannot do a payment type message!
461
+		if (! $payment instanceof EE_Payment) {
462
+			return;
463
+		}
464
+		self::_load_controller();
465
+		$data = array($transaction, $payment);
466
+		EE_Registry::instance()->load_helper('MSG_Template');
467
+		$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
468
+		//if payment amount is less than 0 then switch to payment_refund message type.
469
+		$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
470
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
471
+	}
472
+
473
+
474
+	/**
475
+	 * @param EE_Transaction $transaction
476
+	 * @throws EE_Error
477
+	 * @throws InvalidArgumentException
478
+	 * @throws InvalidDataTypeException
479
+	 * @throws InvalidInterfaceException
480
+	 * @throws ReflectionException
481
+	 */
482
+	public static function cancelled_registration(EE_Transaction $transaction)
483
+	{
484
+		self::_load_controller();
485
+		$data = array($transaction, null);
486
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
487
+	}
488
+
489
+
490
+
491
+	/**
492
+	 * Trigger for Registration messages
493
+	 * Note that what registration message type is sent depends on what the reg status is for the registrations on the
494
+	 * incoming transaction.
495
+	 *
496
+	 * @param EE_Registration $registration
497
+	 * @param array           $extra_details
498
+	 * @return void
499
+	 * @throws EE_Error
500
+	 * @throws InvalidArgumentException
501
+	 * @throws InvalidDataTypeException
502
+	 * @throws InvalidInterfaceException
503
+	 * @throws ReflectionException
504
+	 * @throws EntityNotFoundException
505
+	 */
506
+	public static function maybe_registration(EE_Registration $registration, $extra_details = array())
507
+	{
508
+
509
+		if (! self::_verify_registration_notification_send($registration, $extra_details)) {
510
+			//no messages please
511
+			return;
512
+		}
513
+
514
+		// get all non-trashed registrations so we make sure we send messages for the right status.
515
+		$all_registrations = $registration->transaction()->registrations(
516
+			array(
517
+				array('REG_deleted' => false),
518
+				'order_by' => array(
519
+					'Event.EVT_name'     => 'ASC',
520
+					'Attendee.ATT_lname' => 'ASC',
521
+					'Attendee.ATT_fname' => 'ASC'
522
+				)
523
+			)
524
+		);
525
+		//cached array of statuses so we only trigger messages once per status.
526
+		$statuses_sent = array();
527
+		self::_load_controller();
528
+		$mtgs = array();
529
+
530
+		//loop through registrations and trigger messages once per status.
531
+		foreach ($all_registrations as $reg) {
532
+
533
+			//already triggered?
534
+			if (in_array($reg->status_ID(), $statuses_sent)) {
535
+				continue;
536
+			}
537
+
538
+			$message_type    = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
539
+			$mtgs            = array_merge(
540
+					$mtgs,
541
+					self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
542
+							$message_type,
543
+							array($registration->transaction(), null, $reg->status_ID())
544
+					)
545
+			);
546
+			$statuses_sent[] = $reg->status_ID();
547
+		}
548
+
549
+		if (count($statuses_sent) > 1) {
550
+			$mtgs = array_merge(
551
+				$mtgs,
552
+				self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
553
+					'registration_summary',
554
+					array($registration->transaction(), null)
555
+				)
556
+			);
557
+		}
558
+
559
+		//batch queue and initiate request
560
+		self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
561
+		self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
562
+	}
563
+
564
+
565
+	/**
566
+	 * This is a helper method used to very whether a registration notification should be sent or
567
+	 * not.  Prevents duplicate notifications going out for registration context notifications.
568
+	 *
569
+	 * @param EE_Registration $registration  [description]
570
+	 * @param array           $extra_details [description]
571
+	 * @return bool          true = send away, false = nope halt the presses.
572
+	 */
573
+	protected static function _verify_registration_notification_send(
574
+		EE_Registration $registration,
575
+		$extra_details = array()
576
+	) {
577
+		//self::log(
578
+		//	__CLASS__, __FUNCTION__, __LINE__,
579
+		//	$registration->transaction(),
580
+		//	array( '$extra_details' => $extra_details )
581
+		//);
582
+		// currently only using this to send messages for the primary registrant
583
+		if (! $registration->is_primary_registrant()) {
584
+			return false;
585
+		}
586
+		// first we check if we're in admin and not doing front ajax
587
+		if (is_admin() && ! EE_FRONT_AJAX) {
588
+			//make sure appropriate admin params are set for sending messages
589
+			if (empty($_REQUEST['txn_reg_status_change']['send_notifications']) || ! absint($_REQUEST['txn_reg_status_change']['send_notifications'])) {
590
+				//no messages sent please.
591
+				return false;
592
+			}
593
+		} else {
594
+			// frontend request (either regular or via AJAX)
595
+			// TXN is NOT finalized ?
596
+			if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
597
+				return false;
598
+			}
599
+			// return visit but nothing changed ???
600
+			if (
601
+				isset($extra_details['revisit'], $extra_details['status_updates']) &&
602
+				$extra_details['revisit'] && ! $extra_details['status_updates']
603
+			) {
604
+				return false;
605
+			}
606
+			// NOT sending messages && reg status is something other than "Not-Approved"
607
+			if (
608
+				! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
609
+				$registration->status_ID() !== EEM_Registration::status_id_not_approved
610
+			) {
611
+				return false;
612
+			}
613
+		}
614
+		// release the kraken
615
+		return true;
616
+	}
617
+
618
+
619
+	/**
620
+	 * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
621
+	 * status id.
622
+	 *
623
+	 * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
624
+	 *                    or EEH_MSG_Template::convert_reg_status_to_message_type
625
+	 * @param string $reg_status
626
+	 * @return array
627
+	 * @throws EE_Error
628
+	 * @throws InvalidArgumentException
629
+	 * @throws ReflectionException
630
+	 * @throws InvalidDataTypeException
631
+	 * @throws InvalidInterfaceException
632
+	 */
633
+	protected static function _get_reg_status_array($reg_status = '')
634
+	{
635
+		EE_Registry::instance()->load_helper('MSG_Template');
636
+		return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
637
+			? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
638
+			: EEH_MSG_Template::reg_status_to_message_type_array();
639
+	}
640
+
641
+
642
+	/**
643
+	 * Simply returns the payment message type for the given payment status.
644
+	 *
645
+	 * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
646
+	 *                   or EEH_MSG_Template::convert_payment_status_to_message_type
647
+	 * @param string $payment_status The payment status being matched.
648
+	 * @return bool|string The payment message type slug matching the status or false if no match.
649
+	 * @throws EE_Error
650
+	 * @throws InvalidArgumentException
651
+	 * @throws ReflectionException
652
+	 * @throws InvalidDataTypeException
653
+	 * @throws InvalidInterfaceException
654
+	 */
655
+	protected static function _get_payment_message_type($payment_status)
656
+	{
657
+		EE_Registry::instance()->load_helper('MSG_Template');
658
+		return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
659
+			? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
660
+			: false;
661
+	}
662
+
663
+
664
+	/**
665
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
666
+	 *
667
+	 * @access public
668
+	 * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
669
+	 * @return bool success/fail
670
+	 * @throws EE_Error
671
+	 * @throws InvalidArgumentException
672
+	 * @throws InvalidDataTypeException
673
+	 * @throws InvalidInterfaceException
674
+	 * @throws ReflectionException
675
+	 */
676
+	public static function process_resend($req_data)
677
+	{
678
+		self::_load_controller();
679
+
680
+		//if $msgID in this request then skip to the new resend_message
681
+		if (EE_Registry::instance()->REQ->get('MSG_ID')) {
682
+			return self::resend_message();
683
+		}
684
+
685
+		//make sure any incoming request data is set on the REQ so that it gets picked up later.
686
+		$req_data = (array)$req_data;
687
+		foreach ($req_data as $request_key => $request_value) {
688
+			EE_Registry::instance()->REQ->set($request_key, $request_value);
689
+		}
690
+
691
+		if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request()) {
692
+			return false;
693
+		}
694
+
695
+		try {
696
+			self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
697
+			self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
698
+		} catch (EE_Error $e) {
699
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
700
+			return false;
701
+		}
702
+		EE_Error::add_success(
703
+			__('Messages have been successfully queued for generation and sending.', 'event_espresso')
704
+		);
705
+		return true; //everything got queued.
706
+	}
707
+
708
+
709
+	/**
710
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
711
+	 *
712
+	 * @return bool
713
+	 * @throws EE_Error
714
+	 * @throws InvalidArgumentException
715
+	 * @throws InvalidDataTypeException
716
+	 * @throws InvalidInterfaceException
717
+	 * @throws ReflectionException
718
+	 */
719
+	public static function resend_message()
720
+	{
721
+		self::_load_controller();
722
+
723
+		$msgID = EE_Registry::instance()->REQ->get('MSG_ID');
724
+		if (! $msgID) {
725
+			EE_Error::add_error(__('Something went wrong because there is no "MSG_ID" value in the request',
726
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
727
+			return false;
728
+		}
729
+
730
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array)$msgID);
731
+
732
+		//setup success message.
733
+		$count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
734
+		EE_Error::add_success(sprintf(
735
+			_n(
736
+				'There was %d message queued for resending.',
737
+				'There were %d messages queued for resending.',
738
+				$count_ready_for_resend,
739
+				'event_espresso'
740
+			),
741
+			$count_ready_for_resend
742
+		));
743
+		return true;
744
+	}
745
+
746
+
747
+	/**
748
+	 * Message triggers for manual payment applied by admin
749
+	 *
750
+	 * @param  EE_Payment $payment EE_payment object
751
+	 * @return bool success/fail
752
+	 * @throws EE_Error
753
+	 * @throws InvalidArgumentException
754
+	 * @throws ReflectionException
755
+	 * @throws InvalidDataTypeException
756
+	 * @throws InvalidInterfaceException
757
+	 */
758
+	public static function process_admin_payment(EE_Payment $payment)
759
+	{
760
+		EE_Registry::instance()->load_helper('MSG_Template');
761
+		//we need to get the transaction object
762
+		$transaction = $payment->transaction();
763
+		if ($transaction instanceof EE_Transaction) {
764
+			$data         = array($transaction, $payment);
765
+			$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
766
+
767
+			//if payment amount is less than 0 then switch to payment_refund message type.
768
+			$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
769
+
770
+			//if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
771
+			$message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved ? false : $message_type;
772
+
773
+			self::_load_controller();
774
+
775
+			self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
776
+
777
+			//get count of queued for generation
778
+			$count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(array(
779
+				EEM_Message::status_incomplete,
780
+				EEM_Message::status_idle,
781
+			));
782
+
783
+			if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
784
+				add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
785
+				return true;
786
+			} else {
787
+				$count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::instance()->stati_indicating_failed_sending());
788
+				/**
789
+				 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
790
+				 * IMMEDIATE generation.
791
+				 */
792
+				if ($count_failed > 0) {
793
+					EE_Error::add_error(sprintf(
794
+						_n(
795
+							'The payment notification generation failed.',
796
+							'%d payment notifications failed being sent.',
797
+							$count_failed,
798
+							'event_espresso'
799
+						),
800
+						$count_failed
801
+					), __FILE__, __FUNCTION__, __LINE__);
802
+
803
+					return false;
804
+				} else {
805
+					add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
806
+					return true;
807
+				}
808
+			}
809
+		} else {
810
+			EE_Error::add_error(
811
+				'Unable to generate the payment notification because the given value for the transaction is invalid.',
812
+				'event_espresso'
813
+			);
814
+			return false;
815
+		}
816
+	}
817
+
818
+
819
+	/**
820
+	 * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
821
+	 *
822
+	 * @since   4.3.0
823
+	 * @param  EE_Registration[] $registrations an array of EE_Registration objects
824
+	 * @param  int               $grp_id        a specific message template group id.
825
+	 * @return void
826
+	 * @throws EE_Error
827
+	 * @throws InvalidArgumentException
828
+	 * @throws InvalidDataTypeException
829
+	 * @throws InvalidInterfaceException
830
+	 * @throws ReflectionException
831
+	 */
832
+	public static function send_newsletter_message($registrations, $grp_id)
833
+	{
834
+		//make sure mtp is id and set it in the EE_Request Handler later messages setup.
835
+		EE_Registry::instance()->REQ->set('GRP_ID', (int)$grp_id);
836
+		self::_load_controller();
837
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
838
+	}
839
+
840
+
841
+	/**
842
+	 * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
843
+	 *
844
+	 * @since   4.3.0
845
+	 * @param    string          $registration_message_trigger_url
846
+	 * @param    EE_Registration $registration
847
+	 * @param string             $messenger
848
+	 * @param string             $message_type
849
+	 * @return string
850
+	 * @throws EE_Error
851
+	 * @throws InvalidArgumentException
852
+	 * @throws InvalidDataTypeException
853
+	 * @throws InvalidInterfaceException
854
+	 */
855
+	public static function registration_message_trigger_url(
856
+		$registration_message_trigger_url,
857
+		EE_Registration $registration,
858
+		$messenger = 'html',
859
+		$message_type = 'invoice'
860
+	) {
861
+		// whitelist $messenger
862
+		switch ($messenger) {
863
+			case 'pdf' :
864
+				$sending_messenger    = 'pdf';
865
+				$generating_messenger = 'html';
866
+				break;
867
+			case 'html' :
868
+			default :
869
+				$sending_messenger    = 'html';
870
+				$generating_messenger = 'html';
871
+				break;
872
+		}
873
+		// whitelist $message_type
874
+		switch ($message_type) {
875
+			case 'receipt' :
876
+				$message_type = 'receipt';
877
+				break;
878
+			case 'invoice' :
879
+			default :
880
+				$message_type = 'invoice';
881
+				break;
882
+		}
883
+		// verify that both the messenger AND the message type are active
884
+		if (EEH_MSG_Template::is_messenger_active($sending_messenger) && EEH_MSG_Template::is_mt_active($message_type)) {
885
+			//need to get the correct message template group for this (i.e. is there a custom invoice for the event this registration is registered for?)
886
+			$template_query_params = array(
887
+				'MTP_is_active'    => true,
888
+				'MTP_messenger'    => $generating_messenger,
889
+				'MTP_message_type' => $message_type,
890
+				'Event.EVT_ID'     => $registration->event_ID(),
891
+			);
892
+			//get the message template group.
893
+			$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
894
+			//if we don't have an EE_Message_Template_Group then return
895
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
896
+				// remove EVT_ID from query params so that global templates get picked up
897
+				unset($template_query_params['Event.EVT_ID']);
898
+				//get global template as the fallback
899
+				$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
900
+			}
901
+			//if we don't have an EE_Message_Template_Group then return
902
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
903
+				return '';
904
+			}
905
+			// generate the URL
906
+			$registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
907
+				$sending_messenger,
908
+				$generating_messenger,
909
+				'purchaser',
910
+				$message_type,
911
+				$registration,
912
+				$msg_template_group->ID(),
913
+				$registration->transaction_ID()
914
+			);
915
+
916
+		}
917
+		return $registration_message_trigger_url;
918
+	}
919
+
920
+
921
+	/**
922
+	 * Use to generate and return a message preview!
923
+	 *
924
+	 * @param  string $type      This should correspond with a valid message type
925
+	 * @param  string $context   This should correspond with a valid context for the message type
926
+	 * @param  string $messenger This should correspond with a valid messenger.
927
+	 * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
928
+	 *                           preview
929
+	 * @return bool|string The body of the message or if send is requested, sends.
930
+	 * @throws EE_Error
931
+	 * @throws InvalidArgumentException
932
+	 * @throws InvalidDataTypeException
933
+	 * @throws InvalidInterfaceException
934
+	 * @throws ReflectionException
935
+	 */
936
+	public static function preview_message($type, $context, $messenger, $send = false)
937
+	{
938
+		self::_load_controller();
939
+		$mtg                     = new EE_Message_To_Generate(
940
+			$messenger,
941
+			$type,
942
+			array(),
943
+			$context,
944
+			true
945
+		);
946
+		$generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
947
+		if ($generated_preview_queue instanceof EE_Messages_Queue) {
948
+			//loop through all content for the preview and remove any persisted records.
949
+			$content = '';
950
+			foreach ($generated_preview_queue->get_message_repository() as $message) {
951
+				$content = $message->content();
952
+				if ($message->ID() > 0 && $message->STS_ID() !== EEM_Message::status_failed) {
953
+					$message->delete();
954
+				}
955
+			}
956
+			return $content;
957
+		} else {
958
+			return $generated_preview_queue;
959
+		}
960
+	}
961
+
962
+
963
+	/**
964
+	 * This is a method that allows for sending a message using a messenger matching the string given and the provided
965
+	 * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
966
+	 * content found in the EE_Message objects in the queue.
967
+	 *
968
+	 * @since 4.9.0
969
+	 * @param string            $messenger            a string matching a valid active messenger in the system
970
+	 * @param string            $message_type         Although it seems contrary to the name of the method, a message
971
+	 *                                                type name is still required to send along the message type to the
972
+	 *                                                messenger because this is used for determining what specific
973
+	 *                                                variations might be loaded for the generated message.
974
+	 * @param EE_Messages_Queue $queue
975
+	 * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
976
+	 *                                                aggregate EE_Message object.
977
+	 * @return bool success or fail.
978
+	 * @throws EE_Error
979
+	 * @throws InvalidArgumentException
980
+	 * @throws ReflectionException
981
+	 * @throws InvalidDataTypeException
982
+	 * @throws InvalidInterfaceException
983
+	 */
984
+	public static function send_message_with_messenger_only(
985
+		$messenger,
986
+		$message_type,
987
+		EE_Messages_Queue $queue,
988
+		$custom_subject = ''
989
+	) {
990
+		self::_load_controller();
991
+		/** @type EE_Message_To_Generate_From_Queue $message_to_generate */
992
+		$message_to_generate = EE_Registry::instance()->load_lib(
993
+			'Message_To_Generate_From_Queue',
994
+			array(
995
+				$messenger,
996
+				$message_type,
997
+				$queue,
998
+				$custom_subject,
999
+			)
1000
+		);
1001
+		return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
1002
+	}
1003
+
1004
+
1005
+	/**
1006
+	 * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
1007
+	 *
1008
+	 * @since 4.9.0
1009
+	 * @param array $message_ids An array of message ids
1010
+	 * @return bool|EE_Messages_Queue false if nothing was generated, EE_Messages_Queue containing generated
1011
+	 *                           messages.
1012
+	 * @throws EE_Error
1013
+	 * @throws InvalidArgumentException
1014
+	 * @throws InvalidDataTypeException
1015
+	 * @throws InvalidInterfaceException
1016
+	 * @throws ReflectionException
1017
+	 */
1018
+	public static function generate_now($message_ids)
1019
+	{
1020
+		self::_load_controller();
1021
+		$messages        = EEM_Message::instance()->get_all(
1022
+			array(
1023
+				0 => array(
1024
+					'MSG_ID' => array('IN', $message_ids),
1025
+					'STS_ID' => EEM_Message::status_incomplete,
1026
+				),
1027
+			)
1028
+		);
1029
+		$generated_queue = false;
1030
+		if ($messages) {
1031
+			$generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
1032
+		}
1033
+
1034
+		if (! $generated_queue instanceof EE_Messages_Queue) {
1035
+			EE_Error::add_error(
1036
+				__('The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
1037
+					'event_espresso'),
1038
+				__FILE__, __FUNCTION__, __LINE__
1039
+			);
1040
+		}
1041
+		return $generated_queue;
1042
+	}
1043
+
1044
+
1045
+	/**
1046
+	 * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
1047
+	 * EEM_Message::status_idle
1048
+	 *
1049
+	 * @since 4.9.0
1050
+	 * @param $message_ids
1051
+	 * @return bool|EE_Messages_Queue false if no messages sent.
1052
+	 * @throws EE_Error
1053
+	 * @throws InvalidArgumentException
1054
+	 * @throws InvalidDataTypeException
1055
+	 * @throws InvalidInterfaceException
1056
+	 * @throws ReflectionException
1057
+	 */
1058
+	public static function send_now($message_ids)
1059
+	{
1060
+		self::_load_controller();
1061
+		$messages   = EEM_Message::instance()->get_all(
1062
+			array(
1063
+				0 => array(
1064
+					'MSG_ID' => array('IN', $message_ids),
1065
+					'STS_ID' => array(
1066
+						'IN',
1067
+						array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
1068
+					),
1069
+				),
1070
+			)
1071
+		);
1072
+		$sent_queue = false;
1073
+		if ($messages) {
1074
+			$sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
1075
+		}
1076
+
1077
+		if (! $sent_queue instanceof EE_Messages_Queue) {
1078
+			EE_Error::add_error(
1079
+				__('The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
1080
+					'event_espresso'),
1081
+				__FILE__, __FUNCTION__, __LINE__
1082
+			);
1083
+		} else {
1084
+			//can count how many sent by using the messages in the queue
1085
+			$sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
1086
+			if ($sent_count > 0) {
1087
+				EE_Error::add_success(
1088
+					sprintf(
1089
+						_n(
1090
+							'There was %d message successfully sent.',
1091
+							'There were %d messages successfully sent.',
1092
+							$sent_count,
1093
+							'event_espresso'
1094
+						),
1095
+						$sent_count
1096
+					)
1097
+				);
1098
+			} else {
1099
+				EE_Error::overwrite_errors();
1100
+				EE_Error::add_error(
1101
+					__('No message was sent because of problems with sending. Either all the messages you selected were not a sendable message, they were ALREADY sent on a different scheduled task, or there was an error.
1102 1102
 					If there was an error, you can look at the messages in the message activity list table for any error messages.',
1103
-                        'event_espresso'),
1104
-                    __FILE__, __FUNCTION__, __LINE__
1105
-                );
1106
-            }
1107
-        }
1108
-        return $sent_queue;
1109
-    }
1110
-
1111
-
1112
-    /**
1113
-     * Generate and send immediately from the given $message_ids
1114
-     *
1115
-     * @param array $message_ids EE_Message entity ids.
1116
-     * @throws EE_Error
1117
-     * @throws InvalidArgumentException
1118
-     * @throws InvalidDataTypeException
1119
-     * @throws InvalidInterfaceException
1120
-     * @throws ReflectionException
1121
-     */
1122
-    public static function generate_and_send_now(array $message_ids)
1123
-    {
1124
-        $generated_queue = self::generate_now($message_ids);
1125
-        //now let's just trigger sending immediately from this queue.
1126
-        $messages_sent = $generated_queue instanceof EE_Messages_Queue
1127
-            ? $generated_queue->execute()
1128
-            : 0;
1129
-        if ($messages_sent) {
1130
-            EE_Error::add_success(
1131
-                esc_html(
1132
-                    sprintf(
1133
-                        _n(
1134
-                            'There was %d message successfully generated and sent.',
1135
-                            'There were %d messages successfully generated and sent.',
1136
-                            $messages_sent,
1137
-                            'event_espresso'
1138
-                        ),
1139
-                        $messages_sent
1140
-                    )
1141
-                )
1142
-            );
1143
-            //errors would be added via the generate_now method.
1144
-        }
1145
-    }
1146
-
1147
-
1148
-    /**
1149
-     * This will queue the incoming message ids for resending.
1150
-     * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
1151
-     *
1152
-     * @since 4.9.0
1153
-     * @param array $message_ids An array of EE_Message IDs
1154
-     * @return bool true means messages were successfully queued for resending, false means none were queued for
1155
-     *                           resending.
1156
-     * @throws EE_Error
1157
-     * @throws InvalidArgumentException
1158
-     * @throws InvalidDataTypeException
1159
-     * @throws InvalidInterfaceException
1160
-     * @throws ReflectionException
1161
-     */
1162
-    public static function queue_for_resending($message_ids)
1163
-    {
1164
-        self::_load_controller();
1165
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1166
-
1167
-        //get queue and count
1168
-        $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1169
-
1170
-        if (
1171
-            $queue_count > 0
1172
-        ) {
1173
-            EE_Error::add_success(
1174
-                sprintf(
1175
-                    _n(
1176
-                        '%d message successfully queued for resending.',
1177
-                        '%d messages successfully queued for resending.',
1178
-                        $queue_count,
1179
-                        'event_espresso'
1180
-                    ),
1181
-                    $queue_count
1182
-                )
1183
-            );
1184
-            /**
1185
-             * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1186
-             */
1187
-        } elseif (
1188
-            apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1189
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1190
-        ) {
1191
-            $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1192
-            if ($queue_count > 0) {
1193
-                EE_Error::add_success(
1194
-                    sprintf(
1195
-                        _n(
1196
-                            '%d message successfully sent.',
1197
-                            '%d messages successfully sent.',
1198
-                            $queue_count,
1199
-                            'event_espresso'
1200
-                        ),
1201
-                        $queue_count
1202
-                    )
1203
-                );
1204
-            } else {
1205
-                EE_Error::add_error(
1206
-                    __('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1207
-                        'event_espresso'),
1208
-                    __FILE__, __FUNCTION__, __LINE__
1209
-                );
1210
-            }
1211
-        } else {
1212
-            EE_Error::add_error(
1213
-                __('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1214
-                    'event_espresso'),
1215
-                __FILE__, __FUNCTION__, __LINE__
1216
-            );
1217
-        }
1218
-        return (bool)$queue_count;
1219
-    }
1220
-
1221
-
1222
-    /**
1223
-     * debug
1224
-     *
1225
-     * @param string          $class
1226
-     * @param string          $func
1227
-     * @param string          $line
1228
-     * @param \EE_Transaction $transaction
1229
-     * @param array           $info
1230
-     * @param bool            $display_request
1231
-     * @throws EE_Error
1232
-     * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
1233
-     */
1234
-    protected static function log(
1235
-        $class = '',
1236
-        $func = '',
1237
-        $line = '',
1238
-        EE_Transaction $transaction,
1239
-        $info = array(),
1240
-        $display_request = false
1241
-    ) {
1242
-        if (defined('EE_DEBUG') && EE_DEBUG) {
1243
-            if ($transaction instanceof EE_Transaction) {
1244
-                // don't serialize objects
1245
-                $info                  = EEH_Debug_Tools::strip_objects($info);
1246
-                $info['TXN_status']    = $transaction->status_ID();
1247
-                $info['TXN_reg_steps'] = $transaction->reg_steps();
1248
-                if ($transaction->ID()) {
1249
-                    $index = 'EE_Transaction: ' . $transaction->ID();
1250
-                    EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1251
-                }
1252
-            }
1253
-        }
1254
-
1255
-    }
1256
-
1257
-
1258
-    /**
1259
-     *  Resets all the static properties in this class when called.
1260
-     */
1261
-    public static function reset()
1262
-    {
1263
-        self::$_EEMSG                    = null;
1264
-        self::$_message_resource_manager = null;
1265
-        self::$_MSG_PROCESSOR            = null;
1266
-        self::$_MSG_PATHS                = null;
1267
-        self::$_TMP_PACKS                = array();
1268
-    }
1103
+						'event_espresso'),
1104
+					__FILE__, __FUNCTION__, __LINE__
1105
+				);
1106
+			}
1107
+		}
1108
+		return $sent_queue;
1109
+	}
1110
+
1111
+
1112
+	/**
1113
+	 * Generate and send immediately from the given $message_ids
1114
+	 *
1115
+	 * @param array $message_ids EE_Message entity ids.
1116
+	 * @throws EE_Error
1117
+	 * @throws InvalidArgumentException
1118
+	 * @throws InvalidDataTypeException
1119
+	 * @throws InvalidInterfaceException
1120
+	 * @throws ReflectionException
1121
+	 */
1122
+	public static function generate_and_send_now(array $message_ids)
1123
+	{
1124
+		$generated_queue = self::generate_now($message_ids);
1125
+		//now let's just trigger sending immediately from this queue.
1126
+		$messages_sent = $generated_queue instanceof EE_Messages_Queue
1127
+			? $generated_queue->execute()
1128
+			: 0;
1129
+		if ($messages_sent) {
1130
+			EE_Error::add_success(
1131
+				esc_html(
1132
+					sprintf(
1133
+						_n(
1134
+							'There was %d message successfully generated and sent.',
1135
+							'There were %d messages successfully generated and sent.',
1136
+							$messages_sent,
1137
+							'event_espresso'
1138
+						),
1139
+						$messages_sent
1140
+					)
1141
+				)
1142
+			);
1143
+			//errors would be added via the generate_now method.
1144
+		}
1145
+	}
1146
+
1147
+
1148
+	/**
1149
+	 * This will queue the incoming message ids for resending.
1150
+	 * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
1151
+	 *
1152
+	 * @since 4.9.0
1153
+	 * @param array $message_ids An array of EE_Message IDs
1154
+	 * @return bool true means messages were successfully queued for resending, false means none were queued for
1155
+	 *                           resending.
1156
+	 * @throws EE_Error
1157
+	 * @throws InvalidArgumentException
1158
+	 * @throws InvalidDataTypeException
1159
+	 * @throws InvalidInterfaceException
1160
+	 * @throws ReflectionException
1161
+	 */
1162
+	public static function queue_for_resending($message_ids)
1163
+	{
1164
+		self::_load_controller();
1165
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1166
+
1167
+		//get queue and count
1168
+		$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1169
+
1170
+		if (
1171
+			$queue_count > 0
1172
+		) {
1173
+			EE_Error::add_success(
1174
+				sprintf(
1175
+					_n(
1176
+						'%d message successfully queued for resending.',
1177
+						'%d messages successfully queued for resending.',
1178
+						$queue_count,
1179
+						'event_espresso'
1180
+					),
1181
+					$queue_count
1182
+				)
1183
+			);
1184
+			/**
1185
+			 * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1186
+			 */
1187
+		} elseif (
1188
+			apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1189
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1190
+		) {
1191
+			$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1192
+			if ($queue_count > 0) {
1193
+				EE_Error::add_success(
1194
+					sprintf(
1195
+						_n(
1196
+							'%d message successfully sent.',
1197
+							'%d messages successfully sent.',
1198
+							$queue_count,
1199
+							'event_espresso'
1200
+						),
1201
+						$queue_count
1202
+					)
1203
+				);
1204
+			} else {
1205
+				EE_Error::add_error(
1206
+					__('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1207
+						'event_espresso'),
1208
+					__FILE__, __FUNCTION__, __LINE__
1209
+				);
1210
+			}
1211
+		} else {
1212
+			EE_Error::add_error(
1213
+				__('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1214
+					'event_espresso'),
1215
+				__FILE__, __FUNCTION__, __LINE__
1216
+			);
1217
+		}
1218
+		return (bool)$queue_count;
1219
+	}
1220
+
1221
+
1222
+	/**
1223
+	 * debug
1224
+	 *
1225
+	 * @param string          $class
1226
+	 * @param string          $func
1227
+	 * @param string          $line
1228
+	 * @param \EE_Transaction $transaction
1229
+	 * @param array           $info
1230
+	 * @param bool            $display_request
1231
+	 * @throws EE_Error
1232
+	 * @throws \EventEspresso\core\exceptions\InvalidSessionDataException
1233
+	 */
1234
+	protected static function log(
1235
+		$class = '',
1236
+		$func = '',
1237
+		$line = '',
1238
+		EE_Transaction $transaction,
1239
+		$info = array(),
1240
+		$display_request = false
1241
+	) {
1242
+		if (defined('EE_DEBUG') && EE_DEBUG) {
1243
+			if ($transaction instanceof EE_Transaction) {
1244
+				// don't serialize objects
1245
+				$info                  = EEH_Debug_Tools::strip_objects($info);
1246
+				$info['TXN_status']    = $transaction->status_ID();
1247
+				$info['TXN_reg_steps'] = $transaction->reg_steps();
1248
+				if ($transaction->ID()) {
1249
+					$index = 'EE_Transaction: ' . $transaction->ID();
1250
+					EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1251
+				}
1252
+			}
1253
+		}
1254
+
1255
+	}
1256
+
1257
+
1258
+	/**
1259
+	 *  Resets all the static properties in this class when called.
1260
+	 */
1261
+	public static function reset()
1262
+	{
1263
+		self::$_EEMSG                    = null;
1264
+		self::$_message_resource_manager = null;
1265
+		self::$_MSG_PROCESSOR            = null;
1266
+		self::$_MSG_PATHS                = null;
1267
+		self::$_TMP_PACKS                = array();
1268
+	}
1269 1269
 
1270 1270
 }
1271 1271
 // End of file EED_Messages.module.php
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
             $error_msg = __('Please note that a system message failed to send due to a technical issue.',
161 161
                 'event_espresso');
162 162
             // add specific message for developers if WP_DEBUG in on
163
-            $error_msg .= '||' . $e->getMessage();
163
+            $error_msg .= '||'.$e->getMessage();
164 164
             EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
165 165
         }
166 166
     }
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
             $error_msg = __('Please note that a system message failed to send due to a technical issue.',
244 244
                 'event_espresso');
245 245
             // add specific message for developers if WP_DEBUG in on
246
-            $error_msg .= '||' . $e->getMessage();
246
+            $error_msg .= '||'.$e->getMessage();
247 247
             EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
248 248
         }
249 249
     }
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
         $transient_key = EE_Registry::instance()->REQ->get('key');
275 275
 
276 276
         //now let's verify transient, if not valid exit immediately
277
-        if (! get_transient($transient_key)) {
277
+        if ( ! get_transient($transient_key)) {
278 278
             /**
279 279
              * trigger error so this gets in the error logs.  This is important because it happens on a non-user
280 280
              * request.
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
 
288 288
         if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
289 289
 
290
-            $method = 'batch_' . $cron_type . '_from_queue';
290
+            $method = 'batch_'.$cron_type.'_from_queue';
291 291
             if (method_exists(self::$_MSG_PROCESSOR, $method)) {
292 292
                 self::$_MSG_PROCESSOR->$method();
293 293
             } else {
@@ -396,9 +396,9 @@  discard block
 block discarded – undo
396 396
             'messages/validators/html',
397 397
             'shortcodes',
398 398
         );
399
-        $paths   = array();
399
+        $paths = array();
400 400
         foreach ($dir_ref as $index => $dir) {
401
-            $paths[$index] = EE_LIBRARIES . $dir;
401
+            $paths[$index] = EE_LIBRARIES.$dir;
402 402
         }
403 403
         self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
404 404
     }
@@ -417,7 +417,7 @@  discard block
 block discarded – undo
417 417
      */
418 418
     protected static function _load_controller()
419 419
     {
420
-        if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
420
+        if ( ! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
421 421
             EE_Registry::instance()->load_core('Request_Handler');
422 422
             self::set_autoloaders();
423 423
             self::$_EEMSG                    = EE_Registry::instance()->load_lib('messages');
@@ -458,7 +458,7 @@  discard block
 block discarded – undo
458 458
     public static function payment(EE_Transaction $transaction, EE_Payment $payment = null)
459 459
     {
460 460
         //if there's no payment object, then we cannot do a payment type message!
461
-        if (! $payment instanceof EE_Payment) {
461
+        if ( ! $payment instanceof EE_Payment) {
462 462
             return;
463 463
         }
464 464
         self::_load_controller();
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
     public static function maybe_registration(EE_Registration $registration, $extra_details = array())
507 507
     {
508 508
 
509
-        if (! self::_verify_registration_notification_send($registration, $extra_details)) {
509
+        if ( ! self::_verify_registration_notification_send($registration, $extra_details)) {
510 510
             //no messages please
511 511
             return;
512 512
         }
@@ -580,7 +580,7 @@  discard block
 block discarded – undo
580 580
         //	array( '$extra_details' => $extra_details )
581 581
         //);
582 582
         // currently only using this to send messages for the primary registrant
583
-        if (! $registration->is_primary_registrant()) {
583
+        if ( ! $registration->is_primary_registrant()) {
584 584
             return false;
585 585
         }
586 586
         // first we check if we're in admin and not doing front ajax
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
         } else {
594 594
             // frontend request (either regular or via AJAX)
595 595
             // TXN is NOT finalized ?
596
-            if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
596
+            if ( ! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
597 597
                 return false;
598 598
             }
599 599
             // return visit but nothing changed ???
@@ -683,12 +683,12 @@  discard block
 block discarded – undo
683 683
         }
684 684
 
685 685
         //make sure any incoming request data is set on the REQ so that it gets picked up later.
686
-        $req_data = (array)$req_data;
686
+        $req_data = (array) $req_data;
687 687
         foreach ($req_data as $request_key => $request_value) {
688 688
             EE_Registry::instance()->REQ->set($request_key, $request_value);
689 689
         }
690 690
 
691
-        if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request()) {
691
+        if ( ! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request()) {
692 692
             return false;
693 693
         }
694 694
 
@@ -721,13 +721,13 @@  discard block
 block discarded – undo
721 721
         self::_load_controller();
722 722
 
723 723
         $msgID = EE_Registry::instance()->REQ->get('MSG_ID');
724
-        if (! $msgID) {
724
+        if ( ! $msgID) {
725 725
             EE_Error::add_error(__('Something went wrong because there is no "MSG_ID" value in the request',
726 726
                 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
727 727
             return false;
728 728
         }
729 729
 
730
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array)$msgID);
730
+        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array) $msgID);
731 731
 
732 732
         //setup success message.
733 733
         $count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
@@ -832,7 +832,7 @@  discard block
 block discarded – undo
832 832
     public static function send_newsletter_message($registrations, $grp_id)
833 833
     {
834 834
         //make sure mtp is id and set it in the EE_Request Handler later messages setup.
835
-        EE_Registry::instance()->REQ->set('GRP_ID', (int)$grp_id);
835
+        EE_Registry::instance()->REQ->set('GRP_ID', (int) $grp_id);
836 836
         self::_load_controller();
837 837
         self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
838 838
     }
@@ -892,14 +892,14 @@  discard block
 block discarded – undo
892 892
             //get the message template group.
893 893
             $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
894 894
             //if we don't have an EE_Message_Template_Group then return
895
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
895
+            if ( ! $msg_template_group instanceof EE_Message_Template_Group) {
896 896
                 // remove EVT_ID from query params so that global templates get picked up
897 897
                 unset($template_query_params['Event.EVT_ID']);
898 898
                 //get global template as the fallback
899 899
                 $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
900 900
             }
901 901
             //if we don't have an EE_Message_Template_Group then return
902
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
902
+            if ( ! $msg_template_group instanceof EE_Message_Template_Group) {
903 903
                 return '';
904 904
             }
905 905
             // generate the URL
@@ -936,7 +936,7 @@  discard block
 block discarded – undo
936 936
     public static function preview_message($type, $context, $messenger, $send = false)
937 937
     {
938 938
         self::_load_controller();
939
-        $mtg                     = new EE_Message_To_Generate(
939
+        $mtg = new EE_Message_To_Generate(
940 940
             $messenger,
941 941
             $type,
942 942
             array(),
@@ -1018,7 +1018,7 @@  discard block
 block discarded – undo
1018 1018
     public static function generate_now($message_ids)
1019 1019
     {
1020 1020
         self::_load_controller();
1021
-        $messages        = EEM_Message::instance()->get_all(
1021
+        $messages = EEM_Message::instance()->get_all(
1022 1022
             array(
1023 1023
                 0 => array(
1024 1024
                     'MSG_ID' => array('IN', $message_ids),
@@ -1031,7 +1031,7 @@  discard block
 block discarded – undo
1031 1031
             $generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
1032 1032
         }
1033 1033
 
1034
-        if (! $generated_queue instanceof EE_Messages_Queue) {
1034
+        if ( ! $generated_queue instanceof EE_Messages_Queue) {
1035 1035
             EE_Error::add_error(
1036 1036
                 __('The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
1037 1037
                     'event_espresso'),
@@ -1058,7 +1058,7 @@  discard block
 block discarded – undo
1058 1058
     public static function send_now($message_ids)
1059 1059
     {
1060 1060
         self::_load_controller();
1061
-        $messages   = EEM_Message::instance()->get_all(
1061
+        $messages = EEM_Message::instance()->get_all(
1062 1062
             array(
1063 1063
                 0 => array(
1064 1064
                     'MSG_ID' => array('IN', $message_ids),
@@ -1074,7 +1074,7 @@  discard block
 block discarded – undo
1074 1074
             $sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
1075 1075
         }
1076 1076
 
1077
-        if (! $sent_queue instanceof EE_Messages_Queue) {
1077
+        if ( ! $sent_queue instanceof EE_Messages_Queue) {
1078 1078
             EE_Error::add_error(
1079 1079
                 __('The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
1080 1080
                     'event_espresso'),
@@ -1215,7 +1215,7 @@  discard block
 block discarded – undo
1215 1215
                 __FILE__, __FUNCTION__, __LINE__
1216 1216
             );
1217 1217
         }
1218
-        return (bool)$queue_count;
1218
+        return (bool) $queue_count;
1219 1219
     }
1220 1220
 
1221 1221
 
@@ -1246,7 +1246,7 @@  discard block
 block discarded – undo
1246 1246
                 $info['TXN_status']    = $transaction->status_ID();
1247 1247
                 $info['TXN_reg_steps'] = $transaction->reg_steps();
1248 1248
                 if ($transaction->ID()) {
1249
-                    $index = 'EE_Transaction: ' . $transaction->ID();
1249
+                    $index = 'EE_Transaction: '.$transaction->ID();
1250 1250
                     EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1251 1251
                 }
1252 1252
             }
Please login to merge, or discard this patch.
core/libraries/messages/validators/EE_Messages_Validator.core.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -505,7 +505,7 @@
 block discarded – undo
505 505
      *
506 506
      * @param  string $value            string to evaluate
507 507
      * @param  array  $valid_shortcodes array of shortcodes that are acceptable.
508
-     * @return mixed (bool|string)  return either a list of invalid shortcodes OR false if the shortcodes validate.
508
+     * @return false|string (bool|string)  return either a list of invalid shortcodes OR false if the shortcodes validate.
509 509
      */
510 510
     protected function _invalid_shortcodes($value, $valid_shortcodes)
511 511
     {
Please login to merge, or discard this patch.
Indentation   +626 added lines, -626 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3 3
 if (! defined('EVENT_ESPRESSO_VERSION')) {
4
-    exit('NO direct script access allowed');
4
+	exit('NO direct script access allowed');
5 5
 }
6 6
 
7 7
 /**
@@ -22,630 +22,630 @@  discard block
 block discarded – undo
22 22
 {
23 23
 
24 24
 
25
-    /**
26
-     * These properties just hold the name for the Messenger and Message Type (defined by child classes).
27
-     * These are used for retrieving objects etc.
28
-     *
29
-     * @var string
30
-     */
31
-    protected $_m_name;
32
-    protected $_mt_name;
33
-
34
-
35
-    /**
36
-     * This will hold any error messages from the validation process.
37
-     * The _errors property holds an associative array of error messages
38
-     * listing the field as the key and the message as the value.
39
-     *
40
-     * @var array()
41
-     */
42
-    private $_errors = array();
43
-
44
-
45
-    /**
46
-     * holds an array of fields being validated
47
-     *
48
-     * @var string
49
-     */
50
-    protected $_fields;
51
-
52
-
53
-    /**
54
-     * this will hold the incoming context
55
-     *
56
-     * @var string
57
-     */
58
-    protected $_context;
59
-
60
-
61
-    /**
62
-     * this holds an array of fields and the relevant validation information
63
-     * that the incoming fields data get validated against.
64
-     * This gets setup in the _set_props() method.
65
-     *
66
-     * @var array
67
-     */
68
-    protected $_validators;
69
-
70
-
71
-    /**
72
-     * holds the messenger object
73
-     *
74
-     * @var object
75
-     */
76
-    protected $_messenger;
77
-
78
-
79
-    /**
80
-     * holds the message type object
81
-     *
82
-     * @var object
83
-     */
84
-    protected $_message_type;
85
-
86
-
87
-    /**
88
-     * will hold any valid_shortcode modifications made by the _modify_validator() method.
89
-     *
90
-     * @var array
91
-     */
92
-    protected $_valid_shortcodes_modifier;
93
-
94
-
95
-    /**
96
-     * There may be times where a message type wants to include a shortcode group but exclude specific
97
-     * shortcodes.  If that's the case then it can set this property as an array of shortcodes to exclude and
98
-     * they will not be allowed.
99
-     * Array should be indexed by field and values are an array of specific shortcodes to exclude.
100
-     *
101
-     * @var array
102
-     */
103
-    protected $_specific_shortcode_excludes = array();
104
-
105
-
106
-    /**
107
-     * Runs the validator using the incoming fields array as the fields/values to check.
108
-     *
109
-     * @param array $fields The fields sent by the EEM object.
110
-     * @param       $context
111
-     * @throws \EE_Error
112
-     */
113
-    public function __construct($fields, $context)
114
-    {
115
-        //check that _m_name and _mt_name have been set by child class otherwise we get out.
116
-        if (empty($this->_m_name) || empty($this->_mt_name)) {
117
-            throw new EE_Error(
118
-                __(
119
-                    'EE_Messages_Validator child classes MUST set the $_m_name and $_mt_name property.  Check that the child class is doing this',
120
-                    'event_espresso'
121
-                )
122
-            );
123
-        }
124
-        $this->_fields  = $fields;
125
-        $this->_context = $context;
126
-
127
-        //load messenger and message_type objects and the related shortcode objects.
128
-        $this->_load_objects();
129
-
130
-
131
-        //modify any messenger/message_type specific validation instructions.  This is what child classes define.
132
-        $this->_modify_validator();
133
-
134
-
135
-        //let's set validators property
136
-        $this->_set_validators();
137
-    }
138
-
139
-
140
-    /**
141
-     * Child classes instantiate this and use it to modify the _validator_config array property
142
-     * for the messenger using messengers set_validate_config() method.
143
-     * This is so we can specify specific validation instructions for a messenger/message_type combo
144
-     * that aren't handled by the defaults setup in the messenger.
145
-     *
146
-     * @abstract
147
-     * @access protected
148
-     * @return void
149
-     */
150
-    abstract protected function _modify_validator();
151
-
152
-
153
-    /**
154
-     * loads all objects used by validator
155
-     *
156
-     * @access private
157
-     * @throws \EE_Error
158
-     */
159
-    private function _load_objects()
160
-    {
161
-        //load messenger
162
-        $messenger = ucwords(str_replace('_', ' ', $this->_m_name));
163
-        $messenger = str_replace(' ', '_', $messenger);
164
-        $messenger = 'EE_' . $messenger . '_messenger';
165
-
166
-        if (! class_exists($messenger)) {
167
-            throw new EE_Error(
168
-                sprintf(
169
-                    __('There is no messenger class for the given string (%s)', 'event_espresso'),
170
-                    $this->_m_name
171
-                )
172
-            );
173
-        }
174
-
175
-        $this->_messenger = new $messenger();
176
-
177
-        //load message type
178
-        $message_type = ucwords(str_replace('_', ' ', $this->_mt_name));
179
-        $message_type = str_replace(' ', '_', $message_type);
180
-        $message_type = 'EE_' . $message_type . '_message_type';
181
-
182
-        if (! class_exists($message_type)) {
183
-            throw new EE_Error(
184
-                sprintf(
185
-                    __('There is no message type class for the given string (%s)', 'event_espresso'),
186
-                    $this->_mt_name
187
-                )
188
-            );
189
-        }
190
-
191
-        $this->_message_type = new $message_type();
192
-
193
-    }
194
-
195
-
196
-    /**
197
-     * used to set the $_validators property
198
-     *
199
-     * @access private
200
-     * @return void
201
-     */
202
-    private function _set_validators()
203
-    {
204
-        // let's get all valid shortcodes from mt and message type
205
-        // (messenger will have its set in the _validator_config property for the messenger)
206
-        $mt_codes = $this->_message_type->get_valid_shortcodes();
207
-
208
-
209
-        //get messenger validator_config
210
-        $msgr_validator = $this->_messenger->get_validator_config();
211
-
212
-
213
-        //we only want the valid shortcodes for the given context!
214
-        $context  = $this->_context;
215
-        $mt_codes = $mt_codes[$context];
216
-
217
-        // in this first loop we're just getting all shortcode group indexes from the msgr_validator
218
-        // into a single array (so we can get the appropriate shortcode objects for the groups)
219
-        $shortcode_groups = $mt_codes;
220
-        $groups_per_field = array();
221
-
222
-        foreach ($msgr_validator as $field => $config) {
223
-            if (empty($config) || ! isset($config['shortcodes'])) {
224
-                continue;
225
-            }  //Nothing to see here.
226
-            $groups_per_field[$field] = array_intersect($config['shortcodes'], $mt_codes);
227
-            $shortcode_groups         = array_merge($config['shortcodes'], $shortcode_groups);
228
-        }
229
-
230
-        $shortcode_groups = array_unique($shortcode_groups);
231
-
232
-        // okay now we've got our groups.
233
-        // Let's get the codes from the objects into an array indexed by group for easy retrieval later.
234
-        $codes_from_objs = array();
235
-
236
-        foreach ($shortcode_groups as $group) {
237
-            $ref       = ucwords(str_replace('_', ' ', $group));
238
-            $ref       = str_replace(' ', '_', $ref);
239
-            $classname = 'EE_' . $ref . '_Shortcodes';
240
-            if (class_exists($classname)) {
241
-                $a                       = new ReflectionClass($classname);
242
-                $obj                     = $a->newInstance();
243
-                $codes_from_objs[$group] = $obj->get_shortcodes();
244
-            }
245
-        }
246
-
247
-
248
-        //let's just replace the $mt shortcode group indexes with the actual shortcodes (unique)
249
-        $final_mt_codes = array();
250
-        foreach ($mt_codes as $group) {
251
-            $final_mt_codes = array_merge($final_mt_codes, $codes_from_objs[$group]);
252
-        }
253
-
254
-        $mt_codes = $final_mt_codes;
255
-
256
-
257
-        // k now in this next loop we're going to loop through $msgr_validator again
258
-        // and setup the _validators property from the data we've setup so far.
259
-        foreach ($msgr_validator as $field => $config) {
260
-            //if required shortcode is not in our list of codes for the given field, then we skip this field.
261
-            $required = isset($config['required'])
262
-                ? array_intersect($config['required'], array_keys($mt_codes))
263
-                : true;
264
-            if (empty($required)) {
265
-                continue;
266
-            }
267
-
268
-            //If we have an override then we use it to indicate the codes we want.
269
-            if (isset($this->_valid_shortcodes_modifier[$context][$field])) {
270
-                $this->_validators[$field]['shortcodes'] = $this->_reassemble_valid_shortcodes_from_group(
271
-                    $this->_valid_shortcodes_modifier[$context][$field],
272
-                    $codes_from_objs
273
-                );
274
-            } //if we have specific shortcodes for a field then we need to use them
275
-            else if (isset($groups_per_field[$field])) {
276
-                $this->_validators[$field]['shortcodes'] = $this->_reassemble_valid_shortcodes_from_group(
277
-                    $groups_per_field[$field],
278
-                    $codes_from_objs
279
-                );
280
-            } //if empty config then we're assuming we're just going to use the shortcodes from the message type context
281
-            else if (empty($config)) {
282
-                $this->_validators[$field]['shortcodes'] = $mt_codes;
283
-            } //if we have specific shortcodes then we need to use them
284
-            else if (isset($config['specific_shortcodes'])) {
285
-                $this->_validators[$field]['shortcodes'] = $config['specific_shortcodes'];
286
-            } //otherwise the shortcodes are what is set by the messenger for that field
287
-            else {
288
-                foreach ($config['shortcodes'] as $group) {
289
-                    $this->_validators[$field]['shortcodes'] = isset($this->_validators[$field]['shortcodes'])
290
-                        ? array_merge($this->_validators[$field]['shortcodes'], $codes_from_objs[$group])
291
-                        : $codes_from_objs[$group];
292
-                }
293
-            }
294
-
295
-            //now let's just make sure that any excluded specific shortcodes are removed.
296
-            $specific_excludes = $this->get_specific_shortcode_excludes();
297
-            if (isset($specific_excludes[$field])) {
298
-                foreach ($specific_excludes[$field] as $sex) {
299
-                    if (isset($this->_validators[$field]['shortcodes'][$sex])) {
300
-                        unset($this->_validators[$field]['shortcodes'][$sex]);
301
-                    }
302
-                }
303
-            }
304
-
305
-            //hey! don't forget to include the type if present!
306
-            $this->_validators[$field]['type'] = isset($config['type']) ? $config['type'] : null;
307
-        }
308
-    }
309
-
310
-
311
-    /**
312
-     * This just returns the validators property that contains information
313
-     * about the various shortcodes and their availability with each field
314
-     *
315
-     * @return array
316
-     */
317
-    public function get_validators()
318
-    {
319
-        return $this->_validators;
320
-    }
321
-
322
-
323
-    /**
324
-     * This simply returns the specific shortcode_excludes property that is set.
325
-     *
326
-     * @since 4.5.0
327
-     * @return array
328
-     */
329
-    public function get_specific_shortcode_excludes()
330
-    {
331
-        //specific validator filter
332
-        $shortcode_excludes = apply_filters(
333
-            'FHEE__' . get_class($this) . '__get_specific_shortcode_excludes;',
334
-            $this->_specific_shortcode_excludes,
335
-            $this->_context
336
-        );
337
-        //global filter
338
-        return apply_filters(
339
-            'FHEE__EE_Messages_Validator__get_specific_shortcode_excludes',
340
-            $shortcode_excludes,
341
-            $this->_context,
342
-            $this
343
-        );
344
-    }
345
-
346
-
347
-    /**
348
-     * This is the main method that handles validation
349
-     * What it does is loop through the _fields (the ones that get validated)
350
-     * and checks them against the shortcodes array for the field and the 'type' indicated by the
351
-     *
352
-     * @access public
353
-     * @return mixed (bool|array)  if errors present we return the array otherwise true
354
-     */
355
-    public function validate()
356
-    {
357
-        //some defaults
358
-        $template_fields = $this->_messenger->get_template_fields();
359
-        //loop through the fields and check!
360
-        foreach ($this->_fields as $field => $value) {
361
-            $this->_errors[$field] = array();
362
-            $err_msg               = '';
363
-            $field_label           = '';
364
-            //if field is not present in the _validators array then we continue
365
-            if (! isset($this->_validators[$field])) {
366
-                unset($this->_errors[$field]);
367
-                continue;
368
-            }
369
-
370
-            //get the translated field label!
371
-            //first check if it's in the main fields list
372
-            if (isset($template_fields[$field])) {
373
-                if (empty($template_fields[$field])) {
374
-                    $field_label = $field;
375
-                } //most likely the field is found in the 'extra' array.
376
-                else {
377
-                    $field_label = $template_fields[$field]['label'];
378
-                }
379
-            }
380
-
381
-            // if field label is empty OR is equal to the current field
382
-            // then we need to loop through the 'extra' fields in the template_fields config (if present)
383
-            if (isset($template_fields['extra']) && (empty($field_label)) || $field_label == $field) {
384
-                foreach ($template_fields['extra'] as $main_field => $secondary_field) {
385
-                    foreach ($secondary_field as $name => $values) {
386
-                        if ($name == $field) {
387
-                            $field_label = $values['label'];
388
-                        }
389
-
390
-                        // if we've got a 'main' secondary field, let's see if that matches what field we're on
391
-                        // which means it contains the label for this field.
392
-                        if ($name == 'main' && $main_field == $field_label) {
393
-                            $field_label = $values['label'];
394
-                        }
395
-                    }
396
-                }
397
-            }
398
-
399
-            //field is present. Let's validate shortcodes first (but only if shortcodes present).
400
-            if (
401
-                isset($this->_validators[$field]['shortcodes'])
402
-                && ! empty($this->_validators[$field]['shortcodes'])
403
-            ) {
404
-                $invalid_shortcodes = $this->_invalid_shortcodes($value, $this->_validators[$field]['shortcodes']);
405
-                // if true then that means there is a returned error message
406
-                // that we'll need to add to the _errors array for this field.
407
-                if ($invalid_shortcodes) {
408
-                    $v_s     = array_keys($this->_validators[$field]['shortcodes']);
409
-                    $err_msg = sprintf(
410
-                        __(
411
-                            '%3$sThe following shortcodes were found in the "%1$s" field that ARE not valid: %2$s%4$s',
412
-                            'event_espresso'
413
-                        ),
414
-                        '<strong>' . $field_label . '</strong>',
415
-                        $invalid_shortcodes,
416
-                        '<p>',
417
-                        '</p >'
418
-                    );
419
-                    $err_msg .= sprintf(
420
-                        __('%2$sValid shortcodes for this field are: %1$s%3$s', 'event_espresso'),
421
-                        implode(', ', $v_s),
422
-                        '<strong>',
423
-                        '</strong>'
424
-                    );
425
-                }
426
-            }
427
-
428
-            //if there's a "type" to be validated then let's do that too.
429
-            if (isset($this->_validators[$field]['type']) && ! empty($this->_validators[$field]['type'])) {
430
-                switch ($this->_validators[$field]['type']) {
431
-                    case 'number' :
432
-                        if (! is_numeric($value)) {
433
-                            $err_msg .= sprintf(
434
-                                __(
435
-                                    '%3$sThe %1$s field is supposed to be a number. The value given (%2$s)  is not.  Please double-check and make sure the field contains a number%4$s',
436
-                                    'event_espresso'
437
-                                ),
438
-                                $field_label,
439
-                                $value,
440
-                                '<p>',
441
-                                '</p >'
442
-                            );
443
-                        }
444
-                        break;
445
-                    case 'email' :
446
-                        $valid_email = $this->_validate_email($value);
447
-                        if (! $valid_email) {
448
-                            $err_msg .= htmlentities(
449
-                                sprintf(
450
-                                    __(
451
-                                        'The %1$s field has at least one string that is not a valid email address record.  Valid emails are in the format: "Name <[email protected]>" or "[email protected]" and multiple emails can be separated by a comma.'
452
-                                    ),
453
-                                    $field_label
454
-
455
-                                )
456
-                            );
457
-                        }
458
-                        break;
459
-                    default :
460
-                        break;
461
-                }
462
-            }
463
-
464
-            //if $err_msg isn't empty let's setup the _errors array for this field.
465
-            if (! empty($err_msg)) {
466
-                $this->_errors[$field]['msg'] = $err_msg;
467
-            } else {
468
-                unset($this->_errors[$field]);
469
-            }
470
-        }
471
-
472
-        // if we have ANY errors, then we want to make sure we return the values
473
-        // for ALL the fields so the user doesn't have to retype them all.
474
-        if (! empty($this->_errors)) {
475
-            foreach ($this->_fields as $field => $value) {
476
-                $this->_errors[$field]['value'] = stripslashes($value);
477
-            }
478
-        }
479
-
480
-        //return any errors or just TRUE if everything validates
481
-        return empty($this->_errors) ? true : $this->_errors;
482
-    }
483
-
484
-
485
-    /**
486
-     * Reassembles and returns an array of valid shortcodes
487
-     * given the array of groups and array of shortcodes indexed by group.
488
-     *
489
-     * @param  array $groups          array of shortcode groups that we want shortcodes for
490
-     * @param  array $codes_from_objs All the codes available.
491
-     * @return array                   an array of actual shortcodes (that will be used for validation).
492
-     */
493
-    private function _reassemble_valid_shortcodes_from_group($groups, $codes_from_objs)
494
-    {
495
-        $shortcodes = array();
496
-        foreach ($groups as $group) {
497
-            $shortcodes = array_merge($shortcodes, $codes_from_objs[$group]);
498
-        }
499
-        return $shortcodes;
500
-    }
501
-
502
-
503
-    /**
504
-     * Validates a string against a list of accepted shortcodes
505
-     * This function takes in an array of shortcodes
506
-     * and makes sure that the given string ONLY contains shortcodes in that array.
507
-     *
508
-     * @param  string $value            string to evaluate
509
-     * @param  array  $valid_shortcodes array of shortcodes that are acceptable.
510
-     * @return mixed (bool|string)  return either a list of invalid shortcodes OR false if the shortcodes validate.
511
-     */
512
-    protected function _invalid_shortcodes($value, $valid_shortcodes)
513
-    {
514
-        //first we need to go through the string and get the shortcodes in the string
515
-        preg_match_all('/(\[.+?\])/', $value, $matches);
516
-        $incoming_shortcodes = (array)$matches[0];
517
-
518
-        //get a diff of the shortcodes in the string vs the valid shortcodes
519
-        $diff = array_diff($incoming_shortcodes, array_keys($valid_shortcodes));
520
-
521
-        //we need to account for custom codes so let's loop through the diff and remove any of those type of codes
522
-        foreach ($diff as $ind => $code) {
523
-            if (preg_match('/(\[[A-Za-z0-9\_]+_\*)/', $code)) {
524
-                //strip the shortcode so we just have the BASE string (i.e. [ANSWER_*] )
525
-                $dynamic_sc = preg_replace('/(_\*+.+)/', '_*]', $code);
526
-                //does this exist in the $valid_shortcodes?  If so then unset.
527
-                if (isset($valid_shortcodes[$dynamic_sc])) {
528
-                    unset($diff[$ind]);
529
-                }
530
-            }
531
-        }
532
-
533
-        if (empty($diff)) {
534
-            return false;
535
-        } //there is no diff, we have no invalid shortcodes, so return
536
-
537
-        //made it here? then let's assemble the error message
538
-        $invalid_shortcodes = implode('</strong>,<strong>', $diff);
539
-        $invalid_shortcodes = '<strong>' . $invalid_shortcodes . '</strong>';
540
-        return $invalid_shortcodes;
541
-    }
542
-
543
-
544
-    /**
545
-     * Validates an incoming string and makes sure we have valid emails in the string.
546
-     *
547
-     * @param  string $value incoming value to validate
548
-     * @return bool        true if the string validates, false if it doesn't
549
-     */
550
-    protected function _validate_email($value)
551
-    {
552
-        $validate = true;
553
-        $or_val   = $value;
554
-
555
-        // empty strings will validate because this is how a message template
556
-        // for a particular context can be "turned off" (if there is no email then no message)
557
-        if (empty($value)) {
558
-            return $validate;
559
-        }
560
-
561
-        // first determine if there ARE any shortcodes.
562
-        // If there are shortcodes and then later we find that there were no other valid emails
563
-        // but the field isn't empty...
564
-        // that means we've got extra commas that were left after stripping out shortcodes so probably still valid.
565
-        $has_shortcodes = preg_match('/(\[.+?\])/', $value);
566
-
567
-        //first we need to strip out all the shortcodes!
568
-        $value = preg_replace('/(\[.+?\])/', '', $value);
569
-
570
-        // if original value is not empty and new value is, then we've parsed out a shortcode
571
-        // and we now have an empty string which DOES validate.
572
-        // We also validate complete empty field for email because
573
-        // its possible that this message is being "turned off" for a particular context
574
-
575
-
576
-        if (! empty($or_val) && empty($value)) {
577
-            return $validate;
578
-        }
579
-
580
-        //trim any commas from beginning and end of string ( after whitespace trimmed );
581
-        $value = trim(trim($value), ',');
582
-
583
-
584
-        //next we need to split up the string if its comma delimited.
585
-        $emails = explode(',', $value);
586
-        $empty  = false; //used to indicate that there is an empty comma.
587
-        //now let's loop through the emails and do our checks
588
-        foreach ($emails as $email) {
589
-            if (empty($email)) {
590
-                $empty = true;
591
-                continue;
592
-            }
593
-
594
-            //trim whitespace
595
-            $email = trim($email);
596
-            //either its of type "[email protected]", or its of type "fname lname <[email protected]>"
597
-            if (is_email($email)) {
598
-                continue;
599
-            } else {
600
-                $matches  = array();
601
-                $validate = preg_match('/(.*)<(.+)>/', $email, $matches) ? true : false;
602
-                if ($validate && is_email($matches[2])) {
603
-                    continue;
604
-                } else {
605
-                    return false;
606
-                }
607
-            }
608
-        }
609
-
610
-        $validate = $empty && ! $has_shortcodes ? false : $validate;
611
-
612
-        return $validate;
613
-
614
-    }
615
-
616
-
617
-    /**
618
-     * Magic getter
619
-     * Using this to provide back compat with add-ons referencing deprecated properties.
620
-     *
621
-     * @param string $property Property being requested
622
-     * @throws Exception
623
-     * @return mixed
624
-     */
625
-    public function __get($property)
626
-    {
627
-        $expected_properties_map = array(
628
-            /**
629
-             * @deprecated 4.9.0
630
-             */
631
-            '_MSGR'   => '_messenger',
632
-            /**
633
-             * @deprecated 4.9.0
634
-             */
635
-            '_MSGTYP' => '_message_type',
636
-        );
637
-
638
-        if (isset($expected_properties_map[$property])) {
639
-            return $this->{$expected_properties_map[$property]};
640
-        }
641
-
642
-        throw new Exception(
643
-            sprintf(
644
-                __('The property %1$s being requested on %2$s does not exist', 'event_espresso'),
645
-                $property,
646
-                get_class($this)
647
-            )
648
-        );
649
-    }
25
+	/**
26
+	 * These properties just hold the name for the Messenger and Message Type (defined by child classes).
27
+	 * These are used for retrieving objects etc.
28
+	 *
29
+	 * @var string
30
+	 */
31
+	protected $_m_name;
32
+	protected $_mt_name;
33
+
34
+
35
+	/**
36
+	 * This will hold any error messages from the validation process.
37
+	 * The _errors property holds an associative array of error messages
38
+	 * listing the field as the key and the message as the value.
39
+	 *
40
+	 * @var array()
41
+	 */
42
+	private $_errors = array();
43
+
44
+
45
+	/**
46
+	 * holds an array of fields being validated
47
+	 *
48
+	 * @var string
49
+	 */
50
+	protected $_fields;
51
+
52
+
53
+	/**
54
+	 * this will hold the incoming context
55
+	 *
56
+	 * @var string
57
+	 */
58
+	protected $_context;
59
+
60
+
61
+	/**
62
+	 * this holds an array of fields and the relevant validation information
63
+	 * that the incoming fields data get validated against.
64
+	 * This gets setup in the _set_props() method.
65
+	 *
66
+	 * @var array
67
+	 */
68
+	protected $_validators;
69
+
70
+
71
+	/**
72
+	 * holds the messenger object
73
+	 *
74
+	 * @var object
75
+	 */
76
+	protected $_messenger;
77
+
78
+
79
+	/**
80
+	 * holds the message type object
81
+	 *
82
+	 * @var object
83
+	 */
84
+	protected $_message_type;
85
+
86
+
87
+	/**
88
+	 * will hold any valid_shortcode modifications made by the _modify_validator() method.
89
+	 *
90
+	 * @var array
91
+	 */
92
+	protected $_valid_shortcodes_modifier;
93
+
94
+
95
+	/**
96
+	 * There may be times where a message type wants to include a shortcode group but exclude specific
97
+	 * shortcodes.  If that's the case then it can set this property as an array of shortcodes to exclude and
98
+	 * they will not be allowed.
99
+	 * Array should be indexed by field and values are an array of specific shortcodes to exclude.
100
+	 *
101
+	 * @var array
102
+	 */
103
+	protected $_specific_shortcode_excludes = array();
104
+
105
+
106
+	/**
107
+	 * Runs the validator using the incoming fields array as the fields/values to check.
108
+	 *
109
+	 * @param array $fields The fields sent by the EEM object.
110
+	 * @param       $context
111
+	 * @throws \EE_Error
112
+	 */
113
+	public function __construct($fields, $context)
114
+	{
115
+		//check that _m_name and _mt_name have been set by child class otherwise we get out.
116
+		if (empty($this->_m_name) || empty($this->_mt_name)) {
117
+			throw new EE_Error(
118
+				__(
119
+					'EE_Messages_Validator child classes MUST set the $_m_name and $_mt_name property.  Check that the child class is doing this',
120
+					'event_espresso'
121
+				)
122
+			);
123
+		}
124
+		$this->_fields  = $fields;
125
+		$this->_context = $context;
126
+
127
+		//load messenger and message_type objects and the related shortcode objects.
128
+		$this->_load_objects();
129
+
130
+
131
+		//modify any messenger/message_type specific validation instructions.  This is what child classes define.
132
+		$this->_modify_validator();
133
+
134
+
135
+		//let's set validators property
136
+		$this->_set_validators();
137
+	}
138
+
139
+
140
+	/**
141
+	 * Child classes instantiate this and use it to modify the _validator_config array property
142
+	 * for the messenger using messengers set_validate_config() method.
143
+	 * This is so we can specify specific validation instructions for a messenger/message_type combo
144
+	 * that aren't handled by the defaults setup in the messenger.
145
+	 *
146
+	 * @abstract
147
+	 * @access protected
148
+	 * @return void
149
+	 */
150
+	abstract protected function _modify_validator();
151
+
152
+
153
+	/**
154
+	 * loads all objects used by validator
155
+	 *
156
+	 * @access private
157
+	 * @throws \EE_Error
158
+	 */
159
+	private function _load_objects()
160
+	{
161
+		//load messenger
162
+		$messenger = ucwords(str_replace('_', ' ', $this->_m_name));
163
+		$messenger = str_replace(' ', '_', $messenger);
164
+		$messenger = 'EE_' . $messenger . '_messenger';
165
+
166
+		if (! class_exists($messenger)) {
167
+			throw new EE_Error(
168
+				sprintf(
169
+					__('There is no messenger class for the given string (%s)', 'event_espresso'),
170
+					$this->_m_name
171
+				)
172
+			);
173
+		}
174
+
175
+		$this->_messenger = new $messenger();
176
+
177
+		//load message type
178
+		$message_type = ucwords(str_replace('_', ' ', $this->_mt_name));
179
+		$message_type = str_replace(' ', '_', $message_type);
180
+		$message_type = 'EE_' . $message_type . '_message_type';
181
+
182
+		if (! class_exists($message_type)) {
183
+			throw new EE_Error(
184
+				sprintf(
185
+					__('There is no message type class for the given string (%s)', 'event_espresso'),
186
+					$this->_mt_name
187
+				)
188
+			);
189
+		}
190
+
191
+		$this->_message_type = new $message_type();
192
+
193
+	}
194
+
195
+
196
+	/**
197
+	 * used to set the $_validators property
198
+	 *
199
+	 * @access private
200
+	 * @return void
201
+	 */
202
+	private function _set_validators()
203
+	{
204
+		// let's get all valid shortcodes from mt and message type
205
+		// (messenger will have its set in the _validator_config property for the messenger)
206
+		$mt_codes = $this->_message_type->get_valid_shortcodes();
207
+
208
+
209
+		//get messenger validator_config
210
+		$msgr_validator = $this->_messenger->get_validator_config();
211
+
212
+
213
+		//we only want the valid shortcodes for the given context!
214
+		$context  = $this->_context;
215
+		$mt_codes = $mt_codes[$context];
216
+
217
+		// in this first loop we're just getting all shortcode group indexes from the msgr_validator
218
+		// into a single array (so we can get the appropriate shortcode objects for the groups)
219
+		$shortcode_groups = $mt_codes;
220
+		$groups_per_field = array();
221
+
222
+		foreach ($msgr_validator as $field => $config) {
223
+			if (empty($config) || ! isset($config['shortcodes'])) {
224
+				continue;
225
+			}  //Nothing to see here.
226
+			$groups_per_field[$field] = array_intersect($config['shortcodes'], $mt_codes);
227
+			$shortcode_groups         = array_merge($config['shortcodes'], $shortcode_groups);
228
+		}
229
+
230
+		$shortcode_groups = array_unique($shortcode_groups);
231
+
232
+		// okay now we've got our groups.
233
+		// Let's get the codes from the objects into an array indexed by group for easy retrieval later.
234
+		$codes_from_objs = array();
235
+
236
+		foreach ($shortcode_groups as $group) {
237
+			$ref       = ucwords(str_replace('_', ' ', $group));
238
+			$ref       = str_replace(' ', '_', $ref);
239
+			$classname = 'EE_' . $ref . '_Shortcodes';
240
+			if (class_exists($classname)) {
241
+				$a                       = new ReflectionClass($classname);
242
+				$obj                     = $a->newInstance();
243
+				$codes_from_objs[$group] = $obj->get_shortcodes();
244
+			}
245
+		}
246
+
247
+
248
+		//let's just replace the $mt shortcode group indexes with the actual shortcodes (unique)
249
+		$final_mt_codes = array();
250
+		foreach ($mt_codes as $group) {
251
+			$final_mt_codes = array_merge($final_mt_codes, $codes_from_objs[$group]);
252
+		}
253
+
254
+		$mt_codes = $final_mt_codes;
255
+
256
+
257
+		// k now in this next loop we're going to loop through $msgr_validator again
258
+		// and setup the _validators property from the data we've setup so far.
259
+		foreach ($msgr_validator as $field => $config) {
260
+			//if required shortcode is not in our list of codes for the given field, then we skip this field.
261
+			$required = isset($config['required'])
262
+				? array_intersect($config['required'], array_keys($mt_codes))
263
+				: true;
264
+			if (empty($required)) {
265
+				continue;
266
+			}
267
+
268
+			//If we have an override then we use it to indicate the codes we want.
269
+			if (isset($this->_valid_shortcodes_modifier[$context][$field])) {
270
+				$this->_validators[$field]['shortcodes'] = $this->_reassemble_valid_shortcodes_from_group(
271
+					$this->_valid_shortcodes_modifier[$context][$field],
272
+					$codes_from_objs
273
+				);
274
+			} //if we have specific shortcodes for a field then we need to use them
275
+			else if (isset($groups_per_field[$field])) {
276
+				$this->_validators[$field]['shortcodes'] = $this->_reassemble_valid_shortcodes_from_group(
277
+					$groups_per_field[$field],
278
+					$codes_from_objs
279
+				);
280
+			} //if empty config then we're assuming we're just going to use the shortcodes from the message type context
281
+			else if (empty($config)) {
282
+				$this->_validators[$field]['shortcodes'] = $mt_codes;
283
+			} //if we have specific shortcodes then we need to use them
284
+			else if (isset($config['specific_shortcodes'])) {
285
+				$this->_validators[$field]['shortcodes'] = $config['specific_shortcodes'];
286
+			} //otherwise the shortcodes are what is set by the messenger for that field
287
+			else {
288
+				foreach ($config['shortcodes'] as $group) {
289
+					$this->_validators[$field]['shortcodes'] = isset($this->_validators[$field]['shortcodes'])
290
+						? array_merge($this->_validators[$field]['shortcodes'], $codes_from_objs[$group])
291
+						: $codes_from_objs[$group];
292
+				}
293
+			}
294
+
295
+			//now let's just make sure that any excluded specific shortcodes are removed.
296
+			$specific_excludes = $this->get_specific_shortcode_excludes();
297
+			if (isset($specific_excludes[$field])) {
298
+				foreach ($specific_excludes[$field] as $sex) {
299
+					if (isset($this->_validators[$field]['shortcodes'][$sex])) {
300
+						unset($this->_validators[$field]['shortcodes'][$sex]);
301
+					}
302
+				}
303
+			}
304
+
305
+			//hey! don't forget to include the type if present!
306
+			$this->_validators[$field]['type'] = isset($config['type']) ? $config['type'] : null;
307
+		}
308
+	}
309
+
310
+
311
+	/**
312
+	 * This just returns the validators property that contains information
313
+	 * about the various shortcodes and their availability with each field
314
+	 *
315
+	 * @return array
316
+	 */
317
+	public function get_validators()
318
+	{
319
+		return $this->_validators;
320
+	}
321
+
322
+
323
+	/**
324
+	 * This simply returns the specific shortcode_excludes property that is set.
325
+	 *
326
+	 * @since 4.5.0
327
+	 * @return array
328
+	 */
329
+	public function get_specific_shortcode_excludes()
330
+	{
331
+		//specific validator filter
332
+		$shortcode_excludes = apply_filters(
333
+			'FHEE__' . get_class($this) . '__get_specific_shortcode_excludes;',
334
+			$this->_specific_shortcode_excludes,
335
+			$this->_context
336
+		);
337
+		//global filter
338
+		return apply_filters(
339
+			'FHEE__EE_Messages_Validator__get_specific_shortcode_excludes',
340
+			$shortcode_excludes,
341
+			$this->_context,
342
+			$this
343
+		);
344
+	}
345
+
346
+
347
+	/**
348
+	 * This is the main method that handles validation
349
+	 * What it does is loop through the _fields (the ones that get validated)
350
+	 * and checks them against the shortcodes array for the field and the 'type' indicated by the
351
+	 *
352
+	 * @access public
353
+	 * @return mixed (bool|array)  if errors present we return the array otherwise true
354
+	 */
355
+	public function validate()
356
+	{
357
+		//some defaults
358
+		$template_fields = $this->_messenger->get_template_fields();
359
+		//loop through the fields and check!
360
+		foreach ($this->_fields as $field => $value) {
361
+			$this->_errors[$field] = array();
362
+			$err_msg               = '';
363
+			$field_label           = '';
364
+			//if field is not present in the _validators array then we continue
365
+			if (! isset($this->_validators[$field])) {
366
+				unset($this->_errors[$field]);
367
+				continue;
368
+			}
369
+
370
+			//get the translated field label!
371
+			//first check if it's in the main fields list
372
+			if (isset($template_fields[$field])) {
373
+				if (empty($template_fields[$field])) {
374
+					$field_label = $field;
375
+				} //most likely the field is found in the 'extra' array.
376
+				else {
377
+					$field_label = $template_fields[$field]['label'];
378
+				}
379
+			}
380
+
381
+			// if field label is empty OR is equal to the current field
382
+			// then we need to loop through the 'extra' fields in the template_fields config (if present)
383
+			if (isset($template_fields['extra']) && (empty($field_label)) || $field_label == $field) {
384
+				foreach ($template_fields['extra'] as $main_field => $secondary_field) {
385
+					foreach ($secondary_field as $name => $values) {
386
+						if ($name == $field) {
387
+							$field_label = $values['label'];
388
+						}
389
+
390
+						// if we've got a 'main' secondary field, let's see if that matches what field we're on
391
+						// which means it contains the label for this field.
392
+						if ($name == 'main' && $main_field == $field_label) {
393
+							$field_label = $values['label'];
394
+						}
395
+					}
396
+				}
397
+			}
398
+
399
+			//field is present. Let's validate shortcodes first (but only if shortcodes present).
400
+			if (
401
+				isset($this->_validators[$field]['shortcodes'])
402
+				&& ! empty($this->_validators[$field]['shortcodes'])
403
+			) {
404
+				$invalid_shortcodes = $this->_invalid_shortcodes($value, $this->_validators[$field]['shortcodes']);
405
+				// if true then that means there is a returned error message
406
+				// that we'll need to add to the _errors array for this field.
407
+				if ($invalid_shortcodes) {
408
+					$v_s     = array_keys($this->_validators[$field]['shortcodes']);
409
+					$err_msg = sprintf(
410
+						__(
411
+							'%3$sThe following shortcodes were found in the "%1$s" field that ARE not valid: %2$s%4$s',
412
+							'event_espresso'
413
+						),
414
+						'<strong>' . $field_label . '</strong>',
415
+						$invalid_shortcodes,
416
+						'<p>',
417
+						'</p >'
418
+					);
419
+					$err_msg .= sprintf(
420
+						__('%2$sValid shortcodes for this field are: %1$s%3$s', 'event_espresso'),
421
+						implode(', ', $v_s),
422
+						'<strong>',
423
+						'</strong>'
424
+					);
425
+				}
426
+			}
427
+
428
+			//if there's a "type" to be validated then let's do that too.
429
+			if (isset($this->_validators[$field]['type']) && ! empty($this->_validators[$field]['type'])) {
430
+				switch ($this->_validators[$field]['type']) {
431
+					case 'number' :
432
+						if (! is_numeric($value)) {
433
+							$err_msg .= sprintf(
434
+								__(
435
+									'%3$sThe %1$s field is supposed to be a number. The value given (%2$s)  is not.  Please double-check and make sure the field contains a number%4$s',
436
+									'event_espresso'
437
+								),
438
+								$field_label,
439
+								$value,
440
+								'<p>',
441
+								'</p >'
442
+							);
443
+						}
444
+						break;
445
+					case 'email' :
446
+						$valid_email = $this->_validate_email($value);
447
+						if (! $valid_email) {
448
+							$err_msg .= htmlentities(
449
+								sprintf(
450
+									__(
451
+										'The %1$s field has at least one string that is not a valid email address record.  Valid emails are in the format: "Name <[email protected]>" or "[email protected]" and multiple emails can be separated by a comma.'
452
+									),
453
+									$field_label
454
+
455
+								)
456
+							);
457
+						}
458
+						break;
459
+					default :
460
+						break;
461
+				}
462
+			}
463
+
464
+			//if $err_msg isn't empty let's setup the _errors array for this field.
465
+			if (! empty($err_msg)) {
466
+				$this->_errors[$field]['msg'] = $err_msg;
467
+			} else {
468
+				unset($this->_errors[$field]);
469
+			}
470
+		}
471
+
472
+		// if we have ANY errors, then we want to make sure we return the values
473
+		// for ALL the fields so the user doesn't have to retype them all.
474
+		if (! empty($this->_errors)) {
475
+			foreach ($this->_fields as $field => $value) {
476
+				$this->_errors[$field]['value'] = stripslashes($value);
477
+			}
478
+		}
479
+
480
+		//return any errors or just TRUE if everything validates
481
+		return empty($this->_errors) ? true : $this->_errors;
482
+	}
483
+
484
+
485
+	/**
486
+	 * Reassembles and returns an array of valid shortcodes
487
+	 * given the array of groups and array of shortcodes indexed by group.
488
+	 *
489
+	 * @param  array $groups          array of shortcode groups that we want shortcodes for
490
+	 * @param  array $codes_from_objs All the codes available.
491
+	 * @return array                   an array of actual shortcodes (that will be used for validation).
492
+	 */
493
+	private function _reassemble_valid_shortcodes_from_group($groups, $codes_from_objs)
494
+	{
495
+		$shortcodes = array();
496
+		foreach ($groups as $group) {
497
+			$shortcodes = array_merge($shortcodes, $codes_from_objs[$group]);
498
+		}
499
+		return $shortcodes;
500
+	}
501
+
502
+
503
+	/**
504
+	 * Validates a string against a list of accepted shortcodes
505
+	 * This function takes in an array of shortcodes
506
+	 * and makes sure that the given string ONLY contains shortcodes in that array.
507
+	 *
508
+	 * @param  string $value            string to evaluate
509
+	 * @param  array  $valid_shortcodes array of shortcodes that are acceptable.
510
+	 * @return mixed (bool|string)  return either a list of invalid shortcodes OR false if the shortcodes validate.
511
+	 */
512
+	protected function _invalid_shortcodes($value, $valid_shortcodes)
513
+	{
514
+		//first we need to go through the string and get the shortcodes in the string
515
+		preg_match_all('/(\[.+?\])/', $value, $matches);
516
+		$incoming_shortcodes = (array)$matches[0];
517
+
518
+		//get a diff of the shortcodes in the string vs the valid shortcodes
519
+		$diff = array_diff($incoming_shortcodes, array_keys($valid_shortcodes));
520
+
521
+		//we need to account for custom codes so let's loop through the diff and remove any of those type of codes
522
+		foreach ($diff as $ind => $code) {
523
+			if (preg_match('/(\[[A-Za-z0-9\_]+_\*)/', $code)) {
524
+				//strip the shortcode so we just have the BASE string (i.e. [ANSWER_*] )
525
+				$dynamic_sc = preg_replace('/(_\*+.+)/', '_*]', $code);
526
+				//does this exist in the $valid_shortcodes?  If so then unset.
527
+				if (isset($valid_shortcodes[$dynamic_sc])) {
528
+					unset($diff[$ind]);
529
+				}
530
+			}
531
+		}
532
+
533
+		if (empty($diff)) {
534
+			return false;
535
+		} //there is no diff, we have no invalid shortcodes, so return
536
+
537
+		//made it here? then let's assemble the error message
538
+		$invalid_shortcodes = implode('</strong>,<strong>', $diff);
539
+		$invalid_shortcodes = '<strong>' . $invalid_shortcodes . '</strong>';
540
+		return $invalid_shortcodes;
541
+	}
542
+
543
+
544
+	/**
545
+	 * Validates an incoming string and makes sure we have valid emails in the string.
546
+	 *
547
+	 * @param  string $value incoming value to validate
548
+	 * @return bool        true if the string validates, false if it doesn't
549
+	 */
550
+	protected function _validate_email($value)
551
+	{
552
+		$validate = true;
553
+		$or_val   = $value;
554
+
555
+		// empty strings will validate because this is how a message template
556
+		// for a particular context can be "turned off" (if there is no email then no message)
557
+		if (empty($value)) {
558
+			return $validate;
559
+		}
560
+
561
+		// first determine if there ARE any shortcodes.
562
+		// If there are shortcodes and then later we find that there were no other valid emails
563
+		// but the field isn't empty...
564
+		// that means we've got extra commas that were left after stripping out shortcodes so probably still valid.
565
+		$has_shortcodes = preg_match('/(\[.+?\])/', $value);
566
+
567
+		//first we need to strip out all the shortcodes!
568
+		$value = preg_replace('/(\[.+?\])/', '', $value);
569
+
570
+		// if original value is not empty and new value is, then we've parsed out a shortcode
571
+		// and we now have an empty string which DOES validate.
572
+		// We also validate complete empty field for email because
573
+		// its possible that this message is being "turned off" for a particular context
574
+
575
+
576
+		if (! empty($or_val) && empty($value)) {
577
+			return $validate;
578
+		}
579
+
580
+		//trim any commas from beginning and end of string ( after whitespace trimmed );
581
+		$value = trim(trim($value), ',');
582
+
583
+
584
+		//next we need to split up the string if its comma delimited.
585
+		$emails = explode(',', $value);
586
+		$empty  = false; //used to indicate that there is an empty comma.
587
+		//now let's loop through the emails and do our checks
588
+		foreach ($emails as $email) {
589
+			if (empty($email)) {
590
+				$empty = true;
591
+				continue;
592
+			}
593
+
594
+			//trim whitespace
595
+			$email = trim($email);
596
+			//either its of type "[email protected]", or its of type "fname lname <[email protected]>"
597
+			if (is_email($email)) {
598
+				continue;
599
+			} else {
600
+				$matches  = array();
601
+				$validate = preg_match('/(.*)<(.+)>/', $email, $matches) ? true : false;
602
+				if ($validate && is_email($matches[2])) {
603
+					continue;
604
+				} else {
605
+					return false;
606
+				}
607
+			}
608
+		}
609
+
610
+		$validate = $empty && ! $has_shortcodes ? false : $validate;
611
+
612
+		return $validate;
613
+
614
+	}
615
+
616
+
617
+	/**
618
+	 * Magic getter
619
+	 * Using this to provide back compat with add-ons referencing deprecated properties.
620
+	 *
621
+	 * @param string $property Property being requested
622
+	 * @throws Exception
623
+	 * @return mixed
624
+	 */
625
+	public function __get($property)
626
+	{
627
+		$expected_properties_map = array(
628
+			/**
629
+			 * @deprecated 4.9.0
630
+			 */
631
+			'_MSGR'   => '_messenger',
632
+			/**
633
+			 * @deprecated 4.9.0
634
+			 */
635
+			'_MSGTYP' => '_message_type',
636
+		);
637
+
638
+		if (isset($expected_properties_map[$property])) {
639
+			return $this->{$expected_properties_map[$property]};
640
+		}
641
+
642
+		throw new Exception(
643
+			sprintf(
644
+				__('The property %1$s being requested on %2$s does not exist', 'event_espresso'),
645
+				$property,
646
+				get_class($this)
647
+			)
648
+		);
649
+	}
650 650
 
651 651
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-if (! defined('EVENT_ESPRESSO_VERSION')) {
3
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
4 4
     exit('NO direct script access allowed');
5 5
 }
6 6
 
@@ -161,9 +161,9 @@  discard block
 block discarded – undo
161 161
         //load messenger
162 162
         $messenger = ucwords(str_replace('_', ' ', $this->_m_name));
163 163
         $messenger = str_replace(' ', '_', $messenger);
164
-        $messenger = 'EE_' . $messenger . '_messenger';
164
+        $messenger = 'EE_'.$messenger.'_messenger';
165 165
 
166
-        if (! class_exists($messenger)) {
166
+        if ( ! class_exists($messenger)) {
167 167
             throw new EE_Error(
168 168
                 sprintf(
169 169
                     __('There is no messenger class for the given string (%s)', 'event_espresso'),
@@ -177,9 +177,9 @@  discard block
 block discarded – undo
177 177
         //load message type
178 178
         $message_type = ucwords(str_replace('_', ' ', $this->_mt_name));
179 179
         $message_type = str_replace(' ', '_', $message_type);
180
-        $message_type = 'EE_' . $message_type . '_message_type';
180
+        $message_type = 'EE_'.$message_type.'_message_type';
181 181
 
182
-        if (! class_exists($message_type)) {
182
+        if ( ! class_exists($message_type)) {
183 183
             throw new EE_Error(
184 184
                 sprintf(
185 185
                     __('There is no message type class for the given string (%s)', 'event_espresso'),
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
         foreach ($shortcode_groups as $group) {
237 237
             $ref       = ucwords(str_replace('_', ' ', $group));
238 238
             $ref       = str_replace(' ', '_', $ref);
239
-            $classname = 'EE_' . $ref . '_Shortcodes';
239
+            $classname = 'EE_'.$ref.'_Shortcodes';
240 240
             if (class_exists($classname)) {
241 241
                 $a                       = new ReflectionClass($classname);
242 242
                 $obj                     = $a->newInstance();
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
     {
331 331
         //specific validator filter
332 332
         $shortcode_excludes = apply_filters(
333
-            'FHEE__' . get_class($this) . '__get_specific_shortcode_excludes;',
333
+            'FHEE__'.get_class($this).'__get_specific_shortcode_excludes;',
334 334
             $this->_specific_shortcode_excludes,
335 335
             $this->_context
336 336
         );
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
             $err_msg               = '';
363 363
             $field_label           = '';
364 364
             //if field is not present in the _validators array then we continue
365
-            if (! isset($this->_validators[$field])) {
365
+            if ( ! isset($this->_validators[$field])) {
366 366
                 unset($this->_errors[$field]);
367 367
                 continue;
368 368
             }
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
                             '%3$sThe following shortcodes were found in the "%1$s" field that ARE not valid: %2$s%4$s',
412 412
                             'event_espresso'
413 413
                         ),
414
-                        '<strong>' . $field_label . '</strong>',
414
+                        '<strong>'.$field_label.'</strong>',
415 415
                         $invalid_shortcodes,
416 416
                         '<p>',
417 417
                         '</p >'
@@ -429,7 +429,7 @@  discard block
 block discarded – undo
429 429
             if (isset($this->_validators[$field]['type']) && ! empty($this->_validators[$field]['type'])) {
430 430
                 switch ($this->_validators[$field]['type']) {
431 431
                     case 'number' :
432
-                        if (! is_numeric($value)) {
432
+                        if ( ! is_numeric($value)) {
433 433
                             $err_msg .= sprintf(
434 434
                                 __(
435 435
                                     '%3$sThe %1$s field is supposed to be a number. The value given (%2$s)  is not.  Please double-check and make sure the field contains a number%4$s',
@@ -444,7 +444,7 @@  discard block
 block discarded – undo
444 444
                         break;
445 445
                     case 'email' :
446 446
                         $valid_email = $this->_validate_email($value);
447
-                        if (! $valid_email) {
447
+                        if ( ! $valid_email) {
448 448
                             $err_msg .= htmlentities(
449 449
                                 sprintf(
450 450
                                     __(
@@ -462,7 +462,7 @@  discard block
 block discarded – undo
462 462
             }
463 463
 
464 464
             //if $err_msg isn't empty let's setup the _errors array for this field.
465
-            if (! empty($err_msg)) {
465
+            if ( ! empty($err_msg)) {
466 466
                 $this->_errors[$field]['msg'] = $err_msg;
467 467
             } else {
468 468
                 unset($this->_errors[$field]);
@@ -471,7 +471,7 @@  discard block
 block discarded – undo
471 471
 
472 472
         // if we have ANY errors, then we want to make sure we return the values
473 473
         // for ALL the fields so the user doesn't have to retype them all.
474
-        if (! empty($this->_errors)) {
474
+        if ( ! empty($this->_errors)) {
475 475
             foreach ($this->_fields as $field => $value) {
476 476
                 $this->_errors[$field]['value'] = stripslashes($value);
477 477
             }
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
     {
514 514
         //first we need to go through the string and get the shortcodes in the string
515 515
         preg_match_all('/(\[.+?\])/', $value, $matches);
516
-        $incoming_shortcodes = (array)$matches[0];
516
+        $incoming_shortcodes = (array) $matches[0];
517 517
 
518 518
         //get a diff of the shortcodes in the string vs the valid shortcodes
519 519
         $diff = array_diff($incoming_shortcodes, array_keys($valid_shortcodes));
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
 
537 537
         //made it here? then let's assemble the error message
538 538
         $invalid_shortcodes = implode('</strong>,<strong>', $diff);
539
-        $invalid_shortcodes = '<strong>' . $invalid_shortcodes . '</strong>';
539
+        $invalid_shortcodes = '<strong>'.$invalid_shortcodes.'</strong>';
540 540
         return $invalid_shortcodes;
541 541
     }
542 542
 
@@ -573,7 +573,7 @@  discard block
 block discarded – undo
573 573
         // its possible that this message is being "turned off" for a particular context
574 574
 
575 575
 
576
-        if (! empty($or_val) && empty($value)) {
576
+        if ( ! empty($or_val) && empty($value)) {
577 577
             return $validate;
578 578
         }
579 579
 
Please login to merge, or discard this patch.
core/db_models/fields/EE_Post_Content_Field.php 2 patches
Indentation   +112 added lines, -112 removed lines patch added patch discarded remove patch
@@ -8,128 +8,128 @@
 block discarded – undo
8 8
 class EE_Post_Content_Field extends EE_Text_Field_Base
9 9
 {
10 10
 
11
-    /**
12
-     * @param string $table_column
13
-     * @param string $nicename
14
-     * @param bool   $nullable
15
-     * @param null   $default_value
16
-     */
17
-    public function __construct($table_column, $nicename, $nullable, $default_value = null)
18
-    {
19
-        parent::__construct($table_column, $nicename, $nullable, $default_value);
20
-        $this->setSchemaType('object');
21
-    }
11
+	/**
12
+	 * @param string $table_column
13
+	 * @param string $nicename
14
+	 * @param bool   $nullable
15
+	 * @param null   $default_value
16
+	 */
17
+	public function __construct($table_column, $nicename, $nullable, $default_value = null)
18
+	{
19
+		parent::__construct($table_column, $nicename, $nullable, $default_value);
20
+		$this->setSchemaType('object');
21
+	}
22 22
 
23 23
 
24
-    /**
25
-     * removes all tags which a WP Post wouldn't allow in its content normally
26
-     *
27
-     * @param string $value
28
-     * @return string
29
-     */
30
-    public function prepare_for_set($value)
31
-    {
32
-        if (! current_user_can('unfiltered_html')) {
33
-            $value = wp_kses("$value", wp_kses_allowed_html('post'));
34
-        }
35
-        return parent::prepare_for_set($value);
36
-    }
24
+	/**
25
+	 * removes all tags which a WP Post wouldn't allow in its content normally
26
+	 *
27
+	 * @param string $value
28
+	 * @return string
29
+	 */
30
+	public function prepare_for_set($value)
31
+	{
32
+		if (! current_user_can('unfiltered_html')) {
33
+			$value = wp_kses("$value", wp_kses_allowed_html('post'));
34
+		}
35
+		return parent::prepare_for_set($value);
36
+	}
37 37
 
38 38
 
39 39
 
40
-    /**
41
-     * Runs the content through `the_content`, or if prepares the content for placing in a form input
42
-     * @param string $value_on_field_to_be_outputted
43
-     * @param string   $schema possible values: 'form_input' or null (if null, will run through 'the_content')
44
-     * @return string
45
-     * @throws EE_Error when WP_DEBUG is on and recursive calling is detected
46
-     */
47
-    public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
48
-    {
49
-        switch($schema){
50
-            case 'form_input':
51
-                return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
52
-            case 'the_content':
40
+	/**
41
+	 * Runs the content through `the_content`, or if prepares the content for placing in a form input
42
+	 * @param string $value_on_field_to_be_outputted
43
+	 * @param string   $schema possible values: 'form_input' or null (if null, will run through 'the_content')
44
+	 * @return string
45
+	 * @throws EE_Error when WP_DEBUG is on and recursive calling is detected
46
+	 */
47
+	public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
48
+	{
49
+		switch($schema){
50
+			case 'form_input':
51
+				return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
52
+			case 'the_content':
53 53
 
54
-                if(doing_filter( 'the_content')){
55
-                    if( defined('WP_DEBUG') && WP_DEBUG){
56
-                        throw new EE_Error(
57
-                            sprintf(
58
-                                esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
59
-                                'EE_Post_Content_Field::prepare_for_pretty_echoing',
60
-                                '$schema',
61
-                                'the_content',
62
-                                'the_content_wp_core_only'
63
-                            )
64
-                        );
65
-                    } else {
66
-                        return $this->prepare_for_pretty_echoing($value_on_field_to_be_outputted, 'the_content_wp_core_only');
67
-                    }
68
-                }
69
-                return apply_filters(
70
-                    'the_content',
71
-                    parent::prepare_for_pretty_echoing(
72
-                        $value_on_field_to_be_outputted,
73
-                        $schema
74
-                    )
75
-                );
76
-            case 'the_content_wp_core_only':
77
-            default:
78
-                self::_setup_the_content_wp_core_only_filters();
79
-                $return_value = apply_filters(
80
-                    'the_content_wp_core_only',
81
-                    parent::prepare_for_pretty_echoing(
82
-                        $value_on_field_to_be_outputted,
83
-                        $schema
84
-                    )
85
-                );
86
-                //ya know what? adding these filters is super fast. Let's just
87
-                //avoid needing to maintain global state and set this up as-needed
88
-                remove_all_filters('the_content_wp_core_only');
89
-                do_action( 'AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
90
-                return $return_value;
91
-        }
92
-    }
54
+				if(doing_filter( 'the_content')){
55
+					if( defined('WP_DEBUG') && WP_DEBUG){
56
+						throw new EE_Error(
57
+							sprintf(
58
+								esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
59
+								'EE_Post_Content_Field::prepare_for_pretty_echoing',
60
+								'$schema',
61
+								'the_content',
62
+								'the_content_wp_core_only'
63
+							)
64
+						);
65
+					} else {
66
+						return $this->prepare_for_pretty_echoing($value_on_field_to_be_outputted, 'the_content_wp_core_only');
67
+					}
68
+				}
69
+				return apply_filters(
70
+					'the_content',
71
+					parent::prepare_for_pretty_echoing(
72
+						$value_on_field_to_be_outputted,
73
+						$schema
74
+					)
75
+				);
76
+			case 'the_content_wp_core_only':
77
+			default:
78
+				self::_setup_the_content_wp_core_only_filters();
79
+				$return_value = apply_filters(
80
+					'the_content_wp_core_only',
81
+					parent::prepare_for_pretty_echoing(
82
+						$value_on_field_to_be_outputted,
83
+						$schema
84
+					)
85
+				);
86
+				//ya know what? adding these filters is super fast. Let's just
87
+				//avoid needing to maintain global state and set this up as-needed
88
+				remove_all_filters('the_content_wp_core_only');
89
+				do_action( 'AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
90
+				return $return_value;
91
+		}
92
+	}
93 93
 
94 94
 
95 95
 
96
-    /**
97
-     * Verifies we've setup the standard WP core filters on  'the_content_wp_core_only' filter
98
-     */
99
-    protected static function _setup_the_content_wp_core_only_filters()
100
-    {
101
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
102
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
103
-        add_filter('the_content_wp_core_only', 'wptexturize', 10);
104
-        add_filter('the_content_wp_core_only', 'wpautop', 10);
105
-        add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
106
-        add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
107
-        if(function_exists('wp_make_content_images_responsive')) {
108
-            add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
109
-        }
110
-        add_filter('the_content_wp_core_only', 'do_shortcode', 11);
111
-        add_filter('the_content_wp_core_only', 'convert_smilies', 20);
112
-    }
96
+	/**
97
+	 * Verifies we've setup the standard WP core filters on  'the_content_wp_core_only' filter
98
+	 */
99
+	protected static function _setup_the_content_wp_core_only_filters()
100
+	{
101
+		add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
102
+		add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
103
+		add_filter('the_content_wp_core_only', 'wptexturize', 10);
104
+		add_filter('the_content_wp_core_only', 'wpautop', 10);
105
+		add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
106
+		add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
107
+		if(function_exists('wp_make_content_images_responsive')) {
108
+			add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
109
+		}
110
+		add_filter('the_content_wp_core_only', 'do_shortcode', 11);
111
+		add_filter('the_content_wp_core_only', 'convert_smilies', 20);
112
+	}
113 113
 
114 114
 
115 115
 
116
-    public function getSchemaProperties()
117
-    {
118
-        return array(
119
-            'raw' => array(
120
-                'description' =>  sprintf(
121
-                    __('%s - the content as it exists in the database.', 'event_espresso'),
122
-                    $this->get_nicename()
123
-                ),
124
-                'type' => 'string'
125
-            ),
126
-            'rendered' => array(
127
-                'description' =>  sprintf(
128
-                    __('%s - the content rendered for display.', 'event_espresso'),
129
-                    $this->get_nicename()
130
-                ),
131
-                'type' => 'string'
132
-            )
133
-        );
134
-    }
116
+	public function getSchemaProperties()
117
+	{
118
+		return array(
119
+			'raw' => array(
120
+				'description' =>  sprintf(
121
+					__('%s - the content as it exists in the database.', 'event_espresso'),
122
+					$this->get_nicename()
123
+				),
124
+				'type' => 'string'
125
+			),
126
+			'rendered' => array(
127
+				'description' =>  sprintf(
128
+					__('%s - the content rendered for display.', 'event_espresso'),
129
+					$this->get_nicename()
130
+				),
131
+				'type' => 'string'
132
+			)
133
+		);
134
+	}
135 135
 }
136 136
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
      */
30 30
     public function prepare_for_set($value)
31 31
     {
32
-        if (! current_user_can('unfiltered_html')) {
32
+        if ( ! current_user_can('unfiltered_html')) {
33 33
             $value = wp_kses("$value", wp_kses_allowed_html('post'));
34 34
         }
35 35
         return parent::prepare_for_set($value);
@@ -46,13 +46,13 @@  discard block
 block discarded – undo
46 46
      */
47 47
     public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
48 48
     {
49
-        switch($schema){
49
+        switch ($schema) {
50 50
             case 'form_input':
51 51
                 return parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema);
52 52
             case 'the_content':
53 53
 
54
-                if(doing_filter( 'the_content')){
55
-                    if( defined('WP_DEBUG') && WP_DEBUG){
54
+                if (doing_filter('the_content')) {
55
+                    if (defined('WP_DEBUG') && WP_DEBUG) {
56 56
                         throw new EE_Error(
57 57
                             sprintf(
58 58
                                 esc_html__('You have recursively called "%1$s" with %2$s set to %3$s which uses "%2$s" filter. You should use it with %2$s "%3$s" instead here.', 'event_espresso'),
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
                 //ya know what? adding these filters is super fast. Let's just
87 87
                 //avoid needing to maintain global state and set this up as-needed
88 88
                 remove_all_filters('the_content_wp_core_only');
89
-                do_action( 'AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
89
+                do_action('AHEE__EE_Post_Content_Field__prepare_for_pretty_echoing__the_content_wp_core_only__done');
90 90
                 return $return_value;
91 91
         }
92 92
     }
@@ -98,13 +98,13 @@  discard block
 block discarded – undo
98 98
      */
99 99
     protected static function _setup_the_content_wp_core_only_filters()
100 100
     {
101
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'run_shortcode'), 8);
102
-        add_filter('the_content_wp_core_only', array( $GLOBALS['wp_embed'], 'autoembed'), 8);
101
+        add_filter('the_content_wp_core_only', array($GLOBALS['wp_embed'], 'run_shortcode'), 8);
102
+        add_filter('the_content_wp_core_only', array($GLOBALS['wp_embed'], 'autoembed'), 8);
103 103
         add_filter('the_content_wp_core_only', 'wptexturize', 10);
104 104
         add_filter('the_content_wp_core_only', 'wpautop', 10);
105 105
         add_filter('the_content_wp_core_only', 'shortcode_unautop', 10);
106 106
         add_filter('the_content_wp_core_only', 'prepend_attachment', 10);
107
-        if(function_exists('wp_make_content_images_responsive')) {
107
+        if (function_exists('wp_make_content_images_responsive')) {
108 108
             add_filter('the_content_wp_core_only', 'wp_make_content_images_responsive', 10);
109 109
         }
110 110
         add_filter('the_content_wp_core_only', 'do_shortcode', 11);
Please login to merge, or discard this patch.
core/db_models/fields/EE_Model_Field_Base.php 1 patch
Indentation   +638 added lines, -639 removed lines patch added patch discarded remove patch
@@ -21,643 +21,642 @@
 block discarded – undo
21 21
  */
22 22
 abstract class EE_Model_Field_Base implements HasSchemaInterface
23 23
 {
24
-    /**
25
-     * The alias for the table the column belongs to.
26
-     * @var string
27
-     */
28
-    protected $_table_alias;
29
-
30
-    /**
31
-     * The actual db column name for the table
32
-     * @var string
33
-     */
34
-    protected $_table_column;
35
-
36
-
37
-    /**
38
-     * The authoritative name for the table column (used by client code to reference the field).
39
-     * @var string
40
-     */
41
-    protected $_name;
42
-
43
-
44
-    /**
45
-     * A description for the field.
46
-     * @var string
47
-     */
48
-    protected $_nicename;
49
-
50
-
51
-    /**
52
-     * Whether the field is nullable or not
53
-     * @var bool
54
-     */
55
-    protected $_nullable;
56
-
57
-
58
-    /**
59
-     * What the default value for the field should be.
60
-     * @var mixed
61
-     */
62
-    protected $_default_value;
63
-
64
-
65
-    /**
66
-     * Other configuration for the field
67
-     * @var mixed
68
-     */
69
-    protected $_other_config;
70
-
71
-
72
-    /**
73
-     * The name of the model this field is instantiated for.
74
-     * @var string
75
-     */
76
-    protected $_model_name;
77
-
78
-
79
-    /**
80
-     * This should be a json-schema valid data type for the field.
81
-     * @link http://json-schema.org/latest/json-schema-core.html#rfc.section.4.2
82
-     * @var string
83
-     */
84
-    private $_schema_type = 'string';
85
-
86
-
87
-    /**
88
-     * If the schema has a defined format then it should be defined via this property.
89
-     * @link http://json-schema.org/latest/json-schema-validation.html#rfc.section.7
90
-     * @var string
91
-     */
92
-    private $_schema_format = '';
93
-
94
-
95
-    /**
96
-     * Indicates that the value of the field is managed exclusively by the server/model and not something
97
-     * settable by client code.
98
-     * @link http://json-schema.org/latest/json-schema-hypermedia.html#rfc.section.4.4
99
-     * @var bool
100
-     */
101
-    private $_schema_readonly = false;
102
-
103
-
104
-    /**
105
-     * @param string $table_column
106
-     * @param string $nicename
107
-     * @param bool   $nullable
108
-     * @param null   $default_value
109
-     */
110
-    public function __construct($table_column, $nicename, $nullable, $default_value = null)
111
-    {
112
-        $this->_table_column  = $table_column;
113
-        $this->_nicename      = $nicename;
114
-        $this->_nullable      = $nullable;
115
-        $this->_default_value = $default_value;
116
-    }
117
-
118
-
119
-    /**
120
-     * @param $table_alias
121
-     * @param $name
122
-     * @param $model_name
123
-     */
124
-    public function _construct_finalize($table_alias, $name, $model_name)
125
-    {
126
-        $this->_table_alias = $table_alias;
127
-        $this->_name        = $name;
128
-        $this->_model_name  = $model_name;
129
-        /**
130
-         * allow for changing the defaults
131
-         */
132
-        $this->_nicename      = apply_filters('FHEE__EE_Model_Field_Base___construct_finalize___nicename',
133
-            $this->_nicename, $this);
134
-        $this->_default_value = apply_filters('FHEE__EE_Model_Field_Base___construct_finalize___default_value',
135
-            $this->_default_value, $this);
136
-    }
137
-
138
-    public function get_table_alias()
139
-    {
140
-        return $this->_table_alias;
141
-    }
142
-
143
-    public function get_table_column()
144
-    {
145
-        return $this->_table_column;
146
-    }
147
-
148
-    /**
149
-     * Returns the name of the model this field is on. Eg 'Event' or 'Ticket_Datetime'
150
-     *
151
-     * @return string
152
-     */
153
-    public function get_model_name()
154
-    {
155
-        return $this->_model_name;
156
-    }
157
-
158
-    /**
159
-     * @throws \EE_Error
160
-     * @return string
161
-     */
162
-    public function get_name()
163
-    {
164
-        if ($this->_name) {
165
-            return $this->_name;
166
-        } else {
167
-            throw new EE_Error(sprintf(__("Model field '%s' has no name set. Did you make a model and forget to call the parent model constructor?",
168
-                "event_espresso"), get_class($this)));
169
-        }
170
-    }
171
-
172
-    public function get_nicename()
173
-    {
174
-        return $this->_nicename;
175
-    }
176
-
177
-    public function is_nullable()
178
-    {
179
-        return $this->_nullable;
180
-    }
181
-
182
-    /**
183
-     * returns whether this field is an auto-increment field or not. If it is, then
184
-     * on insertion it can be null. However, on updates it must be present.
185
-     *
186
-     * @return boolean
187
-     */
188
-    public function is_auto_increment()
189
-    {
190
-        return false;
191
-    }
192
-
193
-    /**
194
-     * The default value in the model object's value domain. See lengthy comment about
195
-     * value domains at the top of EEM_Base
196
-     *
197
-     * @return mixed
198
-     */
199
-    public function get_default_value()
200
-    {
201
-        return $this->_default_value;
202
-    }
203
-
204
-    /**
205
-     * Returns the table alias joined to the table column, however this isn't the right
206
-     * table alias if the aliased table is being joined to. In that case, you can use
207
-     * EE_Model_Parser::extract_table_alias_model_relation_chain_prefix() to find the table's current alias
208
-     * in the current query
209
-     *
210
-     * @return string
211
-     */
212
-    public function get_qualified_column()
213
-    {
214
-        return $this->get_table_alias() . "." . $this->get_table_column();
215
-    }
216
-
217
-    /**
218
-     * When get() is called on a model object (eg EE_Event), before returning its value,
219
-     * call this function on it, allowing us to customize the returned value based on
220
-     * the field's type. Eg, we may want to unserialize it, strip tags, etc. By default,
221
-     * we simply return it.
222
-     *
223
-     * @param mixed $value_of_field_on_model_object
224
-     * @return mixed
225
-     */
226
-    public function prepare_for_get($value_of_field_on_model_object)
227
-    {
228
-        return $value_of_field_on_model_object;
229
-    }
230
-
231
-    /**
232
-     * When inserting or updating a field on a model object, run this function on each
233
-     * value to prepare it for insertion into the db. Generally this converts
234
-     * the validated input on the model object into the format used in the DB.
235
-     *
236
-     * @param mixed $value_of_field_on_model_object
237
-     * @return mixed
238
-     */
239
-    public function prepare_for_use_in_db($value_of_field_on_model_object)
240
-    {
241
-        return $value_of_field_on_model_object;
242
-    }
243
-
244
-    /**
245
-     * When creating a brand-new model object, or setting a particular value for one of its fields, this function
246
-     * is called before setting it on the model object. We may want to strip slashes, unserialize the value, etc.
247
-     * By default, we do nothing.
248
-     *
249
-     * If the model field is going to perform any validation on the input, this is where it should be done
250
-     * (once the value is on the model object, it may be used in other ways besides putting it into the DB
251
-     * so it's best to validate it right away).
252
-     *
253
-     * @param mixed $value_inputted_for_field_on_model_object
254
-     * @return mixed
255
-     */
256
-    public function prepare_for_set($value_inputted_for_field_on_model_object)
257
-    {
258
-        return $value_inputted_for_field_on_model_object;
259
-    }
260
-
261
-
262
-    /**
263
-     * When instantiating a model object from DB results, this function is called before setting each field.
264
-     * We may want to serialize the value, etc. By default, we return the value using prepare_for_set() method as that
265
-     * is the one child classes will most often define.
266
-     *
267
-     * @param mixed $value_found_in_db_for_model_object
268
-     * @return mixed
269
-     */
270
-    public function prepare_for_set_from_db($value_found_in_db_for_model_object)
271
-    {
272
-        return $this->prepare_for_set($value_found_in_db_for_model_object);
273
-    }
274
-
275
-    /**
276
-     * When echoing a field's value on a model object, this function is run to prepare the value for presentation in a
277
-     * webpage. For example, we may want to output floats with 2 decimal places by default, dates as "Monday Jan 12,
278
-     * 2013, at 3:23pm" instead of
279
-     * "8765678632", or any other modifications to how the value should be displayed, but not modified itself.
280
-     *
281
-     * @param mixed $value_on_field_to_be_outputted
282
-     * @return mixed
283
-     */
284
-    public function prepare_for_pretty_echoing($value_on_field_to_be_outputted)
285
-    {
286
-        return $value_on_field_to_be_outputted;
287
-    }
288
-
289
-
290
-    /**
291
-     * Returns whatever is set as the nicename for the object.
292
-     * @return string
293
-     */
294
-    public function getSchemaDescription()
295
-    {
296
-        return $this->get_nicename();
297
-    }
298
-
299
-
300
-    /**
301
-     * Returns whatever is set as the $_schema_type property for the object.
302
-     * Note: this will automatically add 'null' to the schema if the object is_nullable()
303
-     * @return string|array
304
-     */
305
-    public function getSchemaType()
306
-    {
307
-        if ($this->is_nullable()) {
308
-            $this->_schema_type = (array) $this->_schema_type;
309
-            if (! in_array('null', $this->_schema_type)) {
310
-                $this->_schema_type[] = 'null';
311
-            };
312
-        }
313
-        return $this->_schema_type;
314
-    }
315
-
316
-
317
-    /**
318
-     * Sets the _schema_type property.  Child classes should call this in their constructors to override the default state
319
-     * for this property.
320
-     * @param string|array $type
321
-     * @throws InvalidArgumentException
322
-     */
323
-    protected function setSchemaType($type)
324
-    {
325
-        $this->validateSchemaType($type);
326
-        $this->_schema_type = $type;
327
-    }
328
-
329
-
330
-    /**
331
-     * This is usually present when the $_schema_type property is 'object'.  Any child classes will need to override
332
-     * this method and return the properties for the schema.
333
-     *
334
-     * The reason this is not a property on the class is because there may be filters set on the values for the property
335
-     * that won't be exposed on construct.  For example enum type schemas may have the enum values filtered.
336
-     *
337
-     * @return array
338
-     */
339
-    public function getSchemaProperties()
340
-    {
341
-        return array();
342
-    }
343
-
344
-
345
-
346
-    /**
347
-     * By default this returns the scalar default value that was sent in on the class prepped according to the class type
348
-     * as the default.  However, when there are schema properties, then the default property is setup to mirror the
349
-     * property keys and correctly prepare the default according to that expected property value.
350
-     * The getSchema method validates whether the schema for default is setup correctly or not according to the schema type
351
-     *
352
-     * @return mixed
353
-     */
354
-    public function getSchemaDefault()
355
-    {
356
-        $default_value = $this->prepare_for_use_in_db($this->prepare_for_set($this->get_default_value()));
357
-        $schema_properties = $this->getSchemaProperties();
358
-
359
-        //if this schema has properties than shape the default value to match the properties shape.
360
-        if ($schema_properties) {
361
-            $value_to_return = array();
362
-            foreach ($schema_properties as $property_key => $property_schema) {
363
-                switch ($property_key) {
364
-                    case 'pretty':
365
-                    case 'rendered':
366
-                        $value_to_return[$property_key] = $this->prepare_for_pretty_echoing($this->prepare_for_set($default_value));
367
-                        break;
368
-                    default:
369
-                        $value_to_return[$property_key] = $default_value;
370
-                        break;
371
-                }
372
-            }
373
-            $default_value = $value_to_return;
374
-        }
375
-        return $default_value;
376
-    }
377
-
378
-
379
-
380
-
381
-    /**
382
-     * If a child class has enum values, they should override this method and provide a simple array
383
-     * of the enum values.
384
-
385
-     * The reason this is not a property on the class is because there may be filterable enum values that
386
-     * are set on the instantiated object that could be filtered after construct.
387
-     *
388
-     * @return array
389
-     */
390
-    public function getSchemaEnum()
391
-    {
392
-        return array();
393
-    }
394
-
395
-
396
-    /**
397
-     * This returns the value of the $_schema_format property on the object.
398
-     * @return string
399
-     */
400
-    public function getSchemaFormat()
401
-    {
402
-        return $this->_schema_format;
403
-    }
404
-
405
-
406
-    /**
407
-     * Sets the schema format property.
408
-     * @throws InvalidArgumentException
409
-     * @param string $format
410
-     */
411
-    protected function setSchemaFormat($format)
412
-    {
413
-        $this->validateSchemaFormat($format);
414
-        $this->_schema_format = $format;
415
-    }
416
-
417
-
418
-    /**
419
-     * This returns the value of the $_schema_readonly property on the object.
420
-     * @return bool
421
-     */
422
-    public function getSchemaReadonly()
423
-    {
424
-        return $this->_schema_readonly;
425
-    }
426
-
427
-
428
-    /**
429
-     * This sets the value for the $_schema_readonly property.
430
-     * @param bool $readonly  (only explicit boolean values are accepted)
431
-     */
432
-    protected function setSchemaReadOnly($readonly)
433
-    {
434
-        if (! is_bool($readonly)) {
435
-            throw new InvalidArgumentException(
436
-                sprintf(
437
-                    esc_html__('The incoming argument (%s) must be a boolean.', 'event_espresso'),
438
-                    print_r($readonly, true)
439
-                )
440
-            );
441
-        }
442
-
443
-        $this->_schema_readonly = $readonly;
444
-    }
445
-
446
-
447
-
448
-
449
-    /**
450
-     * Return `%d`, `%s` or `%f` to indicate the data type for the field.
451
-     * @uses _get_wpdb_data_type()
452
-     *
453
-     * @return string
454
-     */
455
-    public function get_wpdb_data_type()
456
-    {
457
-        return $this->_get_wpdb_data_type();
458
-    }
459
-
460
-
461
-    /**
462
-     * Return `%d`, `%s` or `%f` to indicate the data type for the field that should be indicated in wpdb queries.
463
-     * @param string $type  Included if a specific type is requested.
464
-     * @uses get_schema_type()
465
-     * @return string
466
-     */
467
-    protected function _get_wpdb_data_type($type='')
468
-    {
469
-        $type = empty($type) ? $this->getSchemaType() : $type;
470
-
471
-        //if type is an array, then different parsing is required.
472
-        if (is_array($type)) {
473
-            return $this->_get_wpdb_data_type_for_type_array($type);
474
-        }
475
-
476
-        $wpdb_type = '%s';
477
-        switch ($type) {
478
-            case 'number':
479
-                $wpdb_type = '%f';
480
-                break;
481
-            case 'integer':
482
-            case 'boolean':
483
-                $wpdb_type = '%d';
484
-                break;
485
-            case 'object':
486
-                $properties = $this->getSchemaProperties();
487
-                if (isset($properties['raw'], $properties['raw']['type'])) {
488
-                    $wpdb_type = $this->_get_wpdb_data_type($properties['raw']['type']);
489
-                }
490
-                break; //leave at default
491
-        }
492
-        return $wpdb_type;
493
-    }
494
-
495
-
496
-
497
-    protected function _get_wpdb_data_type_for_type_array($type)
498
-    {
499
-        $type = (array) $type;
500
-        //first let's flip because then we can do a faster key check
501
-        $type = array_flip($type);
502
-
503
-        //check for things that mean '%s'
504
-        if (isset($type['string'],$type['object'],$type['array'])) {
505
-            return '%s';
506
-        }
507
-
508
-        //if makes it past the above condition and there's float in the array
509
-        //then the type is %f
510
-        if (isset($type['number'])) {
511
-            return '%f';
512
-        }
513
-
514
-        //if it makes it above the above conditions and there is an integer in the array
515
-        //then the type is %d
516
-        if (isset($type['integer'])) {
517
-            return '%d';
518
-        }
519
-
520
-        //anything else is a string
521
-        return '%s';
522
-    }
523
-
524
-
525
-    /**
526
-     * This returns elements used to represent this field in the json schema.
527
-     *
528
-     * @link http://json-schema.org/
529
-     * @return array
530
-     */
531
-    public function getSchema()
532
-    {
533
-        $schema = array(
534
-            'description' => $this->getSchemaDescription(),
535
-            'type' => $this->getSchemaType(),
536
-            'readonly' => $this->getSchemaReadonly(),
537
-            'default' => $this->getSchemaDefault()
538
-        );
539
-
540
-        //optional properties of the schema
541
-        $enum = $this->getSchemaEnum();
542
-        $properties = $this->getSchemaProperties();
543
-        $format = $this->getSchemaFormat();
544
-        if ($enum) {
545
-            $schema['enum'] = $enum;
546
-        }
547
-
548
-        if ($properties) {
549
-            $schema['properties'] = $properties;
550
-        }
551
-
552
-        if ($format) {
553
-            $schema['format'] = $format;
554
-        }
555
-        return $schema;
556
-    }
557
-
558
-    /**
559
-     * Some fields are in the database-only, (ie, used in queries etc), but shouldn't necessarily be part
560
-     * of the model objects (ie, client code shouldn't care to ever see their value... if client code does
561
-     * want to see their value, then they shouldn't be db-only fields!)
562
-     * Eg, when doing events as custom post types, querying the post_type is essential, but
563
-     * post_type is irrelevant for EE_Event objects (because they will ALL be of post_type 'esp_event').
564
-     * By default, all fields aren't db-only.
565
-     *
566
-     * @return boolean
567
-     */
568
-    public function is_db_only_field()
569
-    {
570
-        return false;
571
-    }
572
-
573
-
574
-    /**
575
-     * Validates the incoming string|array to ensure its an allowable type.
576
-     * @throws InvalidArgumentException
577
-     * @param string|array $type
578
-     */
579
-    private function validateSchemaType($type)
580
-    {
581
-        if (! (is_string($type) || is_array($type))) {
582
-            throw new InvalidArgumentException(
583
-                sprintf(
584
-                    esc_html__('The incoming argument (%s) must be a string or an array.', 'event_espresso'),
585
-                    print_r($type, true)
586
-                )
587
-            );
588
-        }
589
-
590
-        //validate allowable types.
591
-        //@link http://json-schema.org/latest/json-schema-core.html#rfc.section.4.2
592
-        $allowable_types = array_flip(
593
-            array(
594
-                'string',
595
-                'number',
596
-                'null',
597
-                'object',
598
-                'array',
599
-                'boolean',
600
-                'integer'
601
-            )
602
-        );
603
-
604
-        if (is_array($type)) {
605
-            foreach ($type as $item_in_type) {
606
-                $this->validateSchemaType($item_in_type);
607
-            }
608
-            return;
609
-        }
610
-
611
-        if (! isset($allowable_types[$type])) {
612
-            throw new InvalidArgumentException(
613
-                sprintf(
614
-                    esc_html__('The incoming argument (%1$s) must be one of the allowable types: %2$s', 'event_espresso'),
615
-                    $type,
616
-                    implode(',', array_flip($allowable_types))
617
-                )
618
-            );
619
-        }
620
-    }
621
-
622
-
623
-    /**
624
-     * Validates that the incoming format is an allowable string to use for the _schema_format property
625
-     * @throws InvalidArgumentException
626
-     * @param $format
627
-     */
628
-    private function validateSchemaFormat($format)
629
-    {
630
-        if (! is_string($format)) {
631
-            throw new InvalidArgumentException(
632
-                sprintf(
633
-                    esc_html__('The incoming argument (%s) must be a string.', 'event_espresso'),
634
-                    print_r($format, true)
635
-                )
636
-            );
637
-        }
638
-
639
-        //validate allowable format values
640
-        //@link http://json-schema.org/latest/json-schema-validation.html#rfc.section.7
641
-        $allowable_formats = array_flip(
642
-            array(
643
-                'date-time',
644
-                'email',
645
-                'hostname',
646
-                'ipv4',
647
-                'ipv6',
648
-                'uri',
649
-                'uriref'
650
-            )
651
-        );
652
-
653
-        if (! isset($allowable_formats[$format])) {
654
-            throw new InvalidArgumentException(
655
-                sprintf(
656
-                    esc_html__('The incoming argument (%1$s) must be one of the allowable formats: %2$s', 'event_espresso'),
657
-                    $format,
658
-                    implode(',', array_flip($allowable_formats))
659
-                )
660
-            );
661
-        }
662
-    }
24
+	/**
25
+	 * The alias for the table the column belongs to.
26
+	 * @var string
27
+	 */
28
+	protected $_table_alias;
29
+
30
+	/**
31
+	 * The actual db column name for the table
32
+	 * @var string
33
+	 */
34
+	protected $_table_column;
35
+
36
+
37
+	/**
38
+	 * The authoritative name for the table column (used by client code to reference the field).
39
+	 * @var string
40
+	 */
41
+	protected $_name;
42
+
43
+
44
+	/**
45
+	 * A description for the field.
46
+	 * @var string
47
+	 */
48
+	protected $_nicename;
49
+
50
+
51
+	/**
52
+	 * Whether the field is nullable or not
53
+	 * @var bool
54
+	 */
55
+	protected $_nullable;
56
+
57
+
58
+	/**
59
+	 * What the default value for the field should be.
60
+	 * @var mixed
61
+	 */
62
+	protected $_default_value;
63
+
64
+
65
+	/**
66
+	 * Other configuration for the field
67
+	 * @var mixed
68
+	 */
69
+	protected $_other_config;
70
+
71
+
72
+	/**
73
+	 * The name of the model this field is instantiated for.
74
+	 * @var string
75
+	 */
76
+	protected $_model_name;
77
+
78
+
79
+	/**
80
+	 * This should be a json-schema valid data type for the field.
81
+	 * @link http://json-schema.org/latest/json-schema-core.html#rfc.section.4.2
82
+	 * @var string
83
+	 */
84
+	private $_schema_type = 'string';
85
+
86
+
87
+	/**
88
+	 * If the schema has a defined format then it should be defined via this property.
89
+	 * @link http://json-schema.org/latest/json-schema-validation.html#rfc.section.7
90
+	 * @var string
91
+	 */
92
+	private $_schema_format = '';
93
+
94
+
95
+	/**
96
+	 * Indicates that the value of the field is managed exclusively by the server/model and not something
97
+	 * settable by client code.
98
+	 * @link http://json-schema.org/latest/json-schema-hypermedia.html#rfc.section.4.4
99
+	 * @var bool
100
+	 */
101
+	private $_schema_readonly = false;
102
+
103
+
104
+	/**
105
+	 * @param string $table_column
106
+	 * @param string $nicename
107
+	 * @param bool   $nullable
108
+	 * @param null   $default_value
109
+	 */
110
+	public function __construct($table_column, $nicename, $nullable, $default_value = null)
111
+	{
112
+		$this->_table_column  = $table_column;
113
+		$this->_nicename      = $nicename;
114
+		$this->_nullable      = $nullable;
115
+		$this->_default_value = $default_value;
116
+	}
117
+
118
+
119
+	/**
120
+	 * @param $table_alias
121
+	 * @param $name
122
+	 * @param $model_name
123
+	 */
124
+	public function _construct_finalize($table_alias, $name, $model_name)
125
+	{
126
+		$this->_table_alias = $table_alias;
127
+		$this->_name        = $name;
128
+		$this->_model_name  = $model_name;
129
+		/**
130
+		 * allow for changing the defaults
131
+		 */
132
+		$this->_nicename      = apply_filters('FHEE__EE_Model_Field_Base___construct_finalize___nicename',
133
+			$this->_nicename, $this);
134
+		$this->_default_value = apply_filters('FHEE__EE_Model_Field_Base___construct_finalize___default_value',
135
+			$this->_default_value, $this);
136
+	}
137
+
138
+	public function get_table_alias()
139
+	{
140
+		return $this->_table_alias;
141
+	}
142
+
143
+	public function get_table_column()
144
+	{
145
+		return $this->_table_column;
146
+	}
147
+
148
+	/**
149
+	 * Returns the name of the model this field is on. Eg 'Event' or 'Ticket_Datetime'
150
+	 *
151
+	 * @return string
152
+	 */
153
+	public function get_model_name()
154
+	{
155
+		return $this->_model_name;
156
+	}
157
+
158
+	/**
159
+	 * @throws \EE_Error
160
+	 * @return string
161
+	 */
162
+	public function get_name()
163
+	{
164
+		if ($this->_name) {
165
+			return $this->_name;
166
+		} else {
167
+			throw new EE_Error(sprintf(__("Model field '%s' has no name set. Did you make a model and forget to call the parent model constructor?",
168
+				"event_espresso"), get_class($this)));
169
+		}
170
+	}
171
+
172
+	public function get_nicename()
173
+	{
174
+		return $this->_nicename;
175
+	}
176
+
177
+	public function is_nullable()
178
+	{
179
+		return $this->_nullable;
180
+	}
181
+
182
+	/**
183
+	 * returns whether this field is an auto-increment field or not. If it is, then
184
+	 * on insertion it can be null. However, on updates it must be present.
185
+	 *
186
+	 * @return boolean
187
+	 */
188
+	public function is_auto_increment()
189
+	{
190
+		return false;
191
+	}
192
+
193
+	/**
194
+	 * The default value in the model object's value domain. See lengthy comment about
195
+	 * value domains at the top of EEM_Base
196
+	 *
197
+	 * @return mixed
198
+	 */
199
+	public function get_default_value()
200
+	{
201
+		return $this->_default_value;
202
+	}
203
+
204
+	/**
205
+	 * Returns the table alias joined to the table column, however this isn't the right
206
+	 * table alias if the aliased table is being joined to. In that case, you can use
207
+	 * EE_Model_Parser::extract_table_alias_model_relation_chain_prefix() to find the table's current alias
208
+	 * in the current query
209
+	 *
210
+	 * @return string
211
+	 */
212
+	public function get_qualified_column()
213
+	{
214
+		return $this->get_table_alias() . "." . $this->get_table_column();
215
+	}
216
+
217
+	/**
218
+	 * When get() is called on a model object (eg EE_Event), before returning its value,
219
+	 * call this function on it, allowing us to customize the returned value based on
220
+	 * the field's type. Eg, we may want to unserialize it, strip tags, etc. By default,
221
+	 * we simply return it.
222
+	 *
223
+	 * @param mixed $value_of_field_on_model_object
224
+	 * @return mixed
225
+	 */
226
+	public function prepare_for_get($value_of_field_on_model_object)
227
+	{
228
+		return $value_of_field_on_model_object;
229
+	}
230
+
231
+	/**
232
+	 * When inserting or updating a field on a model object, run this function on each
233
+	 * value to prepare it for insertion into the db. Generally this converts
234
+	 * the validated input on the model object into the format used in the DB.
235
+	 *
236
+	 * @param mixed $value_of_field_on_model_object
237
+	 * @return mixed
238
+	 */
239
+	public function prepare_for_use_in_db($value_of_field_on_model_object)
240
+	{
241
+		return $value_of_field_on_model_object;
242
+	}
243
+
244
+	/**
245
+	 * When creating a brand-new model object, or setting a particular value for one of its fields, this function
246
+	 * is called before setting it on the model object. We may want to strip slashes, unserialize the value, etc.
247
+	 * By default, we do nothing.
248
+	 *
249
+	 * If the model field is going to perform any validation on the input, this is where it should be done
250
+	 * (once the value is on the model object, it may be used in other ways besides putting it into the DB
251
+	 * so it's best to validate it right away).
252
+	 *
253
+	 * @param mixed $value_inputted_for_field_on_model_object
254
+	 * @return mixed
255
+	 */
256
+	public function prepare_for_set($value_inputted_for_field_on_model_object)
257
+	{
258
+		return $value_inputted_for_field_on_model_object;
259
+	}
260
+
261
+
262
+	/**
263
+	 * When instantiating a model object from DB results, this function is called before setting each field.
264
+	 * We may want to serialize the value, etc. By default, we return the value using prepare_for_set() method as that
265
+	 * is the one child classes will most often define.
266
+	 *
267
+	 * @param mixed $value_found_in_db_for_model_object
268
+	 * @return mixed
269
+	 */
270
+	public function prepare_for_set_from_db($value_found_in_db_for_model_object)
271
+	{
272
+		return $this->prepare_for_set($value_found_in_db_for_model_object);
273
+	}
274
+
275
+	/**
276
+	 * When echoing a field's value on a model object, this function is run to prepare the value for presentation in a
277
+	 * webpage. For example, we may want to output floats with 2 decimal places by default, dates as "Monday Jan 12,
278
+	 * 2013, at 3:23pm" instead of
279
+	 * "8765678632", or any other modifications to how the value should be displayed, but not modified itself.
280
+	 *
281
+	 * @param mixed $value_on_field_to_be_outputted
282
+	 * @return mixed
283
+	 */
284
+	public function prepare_for_pretty_echoing($value_on_field_to_be_outputted)
285
+	{
286
+		return $value_on_field_to_be_outputted;
287
+	}
288
+
289
+
290
+	/**
291
+	 * Returns whatever is set as the nicename for the object.
292
+	 * @return string
293
+	 */
294
+	public function getSchemaDescription()
295
+	{
296
+		return $this->get_nicename();
297
+	}
298
+
299
+
300
+	/**
301
+	 * Returns whatever is set as the $_schema_type property for the object.
302
+	 * Note: this will automatically add 'null' to the schema if the object is_nullable()
303
+	 * @return string|array
304
+	 */
305
+	public function getSchemaType()
306
+	{
307
+		if ($this->is_nullable()) {
308
+			$this->_schema_type = (array) $this->_schema_type;
309
+			if (! in_array('null', $this->_schema_type)) {
310
+				$this->_schema_type[] = 'null';
311
+			};
312
+		}
313
+		return $this->_schema_type;
314
+	}
315
+
316
+
317
+	/**
318
+	 * Sets the _schema_type property.  Child classes should call this in their constructors to override the default state
319
+	 * for this property.
320
+	 * @param string|array $type
321
+	 * @throws InvalidArgumentException
322
+	 */
323
+	protected function setSchemaType($type)
324
+	{
325
+		$this->validateSchemaType($type);
326
+		$this->_schema_type = $type;
327
+	}
328
+
329
+
330
+	/**
331
+	 * This is usually present when the $_schema_type property is 'object'.  Any child classes will need to override
332
+	 * this method and return the properties for the schema.
333
+	 *
334
+	 * The reason this is not a property on the class is because there may be filters set on the values for the property
335
+	 * that won't be exposed on construct.  For example enum type schemas may have the enum values filtered.
336
+	 *
337
+	 * @return array
338
+	 */
339
+	public function getSchemaProperties()
340
+	{
341
+		return array();
342
+	}
343
+
344
+
345
+
346
+	/**
347
+	 * By default this returns the scalar default value that was sent in on the class prepped according to the class type
348
+	 * as the default.  However, when there are schema properties, then the default property is setup to mirror the
349
+	 * property keys and correctly prepare the default according to that expected property value.
350
+	 * The getSchema method validates whether the schema for default is setup correctly or not according to the schema type
351
+	 *
352
+	 * @return mixed
353
+	 */
354
+	public function getSchemaDefault()
355
+	{
356
+		$default_value = $this->prepare_for_use_in_db($this->prepare_for_set($this->get_default_value()));
357
+		$schema_properties = $this->getSchemaProperties();
358
+
359
+		//if this schema has properties than shape the default value to match the properties shape.
360
+		if ($schema_properties) {
361
+			$value_to_return = array();
362
+			foreach ($schema_properties as $property_key => $property_schema) {
363
+				switch ($property_key) {
364
+					case 'pretty':
365
+					case 'rendered':
366
+						$value_to_return[$property_key] = $this->prepare_for_pretty_echoing($this->prepare_for_set($default_value));
367
+						break;
368
+					default:
369
+						$value_to_return[$property_key] = $default_value;
370
+						break;
371
+				}
372
+			}
373
+			$default_value = $value_to_return;
374
+		}
375
+		return $default_value;
376
+	}
377
+
378
+
379
+
380
+
381
+	/**
382
+	 * If a child class has enum values, they should override this method and provide a simple array
383
+	 * of the enum values.
384
+	 * The reason this is not a property on the class is because there may be filterable enum values that
385
+	 * are set on the instantiated object that could be filtered after construct.
386
+	 *
387
+	 * @return array
388
+	 */
389
+	public function getSchemaEnum()
390
+	{
391
+		return array();
392
+	}
393
+
394
+
395
+	/**
396
+	 * This returns the value of the $_schema_format property on the object.
397
+	 * @return string
398
+	 */
399
+	public function getSchemaFormat()
400
+	{
401
+		return $this->_schema_format;
402
+	}
403
+
404
+
405
+	/**
406
+	 * Sets the schema format property.
407
+	 * @throws InvalidArgumentException
408
+	 * @param string $format
409
+	 */
410
+	protected function setSchemaFormat($format)
411
+	{
412
+		$this->validateSchemaFormat($format);
413
+		$this->_schema_format = $format;
414
+	}
415
+
416
+
417
+	/**
418
+	 * This returns the value of the $_schema_readonly property on the object.
419
+	 * @return bool
420
+	 */
421
+	public function getSchemaReadonly()
422
+	{
423
+		return $this->_schema_readonly;
424
+	}
425
+
426
+
427
+	/**
428
+	 * This sets the value for the $_schema_readonly property.
429
+	 * @param bool $readonly  (only explicit boolean values are accepted)
430
+	 */
431
+	protected function setSchemaReadOnly($readonly)
432
+	{
433
+		if (! is_bool($readonly)) {
434
+			throw new InvalidArgumentException(
435
+				sprintf(
436
+					esc_html__('The incoming argument (%s) must be a boolean.', 'event_espresso'),
437
+					print_r($readonly, true)
438
+				)
439
+			);
440
+		}
441
+
442
+		$this->_schema_readonly = $readonly;
443
+	}
444
+
445
+
446
+
447
+
448
+	/**
449
+	 * Return `%d`, `%s` or `%f` to indicate the data type for the field.
450
+	 * @uses _get_wpdb_data_type()
451
+	 *
452
+	 * @return string
453
+	 */
454
+	public function get_wpdb_data_type()
455
+	{
456
+		return $this->_get_wpdb_data_type();
457
+	}
458
+
459
+
460
+	/**
461
+	 * Return `%d`, `%s` or `%f` to indicate the data type for the field that should be indicated in wpdb queries.
462
+	 * @param string $type  Included if a specific type is requested.
463
+	 * @uses get_schema_type()
464
+	 * @return string
465
+	 */
466
+	protected function _get_wpdb_data_type($type='')
467
+	{
468
+		$type = empty($type) ? $this->getSchemaType() : $type;
469
+
470
+		//if type is an array, then different parsing is required.
471
+		if (is_array($type)) {
472
+			return $this->_get_wpdb_data_type_for_type_array($type);
473
+		}
474
+
475
+		$wpdb_type = '%s';
476
+		switch ($type) {
477
+			case 'number':
478
+				$wpdb_type = '%f';
479
+				break;
480
+			case 'integer':
481
+			case 'boolean':
482
+				$wpdb_type = '%d';
483
+				break;
484
+			case 'object':
485
+				$properties = $this->getSchemaProperties();
486
+				if (isset($properties['raw'], $properties['raw']['type'])) {
487
+					$wpdb_type = $this->_get_wpdb_data_type($properties['raw']['type']);
488
+				}
489
+				break; //leave at default
490
+		}
491
+		return $wpdb_type;
492
+	}
493
+
494
+
495
+
496
+	protected function _get_wpdb_data_type_for_type_array($type)
497
+	{
498
+		$type = (array) $type;
499
+		//first let's flip because then we can do a faster key check
500
+		$type = array_flip($type);
501
+
502
+		//check for things that mean '%s'
503
+		if (isset($type['string'],$type['object'],$type['array'])) {
504
+			return '%s';
505
+		}
506
+
507
+		//if makes it past the above condition and there's float in the array
508
+		//then the type is %f
509
+		if (isset($type['number'])) {
510
+			return '%f';
511
+		}
512
+
513
+		//if it makes it above the above conditions and there is an integer in the array
514
+		//then the type is %d
515
+		if (isset($type['integer'])) {
516
+			return '%d';
517
+		}
518
+
519
+		//anything else is a string
520
+		return '%s';
521
+	}
522
+
523
+
524
+	/**
525
+	 * This returns elements used to represent this field in the json schema.
526
+	 *
527
+	 * @link http://json-schema.org/
528
+	 * @return array
529
+	 */
530
+	public function getSchema()
531
+	{
532
+		$schema = array(
533
+			'description' => $this->getSchemaDescription(),
534
+			'type' => $this->getSchemaType(),
535
+			'readonly' => $this->getSchemaReadonly(),
536
+			'default' => $this->getSchemaDefault()
537
+		);
538
+
539
+		//optional properties of the schema
540
+		$enum = $this->getSchemaEnum();
541
+		$properties = $this->getSchemaProperties();
542
+		$format = $this->getSchemaFormat();
543
+		if ($enum) {
544
+			$schema['enum'] = $enum;
545
+		}
546
+
547
+		if ($properties) {
548
+			$schema['properties'] = $properties;
549
+		}
550
+
551
+		if ($format) {
552
+			$schema['format'] = $format;
553
+		}
554
+		return $schema;
555
+	}
556
+
557
+	/**
558
+	 * Some fields are in the database-only, (ie, used in queries etc), but shouldn't necessarily be part
559
+	 * of the model objects (ie, client code shouldn't care to ever see their value... if client code does
560
+	 * want to see their value, then they shouldn't be db-only fields!)
561
+	 * Eg, when doing events as custom post types, querying the post_type is essential, but
562
+	 * post_type is irrelevant for EE_Event objects (because they will ALL be of post_type 'esp_event').
563
+	 * By default, all fields aren't db-only.
564
+	 *
565
+	 * @return boolean
566
+	 */
567
+	public function is_db_only_field()
568
+	{
569
+		return false;
570
+	}
571
+
572
+
573
+	/**
574
+	 * Validates the incoming string|array to ensure its an allowable type.
575
+	 * @throws InvalidArgumentException
576
+	 * @param string|array $type
577
+	 */
578
+	private function validateSchemaType($type)
579
+	{
580
+		if (! (is_string($type) || is_array($type))) {
581
+			throw new InvalidArgumentException(
582
+				sprintf(
583
+					esc_html__('The incoming argument (%s) must be a string or an array.', 'event_espresso'),
584
+					print_r($type, true)
585
+				)
586
+			);
587
+		}
588
+
589
+		//validate allowable types.
590
+		//@link http://json-schema.org/latest/json-schema-core.html#rfc.section.4.2
591
+		$allowable_types = array_flip(
592
+			array(
593
+				'string',
594
+				'number',
595
+				'null',
596
+				'object',
597
+				'array',
598
+				'boolean',
599
+				'integer'
600
+			)
601
+		);
602
+
603
+		if (is_array($type)) {
604
+			foreach ($type as $item_in_type) {
605
+				$this->validateSchemaType($item_in_type);
606
+			}
607
+			return;
608
+		}
609
+
610
+		if (! isset($allowable_types[$type])) {
611
+			throw new InvalidArgumentException(
612
+				sprintf(
613
+					esc_html__('The incoming argument (%1$s) must be one of the allowable types: %2$s', 'event_espresso'),
614
+					$type,
615
+					implode(',', array_flip($allowable_types))
616
+				)
617
+			);
618
+		}
619
+	}
620
+
621
+
622
+	/**
623
+	 * Validates that the incoming format is an allowable string to use for the _schema_format property
624
+	 * @throws InvalidArgumentException
625
+	 * @param $format
626
+	 */
627
+	private function validateSchemaFormat($format)
628
+	{
629
+		if (! is_string($format)) {
630
+			throw new InvalidArgumentException(
631
+				sprintf(
632
+					esc_html__('The incoming argument (%s) must be a string.', 'event_espresso'),
633
+					print_r($format, true)
634
+				)
635
+			);
636
+		}
637
+
638
+		//validate allowable format values
639
+		//@link http://json-schema.org/latest/json-schema-validation.html#rfc.section.7
640
+		$allowable_formats = array_flip(
641
+			array(
642
+				'date-time',
643
+				'email',
644
+				'hostname',
645
+				'ipv4',
646
+				'ipv6',
647
+				'uri',
648
+				'uriref'
649
+			)
650
+		);
651
+
652
+		if (! isset($allowable_formats[$format])) {
653
+			throw new InvalidArgumentException(
654
+				sprintf(
655
+					esc_html__('The incoming argument (%1$s) must be one of the allowable formats: %2$s', 'event_espresso'),
656
+					$format,
657
+					implode(',', array_flip($allowable_formats))
658
+				)
659
+			);
660
+		}
661
+	}
663 662
 }
664 663
\ No newline at end of file
Please login to merge, or discard this patch.
core/db_models/fields/EE_Simple_HTML_Field.php 1 patch
Indentation   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -11,14 +11,14 @@
 block discarded – undo
11 11
 
12 12
 
13 13
 
14
-    /**
15
-     * removes all tags which a WP Post wouldn't allow in its content normally
16
-     *
17
-     * @param string $value
18
-     * @return string
19
-     */
20
-    public function prepare_for_set($value)
21
-    {
22
-        return parent::prepare_for_set(wp_kses("$value", EEH_HTML::get_simple_tags()));
23
-    }
14
+	/**
15
+	 * removes all tags which a WP Post wouldn't allow in its content normally
16
+	 *
17
+	 * @param string $value
18
+	 * @return string
19
+	 */
20
+	public function prepare_for_set($value)
21
+	{
22
+		return parent::prepare_for_set(wp_kses("$value", EEH_HTML::get_simple_tags()));
23
+	}
24 24
 }
Please login to merge, or discard this patch.
registrations/templates/attendee_details_main_meta_box.template.php 1 patch
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
 						<label for="ATT_fname"><?php _e('First Name', 'event_espresso'); ?><span class="denotes-required-spn">*</span></label>
21 21
 					</th>
22 22
 					<td>
23
-						<div class="validation-notice-dv"><?php _e( 'The following is  a required field', 'event_espresso' );?></div>
23
+						<div class="validation-notice-dv"><?php _e('The following is  a required field', 'event_espresso'); ?></div>
24 24
 						<input class="regular-text required" type="text" id="ATT_fname" name="ATT_fname" value="<?php echo $attendee->fname(); ?>"/><br/>
25 25
 						<p class="description"><?php _e('The registrant\'s given name. ( required value )', 'event_espresso'); ?></p>
26 26
 					</td>
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
 						<label for="ATT_lname"><?php _e('Last Name', 'event_espresso'); ?><span class="denotes-required-spn">*</span></label>
32 32
 					</th>
33 33
 					<td>
34
-						<div class="validation-notice-dv"><?php _e( 'The following is  a required field', 'event_espresso' );?></div>
34
+						<div class="validation-notice-dv"><?php _e('The following is  a required field', 'event_espresso'); ?></div>
35 35
 						<input class="regular-text required" type="text" id="ATT_lname" name="ATT_lname" value="<?php echo $attendee->lname(); ?>"/><br/>
36 36
 						<p class="description"><?php _e('The registrant\'s family name. ( required value )', 'event_espresso'); ?></p>
37 37
 					</td>
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
 						<label for="ATT_email"><?php _e('Email Address', 'event_espresso'); ?><span class="denotes-required-spn">*</span></label>
43 43
 					</th>
44 44
 					<td>
45
-						<div class="validation-notice-dv"><?php _e( 'The following is  a required field', 'event_espresso' );?></div>
45
+						<div class="validation-notice-dv"><?php _e('The following is  a required field', 'event_espresso'); ?></div>
46 46
 						<input class="regular-text required" type="text" id="ATT_email" name="ATT_email" value="<?php $attendee->f('ATT_email'); ?>"/><br/>
47 47
 						<p class="description"><?php _e('( required value )', 'event_espresso'); ?></p>
48 48
 					</td>
@@ -109,8 +109,8 @@  discard block
 block discarded – undo
109 109
 				
110 110
 				
111 111
 				
112
-				<?php do_action( 'AHEE__attendee_details_main_meta_box__template__table_body_end',$attendee );?>
112
+				<?php do_action('AHEE__attendee_details_main_meta_box__template__table_body_end', $attendee); ?>
113 113
 			</tbody>
114 114
 		</table>
115
-		<?php do_action( 'AHEE__attendee_details_main_meta_box__template__after_table',$attendee );?>
115
+		<?php do_action('AHEE__attendee_details_main_meta_box__template__after_table', $attendee); ?>
116 116
 </div>
117 117
\ No newline at end of file
Please login to merge, or discard this patch.