Completed
Branch FET-8385-datetime-ticket-selec... (dcae27)
by
unknown
34:01 queued 22:12
created
caffeinated/admin/new/pricing/espresso_events_Pricing_Hooks.class.php 2 patches
Indentation   +1406 added lines, -1406 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
 /**
@@ -31,1533 +31,1533 @@  discard block
 block discarded – undo
31 31
 class espresso_events_Pricing_Hooks extends EE_Admin_Hooks
32 32
 {
33 33
     
34
-    /**
35
-     * This property is just used to hold the status of whether an event is currently being
36
-     * created (true) or edited (false)
37
-     * @access protected
38
-     * @var bool
39
-     */
40
-    protected $_is_creating_event;
34
+	/**
35
+	 * This property is just used to hold the status of whether an event is currently being
36
+	 * created (true) or edited (false)
37
+	 * @access protected
38
+	 * @var bool
39
+	 */
40
+	protected $_is_creating_event;
41 41
     
42 42
     
43
-    /**
44
-     * Used to contain the format strings for date and time that will be used for php date and
45
-     * time.
46
-     *
47
-     * Is set in the _set_hooks_properties() method.
48
-     *
49
-     * @var array
50
-     */
51
-    protected $_date_format_strings;
43
+	/**
44
+	 * Used to contain the format strings for date and time that will be used for php date and
45
+	 * time.
46
+	 *
47
+	 * Is set in the _set_hooks_properties() method.
48
+	 *
49
+	 * @var array
50
+	 */
51
+	protected $_date_format_strings;
52 52
     
53 53
     
54
-    protected function _set_hooks_properties()
55
-    {
56
-        $this->_name = 'pricing';
57
-        
58
-        //capability check
59
-        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_default_prices',
60
-            'advanced_ticket_datetime_metabox')
61
-        ) {
62
-            return;
63
-        }
64
-        
65
-        
66
-        //if we were going to add our own metaboxes we'd use the below.
67
-        $this->_metaboxes = array(
68
-            0 => array(
69
-                'page_route' => array('edit', 'create_new'),
70
-                'func'       => 'pricing_metabox',
71
-                'label'      => __('Event Tickets & Datetimes', 'event_espresso'),
72
-                'priority'   => 'high',
73
-                'context'    => 'normal'
74
-            ),
75
-        
76
-        );/**/
77
-        
78
-        $this->_remove_metaboxes = array(
79
-            0 => array(
80
-                'page_route' => array('edit', 'create_new'),
81
-                'id'         => 'espresso_event_editor_tickets',
82
-                'context'    => 'normal'
83
-            )
84
-        );
85
-        
86
-        /**
87
-         * Format strings for date and time.  Defaults are existing behaviour from 4.1.
88
-         * Note, that if you return null as the value for 'date', and 'time' in the array, then
89
-         * EE will automatically use the set wp_options, 'date_format', and 'time_format'.
90
-         *
91
-         * @since 4.6.7
92
-         *
93
-         * @var array  Expected an array returned with 'date' and 'time' keys.
94
-         */
95
-        $this->_date_format_strings = apply_filters('FHEE__espresso_events_Pricing_Hooks___set_hooks_properties__date_format_strings',
96
-            array(
97
-                'date' => 'Y-m-d',
98
-                'time' => 'h:i a'
99
-            ));
100
-        
101
-        //validate
102
-        $this->_date_format_strings['date'] = isset($this->_date_format_strings['date']) ? $this->_date_format_strings['date'] : null;
103
-        $this->_date_format_strings['time'] = isset($this->_date_format_strings['time']) ? $this->_date_format_strings['time'] : null;
104
-        
105
-        //validate format strings
106
-        $format_validation = EEH_DTT_Helper::validate_format_string($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']);
107
-        if (is_array($format_validation)) {
108
-            $msg = '<p>' . sprintf(__('The format "%s" was likely added via a filter and is invalid for the following reasons:',
109
-                    'event_espresso'),
110
-                    $this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']) . '</p><ul>';
111
-            foreach ($format_validation as $error) {
112
-                $msg .= '<li>' . $error . '</li>';
113
-            }
114
-            $msg .= '</ul></p><p>' . sprintf(__('%sPlease note that your date and time formats have been reset to "Y-m-d" and "h:i a" respectively.%s',
115
-                    'event_espresso'), '<span style="color:#D54E21;">', '</span>') . '</p>';
116
-            EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
117
-            $this->_date_format_strings = array(
118
-                'date' => 'Y-m-d',
119
-                'time' => 'h:i a'
120
-            );
121
-        }
122
-        
123
-        
124
-        $this->_scripts_styles = array(
125
-            'registers'   => array(
126
-                'ee-tickets-datetimes-css' => array(
127
-                    'url'  => PRICING_ASSETS_URL . 'event-tickets-datetimes.css',
128
-                    'type' => 'css'
129
-                ),
130
-                'ee-dtt-ticket-metabox'    => array(
131
-                    'url'     => PRICING_ASSETS_URL . 'ee-datetime-ticket-metabox.js',
132
-                    'depends' => array('ee-datepicker', 'ee-dialog', 'underscore')
133
-                )
134
-            ),
135
-            'deregisters' => array(
136
-                'event-editor-css'       => array('type' => 'css'),
137
-                'event-datetime-metabox' => array('type' => 'js')
138
-            ),
139
-            'enqueues'    => array(
140
-                'ee-tickets-datetimes-css' => array('edit', 'create_new'),
141
-                'ee-dtt-ticket-metabox'    => array('edit', 'create_new')
142
-            ),
143
-            'localize'    => array(
144
-                'ee-dtt-ticket-metabox' => array(
145
-                    'DTT_TRASH_BLOCK'       => array(
146
-                        'main_warning'            => __('The Datetime you are attempting to trash is the only datetime selected for the following ticket(s):',
147
-                            'event_espresso'),
148
-                        'after_warning'           => __('In order to trash this datetime you must first make sure the above ticket(s) are assigned to other datetimes.',
149
-                            'event_espresso'),
150
-                        'cancel_button'           => '<button class="button-secondary ee-modal-cancel">' . __('Cancel',
151
-                                'event_espresso') . '</button>',
152
-                        'close_button'            => '<button class="button-secondary ee-modal-cancel">' . __('Close',
153
-                                'event_espresso') . '</button>',
154
-                        'single_warning_from_tkt' => __('The Datetime you are attempting to unassign from this ticket is the only remaining datetime for this ticket. Tickets must always have at least one datetime assigned to them.',
155
-                            'event_espresso'),
156
-                        'single_warning_from_dtt' => __('The ticket you are attempting to unassign from this datetime cannot be unassigned because the datetime is the only remaining datetime for the ticket.  Tickets must always have at least one datetime assigned to them.',
157
-                            'event_espresso'),
158
-                        'dismiss_button'          => '<button class="button-secondary ee-modal-cancel">' . __('Dismiss',
159
-                                'event_espresso') . '</button>'
160
-                    ),
161
-                    'DTT_ERROR_MSG'         => array(
162
-                        'no_ticket_name' => __('General Admission', 'event_espresso'),
163
-                        'dismiss_button' => '<div class="save-cancel-button-container"><button class="button-secondary ee-modal-cancel">' . __('Dismiss',
164
-                                'event_espresso') . '</button></div>'
165
-                    ),
166
-                    'DTT_OVERSELL_WARNING'  => array(
167
-                        'datetime_ticket' => __('You cannot add this ticket to this datetime because it has a sold amount that is greater than the amount of spots remaining for this datetime.',
168
-                            'event_espresso'),
169
-                        'ticket_datetime' => __('You cannot add this datetime to this ticket because the ticket has a sold amount that is greater than the amount of spots remaining on the datetime.',
170
-                            'event_espresso')
171
-                    ),
172
-                    'DTT_CONVERTED_FORMATS' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats($this->_date_format_strings['date'],
173
-                        $this->_date_format_strings['time']),
174
-                    'DTT_START_OF_WEEK'     => array('dayValue' => (int)get_option('start_of_week'))
175
-                )
176
-            )
177
-        );
178
-        
179
-        
180
-        add_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_Extend_Events_Admin_Page',
181
-            array($this, 'autosave_handling'), 10);
182
-        add_filter('FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
183
-            array($this, 'caf_updates'), 10);
184
-    }
54
+	protected function _set_hooks_properties()
55
+	{
56
+		$this->_name = 'pricing';
57
+        
58
+		//capability check
59
+		if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_default_prices',
60
+			'advanced_ticket_datetime_metabox')
61
+		) {
62
+			return;
63
+		}
64
+        
65
+        
66
+		//if we were going to add our own metaboxes we'd use the below.
67
+		$this->_metaboxes = array(
68
+			0 => array(
69
+				'page_route' => array('edit', 'create_new'),
70
+				'func'       => 'pricing_metabox',
71
+				'label'      => __('Event Tickets & Datetimes', 'event_espresso'),
72
+				'priority'   => 'high',
73
+				'context'    => 'normal'
74
+			),
75
+        
76
+		);/**/
77
+        
78
+		$this->_remove_metaboxes = array(
79
+			0 => array(
80
+				'page_route' => array('edit', 'create_new'),
81
+				'id'         => 'espresso_event_editor_tickets',
82
+				'context'    => 'normal'
83
+			)
84
+		);
85
+        
86
+		/**
87
+		 * Format strings for date and time.  Defaults are existing behaviour from 4.1.
88
+		 * Note, that if you return null as the value for 'date', and 'time' in the array, then
89
+		 * EE will automatically use the set wp_options, 'date_format', and 'time_format'.
90
+		 *
91
+		 * @since 4.6.7
92
+		 *
93
+		 * @var array  Expected an array returned with 'date' and 'time' keys.
94
+		 */
95
+		$this->_date_format_strings = apply_filters('FHEE__espresso_events_Pricing_Hooks___set_hooks_properties__date_format_strings',
96
+			array(
97
+				'date' => 'Y-m-d',
98
+				'time' => 'h:i a'
99
+			));
100
+        
101
+		//validate
102
+		$this->_date_format_strings['date'] = isset($this->_date_format_strings['date']) ? $this->_date_format_strings['date'] : null;
103
+		$this->_date_format_strings['time'] = isset($this->_date_format_strings['time']) ? $this->_date_format_strings['time'] : null;
104
+        
105
+		//validate format strings
106
+		$format_validation = EEH_DTT_Helper::validate_format_string($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']);
107
+		if (is_array($format_validation)) {
108
+			$msg = '<p>' . sprintf(__('The format "%s" was likely added via a filter and is invalid for the following reasons:',
109
+					'event_espresso'),
110
+					$this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']) . '</p><ul>';
111
+			foreach ($format_validation as $error) {
112
+				$msg .= '<li>' . $error . '</li>';
113
+			}
114
+			$msg .= '</ul></p><p>' . sprintf(__('%sPlease note that your date and time formats have been reset to "Y-m-d" and "h:i a" respectively.%s',
115
+					'event_espresso'), '<span style="color:#D54E21;">', '</span>') . '</p>';
116
+			EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
117
+			$this->_date_format_strings = array(
118
+				'date' => 'Y-m-d',
119
+				'time' => 'h:i a'
120
+			);
121
+		}
122
+        
123
+        
124
+		$this->_scripts_styles = array(
125
+			'registers'   => array(
126
+				'ee-tickets-datetimes-css' => array(
127
+					'url'  => PRICING_ASSETS_URL . 'event-tickets-datetimes.css',
128
+					'type' => 'css'
129
+				),
130
+				'ee-dtt-ticket-metabox'    => array(
131
+					'url'     => PRICING_ASSETS_URL . 'ee-datetime-ticket-metabox.js',
132
+					'depends' => array('ee-datepicker', 'ee-dialog', 'underscore')
133
+				)
134
+			),
135
+			'deregisters' => array(
136
+				'event-editor-css'       => array('type' => 'css'),
137
+				'event-datetime-metabox' => array('type' => 'js')
138
+			),
139
+			'enqueues'    => array(
140
+				'ee-tickets-datetimes-css' => array('edit', 'create_new'),
141
+				'ee-dtt-ticket-metabox'    => array('edit', 'create_new')
142
+			),
143
+			'localize'    => array(
144
+				'ee-dtt-ticket-metabox' => array(
145
+					'DTT_TRASH_BLOCK'       => array(
146
+						'main_warning'            => __('The Datetime you are attempting to trash is the only datetime selected for the following ticket(s):',
147
+							'event_espresso'),
148
+						'after_warning'           => __('In order to trash this datetime you must first make sure the above ticket(s) are assigned to other datetimes.',
149
+							'event_espresso'),
150
+						'cancel_button'           => '<button class="button-secondary ee-modal-cancel">' . __('Cancel',
151
+								'event_espresso') . '</button>',
152
+						'close_button'            => '<button class="button-secondary ee-modal-cancel">' . __('Close',
153
+								'event_espresso') . '</button>',
154
+						'single_warning_from_tkt' => __('The Datetime you are attempting to unassign from this ticket is the only remaining datetime for this ticket. Tickets must always have at least one datetime assigned to them.',
155
+							'event_espresso'),
156
+						'single_warning_from_dtt' => __('The ticket you are attempting to unassign from this datetime cannot be unassigned because the datetime is the only remaining datetime for the ticket.  Tickets must always have at least one datetime assigned to them.',
157
+							'event_espresso'),
158
+						'dismiss_button'          => '<button class="button-secondary ee-modal-cancel">' . __('Dismiss',
159
+								'event_espresso') . '</button>'
160
+					),
161
+					'DTT_ERROR_MSG'         => array(
162
+						'no_ticket_name' => __('General Admission', 'event_espresso'),
163
+						'dismiss_button' => '<div class="save-cancel-button-container"><button class="button-secondary ee-modal-cancel">' . __('Dismiss',
164
+								'event_espresso') . '</button></div>'
165
+					),
166
+					'DTT_OVERSELL_WARNING'  => array(
167
+						'datetime_ticket' => __('You cannot add this ticket to this datetime because it has a sold amount that is greater than the amount of spots remaining for this datetime.',
168
+							'event_espresso'),
169
+						'ticket_datetime' => __('You cannot add this datetime to this ticket because the ticket has a sold amount that is greater than the amount of spots remaining on the datetime.',
170
+							'event_espresso')
171
+					),
172
+					'DTT_CONVERTED_FORMATS' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats($this->_date_format_strings['date'],
173
+						$this->_date_format_strings['time']),
174
+					'DTT_START_OF_WEEK'     => array('dayValue' => (int)get_option('start_of_week'))
175
+				)
176
+			)
177
+		);
178
+        
179
+        
180
+		add_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_Extend_Events_Admin_Page',
181
+			array($this, 'autosave_handling'), 10);
182
+		add_filter('FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
183
+			array($this, 'caf_updates'), 10);
184
+	}
185 185
     
186 186
     
187
-    public function caf_updates($update_callbacks)
188
-    {
189
-        foreach ($update_callbacks as $key => $callback) {
190
-            if ($callback[1] == '_default_tickets_update') {
191
-                unset($update_callbacks[$key]);
192
-            }
193
-        }
194
-        
195
-        $update_callbacks[] = array($this, 'dtt_and_tickets_caf_update');
196
-        
197
-        return $update_callbacks;
198
-    }
187
+	public function caf_updates($update_callbacks)
188
+	{
189
+		foreach ($update_callbacks as $key => $callback) {
190
+			if ($callback[1] == '_default_tickets_update') {
191
+				unset($update_callbacks[$key]);
192
+			}
193
+		}
194
+        
195
+		$update_callbacks[] = array($this, 'dtt_and_tickets_caf_update');
196
+        
197
+		return $update_callbacks;
198
+	}
199 199
     
200 200
     
201
-    /**
202
-     * Handles saving everything related to Tickets (datetimes, tickets, prices)
203
-     *
204
-     * @param  EE_Event $evtobj The Event object we're attaching data to
205
-     * @param  array    $data   The request data from the form
206
-     *
207
-     * @return bool             success or fail
208
-     */
209
-    public function dtt_and_tickets_caf_update($evtobj, $data)
210
-    {
211
-        //first we need to start with datetimes cause they are the "root" items attached to events.
212
-        $saved_dtts = $this->_update_dtts($evtobj, $data);
213
-        //next tackle the tickets (and prices?)
214
-        $this->_update_tkts($evtobj, $saved_dtts, $data);
215
-    }
201
+	/**
202
+	 * Handles saving everything related to Tickets (datetimes, tickets, prices)
203
+	 *
204
+	 * @param  EE_Event $evtobj The Event object we're attaching data to
205
+	 * @param  array    $data   The request data from the form
206
+	 *
207
+	 * @return bool             success or fail
208
+	 */
209
+	public function dtt_and_tickets_caf_update($evtobj, $data)
210
+	{
211
+		//first we need to start with datetimes cause they are the "root" items attached to events.
212
+		$saved_dtts = $this->_update_dtts($evtobj, $data);
213
+		//next tackle the tickets (and prices?)
214
+		$this->_update_tkts($evtobj, $saved_dtts, $data);
215
+	}
216 216
     
217 217
     
218
-    /**
219
-     * update event_datetimes
220
-     *
221
-     * @param  EE_Event $evt_obj Event being updated
222
-     * @param  array    $data    the request data from the form
223
-     *
224
-     * @return EE_Datetime[]
225
-     */
226
-    protected function _update_dtts($evt_obj, $data)
227
-    {
228
-        $timezone       = isset($data['timezone_string']) ? $data['timezone_string'] : null;
229
-        $saved_dtt_ids  = array();
230
-        $saved_dtt_objs = array();
231
-        
232
-        foreach ($data['edit_event_datetimes'] as $row => $dtt) {
233
-            //trim all values to ensure any excess whitespace is removed.
234
-            $dtt                = array_map(
235
-                function ($datetime_data) {
236
-                    return is_array($datetime_data) ? $datetime_data : trim($datetime_data);
237
-                },
238
-                $dtt
239
-            );
240
-            $dtt['DTT_EVT_end'] = isset($dtt['DTT_EVT_end']) && ! empty($dtt['DTT_EVT_end']) ? $dtt['DTT_EVT_end'] : $dtt['DTT_EVT_start'];
241
-            $datetime_values    = array(
242
-                'DTT_ID'          => ! empty($dtt['DTT_ID']) ? $dtt['DTT_ID'] : null,
243
-                'DTT_name'        => ! empty($dtt['DTT_name']) ? $dtt['DTT_name'] : '',
244
-                'DTT_description' => ! empty($dtt['DTT_description']) ? $dtt['DTT_description'] : '',
245
-                'DTT_EVT_start'   => $dtt['DTT_EVT_start'],
246
-                'DTT_EVT_end'     => $dtt['DTT_EVT_end'],
247
-                'DTT_reg_limit'   => empty($dtt['DTT_reg_limit']) ? EE_INF : $dtt['DTT_reg_limit'],
248
-                'DTT_order'       => ! isset($dtt['DTT_order']) ? $row : $dtt['DTT_order'],
249
-            );
218
+	/**
219
+	 * update event_datetimes
220
+	 *
221
+	 * @param  EE_Event $evt_obj Event being updated
222
+	 * @param  array    $data    the request data from the form
223
+	 *
224
+	 * @return EE_Datetime[]
225
+	 */
226
+	protected function _update_dtts($evt_obj, $data)
227
+	{
228
+		$timezone       = isset($data['timezone_string']) ? $data['timezone_string'] : null;
229
+		$saved_dtt_ids  = array();
230
+		$saved_dtt_objs = array();
231
+        
232
+		foreach ($data['edit_event_datetimes'] as $row => $dtt) {
233
+			//trim all values to ensure any excess whitespace is removed.
234
+			$dtt                = array_map(
235
+				function ($datetime_data) {
236
+					return is_array($datetime_data) ? $datetime_data : trim($datetime_data);
237
+				},
238
+				$dtt
239
+			);
240
+			$dtt['DTT_EVT_end'] = isset($dtt['DTT_EVT_end']) && ! empty($dtt['DTT_EVT_end']) ? $dtt['DTT_EVT_end'] : $dtt['DTT_EVT_start'];
241
+			$datetime_values    = array(
242
+				'DTT_ID'          => ! empty($dtt['DTT_ID']) ? $dtt['DTT_ID'] : null,
243
+				'DTT_name'        => ! empty($dtt['DTT_name']) ? $dtt['DTT_name'] : '',
244
+				'DTT_description' => ! empty($dtt['DTT_description']) ? $dtt['DTT_description'] : '',
245
+				'DTT_EVT_start'   => $dtt['DTT_EVT_start'],
246
+				'DTT_EVT_end'     => $dtt['DTT_EVT_end'],
247
+				'DTT_reg_limit'   => empty($dtt['DTT_reg_limit']) ? EE_INF : $dtt['DTT_reg_limit'],
248
+				'DTT_order'       => ! isset($dtt['DTT_order']) ? $row : $dtt['DTT_order'],
249
+			);
250 250
             
251
-            //if we have an id then let's get existing object first and then set the new values.  Otherwise we instantiate a new object for save.
251
+			//if we have an id then let's get existing object first and then set the new values.  Otherwise we instantiate a new object for save.
252 252
             
253
-            if ( ! empty($dtt['DTT_ID'])) {
254
-                $DTM = EE_Registry::instance()->load_model('Datetime', array($timezone))->get_one_by_ID($dtt['DTT_ID']);
253
+			if ( ! empty($dtt['DTT_ID'])) {
254
+				$DTM = EE_Registry::instance()->load_model('Datetime', array($timezone))->get_one_by_ID($dtt['DTT_ID']);
255 255
                 
256
-                //set date and time format according to what is set in this class.
257
-                $DTM->set_date_format($this->_date_format_strings['date']);
258
-                $DTM->set_time_format($this->_date_format_strings['time']);
256
+				//set date and time format according to what is set in this class.
257
+				$DTM->set_date_format($this->_date_format_strings['date']);
258
+				$DTM->set_time_format($this->_date_format_strings['time']);
259 259
                 
260
-                foreach ($datetime_values as $field => $value) {
261
-                    $DTM->set($field, $value);
262
-                }
260
+				foreach ($datetime_values as $field => $value) {
261
+					$DTM->set($field, $value);
262
+				}
263 263
                 
264
-                // make sure the $dtt_id here is saved just in case after the add_relation_to() the autosave replaces it.
265
-                // We need to do this so we dont' TRASH the parent DTT.(save the ID for both key and value to avoid duplications)
266
-                $saved_dtt_ids[$DTM->ID()] = $DTM->ID();
264
+				// make sure the $dtt_id here is saved just in case after the add_relation_to() the autosave replaces it.
265
+				// We need to do this so we dont' TRASH the parent DTT.(save the ID for both key and value to avoid duplications)
266
+				$saved_dtt_ids[$DTM->ID()] = $DTM->ID();
267 267
                 
268
-            } else {
269
-                $DTM = EE_Registry::instance()->load_class(
270
-                    'Datetime',
271
-                    array(
272
-                        $datetime_values,
273
-                        $timezone,
274
-                        array($this->_date_format_strings['date'], $this->_date_format_strings['time'])
275
-                    ),
276
-                    false,
277
-                    false
278
-                );
268
+			} else {
269
+				$DTM = EE_Registry::instance()->load_class(
270
+					'Datetime',
271
+					array(
272
+						$datetime_values,
273
+						$timezone,
274
+						array($this->_date_format_strings['date'], $this->_date_format_strings['time'])
275
+					),
276
+					false,
277
+					false
278
+				);
279 279
                 
280
-                foreach ($datetime_values as $field => $value) {
281
-                    $DTM->set($field, $value);
282
-                }
283
-            }
280
+				foreach ($datetime_values as $field => $value) {
281
+					$DTM->set($field, $value);
282
+				}
283
+			}
284 284
             
285 285
             
286
-            $DTM->save();
287
-            $DTM = $evt_obj->_add_relation_to($DTM, 'Datetime');
288
-            $evt_obj->save();
286
+			$DTM->save();
287
+			$DTM = $evt_obj->_add_relation_to($DTM, 'Datetime');
288
+			$evt_obj->save();
289 289
             
290
-            //before going any further make sure our dates are setup correctly so that the end date is always equal or greater than the start date.
291
-            if ($DTM->get_raw('DTT_EVT_start') > $DTM->get_raw('DTT_EVT_end')) {
292
-                $DTM->set('DTT_EVT_end', $DTM->get('DTT_EVT_start'));
293
-                $DTM = EEH_DTT_Helper::date_time_add($DTM, 'DTT_EVT_end', 'days');
294
-                $DTM->save();
295
-            }
290
+			//before going any further make sure our dates are setup correctly so that the end date is always equal or greater than the start date.
291
+			if ($DTM->get_raw('DTT_EVT_start') > $DTM->get_raw('DTT_EVT_end')) {
292
+				$DTM->set('DTT_EVT_end', $DTM->get('DTT_EVT_start'));
293
+				$DTM = EEH_DTT_Helper::date_time_add($DTM, 'DTT_EVT_end', 'days');
294
+				$DTM->save();
295
+			}
296 296
             
297
-            //	now we have to make sure we add the new DTT_ID to the $saved_dtt_ids array
298
-            // because it is possible there was a new one created for the autosave.
299
-            // (save the ID for both key and value to avoid duplications)
300
-            $saved_dtt_ids[$DTM->ID()] = $DTM->ID();
301
-            $saved_dtt_objs[$row]      = $DTM;
297
+			//	now we have to make sure we add the new DTT_ID to the $saved_dtt_ids array
298
+			// because it is possible there was a new one created for the autosave.
299
+			// (save the ID for both key and value to avoid duplications)
300
+			$saved_dtt_ids[$DTM->ID()] = $DTM->ID();
301
+			$saved_dtt_objs[$row]      = $DTM;
302 302
             
303
-            //todo if ANY of these updates fail then we want the appropriate global error message.
304
-        }
305
-        
306
-        //now we need to REMOVE any dtts that got deleted.  Keep in mind that this process will only kick in for DTT's that don't have any DTT_sold on them. So its safe to permanently delete at this point.
307
-        $old_datetimes = explode(',', $data['datetime_IDs']);
308
-        $old_datetimes = $old_datetimes[0] == '' ? array() : $old_datetimes;
309
-        
310
-        if (is_array($old_datetimes)) {
311
-            $dtts_to_delete = array_diff($old_datetimes, $saved_dtt_ids);
312
-            foreach ($dtts_to_delete as $id) {
313
-                $id = absint($id);
314
-                if (empty($id)) {
315
-                    continue;
316
-                }
303
+			//todo if ANY of these updates fail then we want the appropriate global error message.
304
+		}
305
+        
306
+		//now we need to REMOVE any dtts that got deleted.  Keep in mind that this process will only kick in for DTT's that don't have any DTT_sold on them. So its safe to permanently delete at this point.
307
+		$old_datetimes = explode(',', $data['datetime_IDs']);
308
+		$old_datetimes = $old_datetimes[0] == '' ? array() : $old_datetimes;
309
+        
310
+		if (is_array($old_datetimes)) {
311
+			$dtts_to_delete = array_diff($old_datetimes, $saved_dtt_ids);
312
+			foreach ($dtts_to_delete as $id) {
313
+				$id = absint($id);
314
+				if (empty($id)) {
315
+					continue;
316
+				}
317 317
                 
318
-                $dtt_to_remove = EE_Registry::instance()->load_model('Datetime')->get_one_by_ID($id);
318
+				$dtt_to_remove = EE_Registry::instance()->load_model('Datetime')->get_one_by_ID($id);
319 319
                 
320
-                //remove tkt relationships.
321
-                $related_tickets = $dtt_to_remove->get_many_related('Ticket');
322
-                foreach ($related_tickets as $tkt) {
323
-                    $dtt_to_remove->_remove_relation_to($tkt, 'Ticket');
324
-                }
320
+				//remove tkt relationships.
321
+				$related_tickets = $dtt_to_remove->get_many_related('Ticket');
322
+				foreach ($related_tickets as $tkt) {
323
+					$dtt_to_remove->_remove_relation_to($tkt, 'Ticket');
324
+				}
325 325
                 
326
-                $evt_obj->_remove_relation_to($id, 'Datetime');
327
-                $dtt_to_remove->refresh_cache_of_related_objects();
326
+				$evt_obj->_remove_relation_to($id, 'Datetime');
327
+				$dtt_to_remove->refresh_cache_of_related_objects();
328 328
                 
329
-            }
330
-        }
329
+			}
330
+		}
331 331
         
332
-        return $saved_dtt_objs;
333
-    }
332
+		return $saved_dtt_objs;
333
+	}
334 334
     
335 335
     
336
-    /**
337
-     * update tickets
338
-     *
339
-     * @param  EE_Event      $evtobj     Event object being updated
340
-     * @param  EE_Datetime[] $saved_dtts an array of datetime ids being updated
341
-     * @param  array         $data       incoming request data
342
-     *
343
-     * @return EE_Ticket[]
344
-     */
345
-    protected function _update_tkts($evtobj, $saved_dtts, $data)
346
-    {
347
-        
348
-        $new_tkt     = null;
349
-        $new_default = null;
350
-        //stripslashes because WP filtered the $_POST ($data) array to add slashes
351
-        $data          = stripslashes_deep($data);
352
-        $timezone      = isset($data['timezone_string']) ? $data['timezone_string'] : null;
353
-        $saved_tickets = $dtts_on_existing = array();
354
-        $old_tickets   = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : array();
355
-        
356
-        //load money helper
357
-        
358
-        foreach ($data['edit_tickets'] as $row => $tkt) {
336
+	/**
337
+	 * update tickets
338
+	 *
339
+	 * @param  EE_Event      $evtobj     Event object being updated
340
+	 * @param  EE_Datetime[] $saved_dtts an array of datetime ids being updated
341
+	 * @param  array         $data       incoming request data
342
+	 *
343
+	 * @return EE_Ticket[]
344
+	 */
345
+	protected function _update_tkts($evtobj, $saved_dtts, $data)
346
+	{
347
+        
348
+		$new_tkt     = null;
349
+		$new_default = null;
350
+		//stripslashes because WP filtered the $_POST ($data) array to add slashes
351
+		$data          = stripslashes_deep($data);
352
+		$timezone      = isset($data['timezone_string']) ? $data['timezone_string'] : null;
353
+		$saved_tickets = $dtts_on_existing = array();
354
+		$old_tickets   = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : array();
355
+        
356
+		//load money helper
357
+        
358
+		foreach ($data['edit_tickets'] as $row => $tkt) {
359 359
             
360
-            $update_prices = $create_new_TKT = false;
360
+			$update_prices = $create_new_TKT = false;
361 361
             
362
-            //figure out what dtts were added to the ticket and what dtts were removed from the ticket in the session.
362
+			//figure out what dtts were added to the ticket and what dtts were removed from the ticket in the session.
363 363
             
364
-            $starting_tkt_dtt_rows = explode(',', $data['starting_ticket_datetime_rows'][$row]);
365
-            $tkt_dtt_rows          = explode(',', $data['ticket_datetime_rows'][$row]);
366
-            $dtts_added            = array_diff($tkt_dtt_rows, $starting_tkt_dtt_rows);
367
-            $dtts_removed          = array_diff($starting_tkt_dtt_rows, $tkt_dtt_rows);
364
+			$starting_tkt_dtt_rows = explode(',', $data['starting_ticket_datetime_rows'][$row]);
365
+			$tkt_dtt_rows          = explode(',', $data['ticket_datetime_rows'][$row]);
366
+			$dtts_added            = array_diff($tkt_dtt_rows, $starting_tkt_dtt_rows);
367
+			$dtts_removed          = array_diff($starting_tkt_dtt_rows, $tkt_dtt_rows);
368 368
             
369
-            // trim inputs to ensure any excess whitespace is removed.
370
-            $tkt = array_map(
371
-                function ($ticket_data) {
372
-                    return is_array($ticket_data) ? $ticket_data : trim($ticket_data);
373
-                },
374
-                $tkt
375
-            );
369
+			// trim inputs to ensure any excess whitespace is removed.
370
+			$tkt = array_map(
371
+				function ($ticket_data) {
372
+					return is_array($ticket_data) ? $ticket_data : trim($ticket_data);
373
+				},
374
+				$tkt
375
+			);
376 376
             
377
-            //note we are doing conversions to floats here instead of allowing EE_Money_Field to handle because we're doing calcs prior to using the models.
378
-            //note incoming ['TKT_price'] value is already in standard notation (via js).
379
-            $ticket_price = isset($tkt['TKT_price']) ? round((float)$tkt['TKT_price'], 3) : 0;
377
+			//note we are doing conversions to floats here instead of allowing EE_Money_Field to handle because we're doing calcs prior to using the models.
378
+			//note incoming ['TKT_price'] value is already in standard notation (via js).
379
+			$ticket_price = isset($tkt['TKT_price']) ? round((float)$tkt['TKT_price'], 3) : 0;
380 380
             
381
-            //note incoming base price needs converted from localized value.
382
-            $base_price = isset($tkt['TKT_base_price']) ? EEH_Money::convert_to_float_from_localized_money($tkt['TKT_base_price']) : 0;
383
-            //if ticket price == 0 and $base_price != 0 then ticket price == base_price
384
-            $ticket_price  = $ticket_price === 0 && $base_price !== 0 ? $base_price : $ticket_price;
385
-            $base_price_id = isset($tkt['TKT_base_price_ID']) ? $tkt['TKT_base_price_ID'] : 0;
381
+			//note incoming base price needs converted from localized value.
382
+			$base_price = isset($tkt['TKT_base_price']) ? EEH_Money::convert_to_float_from_localized_money($tkt['TKT_base_price']) : 0;
383
+			//if ticket price == 0 and $base_price != 0 then ticket price == base_price
384
+			$ticket_price  = $ticket_price === 0 && $base_price !== 0 ? $base_price : $ticket_price;
385
+			$base_price_id = isset($tkt['TKT_base_price_ID']) ? $tkt['TKT_base_price_ID'] : 0;
386 386
             
387
-            $price_rows = is_array($data['edit_prices']) && isset($data['edit_prices'][$row]) ? $data['edit_prices'][$row] : array();
387
+			$price_rows = is_array($data['edit_prices']) && isset($data['edit_prices'][$row]) ? $data['edit_prices'][$row] : array();
388 388
             
389
-            $now = null;
390
-            if (empty($tkt['TKT_start_date'])) {
391
-                //lets' use now in the set timezone.
392
-                $now                   = new DateTime('now', new DateTimeZone($evtobj->get_timezone()));
393
-                $tkt['TKT_start_date'] = $now->format($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']);
394
-            }
389
+			$now = null;
390
+			if (empty($tkt['TKT_start_date'])) {
391
+				//lets' use now in the set timezone.
392
+				$now                   = new DateTime('now', new DateTimeZone($evtobj->get_timezone()));
393
+				$tkt['TKT_start_date'] = $now->format($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']);
394
+			}
395 395
             
396
-            if (empty($tkt['TKT_end_date'])) {
397
-                /**
398
-                 * set the TKT_end_date to the first datetime attached to the ticket.
399
-                 */
400
-                $first_dtt           = $saved_dtts[reset($tkt_dtt_rows)];
401
-                $tkt['TKT_end_date'] = $first_dtt->start_date_and_time($this->_date_format_strings['date'] . ' ' . $this->_date_format_string['time']);
402
-            }
396
+			if (empty($tkt['TKT_end_date'])) {
397
+				/**
398
+				 * set the TKT_end_date to the first datetime attached to the ticket.
399
+				 */
400
+				$first_dtt           = $saved_dtts[reset($tkt_dtt_rows)];
401
+				$tkt['TKT_end_date'] = $first_dtt->start_date_and_time($this->_date_format_strings['date'] . ' ' . $this->_date_format_string['time']);
402
+			}
403 403
             
404
-            $TKT_values = array(
405
-                'TKT_ID'          => ! empty($tkt['TKT_ID']) ? $tkt['TKT_ID'] : null,
406
-                'TTM_ID'          => ! empty($tkt['TTM_ID']) ? $tkt['TTM_ID'] : 0,
407
-                'TKT_name'        => ! empty($tkt['TKT_name']) ? $tkt['TKT_name'] : '',
408
-                'TKT_description' => ! empty($tkt['TKT_description']) && $tkt['TKT_description'] != __('You can modify this description',
409
-                    'event_espresso') ? $tkt['TKT_description'] : '',
410
-                'TKT_start_date'  => $tkt['TKT_start_date'],
411
-                'TKT_end_date'    => $tkt['TKT_end_date'],
412
-                'TKT_qty'         => ! isset($tkt['TKT_qty']) || $tkt['TKT_qty'] === '' ? EE_INF : $tkt['TKT_qty'],
413
-                'TKT_uses'        => ! isset($tkt['TKT_uses']) || $tkt['TKT_uses'] === '' ? EE_INF : $tkt['TKT_uses'],
414
-                'TKT_min'         => empty($tkt['TKT_min']) ? 0 : $tkt['TKT_min'],
415
-                'TKT_max'         => empty($tkt['TKT_max']) ? EE_INF : $tkt['TKT_max'],
416
-                'TKT_row'         => $row,
417
-                'TKT_order'       => isset($tkt['TKT_order']) ? $tkt['TKT_order'] : 0,
418
-                'TKT_taxable'     => ! empty($tkt['TKT_taxable']) ? 1 : 0,
419
-                'TKT_required'    => ! empty($tkt['TKT_required']) ? 1 : 0,
420
-                'TKT_price'       => $ticket_price
421
-            );
404
+			$TKT_values = array(
405
+				'TKT_ID'          => ! empty($tkt['TKT_ID']) ? $tkt['TKT_ID'] : null,
406
+				'TTM_ID'          => ! empty($tkt['TTM_ID']) ? $tkt['TTM_ID'] : 0,
407
+				'TKT_name'        => ! empty($tkt['TKT_name']) ? $tkt['TKT_name'] : '',
408
+				'TKT_description' => ! empty($tkt['TKT_description']) && $tkt['TKT_description'] != __('You can modify this description',
409
+					'event_espresso') ? $tkt['TKT_description'] : '',
410
+				'TKT_start_date'  => $tkt['TKT_start_date'],
411
+				'TKT_end_date'    => $tkt['TKT_end_date'],
412
+				'TKT_qty'         => ! isset($tkt['TKT_qty']) || $tkt['TKT_qty'] === '' ? EE_INF : $tkt['TKT_qty'],
413
+				'TKT_uses'        => ! isset($tkt['TKT_uses']) || $tkt['TKT_uses'] === '' ? EE_INF : $tkt['TKT_uses'],
414
+				'TKT_min'         => empty($tkt['TKT_min']) ? 0 : $tkt['TKT_min'],
415
+				'TKT_max'         => empty($tkt['TKT_max']) ? EE_INF : $tkt['TKT_max'],
416
+				'TKT_row'         => $row,
417
+				'TKT_order'       => isset($tkt['TKT_order']) ? $tkt['TKT_order'] : 0,
418
+				'TKT_taxable'     => ! empty($tkt['TKT_taxable']) ? 1 : 0,
419
+				'TKT_required'    => ! empty($tkt['TKT_required']) ? 1 : 0,
420
+				'TKT_price'       => $ticket_price
421
+			);
422 422
             
423 423
             
424
-            //if this is a default TKT, then we need to set the TKT_ID to 0 and update accordingly, which means in turn that the prices will become new prices as well.
425
-            if (isset($tkt['TKT_is_default']) && $tkt['TKT_is_default']) {
426
-                $TKT_values['TKT_ID']         = 0;
427
-                $TKT_values['TKT_is_default'] = 0;
428
-                $update_prices                = true;
429
-            }
424
+			//if this is a default TKT, then we need to set the TKT_ID to 0 and update accordingly, which means in turn that the prices will become new prices as well.
425
+			if (isset($tkt['TKT_is_default']) && $tkt['TKT_is_default']) {
426
+				$TKT_values['TKT_ID']         = 0;
427
+				$TKT_values['TKT_is_default'] = 0;
428
+				$update_prices                = true;
429
+			}
430 430
             
431
-            // if we have a TKT_ID then we need to get that existing TKT_obj and update it
432
-            // we actually do our saves ahead of doing any add_relations to
433
-            // because its entirely possible that this ticket wasn't removed or added to any datetime in the session
434
-            // but DID have it's items modified.
435
-            // keep in mind that if the TKT has been sold (and we have changed pricing information),
436
-            // then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
437
-            if (absint($TKT_values['TKT_ID'])) {
438
-                $TKT = EE_Registry::instance()->load_model('Ticket', array($timezone))->get_one_by_ID($tkt['TKT_ID']);
439
-                if ($TKT instanceof EE_Ticket) {
431
+			// if we have a TKT_ID then we need to get that existing TKT_obj and update it
432
+			// we actually do our saves ahead of doing any add_relations to
433
+			// because its entirely possible that this ticket wasn't removed or added to any datetime in the session
434
+			// but DID have it's items modified.
435
+			// keep in mind that if the TKT has been sold (and we have changed pricing information),
436
+			// then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
437
+			if (absint($TKT_values['TKT_ID'])) {
438
+				$TKT = EE_Registry::instance()->load_model('Ticket', array($timezone))->get_one_by_ID($tkt['TKT_ID']);
439
+				if ($TKT instanceof EE_Ticket) {
440 440
                     
441
-                    $TKT = $this->_update_ticket_datetimes($TKT, $saved_dtts, $dtts_added, $dtts_removed);
442
-                    // are there any registrations using this ticket ?
443
-                    $tickets_sold = $TKT->count_related(
444
-                        'Registration',
445
-                        array(
446
-                            array(
447
-                                'STS_ID' => array('NOT IN', array(EEM_Registration::status_id_incomplete))
448
-                            )
449
-                        )
450
-                    );
451
-                    //set ticket formats
452
-                    $TKT->set_date_format($this->_date_format_strings['date']);
453
-                    $TKT->set_time_format($this->_date_format_strings['time']);
441
+					$TKT = $this->_update_ticket_datetimes($TKT, $saved_dtts, $dtts_added, $dtts_removed);
442
+					// are there any registrations using this ticket ?
443
+					$tickets_sold = $TKT->count_related(
444
+						'Registration',
445
+						array(
446
+							array(
447
+								'STS_ID' => array('NOT IN', array(EEM_Registration::status_id_incomplete))
448
+							)
449
+						)
450
+					);
451
+					//set ticket formats
452
+					$TKT->set_date_format($this->_date_format_strings['date']);
453
+					$TKT->set_time_format($this->_date_format_strings['time']);
454 454
                     
455
-                    // let's just check the total price for the existing ticket
456
-                    // and determine if it matches the new total price.
457
-                    // if they are different then we create a new ticket (if tkts sold)
458
-                    // if they aren't different then we go ahead and modify existing ticket.
459
-                    $create_new_TKT = $tickets_sold > 0 && $ticket_price != $TKT->price() && ! $TKT->deleted()
460
-                        ? true : false;
455
+					// let's just check the total price for the existing ticket
456
+					// and determine if it matches the new total price.
457
+					// if they are different then we create a new ticket (if tkts sold)
458
+					// if they aren't different then we go ahead and modify existing ticket.
459
+					$create_new_TKT = $tickets_sold > 0 && $ticket_price != $TKT->price() && ! $TKT->deleted()
460
+						? true : false;
461 461
                     
462
-                    //set new values
463
-                    foreach ($TKT_values as $field => $value) {
464
-                        if ($field === 'TKT_qty') {
465
-                            $TKT->set_qty($value);
466
-                        } else {
467
-                            $TKT->set($field, $value);
468
-                        }
469
-                    }
462
+					//set new values
463
+					foreach ($TKT_values as $field => $value) {
464
+						if ($field === 'TKT_qty') {
465
+							$TKT->set_qty($value);
466
+						} else {
467
+							$TKT->set($field, $value);
468
+						}
469
+					}
470 470
                     
471
-                    //if $create_new_TKT is false then we can safely update the existing ticket.  Otherwise we have to create a new ticket.
472
-                    if ($create_new_TKT) {
473
-                        $new_tkt = $this->_duplicate_ticket($TKT, $price_rows, $ticket_price, $base_price,
474
-                            $base_price_id);
475
-                    }
476
-                }
471
+					//if $create_new_TKT is false then we can safely update the existing ticket.  Otherwise we have to create a new ticket.
472
+					if ($create_new_TKT) {
473
+						$new_tkt = $this->_duplicate_ticket($TKT, $price_rows, $ticket_price, $base_price,
474
+							$base_price_id);
475
+					}
476
+				}
477 477
                 
478
-            } else {
479
-                // no TKT_id so a new TKT
480
-                $TKT = EE_Ticket::new_instance(
481
-                    $TKT_values,
482
-                    $timezone,
483
-                    array($this->_date_format_strings['date'], $this->_date_format_strings['time'])
484
-                );
485
-                if ($TKT instanceof EE_Ticket) {
486
-                    // make sure ticket has an ID of setting relations won't work
487
-                    $TKT->save();
488
-                    $TKT           = $this->_update_ticket_datetimes($TKT, $saved_dtts, $dtts_added, $dtts_removed);
489
-                    $update_prices = true;
490
-                }
491
-            }
492
-            //make sure any current values have been saved.
493
-            //$TKT->save();
478
+			} else {
479
+				// no TKT_id so a new TKT
480
+				$TKT = EE_Ticket::new_instance(
481
+					$TKT_values,
482
+					$timezone,
483
+					array($this->_date_format_strings['date'], $this->_date_format_strings['time'])
484
+				);
485
+				if ($TKT instanceof EE_Ticket) {
486
+					// make sure ticket has an ID of setting relations won't work
487
+					$TKT->save();
488
+					$TKT           = $this->_update_ticket_datetimes($TKT, $saved_dtts, $dtts_added, $dtts_removed);
489
+					$update_prices = true;
490
+				}
491
+			}
492
+			//make sure any current values have been saved.
493
+			//$TKT->save();
494 494
             
495
-            //before going any further make sure our dates are setup correctly so that the end date is always equal or greater than the start date.
496
-            if ($TKT->get_raw('TKT_start_date') > $TKT->get_raw('TKT_end_date')) {
497
-                $TKT->set('TKT_end_date', $TKT->get('TKT_start_date'));
498
-                $TKT = EEH_DTT_Helper::date_time_add($TKT, 'TKT_end_date', 'days');
499
-            }
495
+			//before going any further make sure our dates are setup correctly so that the end date is always equal or greater than the start date.
496
+			if ($TKT->get_raw('TKT_start_date') > $TKT->get_raw('TKT_end_date')) {
497
+				$TKT->set('TKT_end_date', $TKT->get('TKT_start_date'));
498
+				$TKT = EEH_DTT_Helper::date_time_add($TKT, 'TKT_end_date', 'days');
499
+			}
500 500
             
501
-            //let's make sure the base price is handled
502
-            $TKT = ! $create_new_TKT ? $this->_add_prices_to_ticket(array(), $TKT, $update_prices, $base_price,
503
-                $base_price_id) : $TKT;
501
+			//let's make sure the base price is handled
502
+			$TKT = ! $create_new_TKT ? $this->_add_prices_to_ticket(array(), $TKT, $update_prices, $base_price,
503
+				$base_price_id) : $TKT;
504 504
             
505
-            //add/update price_modifiers
506
-            $TKT = ! $create_new_TKT ? $this->_add_prices_to_ticket($price_rows, $TKT, $update_prices) : $TKT;
505
+			//add/update price_modifiers
506
+			$TKT = ! $create_new_TKT ? $this->_add_prices_to_ticket($price_rows, $TKT, $update_prices) : $TKT;
507 507
             
508
-            //need to make sue that the TKT_price is accurate after saving the prices.
509
-            $TKT->ensure_TKT_Price_correct();
508
+			//need to make sue that the TKT_price is accurate after saving the prices.
509
+			$TKT->ensure_TKT_Price_correct();
510 510
             
511
-            //handle CREATING a default tkt from the incoming tkt but ONLY if this isn't an autosave.
512
-            if ( ! defined('DOING_AUTOSAVE')) {
513
-                if ( ! empty($tkt['TKT_is_default_selector'])) {
514
-                    $update_prices = true;
515
-                    $new_default   = clone $TKT;
516
-                    $new_default->set('TKT_ID', 0);
517
-                    $new_default->set('TKT_is_default', 1);
518
-                    $new_default->set('TKT_row', 1);
519
-                    $new_default->set('TKT_price', $ticket_price);
520
-                    //remove any dtt relations cause we DON'T want dtt relations attached (note this is just removing the cached relations in the object)
521
-                    $new_default->_remove_relations('Datetime');
522
-                    //todo we need to add the current attached prices as new prices to the new default ticket.
523
-                    $new_default = $this->_add_prices_to_ticket($price_rows, $new_default, $update_prices);
524
-                    //don't forget the base price!
525
-                    $new_default = $this->_add_prices_to_ticket(array(), $new_default, $update_prices, $base_price,
526
-                        $base_price_id);
527
-                    $new_default->save();
528
-                    do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_new_default_ticket', $new_default,
529
-                        $row, $TKT, $data);
530
-                }
531
-            }
511
+			//handle CREATING a default tkt from the incoming tkt but ONLY if this isn't an autosave.
512
+			if ( ! defined('DOING_AUTOSAVE')) {
513
+				if ( ! empty($tkt['TKT_is_default_selector'])) {
514
+					$update_prices = true;
515
+					$new_default   = clone $TKT;
516
+					$new_default->set('TKT_ID', 0);
517
+					$new_default->set('TKT_is_default', 1);
518
+					$new_default->set('TKT_row', 1);
519
+					$new_default->set('TKT_price', $ticket_price);
520
+					//remove any dtt relations cause we DON'T want dtt relations attached (note this is just removing the cached relations in the object)
521
+					$new_default->_remove_relations('Datetime');
522
+					//todo we need to add the current attached prices as new prices to the new default ticket.
523
+					$new_default = $this->_add_prices_to_ticket($price_rows, $new_default, $update_prices);
524
+					//don't forget the base price!
525
+					$new_default = $this->_add_prices_to_ticket(array(), $new_default, $update_prices, $base_price,
526
+						$base_price_id);
527
+					$new_default->save();
528
+					do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_new_default_ticket', $new_default,
529
+						$row, $TKT, $data);
530
+				}
531
+			}
532 532
             
533 533
             
534
-            //DO ALL dtt relationships for both current tickets and any archived tickets for the given dtt that are related to the current ticket. TODO... not sure exactly how we're going to do this considering we don't know what current ticket the archived tickets are related to (and TKT_parent is used for autosaves so that's not a field we can reliably use).
534
+			//DO ALL dtt relationships for both current tickets and any archived tickets for the given dtt that are related to the current ticket. TODO... not sure exactly how we're going to do this considering we don't know what current ticket the archived tickets are related to (and TKT_parent is used for autosaves so that's not a field we can reliably use).
535 535
             
536 536
             
537
-            //let's assign any tickets that have been setup to the saved_tickets tracker
538
-            //save existing TKT
539
-            $TKT->save();
540
-            if ($create_new_TKT && $new_tkt instanceof EE_Ticket) {
541
-                //save new TKT
542
-                $new_tkt->save();
543
-                //add new ticket to array
544
-                $saved_tickets[$new_tkt->ID()] = $new_tkt;
537
+			//let's assign any tickets that have been setup to the saved_tickets tracker
538
+			//save existing TKT
539
+			$TKT->save();
540
+			if ($create_new_TKT && $new_tkt instanceof EE_Ticket) {
541
+				//save new TKT
542
+				$new_tkt->save();
543
+				//add new ticket to array
544
+				$saved_tickets[$new_tkt->ID()] = $new_tkt;
545 545
                 
546
-                do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_new_ticket', $new_tkt, $row, $tkt, $data);
546
+				do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_new_ticket', $new_tkt, $row, $tkt, $data);
547 547
                 
548
-            } else {
549
-                //add tkt to saved tkts
550
-                $saved_tickets[$TKT->ID()] = $TKT;
548
+			} else {
549
+				//add tkt to saved tkts
550
+				$saved_tickets[$TKT->ID()] = $TKT;
551 551
                 
552
-                do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_update_ticket', $TKT, $row, $tkt, $data);
553
-            }
552
+				do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_update_ticket', $TKT, $row, $tkt, $data);
553
+			}
554 554
             
555
-        }
556
-        
557
-        // now we need to handle tickets actually "deleted permanently".
558
-        // There are cases where we'd want this to happen
559
-        // (i.e. autosaves are happening and then in between autosaves the user trashes a ticket).
560
-        // Or a draft event was saved and in the process of editing a ticket is trashed.
561
-        // No sense in keeping all the related data in the db!
562
-        $old_tickets     = isset($old_tickets[0]) && $old_tickets[0] == '' ? array() : $old_tickets;
563
-        $tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
564
-        
565
-        foreach ($tickets_removed as $id) {
566
-            $id = absint($id);
555
+		}
556
+        
557
+		// now we need to handle tickets actually "deleted permanently".
558
+		// There are cases where we'd want this to happen
559
+		// (i.e. autosaves are happening and then in between autosaves the user trashes a ticket).
560
+		// Or a draft event was saved and in the process of editing a ticket is trashed.
561
+		// No sense in keeping all the related data in the db!
562
+		$old_tickets     = isset($old_tickets[0]) && $old_tickets[0] == '' ? array() : $old_tickets;
563
+		$tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
564
+        
565
+		foreach ($tickets_removed as $id) {
566
+			$id = absint($id);
567 567
             
568
-            //get the ticket for this id
569
-            $tkt_to_remove = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($id);
568
+			//get the ticket for this id
569
+			$tkt_to_remove = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($id);
570 570
             
571
-            //if this tkt is a default tkt we leave it alone cause it won't be attached to the datetime
572
-            if ($tkt_to_remove->get('TKT_is_default')) {
573
-                continue;
574
-            }
571
+			//if this tkt is a default tkt we leave it alone cause it won't be attached to the datetime
572
+			if ($tkt_to_remove->get('TKT_is_default')) {
573
+				continue;
574
+			}
575 575
             
576
-            // if this tkt has any registrations attached so then we just ARCHIVE
577
-            // because we don't actually permanently delete these tickets.
578
-            if ($tkt_to_remove->count_related('Registration') > 0) {
579
-                $tkt_to_remove->delete();
580
-                continue;
581
-            }
576
+			// if this tkt has any registrations attached so then we just ARCHIVE
577
+			// because we don't actually permanently delete these tickets.
578
+			if ($tkt_to_remove->count_related('Registration') > 0) {
579
+				$tkt_to_remove->delete();
580
+				continue;
581
+			}
582 582
             
583
-            // need to get all the related datetimes on this ticket and remove from every single one of them
584
-            // (remember this process can ONLY kick off if there are NO tkts_sold)
585
-            $dtts = $tkt_to_remove->get_many_related('Datetime');
583
+			// need to get all the related datetimes on this ticket and remove from every single one of them
584
+			// (remember this process can ONLY kick off if there are NO tkts_sold)
585
+			$dtts = $tkt_to_remove->get_many_related('Datetime');
586 586
             
587
-            foreach ($dtts as $dtt) {
588
-                $tkt_to_remove->_remove_relation_to($dtt, 'Datetime');
589
-            }
587
+			foreach ($dtts as $dtt) {
588
+				$tkt_to_remove->_remove_relation_to($dtt, 'Datetime');
589
+			}
590 590
             
591
-            // need to do the same for prices (except these prices can also be deleted because again,
592
-            // tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
593
-            $tkt_to_remove->delete_related_permanently('Price');
591
+			// need to do the same for prices (except these prices can also be deleted because again,
592
+			// tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
593
+			$tkt_to_remove->delete_related_permanently('Price');
594 594
             
595
-            do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_delete_ticket', $tkt_to_remove);
595
+			do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_delete_ticket', $tkt_to_remove);
596 596
             
597
-            // finally let's delete this ticket
598
-            // (which should not be blocked at this point b/c we've removed all our relationships)
599
-            $tkt_to_remove->delete_permanently();
600
-        }
597
+			// finally let's delete this ticket
598
+			// (which should not be blocked at this point b/c we've removed all our relationships)
599
+			$tkt_to_remove->delete_permanently();
600
+		}
601 601
         
602
-        return $saved_tickets;
603
-    }
602
+		return $saved_tickets;
603
+	}
604 604
     
605 605
     
606
-    /**
607
-     *
608
-     * @access  protected
609
-     *
610
-     * @param \EE_Ticket     $ticket
611
-     * @param \EE_Datetime[] $saved_datetimes
612
-     * @param \EE_Datetime[] $added_datetimes
613
-     * @param \EE_Datetime[] $removed_datetimes
614
-     *
615
-     * @return \EE_Ticket
616
-     * @throws \EE_Error
617
-     */
618
-    protected function _update_ticket_datetimes(
619
-        EE_Ticket $ticket,
620
-        $saved_datetimes = array(),
621
-        $added_datetimes = array(),
622
-        $removed_datetimes = array()
623
-    ) {
624
-        
625
-        // to start we have to add the ticket to all the datetimes its supposed to be with,
626
-        // and removing the ticket from datetimes it got removed from.
627
-        
628
-        // first let's add datetimes
629
-        if ( ! empty($added_datetimes) && is_array($added_datetimes)) {
630
-            foreach ($added_datetimes as $row_id) {
631
-                $row_id = (int)$row_id;
632
-                if (isset($saved_datetimes[$row_id]) && $saved_datetimes[$row_id] instanceof EE_Datetime) {
633
-                    $ticket->_add_relation_to($saved_datetimes[$row_id], 'Datetime');
634
-                    // Is this an existing ticket (has an ID) and does it have any sold?
635
-                    // If so, then we need to add that to the DTT sold because this DTT is getting added.
636
-                    if ($ticket->ID() && $ticket->sold() > 0) {
637
-                        $saved_datetimes[$row_id]->increase_sold($ticket->sold());
638
-                        $saved_datetimes[$row_id]->save();
639
-                    }
640
-                }
641
-            }
642
-        }
643
-        // then remove datetimes
644
-        if ( ! empty($removed_datetimes) && is_array($removed_datetimes)) {
645
-            foreach ($removed_datetimes as $row_id) {
646
-                $row_id = (int)$row_id;
647
-                // its entirely possible that a datetime got deleted (instead of just removed from relationship.
648
-                // So make sure we skip over this if the dtt isn't in the $saved_datetimes array)
649
-                if (isset($saved_datetimes[$row_id]) && $saved_datetimes[$row_id] instanceof EE_Datetime) {
650
-                    $ticket->_remove_relation_to($saved_datetimes[$row_id], 'Datetime');
651
-                    // Is this an existing ticket (has an ID) and does it have any sold?
652
-                    // If so, then we need to remove it's sold from the DTT_sold.
653
-                    if ($ticket->ID() && $ticket->sold() > 0) {
654
-                        $saved_datetimes[$row_id]->decrease_sold($ticket->sold());
655
-                        $saved_datetimes[$row_id]->save();
656
-                    }
657
-                }
658
-            }
659
-        }
660
-        // cap ticket qty by datetime reg limits
661
-        $ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
662
-        
663
-        return $ticket;
664
-    }
606
+	/**
607
+	 *
608
+	 * @access  protected
609
+	 *
610
+	 * @param \EE_Ticket     $ticket
611
+	 * @param \EE_Datetime[] $saved_datetimes
612
+	 * @param \EE_Datetime[] $added_datetimes
613
+	 * @param \EE_Datetime[] $removed_datetimes
614
+	 *
615
+	 * @return \EE_Ticket
616
+	 * @throws \EE_Error
617
+	 */
618
+	protected function _update_ticket_datetimes(
619
+		EE_Ticket $ticket,
620
+		$saved_datetimes = array(),
621
+		$added_datetimes = array(),
622
+		$removed_datetimes = array()
623
+	) {
624
+        
625
+		// to start we have to add the ticket to all the datetimes its supposed to be with,
626
+		// and removing the ticket from datetimes it got removed from.
627
+        
628
+		// first let's add datetimes
629
+		if ( ! empty($added_datetimes) && is_array($added_datetimes)) {
630
+			foreach ($added_datetimes as $row_id) {
631
+				$row_id = (int)$row_id;
632
+				if (isset($saved_datetimes[$row_id]) && $saved_datetimes[$row_id] instanceof EE_Datetime) {
633
+					$ticket->_add_relation_to($saved_datetimes[$row_id], 'Datetime');
634
+					// Is this an existing ticket (has an ID) and does it have any sold?
635
+					// If so, then we need to add that to the DTT sold because this DTT is getting added.
636
+					if ($ticket->ID() && $ticket->sold() > 0) {
637
+						$saved_datetimes[$row_id]->increase_sold($ticket->sold());
638
+						$saved_datetimes[$row_id]->save();
639
+					}
640
+				}
641
+			}
642
+		}
643
+		// then remove datetimes
644
+		if ( ! empty($removed_datetimes) && is_array($removed_datetimes)) {
645
+			foreach ($removed_datetimes as $row_id) {
646
+				$row_id = (int)$row_id;
647
+				// its entirely possible that a datetime got deleted (instead of just removed from relationship.
648
+				// So make sure we skip over this if the dtt isn't in the $saved_datetimes array)
649
+				if (isset($saved_datetimes[$row_id]) && $saved_datetimes[$row_id] instanceof EE_Datetime) {
650
+					$ticket->_remove_relation_to($saved_datetimes[$row_id], 'Datetime');
651
+					// Is this an existing ticket (has an ID) and does it have any sold?
652
+					// If so, then we need to remove it's sold from the DTT_sold.
653
+					if ($ticket->ID() && $ticket->sold() > 0) {
654
+						$saved_datetimes[$row_id]->decrease_sold($ticket->sold());
655
+						$saved_datetimes[$row_id]->save();
656
+					}
657
+				}
658
+			}
659
+		}
660
+		// cap ticket qty by datetime reg limits
661
+		$ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
662
+        
663
+		return $ticket;
664
+	}
665 665
     
666 666
     
667
-    /**
668
-     *
669
-     * @access  protected
670
-     *
671
-     * @param \EE_Ticket $ticket
672
-     * @param array      $price_rows
673
-     * @param int        $ticket_price
674
-     * @param int        $base_price
675
-     * @param int        $base_price_id
676
-     *
677
-     * @return \EE_Ticket
678
-     * @throws \EE_Error
679
-     */
680
-    protected function _duplicate_ticket(
681
-        EE_Ticket $ticket,
682
-        $price_rows = array(),
683
-        $ticket_price = 0,
684
-        $base_price = 0,
685
-        $base_price_id = 0
686
-    ) {
687
-        
688
-        // create new ticket that's a copy of the existing
689
-        // except a new id of course (and not archived)
690
-        // AND has the new TKT_price associated with it.
691
-        $new_ticket = clone($ticket);
692
-        $new_ticket->set('TKT_ID', 0);
693
-        $new_ticket->set('TKT_deleted', 0);
694
-        $new_ticket->set('TKT_price', $ticket_price);
695
-        $new_ticket->set('TKT_sold', 0);
696
-        // let's get a new ID for this ticket
697
-        $new_ticket->save();
698
-        // we also need to make sure this new ticket gets the same datetime attachments as the archived ticket
699
-        $datetimes_on_existing = $ticket->get_many_related('Datetime');
700
-        $new_ticket            = $this->_update_ticket_datetimes(
701
-            $new_ticket,
702
-            $datetimes_on_existing,
703
-            array_keys($datetimes_on_existing)
704
-        );
705
-        
706
-        // $ticket will get archived later b/c we are NOT adding it to the saved_tickets array.
707
-        // if existing $ticket has sold amount, then we need to adjust the qty for the new TKT to = the remaining
708
-        // available.
709
-        if ($ticket->sold() > 0) {
710
-            $new_qty = $ticket->qty() - $ticket->sold();
711
-            $new_ticket->set_qty($new_qty);
712
-        }
713
-        //now we update the prices just for this ticket
714
-        $new_ticket = $this->_add_prices_to_ticket($price_rows, $new_ticket, true);
715
-        //and we update the base price
716
-        $new_ticket = $this->_add_prices_to_ticket(array(), $new_ticket, true, $base_price, $base_price_id);
717
-        
718
-        return $new_ticket;
719
-    }
667
+	/**
668
+	 *
669
+	 * @access  protected
670
+	 *
671
+	 * @param \EE_Ticket $ticket
672
+	 * @param array      $price_rows
673
+	 * @param int        $ticket_price
674
+	 * @param int        $base_price
675
+	 * @param int        $base_price_id
676
+	 *
677
+	 * @return \EE_Ticket
678
+	 * @throws \EE_Error
679
+	 */
680
+	protected function _duplicate_ticket(
681
+		EE_Ticket $ticket,
682
+		$price_rows = array(),
683
+		$ticket_price = 0,
684
+		$base_price = 0,
685
+		$base_price_id = 0
686
+	) {
687
+        
688
+		// create new ticket that's a copy of the existing
689
+		// except a new id of course (and not archived)
690
+		// AND has the new TKT_price associated with it.
691
+		$new_ticket = clone($ticket);
692
+		$new_ticket->set('TKT_ID', 0);
693
+		$new_ticket->set('TKT_deleted', 0);
694
+		$new_ticket->set('TKT_price', $ticket_price);
695
+		$new_ticket->set('TKT_sold', 0);
696
+		// let's get a new ID for this ticket
697
+		$new_ticket->save();
698
+		// we also need to make sure this new ticket gets the same datetime attachments as the archived ticket
699
+		$datetimes_on_existing = $ticket->get_many_related('Datetime');
700
+		$new_ticket            = $this->_update_ticket_datetimes(
701
+			$new_ticket,
702
+			$datetimes_on_existing,
703
+			array_keys($datetimes_on_existing)
704
+		);
705
+        
706
+		// $ticket will get archived later b/c we are NOT adding it to the saved_tickets array.
707
+		// if existing $ticket has sold amount, then we need to adjust the qty for the new TKT to = the remaining
708
+		// available.
709
+		if ($ticket->sold() > 0) {
710
+			$new_qty = $ticket->qty() - $ticket->sold();
711
+			$new_ticket->set_qty($new_qty);
712
+		}
713
+		//now we update the prices just for this ticket
714
+		$new_ticket = $this->_add_prices_to_ticket($price_rows, $new_ticket, true);
715
+		//and we update the base price
716
+		$new_ticket = $this->_add_prices_to_ticket(array(), $new_ticket, true, $base_price, $base_price_id);
717
+        
718
+		return $new_ticket;
719
+	}
720 720
     
721 721
     
722
-    /**
723
-     * This attaches a list of given prices to a ticket.
724
-     * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
725
-     * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
726
-     * price info and prices are automatically "archived" via the ticket.
727
-     *
728
-     * @access  private
729
-     *
730
-     * @param array     $prices        Array of prices from the form.
731
-     * @param EE_Ticket $ticket        EE_Ticket object that prices are being attached to.
732
-     * @param bool      $new_prices    Whether attach existing incoming prices or create new ones.
733
-     * @param int|bool  $base_price    if FALSE then NOT doing a base price add.
734
-     * @param int|bool  $base_price_id if present then this is the base_price_id being updated.
735
-     *
736
-     * @return EE_Ticket
737
-     */
738
-    protected function _add_prices_to_ticket(
739
-        $prices = array(),
740
-        EE_Ticket $ticket,
741
-        $new_prices = false,
742
-        $base_price = false,
743
-        $base_price_id = false
744
-    ) {
745
-        
746
-        //let's just get any current prices that may exist on the given ticket so we can remove any prices that got trashed in this session.
747
-        $current_prices_on_ticket = $base_price !== false ? $ticket->base_price(true) : $ticket->price_modifiers();
748
-        
749
-        $updated_prices = array();
750
-        
751
-        // if $base_price ! FALSE then updating a base price.
752
-        if ($base_price !== false) {
753
-            $prices[1] = array(
754
-                'PRC_ID'     => $new_prices || $base_price_id === 1 ? null : $base_price_id,
755
-                'PRT_ID'     => 1,
756
-                'PRC_amount' => $base_price,
757
-                'PRC_name'   => $ticket->get('TKT_name'),
758
-                'PRC_desc'   => $ticket->get('TKT_description')
759
-            );
760
-        }
761
-        
762
-        //possibly need to save tkt
763
-        if ( ! $ticket->ID()) {
764
-            $ticket->save();
765
-        }
766
-        
767
-        foreach ($prices as $row => $prc) {
768
-            $prt_id = ! empty($prc['PRT_ID']) ? $prc['PRT_ID'] : null;
769
-            if (empty($prt_id)) {
770
-                continue;
771
-            } //prices MUST have a price type id.
772
-            $PRC_values = array(
773
-                'PRC_ID'         => ! empty($prc['PRC_ID']) ? $prc['PRC_ID'] : null,
774
-                'PRT_ID'         => $prt_id,
775
-                'PRC_amount'     => ! empty($prc['PRC_amount']) ? $prc['PRC_amount'] : 0,
776
-                'PRC_name'       => ! empty($prc['PRC_name']) ? $prc['PRC_name'] : '',
777
-                'PRC_desc'       => ! empty($prc['PRC_desc']) ? $prc['PRC_desc'] : '',
778
-                'PRC_is_default' => false,
779
-                //make sure we set PRC_is_default to false for all ticket saves from event_editor
780
-                'PRC_order'      => $row
781
-            );
782
-            if ($new_prices || empty($PRC_values['PRC_ID'])) {
783
-                $PRC_values['PRC_ID'] = 0;
784
-                $PRC                  = EE_Registry::instance()->load_class('Price', array($PRC_values), false, false);
785
-            } else {
786
-                $PRC = EE_Registry::instance()->load_model('Price')->get_one_by_ID($prc['PRC_ID']);
787
-                //update this price with new values
788
-                foreach ($PRC_values as $field => $newprc) {
789
-                    $PRC->set($field, $newprc);
790
-                }
791
-            }
792
-            $PRC->save();
793
-            $prcid                  = $PRC->ID();
794
-            $updated_prices[$prcid] = $PRC;
795
-            $ticket->_add_relation_to($PRC, 'Price');
796
-        }
797
-        
798
-        //now let's remove any prices that got removed from the ticket
799
-        if ( ! empty ($current_prices_on_ticket)) {
800
-            $current          = array_keys($current_prices_on_ticket);
801
-            $updated          = array_keys($updated_prices);
802
-            $prices_to_remove = array_diff($current, $updated);
803
-            if ( ! empty($prices_to_remove)) {
804
-                foreach ($prices_to_remove as $prc_id) {
805
-                    $p = $current_prices_on_ticket[$prc_id];
806
-                    $ticket->_remove_relation_to($p, 'Price');
722
+	/**
723
+	 * This attaches a list of given prices to a ticket.
724
+	 * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
725
+	 * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
726
+	 * price info and prices are automatically "archived" via the ticket.
727
+	 *
728
+	 * @access  private
729
+	 *
730
+	 * @param array     $prices        Array of prices from the form.
731
+	 * @param EE_Ticket $ticket        EE_Ticket object that prices are being attached to.
732
+	 * @param bool      $new_prices    Whether attach existing incoming prices or create new ones.
733
+	 * @param int|bool  $base_price    if FALSE then NOT doing a base price add.
734
+	 * @param int|bool  $base_price_id if present then this is the base_price_id being updated.
735
+	 *
736
+	 * @return EE_Ticket
737
+	 */
738
+	protected function _add_prices_to_ticket(
739
+		$prices = array(),
740
+		EE_Ticket $ticket,
741
+		$new_prices = false,
742
+		$base_price = false,
743
+		$base_price_id = false
744
+	) {
745
+        
746
+		//let's just get any current prices that may exist on the given ticket so we can remove any prices that got trashed in this session.
747
+		$current_prices_on_ticket = $base_price !== false ? $ticket->base_price(true) : $ticket->price_modifiers();
748
+        
749
+		$updated_prices = array();
750
+        
751
+		// if $base_price ! FALSE then updating a base price.
752
+		if ($base_price !== false) {
753
+			$prices[1] = array(
754
+				'PRC_ID'     => $new_prices || $base_price_id === 1 ? null : $base_price_id,
755
+				'PRT_ID'     => 1,
756
+				'PRC_amount' => $base_price,
757
+				'PRC_name'   => $ticket->get('TKT_name'),
758
+				'PRC_desc'   => $ticket->get('TKT_description')
759
+			);
760
+		}
761
+        
762
+		//possibly need to save tkt
763
+		if ( ! $ticket->ID()) {
764
+			$ticket->save();
765
+		}
766
+        
767
+		foreach ($prices as $row => $prc) {
768
+			$prt_id = ! empty($prc['PRT_ID']) ? $prc['PRT_ID'] : null;
769
+			if (empty($prt_id)) {
770
+				continue;
771
+			} //prices MUST have a price type id.
772
+			$PRC_values = array(
773
+				'PRC_ID'         => ! empty($prc['PRC_ID']) ? $prc['PRC_ID'] : null,
774
+				'PRT_ID'         => $prt_id,
775
+				'PRC_amount'     => ! empty($prc['PRC_amount']) ? $prc['PRC_amount'] : 0,
776
+				'PRC_name'       => ! empty($prc['PRC_name']) ? $prc['PRC_name'] : '',
777
+				'PRC_desc'       => ! empty($prc['PRC_desc']) ? $prc['PRC_desc'] : '',
778
+				'PRC_is_default' => false,
779
+				//make sure we set PRC_is_default to false for all ticket saves from event_editor
780
+				'PRC_order'      => $row
781
+			);
782
+			if ($new_prices || empty($PRC_values['PRC_ID'])) {
783
+				$PRC_values['PRC_ID'] = 0;
784
+				$PRC                  = EE_Registry::instance()->load_class('Price', array($PRC_values), false, false);
785
+			} else {
786
+				$PRC = EE_Registry::instance()->load_model('Price')->get_one_by_ID($prc['PRC_ID']);
787
+				//update this price with new values
788
+				foreach ($PRC_values as $field => $newprc) {
789
+					$PRC->set($field, $newprc);
790
+				}
791
+			}
792
+			$PRC->save();
793
+			$prcid                  = $PRC->ID();
794
+			$updated_prices[$prcid] = $PRC;
795
+			$ticket->_add_relation_to($PRC, 'Price');
796
+		}
797
+        
798
+		//now let's remove any prices that got removed from the ticket
799
+		if ( ! empty ($current_prices_on_ticket)) {
800
+			$current          = array_keys($current_prices_on_ticket);
801
+			$updated          = array_keys($updated_prices);
802
+			$prices_to_remove = array_diff($current, $updated);
803
+			if ( ! empty($prices_to_remove)) {
804
+				foreach ($prices_to_remove as $prc_id) {
805
+					$p = $current_prices_on_ticket[$prc_id];
806
+					$ticket->_remove_relation_to($p, 'Price');
807 807
                     
808
-                    //delete permanently the price
809
-                    $p->delete_permanently();
810
-                }
811
-            }
812
-        }
813
-        
814
-        return $ticket;
815
-    }
808
+					//delete permanently the price
809
+					$p->delete_permanently();
810
+				}
811
+			}
812
+		}
813
+        
814
+		return $ticket;
815
+	}
816 816
     
817 817
     
818
-    public function autosave_handling($event_admin_obj)
819
-    {
820
-        return $event_admin_obj; //doing nothing for the moment.
821
-        //todo when I get to this remember that I need to set the template args on the $event_admin_obj (use the set_template_args() method)
822
-        
823
-        /**
824
-         * need to remember to handle TICKET DEFAULT saves correctly:  I've got two input fields in the dom:
825
-         *
826
-         * 1. TKT_is_default_selector (visible)
827
-         * 2. TKT_is_default (hidden)
828
-         *
829
-         * I think we'll use the TKT_is_default for recording whether the ticket displayed IS a default ticket (on new event creations). Whereas the TKT_is_default_selector is for the user to indicate they want this ticket to be saved as a default.
830
-         *
831
-         * The tricky part is, on an initial display on create or edit (or after manually updating), the TKT_is_default_selector will always be unselected and the TKT_is_default will only be true if this is a create.  However, after an autosave, users will want some sort of indicator that the TKT HAS been saved as a default.. in other words we don't want to remove the check on TKT_is_default_selector. So here's what I'm thinking.
832
-         * On Autosave:
833
-         * 1. If TKT_is_default is true: we create a new TKT, send back the new id and add id to related elements, then set the TKT_is_default to false.
834
-         * 2. If TKT_is_default_selector is true: we create/edit existing ticket (following conditions above as well).  We do NOT create a new default ticket.  The checkbox stays selected after autosave.
835
-         * 3. only on MANUAL update do we check for the selection and if selected create the new default ticket.
836
-         */
837
-    }
818
+	public function autosave_handling($event_admin_obj)
819
+	{
820
+		return $event_admin_obj; //doing nothing for the moment.
821
+		//todo when I get to this remember that I need to set the template args on the $event_admin_obj (use the set_template_args() method)
822
+        
823
+		/**
824
+		 * need to remember to handle TICKET DEFAULT saves correctly:  I've got two input fields in the dom:
825
+		 *
826
+		 * 1. TKT_is_default_selector (visible)
827
+		 * 2. TKT_is_default (hidden)
828
+		 *
829
+		 * I think we'll use the TKT_is_default for recording whether the ticket displayed IS a default ticket (on new event creations). Whereas the TKT_is_default_selector is for the user to indicate they want this ticket to be saved as a default.
830
+		 *
831
+		 * The tricky part is, on an initial display on create or edit (or after manually updating), the TKT_is_default_selector will always be unselected and the TKT_is_default will only be true if this is a create.  However, after an autosave, users will want some sort of indicator that the TKT HAS been saved as a default.. in other words we don't want to remove the check on TKT_is_default_selector. So here's what I'm thinking.
832
+		 * On Autosave:
833
+		 * 1. If TKT_is_default is true: we create a new TKT, send back the new id and add id to related elements, then set the TKT_is_default to false.
834
+		 * 2. If TKT_is_default_selector is true: we create/edit existing ticket (following conditions above as well).  We do NOT create a new default ticket.  The checkbox stays selected after autosave.
835
+		 * 3. only on MANUAL update do we check for the selection and if selected create the new default ticket.
836
+		 */
837
+	}
838 838
     
839 839
     
840
-    public function pricing_metabox()
841
-    {
842
-        $existing_datetime_ids = $existing_ticket_ids = $datetime_tickets = $ticket_datetimes = array();
843
-        
844
-        $evtobj = $this->_adminpage_obj->get_cpt_model_obj();
845
-        
846
-        //set is_creating_event property.
847
-        $evtID                    = $evtobj->ID();
848
-        $this->_is_creating_event = absint($evtID) != 0 ? false : true;
849
-        
850
-        //default main template args
851
-        $main_template_args = array(
852
-            'event_datetime_help_link' => EEH_Template::get_help_tab_link('event_editor_event_datetimes_help_tab',
853
-                $this->_adminpage_obj->page_slug, $this->_adminpage_obj->get_req_action(), false, false),
854
-            //todo need to add a filter to the template for the help text in the Events_Admin_Page core file so we can add further help
855
-            'existing_datetime_ids'    => '',
856
-            'total_dtt_rows'           => 1,
857
-            'add_new_dtt_help_link'    => EEH_Template::get_help_tab_link('add_new_dtt_info',
858
-                $this->_adminpage_obj->page_slug, $this->_adminpage_obj->get_req_action(), false, false),
859
-            //todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
860
-            'datetime_rows'            => '',
861
-            'show_tickets_container'   => '',
862
-            //$this->_adminpage_obj->get_cpt_model_obj()->ID() > 1 ? ' style="display:none;"' : '',
863
-            'ticket_rows'              => '',
864
-            'existing_ticket_ids'      => '',
865
-            'total_ticket_rows'        => 1,
866
-            'ticket_js_structure'      => '',
867
-            'ee_collapsible_status'    => ' ee-collapsible-open'
868
-            //$this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? ' ee-collapsible-closed' : ' ee-collapsible-open'
869
-        );
870
-        
871
-        $timezone = $evtobj instanceof EE_Event ? $evtobj->timezone_string() : null;
872
-        
873
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
874
-        
875
-        /**
876
-         * 1. Start with retrieving Datetimes
877
-         * 2. For each datetime get related tickets
878
-         * 3. For each ticket get related prices
879
-         */
880
-        
881
-        $DTM   = EE_Registry::instance()->load_model('Datetime', array($timezone));
882
-        $times = $DTM->get_all_event_dates($evtID);
883
-        
884
-        
885
-        $main_template_args['total_dtt_rows'] = count($times);
886
-        
887
-        /** @see https://events.codebasehq.com/projects/event-espresso/tickets/9486 for why we are counting $dttrow and then setting that on the Datetime object */
888
-        $dttrow = 1;
889
-        foreach ($times as $time) {
890
-            $dttid = $time->get('DTT_ID');
891
-            $time->set('DTT_order', $dttrow);
892
-            $existing_datetime_ids[] = $dttid;
840
+	public function pricing_metabox()
841
+	{
842
+		$existing_datetime_ids = $existing_ticket_ids = $datetime_tickets = $ticket_datetimes = array();
843
+        
844
+		$evtobj = $this->_adminpage_obj->get_cpt_model_obj();
845
+        
846
+		//set is_creating_event property.
847
+		$evtID                    = $evtobj->ID();
848
+		$this->_is_creating_event = absint($evtID) != 0 ? false : true;
849
+        
850
+		//default main template args
851
+		$main_template_args = array(
852
+			'event_datetime_help_link' => EEH_Template::get_help_tab_link('event_editor_event_datetimes_help_tab',
853
+				$this->_adminpage_obj->page_slug, $this->_adminpage_obj->get_req_action(), false, false),
854
+			//todo need to add a filter to the template for the help text in the Events_Admin_Page core file so we can add further help
855
+			'existing_datetime_ids'    => '',
856
+			'total_dtt_rows'           => 1,
857
+			'add_new_dtt_help_link'    => EEH_Template::get_help_tab_link('add_new_dtt_info',
858
+				$this->_adminpage_obj->page_slug, $this->_adminpage_obj->get_req_action(), false, false),
859
+			//todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
860
+			'datetime_rows'            => '',
861
+			'show_tickets_container'   => '',
862
+			//$this->_adminpage_obj->get_cpt_model_obj()->ID() > 1 ? ' style="display:none;"' : '',
863
+			'ticket_rows'              => '',
864
+			'existing_ticket_ids'      => '',
865
+			'total_ticket_rows'        => 1,
866
+			'ticket_js_structure'      => '',
867
+			'ee_collapsible_status'    => ' ee-collapsible-open'
868
+			//$this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? ' ee-collapsible-closed' : ' ee-collapsible-open'
869
+		);
870
+        
871
+		$timezone = $evtobj instanceof EE_Event ? $evtobj->timezone_string() : null;
872
+        
873
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
874
+        
875
+		/**
876
+		 * 1. Start with retrieving Datetimes
877
+		 * 2. For each datetime get related tickets
878
+		 * 3. For each ticket get related prices
879
+		 */
880
+        
881
+		$DTM   = EE_Registry::instance()->load_model('Datetime', array($timezone));
882
+		$times = $DTM->get_all_event_dates($evtID);
883
+        
884
+        
885
+		$main_template_args['total_dtt_rows'] = count($times);
886
+        
887
+		/** @see https://events.codebasehq.com/projects/event-espresso/tickets/9486 for why we are counting $dttrow and then setting that on the Datetime object */
888
+		$dttrow = 1;
889
+		foreach ($times as $time) {
890
+			$dttid = $time->get('DTT_ID');
891
+			$time->set('DTT_order', $dttrow);
892
+			$existing_datetime_ids[] = $dttid;
893 893
             
894
-            //tickets attached
895
-            $related_tickets = $time->ID() > 0 ? $time->get_many_related('Ticket', array(
896
-                array('OR' => array('TKT_deleted' => 1, 'TKT_deleted*' => 0)),
897
-                'default_where_conditions' => 'none',
898
-                'order_by'                 => array('TKT_order' => 'ASC')
899
-            )) : array();
894
+			//tickets attached
895
+			$related_tickets = $time->ID() > 0 ? $time->get_many_related('Ticket', array(
896
+				array('OR' => array('TKT_deleted' => 1, 'TKT_deleted*' => 0)),
897
+				'default_where_conditions' => 'none',
898
+				'order_by'                 => array('TKT_order' => 'ASC')
899
+			)) : array();
900 900
             
901
-            //if there are no related tickets this is likely a new event OR autodraft
902
-            // event so we need to generate the default tickets because dtts
903
-            // ALWAYS have at least one related ticket!!.  EXCEPT, we dont' do this if there is already more than one
904
-            // datetime on the event.
905
-            if (empty ($related_tickets) && count($times) < 2) {
906
-                $related_tickets = EE_Registry::instance()->load_model('Ticket')->get_all_default_tickets();
901
+			//if there are no related tickets this is likely a new event OR autodraft
902
+			// event so we need to generate the default tickets because dtts
903
+			// ALWAYS have at least one related ticket!!.  EXCEPT, we dont' do this if there is already more than one
904
+			// datetime on the event.
905
+			if (empty ($related_tickets) && count($times) < 2) {
906
+				$related_tickets = EE_Registry::instance()->load_model('Ticket')->get_all_default_tickets();
907 907
                 
908
-                //this should be ordered by TKT_ID, so let's grab the first default ticket (which will be the main default) and ensure it has any default prices added to it (but do NOT save).
909
-                $default_prices = EEM_Price::instance()->get_all_default_prices();
908
+				//this should be ordered by TKT_ID, so let's grab the first default ticket (which will be the main default) and ensure it has any default prices added to it (but do NOT save).
909
+				$default_prices = EEM_Price::instance()->get_all_default_prices();
910 910
                 
911
-                $main_default_ticket = reset($related_tickets);
912
-                if ($main_default_ticket instanceof EE_Ticket) {
913
-                    foreach ($default_prices as $default_price) {
914
-                        if ($default_price->is_base_price()) {
915
-                            continue;
916
-                        }
917
-                        $main_default_ticket->cache('Price', $default_price);
918
-                    }
919
-                }
920
-            }
911
+				$main_default_ticket = reset($related_tickets);
912
+				if ($main_default_ticket instanceof EE_Ticket) {
913
+					foreach ($default_prices as $default_price) {
914
+						if ($default_price->is_base_price()) {
915
+							continue;
916
+						}
917
+						$main_default_ticket->cache('Price', $default_price);
918
+					}
919
+				}
920
+			}
921 921
             
922 922
             
923
-            //we can't actually setup rows in this loop yet cause we don't know all the unique tickets for this event yet (tickets are linked through all datetimes). So we're going to temporarily cache some of that information.
923
+			//we can't actually setup rows in this loop yet cause we don't know all the unique tickets for this event yet (tickets are linked through all datetimes). So we're going to temporarily cache some of that information.
924 924
             
925
-            //loop through and setup the ticket rows and make sure the order is set.
926
-            foreach ($related_tickets as $ticket) {
927
-                $tktid  = $ticket->get('TKT_ID');
928
-                $tktrow = $ticket->get('TKT_row');
929
-                //we only want unique tickets in our final display!!
930
-                if ( ! in_array($tktid, $existing_ticket_ids)) {
931
-                    $existing_ticket_ids[] = $tktid;
932
-                    $all_tickets[]         = $ticket;
933
-                }
925
+			//loop through and setup the ticket rows and make sure the order is set.
926
+			foreach ($related_tickets as $ticket) {
927
+				$tktid  = $ticket->get('TKT_ID');
928
+				$tktrow = $ticket->get('TKT_row');
929
+				//we only want unique tickets in our final display!!
930
+				if ( ! in_array($tktid, $existing_ticket_ids)) {
931
+					$existing_ticket_ids[] = $tktid;
932
+					$all_tickets[]         = $ticket;
933
+				}
934 934
                 
935
-                //temporary cache of this ticket info for this datetime for later processing of datetime rows.
936
-                $datetime_tickets[$dttid][] = $tktrow;
935
+				//temporary cache of this ticket info for this datetime for later processing of datetime rows.
936
+				$datetime_tickets[$dttid][] = $tktrow;
937 937
                 
938
-                //temporary cache of this datetime info for this ticket for later processing of ticket rows.
939
-                if ( ! isset($ticket_datetimes[$tktid]) || ! in_array($dttrow, $ticket_datetimes[$tktid])) {
940
-                    $ticket_datetimes[$tktid][] = $dttrow;
941
-                }
942
-            }
943
-            $dttrow++;
944
-        }
945
-        
946
-        $main_template_args['total_ticket_rows']     = count($existing_ticket_ids);
947
-        $main_template_args['existing_ticket_ids']   = implode(',', $existing_ticket_ids);
948
-        $main_template_args['existing_datetime_ids'] = implode(',', $existing_datetime_ids);
949
-        
950
-        //sort $all_tickets by order
951
-        usort($all_tickets, function ($a, $b) {
952
-            $a_order = (int)$a->get('TKT_order');
953
-            $b_order = (int)$b->get('TKT_order');
954
-            if ($a_order == $b_order) {
955
-                return 0;
956
-            }
938
+				//temporary cache of this datetime info for this ticket for later processing of ticket rows.
939
+				if ( ! isset($ticket_datetimes[$tktid]) || ! in_array($dttrow, $ticket_datetimes[$tktid])) {
940
+					$ticket_datetimes[$tktid][] = $dttrow;
941
+				}
942
+			}
943
+			$dttrow++;
944
+		}
945
+        
946
+		$main_template_args['total_ticket_rows']     = count($existing_ticket_ids);
947
+		$main_template_args['existing_ticket_ids']   = implode(',', $existing_ticket_ids);
948
+		$main_template_args['existing_datetime_ids'] = implode(',', $existing_datetime_ids);
949
+        
950
+		//sort $all_tickets by order
951
+		usort($all_tickets, function ($a, $b) {
952
+			$a_order = (int)$a->get('TKT_order');
953
+			$b_order = (int)$b->get('TKT_order');
954
+			if ($a_order == $b_order) {
955
+				return 0;
956
+			}
957 957
             
958
-            return ($a_order < $b_order) ? -1 : 1;
959
-        });
960
-        
961
-        //k NOW we have all the data we need for setting up the dtt rows and ticket rows so we start our dtt loop again.
962
-        $dttrow = 1;
963
-        foreach ($times as $time) {
964
-            $main_template_args['datetime_rows'] .= $this->_get_datetime_row($dttrow, $time, $datetime_tickets,
965
-                $all_tickets, false, $times);
966
-            $dttrow++;
967
-        }
968
-        
969
-        //then loop through all tickets for the ticket rows.
970
-        $tktrow = 1;
971
-        foreach ($all_tickets as $ticket) {
972
-            $main_template_args['ticket_rows'] .= $this->_get_ticket_row($tktrow, $ticket, $ticket_datetimes, $times,
973
-                false, $all_tickets);
974
-            $tktrow++;
975
-        }
976
-        
977
-        $main_template_args['ticket_js_structure'] = $this->_get_ticket_js_structure($times, $all_tickets);
978
-        $template                                  = PRICING_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php';
979
-        EEH_Template::display_template($template, $main_template_args);
980
-        
981
-        return;
982
-    }
958
+			return ($a_order < $b_order) ? -1 : 1;
959
+		});
960
+        
961
+		//k NOW we have all the data we need for setting up the dtt rows and ticket rows so we start our dtt loop again.
962
+		$dttrow = 1;
963
+		foreach ($times as $time) {
964
+			$main_template_args['datetime_rows'] .= $this->_get_datetime_row($dttrow, $time, $datetime_tickets,
965
+				$all_tickets, false, $times);
966
+			$dttrow++;
967
+		}
968
+        
969
+		//then loop through all tickets for the ticket rows.
970
+		$tktrow = 1;
971
+		foreach ($all_tickets as $ticket) {
972
+			$main_template_args['ticket_rows'] .= $this->_get_ticket_row($tktrow, $ticket, $ticket_datetimes, $times,
973
+				false, $all_tickets);
974
+			$tktrow++;
975
+		}
976
+        
977
+		$main_template_args['ticket_js_structure'] = $this->_get_ticket_js_structure($times, $all_tickets);
978
+		$template                                  = PRICING_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php';
979
+		EEH_Template::display_template($template, $main_template_args);
980
+        
981
+		return;
982
+	}
983 983
     
984 984
     
985
-    protected function _get_datetime_row(
986
-        $dttrow,
987
-        EE_Datetime $dtt,
988
-        $datetime_tickets,
989
-        $all_tickets,
990
-        $default = false,
991
-        $all_dtts = array()
992
-    ) {
993
-        
994
-        $dtt_display_template_args = array(
995
-            'dtt_edit_row'             => $this->_get_dtt_edit_row($dttrow, $dtt, $default, $all_dtts),
996
-            'dtt_attached_tickets_row' => $this->_get_dtt_attached_tickets_row($dttrow, $dtt, $datetime_tickets,
997
-                $all_tickets, $default),
998
-            'dtt_row'                  => $default ? 'DTTNUM' : $dttrow
999
-        );
1000
-        $template                  = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_row_wrapper.template.php';
1001
-        
1002
-        return EEH_Template::display_template($template, $dtt_display_template_args, true);
1003
-    }
985
+	protected function _get_datetime_row(
986
+		$dttrow,
987
+		EE_Datetime $dtt,
988
+		$datetime_tickets,
989
+		$all_tickets,
990
+		$default = false,
991
+		$all_dtts = array()
992
+	) {
993
+        
994
+		$dtt_display_template_args = array(
995
+			'dtt_edit_row'             => $this->_get_dtt_edit_row($dttrow, $dtt, $default, $all_dtts),
996
+			'dtt_attached_tickets_row' => $this->_get_dtt_attached_tickets_row($dttrow, $dtt, $datetime_tickets,
997
+				$all_tickets, $default),
998
+			'dtt_row'                  => $default ? 'DTTNUM' : $dttrow
999
+		);
1000
+		$template                  = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_row_wrapper.template.php';
1001
+        
1002
+		return EEH_Template::display_template($template, $dtt_display_template_args, true);
1003
+	}
1004 1004
     
1005 1005
     
1006
-    /**
1007
-     * This method is used to generate a dtt fields  edit row.
1008
-     * The same row is used to generate a row with valid DTT objects and the default row that is used as the
1009
-     * skeleton by the js.
1010
-     *
1011
-     * @param int           $dttrow                         The row number for the row being generated.
1012
-     * @param               mixed                           EE_Datetime|null $dtt      If not default row being
1013
-     *                                                                       generated, this must be a EE_Datetime
1014
-     *                                                                       object.
1015
-     * @param bool          $default                        Whether a default row is being generated or not.
1016
-     * @param EE_Datetime[] $all_dtts                       This is the array of all datetimes used in the editor.
1017
-     *
1018
-     * @return string Generated edit row.
1019
-     */
1020
-    protected function _get_dtt_edit_row($dttrow, $dtt, $default, $all_dtts)
1021
-    {
1022
-        
1023
-        // if the incoming $dtt object is NOT an instance of EE_Datetime then force default to true.
1024
-        $default = ! $dtt instanceof EE_Datetime ? true : false;
1025
-        
1026
-        $template_args = array(
1027
-            'dtt_row'              => $default ? 'DTTNUM' : $dttrow,
1028
-            'event_datetimes_name' => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1029
-            'edit_dtt_expanded'    => '',
1030
-            //$this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? '' : ' ee-edit-editing',
1031
-            'DTT_ID'               => $default ? '' : $dtt->ID(),
1032
-            'DTT_name'             => $default ? '' : $dtt->name(),
1033
-            'DTT_description'      => $default ? '' : $dtt->description(),
1034
-            'DTT_EVT_start'        => $default ? '' : $dtt->start_date($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']),
1035
-            'DTT_EVT_end'          => $default ? '' : $dtt->end_date($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']),
1036
-            'DTT_reg_limit'        => $default ? '' : $dtt->get_pretty('DTT_reg_limit', 'input'),
1037
-            'DTT_order'            => $default ? 'DTTNUM' : $dttrow,
1038
-            'dtt_sold'             => $default ? '0' : $dtt->get('DTT_sold'),
1039
-            'clone_icon'           => ! empty($dtt) && $dtt->get('DTT_sold') > 0 ? '' : 'clone-icon ee-icon ee-icon-clone clickable',
1040
-            'trash_icon'           => ! empty($dtt) && $dtt->get('DTT_sold') > 0 ? 'ee-lock-icon' : 'trash-icon dashicons dashicons-post-trash clickable',
1041
-            'reg_list_url'         => $default || ! $dtt->event() instanceof \EE_Event
1042
-                ? ''
1043
-                : EE_Admin_Page::add_query_args_and_nonce(
1044
-                    array('event_id' => $dtt->event()->ID(), 'datetime_id' => $dtt->ID()),
1045
-                    REG_ADMIN_URL
1046
-                )
1047
-        );
1048
-        
1049
-        $template_args['show_trash'] = count($all_dtts) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon' ? ' style="display:none"' : '';
1050
-        
1051
-        //allow filtering of template args at this point.
1052
-        $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_dtt_edit_row__template_args',
1053
-            $template_args, $dttrow, $dtt, $default, $all_dtts, $this->_is_creating_event);
1054
-        
1055
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_edit_row.template.php';
1056
-        
1057
-        return EEH_Template::display_template($template, $template_args, true);
1058
-    }
1006
+	/**
1007
+	 * This method is used to generate a dtt fields  edit row.
1008
+	 * The same row is used to generate a row with valid DTT objects and the default row that is used as the
1009
+	 * skeleton by the js.
1010
+	 *
1011
+	 * @param int           $dttrow                         The row number for the row being generated.
1012
+	 * @param               mixed                           EE_Datetime|null $dtt      If not default row being
1013
+	 *                                                                       generated, this must be a EE_Datetime
1014
+	 *                                                                       object.
1015
+	 * @param bool          $default                        Whether a default row is being generated or not.
1016
+	 * @param EE_Datetime[] $all_dtts                       This is the array of all datetimes used in the editor.
1017
+	 *
1018
+	 * @return string Generated edit row.
1019
+	 */
1020
+	protected function _get_dtt_edit_row($dttrow, $dtt, $default, $all_dtts)
1021
+	{
1022
+        
1023
+		// if the incoming $dtt object is NOT an instance of EE_Datetime then force default to true.
1024
+		$default = ! $dtt instanceof EE_Datetime ? true : false;
1025
+        
1026
+		$template_args = array(
1027
+			'dtt_row'              => $default ? 'DTTNUM' : $dttrow,
1028
+			'event_datetimes_name' => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1029
+			'edit_dtt_expanded'    => '',
1030
+			//$this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? '' : ' ee-edit-editing',
1031
+			'DTT_ID'               => $default ? '' : $dtt->ID(),
1032
+			'DTT_name'             => $default ? '' : $dtt->name(),
1033
+			'DTT_description'      => $default ? '' : $dtt->description(),
1034
+			'DTT_EVT_start'        => $default ? '' : $dtt->start_date($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']),
1035
+			'DTT_EVT_end'          => $default ? '' : $dtt->end_date($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']),
1036
+			'DTT_reg_limit'        => $default ? '' : $dtt->get_pretty('DTT_reg_limit', 'input'),
1037
+			'DTT_order'            => $default ? 'DTTNUM' : $dttrow,
1038
+			'dtt_sold'             => $default ? '0' : $dtt->get('DTT_sold'),
1039
+			'clone_icon'           => ! empty($dtt) && $dtt->get('DTT_sold') > 0 ? '' : 'clone-icon ee-icon ee-icon-clone clickable',
1040
+			'trash_icon'           => ! empty($dtt) && $dtt->get('DTT_sold') > 0 ? 'ee-lock-icon' : 'trash-icon dashicons dashicons-post-trash clickable',
1041
+			'reg_list_url'         => $default || ! $dtt->event() instanceof \EE_Event
1042
+				? ''
1043
+				: EE_Admin_Page::add_query_args_and_nonce(
1044
+					array('event_id' => $dtt->event()->ID(), 'datetime_id' => $dtt->ID()),
1045
+					REG_ADMIN_URL
1046
+				)
1047
+		);
1048
+        
1049
+		$template_args['show_trash'] = count($all_dtts) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon' ? ' style="display:none"' : '';
1050
+        
1051
+		//allow filtering of template args at this point.
1052
+		$template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_dtt_edit_row__template_args',
1053
+			$template_args, $dttrow, $dtt, $default, $all_dtts, $this->_is_creating_event);
1054
+        
1055
+		$template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_edit_row.template.php';
1056
+        
1057
+		return EEH_Template::display_template($template, $template_args, true);
1058
+	}
1059 1059
     
1060 1060
     
1061
-    protected function _get_dtt_attached_tickets_row($dttrow, $dtt, $datetime_tickets, $all_tickets, $default)
1062
-    {
1063
-        
1064
-        $template_args = array(
1065
-            'dtt_row'                           => $default ? 'DTTNUM' : $dttrow,
1066
-            'event_datetimes_name'              => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1067
-            'DTT_description'                   => $default ? '' : $dtt->description(),
1068
-            'datetime_tickets_list'             => $default ? '<li class="hidden"></li>' : '',
1069
-            'show_tickets_row'                  => ' style="display:none;"',
1070
-            //$default || $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? ' style="display:none;"' : '',
1071
-            'add_new_datetime_ticket_help_link' => EEH_Template::get_help_tab_link('add_new_ticket_via_datetime',
1072
-                $this->_adminpage_obj->page_slug, $this->_adminpage_obj->get_req_action(), false, false),
1073
-            //todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1074
-            'DTT_ID'                            => $default ? '' : $dtt->ID()
1075
-        );
1076
-        
1077
-        //need to setup the list items (but only if this isnt' a default skeleton setup)
1078
-        if ( ! $default) {
1079
-            $tktrow = 1;
1080
-            foreach ($all_tickets as $ticket) {
1081
-                $template_args['datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item($dttrow, $tktrow,
1082
-                    $dtt, $ticket, $datetime_tickets, $default);
1083
-                $tktrow++;
1084
-            }
1085
-        }
1086
-        
1087
-        //filter template args at this point
1088
-        $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_dtt_attached_ticket_row__template_args',
1089
-            $template_args, $dttrow, $dtt, $datetime_tickets, $all_tickets, $default, $this->_is_creating_event);
1090
-        
1091
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_attached_tickets_row.template.php';
1092
-        
1093
-        return EEH_Template::display_template($template, $template_args, true);
1094
-    }
1061
+	protected function _get_dtt_attached_tickets_row($dttrow, $dtt, $datetime_tickets, $all_tickets, $default)
1062
+	{
1063
+        
1064
+		$template_args = array(
1065
+			'dtt_row'                           => $default ? 'DTTNUM' : $dttrow,
1066
+			'event_datetimes_name'              => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1067
+			'DTT_description'                   => $default ? '' : $dtt->description(),
1068
+			'datetime_tickets_list'             => $default ? '<li class="hidden"></li>' : '',
1069
+			'show_tickets_row'                  => ' style="display:none;"',
1070
+			//$default || $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? ' style="display:none;"' : '',
1071
+			'add_new_datetime_ticket_help_link' => EEH_Template::get_help_tab_link('add_new_ticket_via_datetime',
1072
+				$this->_adminpage_obj->page_slug, $this->_adminpage_obj->get_req_action(), false, false),
1073
+			//todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1074
+			'DTT_ID'                            => $default ? '' : $dtt->ID()
1075
+		);
1076
+        
1077
+		//need to setup the list items (but only if this isnt' a default skeleton setup)
1078
+		if ( ! $default) {
1079
+			$tktrow = 1;
1080
+			foreach ($all_tickets as $ticket) {
1081
+				$template_args['datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item($dttrow, $tktrow,
1082
+					$dtt, $ticket, $datetime_tickets, $default);
1083
+				$tktrow++;
1084
+			}
1085
+		}
1086
+        
1087
+		//filter template args at this point
1088
+		$template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_dtt_attached_ticket_row__template_args',
1089
+			$template_args, $dttrow, $dtt, $datetime_tickets, $all_tickets, $default, $this->_is_creating_event);
1090
+        
1091
+		$template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_attached_tickets_row.template.php';
1092
+        
1093
+		return EEH_Template::display_template($template, $template_args, true);
1094
+	}
1095 1095
     
1096 1096
     
1097
-    protected function _get_datetime_tickets_list_item($dttrow, $tktrow, $dtt, $ticket, $datetime_tickets, $default)
1098
-    {
1099
-        $tktid    = ! empty($ticket) ? $ticket->ID() : 0;
1100
-        $dtt_tkts = $dtt instanceof EE_Datetime && isset($datetime_tickets[$dtt->ID()]) ? $datetime_tickets[$dtt->ID()] : array();
1101
-        
1102
-        $displayrow    = ! empty($ticket) ? $ticket->get('TKT_row') : 0;
1103
-        $template_args = array(
1104
-            'dtt_row'                 => $default ? 'DTTNUM' : $dttrow,
1105
-            'tkt_row'                 => $default && empty($ticket) ? 'TICKETNUM' : $tktrow,
1106
-            'datetime_ticket_checked' => in_array($displayrow, $dtt_tkts) ? ' checked="checked"' : '',
1107
-            'ticket_selected'         => in_array($displayrow, $dtt_tkts) ? ' ticket-selected' : '',
1108
-            'TKT_name'                => $default && empty($ticket) ? 'TKTNAME' : $ticket->get('TKT_name'),
1109
-            'tkt_status_class'        => ($default && empty($ticket)) || $this->_is_creating_event ? ' tkt-status-' . EE_Ticket::onsale : ' tkt-status-' . $ticket->ticket_status(),
1110
-        );
1111
-        
1112
-        //filter template args
1113
-        $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_datetime_tickets_list_item__template_args',
1114
-            $template_args, $dttrow, $tktrow, $dtt, $ticket, $datetime_tickets, $default, $this->_is_creating_event);
1115
-        
1116
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_dtt_tickets_list.template.php';
1117
-        
1118
-        return EEH_Template::display_template($template, $template_args, true);
1119
-    }
1097
+	protected function _get_datetime_tickets_list_item($dttrow, $tktrow, $dtt, $ticket, $datetime_tickets, $default)
1098
+	{
1099
+		$tktid    = ! empty($ticket) ? $ticket->ID() : 0;
1100
+		$dtt_tkts = $dtt instanceof EE_Datetime && isset($datetime_tickets[$dtt->ID()]) ? $datetime_tickets[$dtt->ID()] : array();
1101
+        
1102
+		$displayrow    = ! empty($ticket) ? $ticket->get('TKT_row') : 0;
1103
+		$template_args = array(
1104
+			'dtt_row'                 => $default ? 'DTTNUM' : $dttrow,
1105
+			'tkt_row'                 => $default && empty($ticket) ? 'TICKETNUM' : $tktrow,
1106
+			'datetime_ticket_checked' => in_array($displayrow, $dtt_tkts) ? ' checked="checked"' : '',
1107
+			'ticket_selected'         => in_array($displayrow, $dtt_tkts) ? ' ticket-selected' : '',
1108
+			'TKT_name'                => $default && empty($ticket) ? 'TKTNAME' : $ticket->get('TKT_name'),
1109
+			'tkt_status_class'        => ($default && empty($ticket)) || $this->_is_creating_event ? ' tkt-status-' . EE_Ticket::onsale : ' tkt-status-' . $ticket->ticket_status(),
1110
+		);
1111
+        
1112
+		//filter template args
1113
+		$template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_datetime_tickets_list_item__template_args',
1114
+			$template_args, $dttrow, $tktrow, $dtt, $ticket, $datetime_tickets, $default, $this->_is_creating_event);
1115
+        
1116
+		$template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_dtt_tickets_list.template.php';
1117
+        
1118
+		return EEH_Template::display_template($template, $template_args, true);
1119
+	}
1120 1120
     
1121 1121
     
1122
-    /**
1123
-     * This generates the ticket row for tickets.
1124
-     * This same method is used to generate both the actual rows and the js skeleton row (when default ==
1125
-     * true)
1126
-     *
1127
-     * @param int           $tktrow                          Represents the row number being generated.
1128
-     * @param               mixed                            null|EE_Ticket $ticket           If default then this will
1129
-     *                                                                      be null.
1130
-     * @param EE_Datetime[] $ticket_datetimes                Either an array of all datetimes on all tickets indexed by
1131
-     *                                                       each ticket or empty for  default
1132
-     * @param EE_Datetime[] $all_dtts                        All Datetimes on the event or empty for default.
1133
-     * @param bool          $default                         Whether default row being generated or not.
1134
-     * @param EE_Ticket[]   $all_tickets                     This is an array of all tickets attached to the event (or
1135
-     *                                                       empty in the case of defaults)
1136
-     *
1137
-     * @return [type] [description]
1138
-     */
1139
-    protected function _get_ticket_row(
1140
-        $tktrow,
1141
-        $ticket,
1142
-        $ticket_datetimes,
1143
-        $all_dtts,
1144
-        $default = false,
1145
-        $all_tickets = array()
1146
-    ) {
1147
-        
1148
-        //if $ticket is not an instance of EE_Ticket then force default to true.
1149
-        $default = ! $ticket instanceof EE_Ticket ? true : false;
1150
-        
1151
-        $prices = ! empty($ticket) && ! $default ? $ticket->get_many_related('Price',
1152
-            array('default_where_conditions' => 'none', 'order_by' => array('PRC_order' => 'ASC'))) : array();
1153
-        
1154
-        //if there is only one price (which would be the base price) or NO prices and this ticket is a default ticket, let's just make sure there are no cached default prices on
1155
-        //the object.  This is done by not including any query_params.
1156
-        if ($ticket instanceof EE_Ticket && $ticket->is_default() && (count($prices) === 1 || empty($prices))) {
1157
-            $prices = $ticket->get_many_related('Price');
1158
-        }
1159
-        
1160
-        // check if we're dealing with a default ticket in which case we don't want any starting_ticket_datetime_row values set (otherwise there won't be any new relationships created for tickets based off of the default ticket).  This will future proof in case there is ever any behaviour change between what the primary_key defaults to.
1161
-        $default_dtt = $default || ($ticket instanceof EE_Ticket && $ticket->get('TKT_is_default')) ? true : false;
1162
-        
1163
-        $tkt_dtts = $ticket instanceof EE_Ticket && isset($ticket_datetimes[$ticket->ID()]) ? $ticket_datetimes[$ticket->ID()] : array();
1164
-        
1165
-        $ticket_subtotal  = $default ? 0 : $ticket->get_ticket_subtotal();
1166
-        $base_price       = $default ? null : $ticket->base_price();
1167
-        $count_price_mods = EEM_Price::instance()->get_all_default_prices(true);
1168
-        
1169
-        //breaking out complicated condition for ticket_status
1170
-        if ($default) {
1171
-            $ticket_status_class = ' tkt-status-' . EE_Ticket::onsale;
1172
-        } else {
1173
-            $ticket_status_class = $ticket->is_default() ? ' tkt-status-' . EE_Ticket::onsale : ' tkt-status-' . $ticket->ticket_status();
1174
-        }
1175
-        
1176
-        //breaking out complicated condition for TKT_taxable
1177
-        if ($default) {
1178
-            $TKT_taxable = '';
1179
-        } else {
1180
-            $TKT_taxable = $ticket->get('TKT_taxable') ? ' checked="checked"' : '';
1181
-        }
1122
+	/**
1123
+	 * This generates the ticket row for tickets.
1124
+	 * This same method is used to generate both the actual rows and the js skeleton row (when default ==
1125
+	 * true)
1126
+	 *
1127
+	 * @param int           $tktrow                          Represents the row number being generated.
1128
+	 * @param               mixed                            null|EE_Ticket $ticket           If default then this will
1129
+	 *                                                                      be null.
1130
+	 * @param EE_Datetime[] $ticket_datetimes                Either an array of all datetimes on all tickets indexed by
1131
+	 *                                                       each ticket or empty for  default
1132
+	 * @param EE_Datetime[] $all_dtts                        All Datetimes on the event or empty for default.
1133
+	 * @param bool          $default                         Whether default row being generated or not.
1134
+	 * @param EE_Ticket[]   $all_tickets                     This is an array of all tickets attached to the event (or
1135
+	 *                                                       empty in the case of defaults)
1136
+	 *
1137
+	 * @return [type] [description]
1138
+	 */
1139
+	protected function _get_ticket_row(
1140
+		$tktrow,
1141
+		$ticket,
1142
+		$ticket_datetimes,
1143
+		$all_dtts,
1144
+		$default = false,
1145
+		$all_tickets = array()
1146
+	) {
1147
+        
1148
+		//if $ticket is not an instance of EE_Ticket then force default to true.
1149
+		$default = ! $ticket instanceof EE_Ticket ? true : false;
1150
+        
1151
+		$prices = ! empty($ticket) && ! $default ? $ticket->get_many_related('Price',
1152
+			array('default_where_conditions' => 'none', 'order_by' => array('PRC_order' => 'ASC'))) : array();
1153
+        
1154
+		//if there is only one price (which would be the base price) or NO prices and this ticket is a default ticket, let's just make sure there are no cached default prices on
1155
+		//the object.  This is done by not including any query_params.
1156
+		if ($ticket instanceof EE_Ticket && $ticket->is_default() && (count($prices) === 1 || empty($prices))) {
1157
+			$prices = $ticket->get_many_related('Price');
1158
+		}
1159
+        
1160
+		// check if we're dealing with a default ticket in which case we don't want any starting_ticket_datetime_row values set (otherwise there won't be any new relationships created for tickets based off of the default ticket).  This will future proof in case there is ever any behaviour change between what the primary_key defaults to.
1161
+		$default_dtt = $default || ($ticket instanceof EE_Ticket && $ticket->get('TKT_is_default')) ? true : false;
1162
+        
1163
+		$tkt_dtts = $ticket instanceof EE_Ticket && isset($ticket_datetimes[$ticket->ID()]) ? $ticket_datetimes[$ticket->ID()] : array();
1164
+        
1165
+		$ticket_subtotal  = $default ? 0 : $ticket->get_ticket_subtotal();
1166
+		$base_price       = $default ? null : $ticket->base_price();
1167
+		$count_price_mods = EEM_Price::instance()->get_all_default_prices(true);
1168
+        
1169
+		//breaking out complicated condition for ticket_status
1170
+		if ($default) {
1171
+			$ticket_status_class = ' tkt-status-' . EE_Ticket::onsale;
1172
+		} else {
1173
+			$ticket_status_class = $ticket->is_default() ? ' tkt-status-' . EE_Ticket::onsale : ' tkt-status-' . $ticket->ticket_status();
1174
+		}
1175
+        
1176
+		//breaking out complicated condition for TKT_taxable
1177
+		if ($default) {
1178
+			$TKT_taxable = '';
1179
+		} else {
1180
+			$TKT_taxable = $ticket->get('TKT_taxable') ? ' checked="checked"' : '';
1181
+		}
1182 1182
 
1183 1183
         
1184
-        $template_args = array(
1185
-            'tkt_row'                       => $default ? 'TICKETNUM' : $tktrow,
1186
-            'TKT_order'                     => $default ? 'TICKETNUM' : $tktrow,
1187
-            //on initial page load this will always be the correct order.
1188
-            'tkt_status_class'              => $ticket_status_class,
1189
-            'display_edit_tkt_row'          => ' style="display:none;"',
1190
-            'edit_tkt_expanded'             => '',
1191
-            'edit_tickets_name'             => $default ? 'TICKETNAMEATTR' : 'edit_tickets',
1192
-            'TKT_name'                      => $default ? '' : $ticket->get('TKT_name'),
1193
-            'TKT_start_date'                => $default ? '' : $ticket->get_date('TKT_start_date',
1194
-                $this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']),
1195
-            'TKT_end_date'                  => $default ? '' : $ticket->get_date('TKT_end_date',
1196
-                $this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']),
1197
-            'TKT_status'                    => $default ? EEH_Template::pretty_status(EE_Ticket::onsale, false,
1198
-                'sentence') : $ticket->is_default() ? EEH_Template::pretty_status(EE_Ticket::onsale, false,
1199
-                'sentence') : $ticket->ticket_status(true),
1200
-            'TKT_price'                     => $default ? '' : EEH_Template::format_currency($ticket->get_ticket_total_with_taxes(),
1201
-                false, false),
1202
-            'TKT_price_code'                => EE_Registry::instance()->CFG->currency->code,
1203
-            'TKT_price_amount'              => $default ? 0 : $ticket_subtotal,
1204
-            'TKT_qty'                       => $default ? '' : $ticket->get_pretty('TKT_qty', 'symbol'),
1205
-            'TKT_qty_for_input'             => $default ? '' : $ticket->get_pretty('TKT_qty', 'input'),
1206
-            'TKT_uses'                      => $default ? '' : $ticket->get_pretty('TKT_uses', 'input'),
1207
-            'TKT_min'                       => $default ? '' : ($ticket->get('TKT_min') === -1 || $ticket->get('TKT_min') === 0 ? '' : $ticket->get('TKT_min')),
1208
-            'TKT_max'                       => $default ? '' : $ticket->get_pretty('TKT_max', 'input'),
1209
-            'TKT_sold'                      => $default ? 0 : $ticket->tickets_sold('ticket'),
1210
-            'TKT_registrations'             => $default ? 0 : $ticket->count_registrations(array(
1211
-                array(
1212
-                    'STS_ID' => array(
1213
-                        '!=',
1214
-                        EEM_Registration::status_id_incomplete
1215
-                    )
1216
-                )
1217
-            )),
1218
-            'TKT_ID'                        => $default ? 0 : $ticket->get('TKT_ID'),
1219
-            'TKT_description'               => $default ? '' : $ticket->get('TKT_description'),
1220
-            'TKT_is_default'                => $default ? 0 : $ticket->get('TKT_is_default'),
1221
-            'TKT_required'                  => $default ? 0 : $ticket->required(),
1222
-            'TKT_is_default_selector'       => '',
1223
-            'ticket_price_rows'             => '',
1224
-            'TKT_base_price'                => $default || ! $base_price instanceof EE_Price ? '' : $base_price->get_pretty('PRC_amount',
1225
-                'localized_float'),
1226
-            'TKT_base_price_ID'             => $default || ! $base_price instanceof EE_Price ? 0 : $base_price->ID(),
1227
-            'show_price_modifier'           => count($prices) > 1 || ($default && $count_price_mods > 0) ? '' : ' style="display:none;"',
1228
-            'show_price_mod_button'         => count($prices) > 1 || ($default && $count_price_mods > 0) || ( ! $default && $ticket->get('TKT_deleted')) ? ' style="display:none;"' : '',
1229
-            'total_price_rows'              => count($prices) > 1 ? count($prices) : 1,
1230
-            'ticket_datetimes_list'         => $default ? '<li class="hidden"></li>' : '',
1231
-            'starting_ticket_datetime_rows' => $default || $default_dtt ? '' : implode(',', $tkt_dtts),
1232
-            'ticket_datetime_rows'          => $default ? '' : implode(',', $tkt_dtts),
1233
-            'existing_ticket_price_ids'     => $default ? '' : implode(',', array_keys($prices)),
1234
-            'ticket_template_id'            => $default ? 0 : $ticket->get('TTM_ID'),
1235
-            'TKT_taxable'                   => $TKT_taxable,
1236
-            'display_subtotal'              => $ticket instanceof EE_Ticket && $ticket->get('TKT_taxable') ? '' : ' style="display:none"',
1237
-            'price_currency_symbol'         => EE_Registry::instance()->CFG->currency->sign,
1238
-            'TKT_subtotal_amount_display'   => EEH_Template::format_currency($ticket_subtotal, false, false),
1239
-            'TKT_subtotal_amount'           => $ticket_subtotal,
1240
-            'tax_rows'                      => $this->_get_tax_rows($tktrow, $ticket),
1241
-            'disabled'                      => $ticket instanceof EE_Ticket && $ticket->get('TKT_deleted') ? true : false,
1242
-            'ticket_archive_class'          => $ticket instanceof EE_Ticket && $ticket->get('TKT_deleted') ? ' ticket-archived' : '',
1243
-            'trash_icon'                    => $ticket instanceof EE_Ticket && $ticket->get('TKT_deleted') ? 'ee-lock-icon ' : 'trash-icon dashicons dashicons-post-trash clickable',
1244
-            'clone_icon'                    => $ticket instanceof EE_Ticket && $ticket->get('TKT_deleted') ? '' : 'clone-icon ee-icon ee-icon-clone clickable'
1245
-        );
1246
-        
1247
-        $template_args['trash_hidden'] = count($all_tickets) === 1 && $template_args['trash_icon'] != 'ee-lock-icon' ? ' style="display:none"' : '';
1248
-        
1249
-        //handle rows that should NOT be empty
1250
-        if (empty($template_args['TKT_start_date'])) {
1251
-            //if empty then the start date will be now.
1252
-            $template_args['TKT_start_date']   = date($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time'],
1253
-                current_time('timestamp'));
1254
-            $template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1255
-        }
1256
-        
1257
-        if (empty($template_args['TKT_end_date'])) {
1184
+		$template_args = array(
1185
+			'tkt_row'                       => $default ? 'TICKETNUM' : $tktrow,
1186
+			'TKT_order'                     => $default ? 'TICKETNUM' : $tktrow,
1187
+			//on initial page load this will always be the correct order.
1188
+			'tkt_status_class'              => $ticket_status_class,
1189
+			'display_edit_tkt_row'          => ' style="display:none;"',
1190
+			'edit_tkt_expanded'             => '',
1191
+			'edit_tickets_name'             => $default ? 'TICKETNAMEATTR' : 'edit_tickets',
1192
+			'TKT_name'                      => $default ? '' : $ticket->get('TKT_name'),
1193
+			'TKT_start_date'                => $default ? '' : $ticket->get_date('TKT_start_date',
1194
+				$this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']),
1195
+			'TKT_end_date'                  => $default ? '' : $ticket->get_date('TKT_end_date',
1196
+				$this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']),
1197
+			'TKT_status'                    => $default ? EEH_Template::pretty_status(EE_Ticket::onsale, false,
1198
+				'sentence') : $ticket->is_default() ? EEH_Template::pretty_status(EE_Ticket::onsale, false,
1199
+				'sentence') : $ticket->ticket_status(true),
1200
+			'TKT_price'                     => $default ? '' : EEH_Template::format_currency($ticket->get_ticket_total_with_taxes(),
1201
+				false, false),
1202
+			'TKT_price_code'                => EE_Registry::instance()->CFG->currency->code,
1203
+			'TKT_price_amount'              => $default ? 0 : $ticket_subtotal,
1204
+			'TKT_qty'                       => $default ? '' : $ticket->get_pretty('TKT_qty', 'symbol'),
1205
+			'TKT_qty_for_input'             => $default ? '' : $ticket->get_pretty('TKT_qty', 'input'),
1206
+			'TKT_uses'                      => $default ? '' : $ticket->get_pretty('TKT_uses', 'input'),
1207
+			'TKT_min'                       => $default ? '' : ($ticket->get('TKT_min') === -1 || $ticket->get('TKT_min') === 0 ? '' : $ticket->get('TKT_min')),
1208
+			'TKT_max'                       => $default ? '' : $ticket->get_pretty('TKT_max', 'input'),
1209
+			'TKT_sold'                      => $default ? 0 : $ticket->tickets_sold('ticket'),
1210
+			'TKT_registrations'             => $default ? 0 : $ticket->count_registrations(array(
1211
+				array(
1212
+					'STS_ID' => array(
1213
+						'!=',
1214
+						EEM_Registration::status_id_incomplete
1215
+					)
1216
+				)
1217
+			)),
1218
+			'TKT_ID'                        => $default ? 0 : $ticket->get('TKT_ID'),
1219
+			'TKT_description'               => $default ? '' : $ticket->get('TKT_description'),
1220
+			'TKT_is_default'                => $default ? 0 : $ticket->get('TKT_is_default'),
1221
+			'TKT_required'                  => $default ? 0 : $ticket->required(),
1222
+			'TKT_is_default_selector'       => '',
1223
+			'ticket_price_rows'             => '',
1224
+			'TKT_base_price'                => $default || ! $base_price instanceof EE_Price ? '' : $base_price->get_pretty('PRC_amount',
1225
+				'localized_float'),
1226
+			'TKT_base_price_ID'             => $default || ! $base_price instanceof EE_Price ? 0 : $base_price->ID(),
1227
+			'show_price_modifier'           => count($prices) > 1 || ($default && $count_price_mods > 0) ? '' : ' style="display:none;"',
1228
+			'show_price_mod_button'         => count($prices) > 1 || ($default && $count_price_mods > 0) || ( ! $default && $ticket->get('TKT_deleted')) ? ' style="display:none;"' : '',
1229
+			'total_price_rows'              => count($prices) > 1 ? count($prices) : 1,
1230
+			'ticket_datetimes_list'         => $default ? '<li class="hidden"></li>' : '',
1231
+			'starting_ticket_datetime_rows' => $default || $default_dtt ? '' : implode(',', $tkt_dtts),
1232
+			'ticket_datetime_rows'          => $default ? '' : implode(',', $tkt_dtts),
1233
+			'existing_ticket_price_ids'     => $default ? '' : implode(',', array_keys($prices)),
1234
+			'ticket_template_id'            => $default ? 0 : $ticket->get('TTM_ID'),
1235
+			'TKT_taxable'                   => $TKT_taxable,
1236
+			'display_subtotal'              => $ticket instanceof EE_Ticket && $ticket->get('TKT_taxable') ? '' : ' style="display:none"',
1237
+			'price_currency_symbol'         => EE_Registry::instance()->CFG->currency->sign,
1238
+			'TKT_subtotal_amount_display'   => EEH_Template::format_currency($ticket_subtotal, false, false),
1239
+			'TKT_subtotal_amount'           => $ticket_subtotal,
1240
+			'tax_rows'                      => $this->_get_tax_rows($tktrow, $ticket),
1241
+			'disabled'                      => $ticket instanceof EE_Ticket && $ticket->get('TKT_deleted') ? true : false,
1242
+			'ticket_archive_class'          => $ticket instanceof EE_Ticket && $ticket->get('TKT_deleted') ? ' ticket-archived' : '',
1243
+			'trash_icon'                    => $ticket instanceof EE_Ticket && $ticket->get('TKT_deleted') ? 'ee-lock-icon ' : 'trash-icon dashicons dashicons-post-trash clickable',
1244
+			'clone_icon'                    => $ticket instanceof EE_Ticket && $ticket->get('TKT_deleted') ? '' : 'clone-icon ee-icon ee-icon-clone clickable'
1245
+		);
1246
+        
1247
+		$template_args['trash_hidden'] = count($all_tickets) === 1 && $template_args['trash_icon'] != 'ee-lock-icon' ? ' style="display:none"' : '';
1248
+        
1249
+		//handle rows that should NOT be empty
1250
+		if (empty($template_args['TKT_start_date'])) {
1251
+			//if empty then the start date will be now.
1252
+			$template_args['TKT_start_date']   = date($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time'],
1253
+				current_time('timestamp'));
1254
+			$template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1255
+		}
1256
+        
1257
+		if (empty($template_args['TKT_end_date'])) {
1258 1258
             
1259
-            //get the earliest datetime (if present);
1260
-            $earliest_dtt = $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? $this->_adminpage_obj->get_cpt_model_obj()->get_first_related('Datetime',
1261
-                array('order_by' => array('DTT_EVT_start' => 'ASC'))) : null;
1259
+			//get the earliest datetime (if present);
1260
+			$earliest_dtt = $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? $this->_adminpage_obj->get_cpt_model_obj()->get_first_related('Datetime',
1261
+				array('order_by' => array('DTT_EVT_start' => 'ASC'))) : null;
1262 1262
             
1263
-            if ( ! empty($earliest_dtt)) {
1264
-                $template_args['TKT_end_date'] = $earliest_dtt->get_datetime('DTT_EVT_start',
1265
-                    $this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']);
1266
-            } else {
1267
-                //default so let's just use what's been set for the default date-time which is 30 days from now.
1268
-                $template_args['TKT_end_date'] = date($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time'],
1269
-                    mktime(24, 0, 0, date("m"), date("d") + 29, date("Y")));
1270
-            }
1271
-            $template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1272
-        }
1273
-        
1274
-        //generate ticket_datetime items
1275
-        if ( ! $default) {
1276
-            $dttrow = 1;
1277
-            foreach ($all_dtts as $dtt) {
1278
-                $template_args['ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item($dttrow, $tktrow, $dtt,
1279
-                    $ticket, $ticket_datetimes, $default);
1280
-                $dttrow++;
1281
-            }
1282
-        }
1283
-        
1284
-        $prcrow = 1;
1285
-        foreach ($prices as $price) {
1286
-            if ($price->is_base_price()) {
1287
-                $prcrow++;
1288
-                continue;
1289
-            }
1290
-            $show_trash  = (count($prices) > 1 && $prcrow === 1) || count($prices) === 1 ? false : true;
1291
-            $show_create = count($prices) > 1 && count($prices) !== $prcrow ? false : true;
1292
-            $template_args['ticket_price_rows'] .= $this->_get_ticket_price_row($tktrow, $prcrow, $price, $default,
1293
-                $ticket, $show_trash, $show_create);
1294
-            $prcrow++;
1295
-        }
1296
-        
1297
-        //filter $template_args
1298
-        $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_ticket_row__template_args',
1299
-            $template_args, $tktrow, $ticket, $ticket_datetimes, $all_dtts, $default, $all_tickets,
1300
-            $this->_is_creating_event);
1301
-        
1302
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_row.template.php';
1303
-        
1304
-        return EEH_Template::display_template($template, $template_args, true);
1305
-    }
1263
+			if ( ! empty($earliest_dtt)) {
1264
+				$template_args['TKT_end_date'] = $earliest_dtt->get_datetime('DTT_EVT_start',
1265
+					$this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']);
1266
+			} else {
1267
+				//default so let's just use what's been set for the default date-time which is 30 days from now.
1268
+				$template_args['TKT_end_date'] = date($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time'],
1269
+					mktime(24, 0, 0, date("m"), date("d") + 29, date("Y")));
1270
+			}
1271
+			$template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1272
+		}
1273
+        
1274
+		//generate ticket_datetime items
1275
+		if ( ! $default) {
1276
+			$dttrow = 1;
1277
+			foreach ($all_dtts as $dtt) {
1278
+				$template_args['ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item($dttrow, $tktrow, $dtt,
1279
+					$ticket, $ticket_datetimes, $default);
1280
+				$dttrow++;
1281
+			}
1282
+		}
1283
+        
1284
+		$prcrow = 1;
1285
+		foreach ($prices as $price) {
1286
+			if ($price->is_base_price()) {
1287
+				$prcrow++;
1288
+				continue;
1289
+			}
1290
+			$show_trash  = (count($prices) > 1 && $prcrow === 1) || count($prices) === 1 ? false : true;
1291
+			$show_create = count($prices) > 1 && count($prices) !== $prcrow ? false : true;
1292
+			$template_args['ticket_price_rows'] .= $this->_get_ticket_price_row($tktrow, $prcrow, $price, $default,
1293
+				$ticket, $show_trash, $show_create);
1294
+			$prcrow++;
1295
+		}
1296
+        
1297
+		//filter $template_args
1298
+		$template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_ticket_row__template_args',
1299
+			$template_args, $tktrow, $ticket, $ticket_datetimes, $all_dtts, $default, $all_tickets,
1300
+			$this->_is_creating_event);
1301
+        
1302
+		$template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_row.template.php';
1303
+        
1304
+		return EEH_Template::display_template($template, $template_args, true);
1305
+	}
1306 1306
     
1307 1307
     
1308
-    protected function _get_tax_rows($tktrow, $ticket)
1309
-    {
1310
-        $tax_rows      = '';
1311
-        $template      = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_tax_row.template.php';
1312
-        $template_args = array();
1313
-        $taxes         = empty($ticket) ? EE_Taxes::get_taxes_for_admin() : $ticket->get_ticket_taxes_for_admin();
1314
-        foreach ($taxes as $tax) {
1315
-            $tax_added     = $this->_get_tax_added($tax, $ticket);
1316
-            $template_args = array(
1317
-                'display_tax'       => ! empty($ticket) && $ticket->get('TKT_taxable') ? '' : ' style="display:none;"',
1318
-                'tax_id'            => $tax->ID(),
1319
-                'tkt_row'           => $tktrow,
1320
-                'tax_label'         => $tax->get('PRC_name'),
1321
-                'tax_added'         => $tax_added,
1322
-                'tax_added_display' => EEH_Template::format_currency($tax_added, false, false),
1323
-                'tax_amount'        => $tax->get('PRC_amount')
1324
-            );
1325
-            $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_tax_rows__template_args',
1326
-                $template_args, $tktrow, $ticket, $this->_is_creating_event);
1327
-            $tax_rows .= EEH_Template::display_template($template, $template_args, true);
1328
-        }
1329
-        
1330
-        
1331
-        return $tax_rows;
1332
-    }
1308
+	protected function _get_tax_rows($tktrow, $ticket)
1309
+	{
1310
+		$tax_rows      = '';
1311
+		$template      = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_tax_row.template.php';
1312
+		$template_args = array();
1313
+		$taxes         = empty($ticket) ? EE_Taxes::get_taxes_for_admin() : $ticket->get_ticket_taxes_for_admin();
1314
+		foreach ($taxes as $tax) {
1315
+			$tax_added     = $this->_get_tax_added($tax, $ticket);
1316
+			$template_args = array(
1317
+				'display_tax'       => ! empty($ticket) && $ticket->get('TKT_taxable') ? '' : ' style="display:none;"',
1318
+				'tax_id'            => $tax->ID(),
1319
+				'tkt_row'           => $tktrow,
1320
+				'tax_label'         => $tax->get('PRC_name'),
1321
+				'tax_added'         => $tax_added,
1322
+				'tax_added_display' => EEH_Template::format_currency($tax_added, false, false),
1323
+				'tax_amount'        => $tax->get('PRC_amount')
1324
+			);
1325
+			$template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_tax_rows__template_args',
1326
+				$template_args, $tktrow, $ticket, $this->_is_creating_event);
1327
+			$tax_rows .= EEH_Template::display_template($template, $template_args, true);
1328
+		}
1329
+        
1330
+        
1331
+		return $tax_rows;
1332
+	}
1333 1333
     
1334 1334
     
1335
-    protected function _get_tax_added(EE_Price $tax, $ticket)
1336
-    {
1337
-        $subtotal = empty($ticket) ? 0 : $ticket->get_ticket_subtotal();
1335
+	protected function _get_tax_added(EE_Price $tax, $ticket)
1336
+	{
1337
+		$subtotal = empty($ticket) ? 0 : $ticket->get_ticket_subtotal();
1338 1338
         
1339
-        return $subtotal * $tax->get('PRC_amount') / 100;
1340
-    }
1339
+		return $subtotal * $tax->get('PRC_amount') / 100;
1340
+	}
1341 1341
     
1342 1342
     
1343
-    protected function _get_ticket_price_row(
1344
-        $tktrow,
1345
-        $prcrow,
1346
-        $price,
1347
-        $default,
1348
-        $ticket,
1349
-        $show_trash = true,
1350
-        $show_create = true
1351
-    ) {
1352
-        $send_disabled = ! empty($ticket) && $ticket->get('TKT_deleted') ? true : false;
1353
-        $template_args = array(
1354
-            'tkt_row'               => $default && empty($ticket) ? 'TICKETNUM' : $tktrow,
1355
-            'PRC_order'             => $default && empty($price) ? 'PRICENUM' : $prcrow,
1356
-            'edit_prices_name'      => $default && empty($price) ? 'PRICENAMEATTR' : 'edit_prices',
1357
-            'price_type_selector'   => $default && empty($price) ? $this->_get_base_price_template($tktrow, $prcrow,
1358
-                $price, $default) : $this->_get_price_type_selector($tktrow, $prcrow, $price, $default, $send_disabled),
1359
-            'PRC_ID'                => $default && empty($price) ? 0 : $price->ID(),
1360
-            'PRC_is_default'        => $default && empty($price) ? 0 : $price->get('PRC_is_default'),
1361
-            'PRC_name'              => $default && empty($price) ? '' : $price->get('PRC_name'),
1362
-            'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1363
-            'show_plus_or_minus'    => $default && empty($price) ? '' : ' style="display:none;"',
1364
-            'show_plus'             => $default && empty($price) ? ' style="display:none;"' : ($price->is_discount() || $price->is_base_price() ? ' style="display:none;"' : ''),
1365
-            'show_minus'            => $default && empty($price) ? ' style="display:none;"' : ($price->is_discount() ? '' : ' style="display:none;"'),
1366
-            'show_currency_symbol'  => $default && empty($price) ? ' style="display:none"' : ($price->is_percent() ? ' style="display:none"' : ''),
1367
-            'PRC_amount'            => $default && empty($price) ? 0 : $price->get_pretty('PRC_amount',
1368
-                'localized_float'),
1369
-            'show_percentage'       => $default && empty($price) ? ' style="display:none;"' : ($price->is_percent() ? '' : ' style="display:none;"'),
1370
-            'show_trash_icon'       => $show_trash ? '' : ' style="display:none;"',
1371
-            'show_create_button'    => $show_create ? '' : ' style="display:none;"',
1372
-            'PRC_desc'              => $default && empty($price) ? '' : $price->get('PRC_desc'),
1373
-            'disabled'              => ! empty($ticket) && $ticket->get('TKT_deleted') ? true : false
1374
-        );
1375
-        
1376
-        $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_ticket_price_row__template_args',
1377
-            $template_args, $tktrow, $prcrow, $price, $default, $ticket, $show_trash, $show_create,
1378
-            $this->_is_creating_event);
1379
-        
1380
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_price_row.template.php';
1381
-        
1382
-        return EEH_Template::display_template($template, $template_args, true);
1383
-    }
1343
+	protected function _get_ticket_price_row(
1344
+		$tktrow,
1345
+		$prcrow,
1346
+		$price,
1347
+		$default,
1348
+		$ticket,
1349
+		$show_trash = true,
1350
+		$show_create = true
1351
+	) {
1352
+		$send_disabled = ! empty($ticket) && $ticket->get('TKT_deleted') ? true : false;
1353
+		$template_args = array(
1354
+			'tkt_row'               => $default && empty($ticket) ? 'TICKETNUM' : $tktrow,
1355
+			'PRC_order'             => $default && empty($price) ? 'PRICENUM' : $prcrow,
1356
+			'edit_prices_name'      => $default && empty($price) ? 'PRICENAMEATTR' : 'edit_prices',
1357
+			'price_type_selector'   => $default && empty($price) ? $this->_get_base_price_template($tktrow, $prcrow,
1358
+				$price, $default) : $this->_get_price_type_selector($tktrow, $prcrow, $price, $default, $send_disabled),
1359
+			'PRC_ID'                => $default && empty($price) ? 0 : $price->ID(),
1360
+			'PRC_is_default'        => $default && empty($price) ? 0 : $price->get('PRC_is_default'),
1361
+			'PRC_name'              => $default && empty($price) ? '' : $price->get('PRC_name'),
1362
+			'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1363
+			'show_plus_or_minus'    => $default && empty($price) ? '' : ' style="display:none;"',
1364
+			'show_plus'             => $default && empty($price) ? ' style="display:none;"' : ($price->is_discount() || $price->is_base_price() ? ' style="display:none;"' : ''),
1365
+			'show_minus'            => $default && empty($price) ? ' style="display:none;"' : ($price->is_discount() ? '' : ' style="display:none;"'),
1366
+			'show_currency_symbol'  => $default && empty($price) ? ' style="display:none"' : ($price->is_percent() ? ' style="display:none"' : ''),
1367
+			'PRC_amount'            => $default && empty($price) ? 0 : $price->get_pretty('PRC_amount',
1368
+				'localized_float'),
1369
+			'show_percentage'       => $default && empty($price) ? ' style="display:none;"' : ($price->is_percent() ? '' : ' style="display:none;"'),
1370
+			'show_trash_icon'       => $show_trash ? '' : ' style="display:none;"',
1371
+			'show_create_button'    => $show_create ? '' : ' style="display:none;"',
1372
+			'PRC_desc'              => $default && empty($price) ? '' : $price->get('PRC_desc'),
1373
+			'disabled'              => ! empty($ticket) && $ticket->get('TKT_deleted') ? true : false
1374
+		);
1375
+        
1376
+		$template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_ticket_price_row__template_args',
1377
+			$template_args, $tktrow, $prcrow, $price, $default, $ticket, $show_trash, $show_create,
1378
+			$this->_is_creating_event);
1379
+        
1380
+		$template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_price_row.template.php';
1381
+        
1382
+		return EEH_Template::display_template($template, $template_args, true);
1383
+	}
1384 1384
     
1385 1385
     
1386
-    protected function _get_price_type_selector($tktrow, $prcrow, $price, $default, $disabled = false)
1387
-    {
1388
-        if ($price->is_base_price()) {
1389
-            return $this->_get_base_price_template($tktrow, $prcrow, $price, $default);
1390
-        } else {
1391
-            return $this->_get_price_modifier_template($tktrow, $prcrow, $price, $default, $disabled);
1392
-        }
1393
-        
1394
-    }
1386
+	protected function _get_price_type_selector($tktrow, $prcrow, $price, $default, $disabled = false)
1387
+	{
1388
+		if ($price->is_base_price()) {
1389
+			return $this->_get_base_price_template($tktrow, $prcrow, $price, $default);
1390
+		} else {
1391
+			return $this->_get_price_modifier_template($tktrow, $prcrow, $price, $default, $disabled);
1392
+		}
1393
+        
1394
+	}
1395 1395
     
1396 1396
     
1397
-    protected function _get_base_price_template($tktrow, $prcrow, $price, $default)
1398
-    {
1399
-        $template_args = array(
1400
-            'tkt_row'                   => $default ? 'TICKETNUM' : $tktrow,
1401
-            'PRC_order'                 => $default && empty($price) ? 'PRICENUM' : $prcrow,
1402
-            'PRT_ID'                    => $default && empty($price) ? 1 : $price->get('PRT_ID'),
1403
-            'PRT_name'                  => __('Price', 'event_espresso'),
1404
-            'price_selected_operator'   => '+',
1405
-            'price_selected_is_percent' => 0
1406
-        );
1407
-        $template      = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_type_base.template.php';
1408
-        
1409
-        $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_base_price_template__template_args',
1410
-            $template_args, $tktrow, $prcrow, $price, $default, $this->_is_creating_event);
1411
-        
1412
-        return EEH_Template::display_template($template, $template_args, true);
1413
-    }
1397
+	protected function _get_base_price_template($tktrow, $prcrow, $price, $default)
1398
+	{
1399
+		$template_args = array(
1400
+			'tkt_row'                   => $default ? 'TICKETNUM' : $tktrow,
1401
+			'PRC_order'                 => $default && empty($price) ? 'PRICENUM' : $prcrow,
1402
+			'PRT_ID'                    => $default && empty($price) ? 1 : $price->get('PRT_ID'),
1403
+			'PRT_name'                  => __('Price', 'event_espresso'),
1404
+			'price_selected_operator'   => '+',
1405
+			'price_selected_is_percent' => 0
1406
+		);
1407
+		$template      = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_type_base.template.php';
1408
+        
1409
+		$template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_base_price_template__template_args',
1410
+			$template_args, $tktrow, $prcrow, $price, $default, $this->_is_creating_event);
1411
+        
1412
+		return EEH_Template::display_template($template, $template_args, true);
1413
+	}
1414 1414
     
1415 1415
     
1416
-    protected function _get_price_modifier_template($tktrow, $prcrow, $price, $default, $disabled = false)
1417
-    {
1418
-        $select_name                = $default && empty($price) ? 'edit_prices[TICKETNUM][PRICENUM][PRT_ID]' : 'edit_prices[' . $tktrow . '][' . $prcrow . '][PRT_ID]';
1419
-        $price_types                = EE_Registry::instance()->load_model('Price_Type')->get_all(array(
1420
-            array(
1421
-                'OR' => array(
1422
-                    'PBT_ID'  => '2',
1423
-                    'PBT_ID*' => '3'
1424
-                )
1425
-            )
1426
-        ));
1427
-        $price_option_span_template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_option_span.template.php';
1428
-        $all_price_types            = $default && empty($price) ? array(
1429
-            array(
1430
-                'id'   => 0,
1431
-                'text' => __('Select Modifier', 'event_espresso')
1432
-            )
1433
-        ) : array();
1434
-        $selected_price_type_id     = $default && empty($price) ? 0 : $price->type();
1435
-        $price_option_spans         = '';
1436
-        //setup pricetypes for selector
1437
-        foreach ($price_types as $price_type) {
1438
-            $all_price_types[] = array(
1439
-                'id'   => $price_type->ID(),
1440
-                'text' => $price_type->get('PRT_name'),
1441
-            );
1416
+	protected function _get_price_modifier_template($tktrow, $prcrow, $price, $default, $disabled = false)
1417
+	{
1418
+		$select_name                = $default && empty($price) ? 'edit_prices[TICKETNUM][PRICENUM][PRT_ID]' : 'edit_prices[' . $tktrow . '][' . $prcrow . '][PRT_ID]';
1419
+		$price_types                = EE_Registry::instance()->load_model('Price_Type')->get_all(array(
1420
+			array(
1421
+				'OR' => array(
1422
+					'PBT_ID'  => '2',
1423
+					'PBT_ID*' => '3'
1424
+				)
1425
+			)
1426
+		));
1427
+		$price_option_span_template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_option_span.template.php';
1428
+		$all_price_types            = $default && empty($price) ? array(
1429
+			array(
1430
+				'id'   => 0,
1431
+				'text' => __('Select Modifier', 'event_espresso')
1432
+			)
1433
+		) : array();
1434
+		$selected_price_type_id     = $default && empty($price) ? 0 : $price->type();
1435
+		$price_option_spans         = '';
1436
+		//setup pricetypes for selector
1437
+		foreach ($price_types as $price_type) {
1438
+			$all_price_types[] = array(
1439
+				'id'   => $price_type->ID(),
1440
+				'text' => $price_type->get('PRT_name'),
1441
+			);
1442 1442
             
1443
-            //while we're in the loop let's setup the option spans used by js
1444
-            $spanargs = array(
1445
-                'PRT_ID'         => $price_type->ID(),
1446
-                'PRT_operator'   => $price_type->is_discount() ? '-' : '+',
1447
-                'PRT_is_percent' => $price_type->get('PRT_is_percent') ? 1 : 0
1448
-            );
1449
-            $price_option_spans .= EEH_Template::display_template($price_option_span_template, $spanargs, true);
1450
-        }
1451
-        
1452
-        $select_params = $disabled ? 'style="width:auto;" disabled' : 'style="width:auto;"';
1453
-        $main_name     = $select_name;
1454
-        $select_name   = $disabled ? 'archive_price[' . $tktrow . '][' . $prcrow . '][PRT_ID]' : $main_name;
1455
-        
1456
-        $template_args = array(
1457
-            'tkt_row'                   => $default ? 'TICKETNUM' : $tktrow,
1458
-            'PRC_order'                 => $default && empty($price) ? 'PRICENUM' : $prcrow,
1459
-            'price_modifier_selector'   => EEH_Form_Fields::select_input($select_name, $all_price_types,
1460
-                $selected_price_type_id, $select_params, 'edit-price-PRT_ID'),
1461
-            'main_name'                 => $main_name,
1462
-            'selected_price_type_id'    => $selected_price_type_id,
1463
-            'price_option_spans'        => $price_option_spans,
1464
-            'price_selected_operator'   => $default && empty($price) ? '' : ($price->is_discount() ? '-' : '+'),
1465
-            'price_selected_is_percent' => $default && empty($price) ? '' : ($price->is_percent() ? 1 : 0),
1466
-            'disabled'                  => $disabled
1467
-        );
1468
-        
1469
-        $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_price_modifier_template__template_args',
1470
-            $template_args, $tktrow, $prcrow, $price, $default, $disabled, $this->_is_creating_event);
1471
-        
1472
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_modifier_selector.template.php';
1473
-        
1474
-        return EEH_Template::display_template($template, $template_args, true);
1475
-    }
1443
+			//while we're in the loop let's setup the option spans used by js
1444
+			$spanargs = array(
1445
+				'PRT_ID'         => $price_type->ID(),
1446
+				'PRT_operator'   => $price_type->is_discount() ? '-' : '+',
1447
+				'PRT_is_percent' => $price_type->get('PRT_is_percent') ? 1 : 0
1448
+			);
1449
+			$price_option_spans .= EEH_Template::display_template($price_option_span_template, $spanargs, true);
1450
+		}
1451
+        
1452
+		$select_params = $disabled ? 'style="width:auto;" disabled' : 'style="width:auto;"';
1453
+		$main_name     = $select_name;
1454
+		$select_name   = $disabled ? 'archive_price[' . $tktrow . '][' . $prcrow . '][PRT_ID]' : $main_name;
1455
+        
1456
+		$template_args = array(
1457
+			'tkt_row'                   => $default ? 'TICKETNUM' : $tktrow,
1458
+			'PRC_order'                 => $default && empty($price) ? 'PRICENUM' : $prcrow,
1459
+			'price_modifier_selector'   => EEH_Form_Fields::select_input($select_name, $all_price_types,
1460
+				$selected_price_type_id, $select_params, 'edit-price-PRT_ID'),
1461
+			'main_name'                 => $main_name,
1462
+			'selected_price_type_id'    => $selected_price_type_id,
1463
+			'price_option_spans'        => $price_option_spans,
1464
+			'price_selected_operator'   => $default && empty($price) ? '' : ($price->is_discount() ? '-' : '+'),
1465
+			'price_selected_is_percent' => $default && empty($price) ? '' : ($price->is_percent() ? 1 : 0),
1466
+			'disabled'                  => $disabled
1467
+		);
1468
+        
1469
+		$template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_price_modifier_template__template_args',
1470
+			$template_args, $tktrow, $prcrow, $price, $default, $disabled, $this->_is_creating_event);
1471
+        
1472
+		$template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_modifier_selector.template.php';
1473
+        
1474
+		return EEH_Template::display_template($template, $template_args, true);
1475
+	}
1476 1476
     
1477 1477
     
1478
-    protected function _get_ticket_datetime_list_item($dttrow, $tktrow, $dtt, $ticket, $ticket_datetimes, $default)
1479
-    {
1480
-        $tkt_dtts      = $ticket instanceof EE_Ticket && isset($ticket_datetimes[$ticket->ID()]) ? $ticket_datetimes[$ticket->ID()] : array();
1481
-        $template_args = array(
1482
-            'dtt_row'                  => $default && ! $dtt instanceof EE_Datetime ? 'DTTNUM' : $dttrow,
1483
-            'tkt_row'                  => $default ? 'TICKETNUM' : $tktrow,
1484
-            'ticket_datetime_selected' => in_array($dttrow, $tkt_dtts) ? ' ticket-selected' : '',
1485
-            'ticket_datetime_checked'  => in_array($dttrow, $tkt_dtts) ? ' checked="checked"' : '',
1486
-            'DTT_name'                 => $default && empty($dtt) ? 'DTTNAME' : $dtt->get_dtt_display_name(true),
1487
-            'tkt_status_class'         => '',
1488
-        );
1489
-        
1490
-        $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_ticket_datetime_list_item__template_args',
1491
-            $template_args, $dttrow, $tktrow, $dtt, $ticket, $ticket_datetimes, $default, $this->_is_creating_event);
1492
-        $template      = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_datetimes_list_item.template.php';
1493
-        
1494
-        return EEH_Template::display_template($template, $template_args, true);
1495
-    }
1478
+	protected function _get_ticket_datetime_list_item($dttrow, $tktrow, $dtt, $ticket, $ticket_datetimes, $default)
1479
+	{
1480
+		$tkt_dtts      = $ticket instanceof EE_Ticket && isset($ticket_datetimes[$ticket->ID()]) ? $ticket_datetimes[$ticket->ID()] : array();
1481
+		$template_args = array(
1482
+			'dtt_row'                  => $default && ! $dtt instanceof EE_Datetime ? 'DTTNUM' : $dttrow,
1483
+			'tkt_row'                  => $default ? 'TICKETNUM' : $tktrow,
1484
+			'ticket_datetime_selected' => in_array($dttrow, $tkt_dtts) ? ' ticket-selected' : '',
1485
+			'ticket_datetime_checked'  => in_array($dttrow, $tkt_dtts) ? ' checked="checked"' : '',
1486
+			'DTT_name'                 => $default && empty($dtt) ? 'DTTNAME' : $dtt->get_dtt_display_name(true),
1487
+			'tkt_status_class'         => '',
1488
+		);
1489
+        
1490
+		$template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_ticket_datetime_list_item__template_args',
1491
+			$template_args, $dttrow, $tktrow, $dtt, $ticket, $ticket_datetimes, $default, $this->_is_creating_event);
1492
+		$template      = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_datetimes_list_item.template.php';
1493
+        
1494
+		return EEH_Template::display_template($template, $template_args, true);
1495
+	}
1496 1496
     
1497 1497
     
1498
-    protected function _get_ticket_js_structure($all_dtts, $all_tickets)
1499
-    {
1500
-        $template_args = array(
1501
-            'default_datetime_edit_row'                => $this->_get_dtt_edit_row('DTTNUM', null, true, $all_dtts),
1502
-            'default_ticket_row'                       => $this->_get_ticket_row('TICKETNUM', null, array(), array(),
1503
-                true),
1504
-            'default_price_row'                        => $this->_get_ticket_price_row('TICKETNUM', 'PRICENUM', null,
1505
-                true, null),
1506
-            'default_price_rows'                       => '',
1507
-            'default_base_price_amount'                => 0,
1508
-            'default_base_price_name'                  => '',
1509
-            'default_base_price_description'           => '',
1510
-            'default_price_modifier_selector_row'      => $this->_get_price_modifier_template('TICKETNUM', 'PRICENUM',
1511
-                null, true),
1512
-            'default_available_tickets_for_datetime'   => $this->_get_dtt_attached_tickets_row('DTTNUM', null, array(),
1513
-                array(), true),
1514
-            'existing_available_datetime_tickets_list' => '',
1515
-            'existing_available_ticket_datetimes_list' => '',
1516
-            'new_available_datetime_ticket_list_item'  => $this->_get_datetime_tickets_list_item('DTTNUM', 'TICKETNUM',
1517
-                null, null, array(), true),
1518
-            'new_available_ticket_datetime_list_item'  => $this->_get_ticket_datetime_list_item('DTTNUM', 'TICKETNUM',
1519
-                null, null, array(), true)
1520
-        );
1521
-        
1522
-        $tktrow = 1;
1523
-        foreach ($all_tickets as $ticket) {
1524
-            $template_args['existing_available_datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item('DTTNUM',
1525
-                $tktrow, null, $ticket, array(), true);
1526
-            $tktrow++;
1527
-        }
1528
-        
1529
-        
1530
-        $dttrow = 1;
1531
-        foreach ($all_dtts as $dtt) {
1532
-            $template_args['existing_available_ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item($dttrow,
1533
-                'TICKETNUM', $dtt, null, array(), true);
1534
-            $dttrow++;
1535
-        }
1536
-        
1537
-        $default_prices = EE_Registry::instance()->load_model('Price')->get_all_default_prices();
1538
-        $prcrow         = 1;
1539
-        foreach ($default_prices as $price) {
1540
-            if ($price->is_base_price()) {
1541
-                $template_args['default_base_price_amount']      = $price->get_pretty('PRC_amount', 'localized_float');
1542
-                $template_args['default_base_price_name']        = $price->get('PRC_name');
1543
-                $template_args['default_base_price_description'] = $price->get('PRC_desc');
1544
-                $prcrow++;
1545
-                continue;
1546
-            }
1547
-            $show_trash  = (count($default_prices) > 1 && $prcrow === 1) || count($default_prices) === 1 ? false : true;
1548
-            $show_create = count($default_prices) > 1 && count($default_prices) !== $prcrow ? false : true;
1549
-            $template_args['default_price_rows'] .= $this->_get_ticket_price_row('TICKETNUM', $prcrow, $price, true,
1550
-                null, $show_trash, $show_create);
1551
-            $prcrow++;
1552
-        }
1553
-        
1554
-        $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_ticket_js_structure__template_args',
1555
-            $template_args, $all_dtts, $all_tickets, $this->_is_creating_event);
1556
-        
1557
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_js_structure.template.php';
1558
-        
1559
-        return EEH_Template::display_template($template, $template_args, true);
1560
-    }
1498
+	protected function _get_ticket_js_structure($all_dtts, $all_tickets)
1499
+	{
1500
+		$template_args = array(
1501
+			'default_datetime_edit_row'                => $this->_get_dtt_edit_row('DTTNUM', null, true, $all_dtts),
1502
+			'default_ticket_row'                       => $this->_get_ticket_row('TICKETNUM', null, array(), array(),
1503
+				true),
1504
+			'default_price_row'                        => $this->_get_ticket_price_row('TICKETNUM', 'PRICENUM', null,
1505
+				true, null),
1506
+			'default_price_rows'                       => '',
1507
+			'default_base_price_amount'                => 0,
1508
+			'default_base_price_name'                  => '',
1509
+			'default_base_price_description'           => '',
1510
+			'default_price_modifier_selector_row'      => $this->_get_price_modifier_template('TICKETNUM', 'PRICENUM',
1511
+				null, true),
1512
+			'default_available_tickets_for_datetime'   => $this->_get_dtt_attached_tickets_row('DTTNUM', null, array(),
1513
+				array(), true),
1514
+			'existing_available_datetime_tickets_list' => '',
1515
+			'existing_available_ticket_datetimes_list' => '',
1516
+			'new_available_datetime_ticket_list_item'  => $this->_get_datetime_tickets_list_item('DTTNUM', 'TICKETNUM',
1517
+				null, null, array(), true),
1518
+			'new_available_ticket_datetime_list_item'  => $this->_get_ticket_datetime_list_item('DTTNUM', 'TICKETNUM',
1519
+				null, null, array(), true)
1520
+		);
1521
+        
1522
+		$tktrow = 1;
1523
+		foreach ($all_tickets as $ticket) {
1524
+			$template_args['existing_available_datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item('DTTNUM',
1525
+				$tktrow, null, $ticket, array(), true);
1526
+			$tktrow++;
1527
+		}
1528
+        
1529
+        
1530
+		$dttrow = 1;
1531
+		foreach ($all_dtts as $dtt) {
1532
+			$template_args['existing_available_ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item($dttrow,
1533
+				'TICKETNUM', $dtt, null, array(), true);
1534
+			$dttrow++;
1535
+		}
1536
+        
1537
+		$default_prices = EE_Registry::instance()->load_model('Price')->get_all_default_prices();
1538
+		$prcrow         = 1;
1539
+		foreach ($default_prices as $price) {
1540
+			if ($price->is_base_price()) {
1541
+				$template_args['default_base_price_amount']      = $price->get_pretty('PRC_amount', 'localized_float');
1542
+				$template_args['default_base_price_name']        = $price->get('PRC_name');
1543
+				$template_args['default_base_price_description'] = $price->get('PRC_desc');
1544
+				$prcrow++;
1545
+				continue;
1546
+			}
1547
+			$show_trash  = (count($default_prices) > 1 && $prcrow === 1) || count($default_prices) === 1 ? false : true;
1548
+			$show_create = count($default_prices) > 1 && count($default_prices) !== $prcrow ? false : true;
1549
+			$template_args['default_price_rows'] .= $this->_get_ticket_price_row('TICKETNUM', $prcrow, $price, true,
1550
+				null, $show_trash, $show_create);
1551
+			$prcrow++;
1552
+		}
1553
+        
1554
+		$template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_ticket_js_structure__template_args',
1555
+			$template_args, $all_dtts, $all_tickets, $this->_is_creating_event);
1556
+        
1557
+		$template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_js_structure.template.php';
1558
+        
1559
+		return EEH_Template::display_template($template, $template_args, true);
1560
+	}
1561 1561
     
1562 1562
     
1563 1563
 } //end class espresso_events_Pricing_Hooks
Please login to merge, or discard this patch.
Spacing   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
                 'context'    => 'normal'
74 74
             ),
75 75
         
76
-        );/**/
76
+        ); /**/
77 77
         
78 78
         $this->_remove_metaboxes = array(
79 79
             0 => array(
@@ -103,16 +103,16 @@  discard block
 block discarded – undo
103 103
         $this->_date_format_strings['time'] = isset($this->_date_format_strings['time']) ? $this->_date_format_strings['time'] : null;
104 104
         
105 105
         //validate format strings
106
-        $format_validation = EEH_DTT_Helper::validate_format_string($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']);
106
+        $format_validation = EEH_DTT_Helper::validate_format_string($this->_date_format_strings['date'].' '.$this->_date_format_strings['time']);
107 107
         if (is_array($format_validation)) {
108
-            $msg = '<p>' . sprintf(__('The format "%s" was likely added via a filter and is invalid for the following reasons:',
108
+            $msg = '<p>'.sprintf(__('The format "%s" was likely added via a filter and is invalid for the following reasons:',
109 109
                     'event_espresso'),
110
-                    $this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']) . '</p><ul>';
110
+                    $this->_date_format_strings['date'].' '.$this->_date_format_strings['time']).'</p><ul>';
111 111
             foreach ($format_validation as $error) {
112
-                $msg .= '<li>' . $error . '</li>';
112
+                $msg .= '<li>'.$error.'</li>';
113 113
             }
114
-            $msg .= '</ul></p><p>' . sprintf(__('%sPlease note that your date and time formats have been reset to "Y-m-d" and "h:i a" respectively.%s',
115
-                    'event_espresso'), '<span style="color:#D54E21;">', '</span>') . '</p>';
114
+            $msg .= '</ul></p><p>'.sprintf(__('%sPlease note that your date and time formats have been reset to "Y-m-d" and "h:i a" respectively.%s',
115
+                    'event_espresso'), '<span style="color:#D54E21;">', '</span>').'</p>';
116 116
             EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
117 117
             $this->_date_format_strings = array(
118 118
                 'date' => 'Y-m-d',
@@ -124,11 +124,11 @@  discard block
 block discarded – undo
124 124
         $this->_scripts_styles = array(
125 125
             'registers'   => array(
126 126
                 'ee-tickets-datetimes-css' => array(
127
-                    'url'  => PRICING_ASSETS_URL . 'event-tickets-datetimes.css',
127
+                    'url'  => PRICING_ASSETS_URL.'event-tickets-datetimes.css',
128 128
                     'type' => 'css'
129 129
                 ),
130 130
                 'ee-dtt-ticket-metabox'    => array(
131
-                    'url'     => PRICING_ASSETS_URL . 'ee-datetime-ticket-metabox.js',
131
+                    'url'     => PRICING_ASSETS_URL.'ee-datetime-ticket-metabox.js',
132 132
                     'depends' => array('ee-datepicker', 'ee-dialog', 'underscore')
133 133
                 )
134 134
             ),
@@ -147,21 +147,21 @@  discard block
 block discarded – undo
147 147
                             'event_espresso'),
148 148
                         'after_warning'           => __('In order to trash this datetime you must first make sure the above ticket(s) are assigned to other datetimes.',
149 149
                             'event_espresso'),
150
-                        'cancel_button'           => '<button class="button-secondary ee-modal-cancel">' . __('Cancel',
151
-                                'event_espresso') . '</button>',
152
-                        'close_button'            => '<button class="button-secondary ee-modal-cancel">' . __('Close',
153
-                                'event_espresso') . '</button>',
150
+                        'cancel_button'           => '<button class="button-secondary ee-modal-cancel">'.__('Cancel',
151
+                                'event_espresso').'</button>',
152
+                        'close_button'            => '<button class="button-secondary ee-modal-cancel">'.__('Close',
153
+                                'event_espresso').'</button>',
154 154
                         'single_warning_from_tkt' => __('The Datetime you are attempting to unassign from this ticket is the only remaining datetime for this ticket. Tickets must always have at least one datetime assigned to them.',
155 155
                             'event_espresso'),
156 156
                         'single_warning_from_dtt' => __('The ticket you are attempting to unassign from this datetime cannot be unassigned because the datetime is the only remaining datetime for the ticket.  Tickets must always have at least one datetime assigned to them.',
157 157
                             'event_espresso'),
158
-                        'dismiss_button'          => '<button class="button-secondary ee-modal-cancel">' . __('Dismiss',
159
-                                'event_espresso') . '</button>'
158
+                        'dismiss_button'          => '<button class="button-secondary ee-modal-cancel">'.__('Dismiss',
159
+                                'event_espresso').'</button>'
160 160
                     ),
161 161
                     'DTT_ERROR_MSG'         => array(
162 162
                         'no_ticket_name' => __('General Admission', 'event_espresso'),
163
-                        'dismiss_button' => '<div class="save-cancel-button-container"><button class="button-secondary ee-modal-cancel">' . __('Dismiss',
164
-                                'event_espresso') . '</button></div>'
163
+                        'dismiss_button' => '<div class="save-cancel-button-container"><button class="button-secondary ee-modal-cancel">'.__('Dismiss',
164
+                                'event_espresso').'</button></div>'
165 165
                     ),
166 166
                     'DTT_OVERSELL_WARNING'  => array(
167 167
                         'datetime_ticket' => __('You cannot add this ticket to this datetime because it has a sold amount that is greater than the amount of spots remaining for this datetime.',
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
                     ),
172 172
                     'DTT_CONVERTED_FORMATS' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats($this->_date_format_strings['date'],
173 173
                         $this->_date_format_strings['time']),
174
-                    'DTT_START_OF_WEEK'     => array('dayValue' => (int)get_option('start_of_week'))
174
+                    'DTT_START_OF_WEEK'     => array('dayValue' => (int) get_option('start_of_week'))
175 175
                 )
176 176
             )
177 177
         );
@@ -231,8 +231,8 @@  discard block
 block discarded – undo
231 231
         
232 232
         foreach ($data['edit_event_datetimes'] as $row => $dtt) {
233 233
             //trim all values to ensure any excess whitespace is removed.
234
-            $dtt                = array_map(
235
-                function ($datetime_data) {
234
+            $dtt = array_map(
235
+                function($datetime_data) {
236 236
                     return is_array($datetime_data) ? $datetime_data : trim($datetime_data);
237 237
                 },
238 238
                 $dtt
@@ -368,7 +368,7 @@  discard block
 block discarded – undo
368 368
             
369 369
             // trim inputs to ensure any excess whitespace is removed.
370 370
             $tkt = array_map(
371
-                function ($ticket_data) {
371
+                function($ticket_data) {
372 372
                     return is_array($ticket_data) ? $ticket_data : trim($ticket_data);
373 373
                 },
374 374
                 $tkt
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
             
377 377
             //note we are doing conversions to floats here instead of allowing EE_Money_Field to handle because we're doing calcs prior to using the models.
378 378
             //note incoming ['TKT_price'] value is already in standard notation (via js).
379
-            $ticket_price = isset($tkt['TKT_price']) ? round((float)$tkt['TKT_price'], 3) : 0;
379
+            $ticket_price = isset($tkt['TKT_price']) ? round((float) $tkt['TKT_price'], 3) : 0;
380 380
             
381 381
             //note incoming base price needs converted from localized value.
382 382
             $base_price = isset($tkt['TKT_base_price']) ? EEH_Money::convert_to_float_from_localized_money($tkt['TKT_base_price']) : 0;
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
             if (empty($tkt['TKT_start_date'])) {
391 391
                 //lets' use now in the set timezone.
392 392
                 $now                   = new DateTime('now', new DateTimeZone($evtobj->get_timezone()));
393
-                $tkt['TKT_start_date'] = $now->format($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']);
393
+                $tkt['TKT_start_date'] = $now->format($this->_date_format_strings['date'].' '.$this->_date_format_strings['time']);
394 394
             }
395 395
             
396 396
             if (empty($tkt['TKT_end_date'])) {
@@ -398,7 +398,7 @@  discard block
 block discarded – undo
398 398
                  * set the TKT_end_date to the first datetime attached to the ticket.
399 399
                  */
400 400
                 $first_dtt           = $saved_dtts[reset($tkt_dtt_rows)];
401
-                $tkt['TKT_end_date'] = $first_dtt->start_date_and_time($this->_date_format_strings['date'] . ' ' . $this->_date_format_string['time']);
401
+                $tkt['TKT_end_date'] = $first_dtt->start_date_and_time($this->_date_format_strings['date'].' '.$this->_date_format_string['time']);
402 402
             }
403 403
             
404 404
             $TKT_values = array(
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
         // first let's add datetimes
629 629
         if ( ! empty($added_datetimes) && is_array($added_datetimes)) {
630 630
             foreach ($added_datetimes as $row_id) {
631
-                $row_id = (int)$row_id;
631
+                $row_id = (int) $row_id;
632 632
                 if (isset($saved_datetimes[$row_id]) && $saved_datetimes[$row_id] instanceof EE_Datetime) {
633 633
                     $ticket->_add_relation_to($saved_datetimes[$row_id], 'Datetime');
634 634
                     // Is this an existing ticket (has an ID) and does it have any sold?
@@ -643,7 +643,7 @@  discard block
 block discarded – undo
643 643
         // then remove datetimes
644 644
         if ( ! empty($removed_datetimes) && is_array($removed_datetimes)) {
645 645
             foreach ($removed_datetimes as $row_id) {
646
-                $row_id = (int)$row_id;
646
+                $row_id = (int) $row_id;
647 647
                 // its entirely possible that a datetime got deleted (instead of just removed from relationship.
648 648
                 // So make sure we skip over this if the dtt isn't in the $saved_datetimes array)
649 649
                 if (isset($saved_datetimes[$row_id]) && $saved_datetimes[$row_id] instanceof EE_Datetime) {
@@ -948,9 +948,9 @@  discard block
 block discarded – undo
948 948
         $main_template_args['existing_datetime_ids'] = implode(',', $existing_datetime_ids);
949 949
         
950 950
         //sort $all_tickets by order
951
-        usort($all_tickets, function ($a, $b) {
952
-            $a_order = (int)$a->get('TKT_order');
953
-            $b_order = (int)$b->get('TKT_order');
951
+        usort($all_tickets, function($a, $b) {
952
+            $a_order = (int) $a->get('TKT_order');
953
+            $b_order = (int) $b->get('TKT_order');
954 954
             if ($a_order == $b_order) {
955 955
                 return 0;
956 956
             }
@@ -975,7 +975,7 @@  discard block
 block discarded – undo
975 975
         }
976 976
         
977 977
         $main_template_args['ticket_js_structure'] = $this->_get_ticket_js_structure($times, $all_tickets);
978
-        $template                                  = PRICING_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php';
978
+        $template                                  = PRICING_TEMPLATE_PATH.'event_tickets_metabox_main.template.php';
979 979
         EEH_Template::display_template($template, $main_template_args);
980 980
         
981 981
         return;
@@ -997,7 +997,7 @@  discard block
 block discarded – undo
997 997
                 $all_tickets, $default),
998 998
             'dtt_row'                  => $default ? 'DTTNUM' : $dttrow
999 999
         );
1000
-        $template                  = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_row_wrapper.template.php';
1000
+        $template = PRICING_TEMPLATE_PATH.'event_tickets_datetime_row_wrapper.template.php';
1001 1001
         
1002 1002
         return EEH_Template::display_template($template, $dtt_display_template_args, true);
1003 1003
     }
@@ -1031,8 +1031,8 @@  discard block
 block discarded – undo
1031 1031
             'DTT_ID'               => $default ? '' : $dtt->ID(),
1032 1032
             'DTT_name'             => $default ? '' : $dtt->name(),
1033 1033
             'DTT_description'      => $default ? '' : $dtt->description(),
1034
-            'DTT_EVT_start'        => $default ? '' : $dtt->start_date($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']),
1035
-            'DTT_EVT_end'          => $default ? '' : $dtt->end_date($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']),
1034
+            'DTT_EVT_start'        => $default ? '' : $dtt->start_date($this->_date_format_strings['date'].' '.$this->_date_format_strings['time']),
1035
+            'DTT_EVT_end'          => $default ? '' : $dtt->end_date($this->_date_format_strings['date'].' '.$this->_date_format_strings['time']),
1036 1036
             'DTT_reg_limit'        => $default ? '' : $dtt->get_pretty('DTT_reg_limit', 'input'),
1037 1037
             'DTT_order'            => $default ? 'DTTNUM' : $dttrow,
1038 1038
             'dtt_sold'             => $default ? '0' : $dtt->get('DTT_sold'),
@@ -1052,7 +1052,7 @@  discard block
 block discarded – undo
1052 1052
         $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_dtt_edit_row__template_args',
1053 1053
             $template_args, $dttrow, $dtt, $default, $all_dtts, $this->_is_creating_event);
1054 1054
         
1055
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_edit_row.template.php';
1055
+        $template = PRICING_TEMPLATE_PATH.'event_tickets_datetime_edit_row.template.php';
1056 1056
         
1057 1057
         return EEH_Template::display_template($template, $template_args, true);
1058 1058
     }
@@ -1088,7 +1088,7 @@  discard block
 block discarded – undo
1088 1088
         $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_dtt_attached_ticket_row__template_args',
1089 1089
             $template_args, $dttrow, $dtt, $datetime_tickets, $all_tickets, $default, $this->_is_creating_event);
1090 1090
         
1091
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_attached_tickets_row.template.php';
1091
+        $template = PRICING_TEMPLATE_PATH.'event_tickets_datetime_attached_tickets_row.template.php';
1092 1092
         
1093 1093
         return EEH_Template::display_template($template, $template_args, true);
1094 1094
     }
@@ -1106,14 +1106,14 @@  discard block
 block discarded – undo
1106 1106
             'datetime_ticket_checked' => in_array($displayrow, $dtt_tkts) ? ' checked="checked"' : '',
1107 1107
             'ticket_selected'         => in_array($displayrow, $dtt_tkts) ? ' ticket-selected' : '',
1108 1108
             'TKT_name'                => $default && empty($ticket) ? 'TKTNAME' : $ticket->get('TKT_name'),
1109
-            'tkt_status_class'        => ($default && empty($ticket)) || $this->_is_creating_event ? ' tkt-status-' . EE_Ticket::onsale : ' tkt-status-' . $ticket->ticket_status(),
1109
+            'tkt_status_class'        => ($default && empty($ticket)) || $this->_is_creating_event ? ' tkt-status-'.EE_Ticket::onsale : ' tkt-status-'.$ticket->ticket_status(),
1110 1110
         );
1111 1111
         
1112 1112
         //filter template args
1113 1113
         $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_datetime_tickets_list_item__template_args',
1114 1114
             $template_args, $dttrow, $tktrow, $dtt, $ticket, $datetime_tickets, $default, $this->_is_creating_event);
1115 1115
         
1116
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_dtt_tickets_list.template.php';
1116
+        $template = PRICING_TEMPLATE_PATH.'event_tickets_datetime_dtt_tickets_list.template.php';
1117 1117
         
1118 1118
         return EEH_Template::display_template($template, $template_args, true);
1119 1119
     }
@@ -1168,9 +1168,9 @@  discard block
 block discarded – undo
1168 1168
         
1169 1169
         //breaking out complicated condition for ticket_status
1170 1170
         if ($default) {
1171
-            $ticket_status_class = ' tkt-status-' . EE_Ticket::onsale;
1171
+            $ticket_status_class = ' tkt-status-'.EE_Ticket::onsale;
1172 1172
         } else {
1173
-            $ticket_status_class = $ticket->is_default() ? ' tkt-status-' . EE_Ticket::onsale : ' tkt-status-' . $ticket->ticket_status();
1173
+            $ticket_status_class = $ticket->is_default() ? ' tkt-status-'.EE_Ticket::onsale : ' tkt-status-'.$ticket->ticket_status();
1174 1174
         }
1175 1175
         
1176 1176
         //breaking out complicated condition for TKT_taxable
@@ -1191,9 +1191,9 @@  discard block
 block discarded – undo
1191 1191
             'edit_tickets_name'             => $default ? 'TICKETNAMEATTR' : 'edit_tickets',
1192 1192
             'TKT_name'                      => $default ? '' : $ticket->get('TKT_name'),
1193 1193
             'TKT_start_date'                => $default ? '' : $ticket->get_date('TKT_start_date',
1194
-                $this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']),
1194
+                $this->_date_format_strings['date'].' '.$this->_date_format_strings['time']),
1195 1195
             'TKT_end_date'                  => $default ? '' : $ticket->get_date('TKT_end_date',
1196
-                $this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']),
1196
+                $this->_date_format_strings['date'].' '.$this->_date_format_strings['time']),
1197 1197
             'TKT_status'                    => $default ? EEH_Template::pretty_status(EE_Ticket::onsale, false,
1198 1198
                 'sentence') : $ticket->is_default() ? EEH_Template::pretty_status(EE_Ticket::onsale, false,
1199 1199
                 'sentence') : $ticket->ticket_status(true),
@@ -1249,9 +1249,9 @@  discard block
 block discarded – undo
1249 1249
         //handle rows that should NOT be empty
1250 1250
         if (empty($template_args['TKT_start_date'])) {
1251 1251
             //if empty then the start date will be now.
1252
-            $template_args['TKT_start_date']   = date($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time'],
1252
+            $template_args['TKT_start_date']   = date($this->_date_format_strings['date'].' '.$this->_date_format_strings['time'],
1253 1253
                 current_time('timestamp'));
1254
-            $template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1254
+            $template_args['tkt_status_class'] = ' tkt-status-'.EE_Ticket::onsale;
1255 1255
         }
1256 1256
         
1257 1257
         if (empty($template_args['TKT_end_date'])) {
@@ -1262,13 +1262,13 @@  discard block
 block discarded – undo
1262 1262
             
1263 1263
             if ( ! empty($earliest_dtt)) {
1264 1264
                 $template_args['TKT_end_date'] = $earliest_dtt->get_datetime('DTT_EVT_start',
1265
-                    $this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time']);
1265
+                    $this->_date_format_strings['date'].' '.$this->_date_format_strings['time']);
1266 1266
             } else {
1267 1267
                 //default so let's just use what's been set for the default date-time which is 30 days from now.
1268
-                $template_args['TKT_end_date'] = date($this->_date_format_strings['date'] . ' ' . $this->_date_format_strings['time'],
1268
+                $template_args['TKT_end_date'] = date($this->_date_format_strings['date'].' '.$this->_date_format_strings['time'],
1269 1269
                     mktime(24, 0, 0, date("m"), date("d") + 29, date("Y")));
1270 1270
             }
1271
-            $template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1271
+            $template_args['tkt_status_class'] = ' tkt-status-'.EE_Ticket::onsale;
1272 1272
         }
1273 1273
         
1274 1274
         //generate ticket_datetime items
@@ -1299,7 +1299,7 @@  discard block
 block discarded – undo
1299 1299
             $template_args, $tktrow, $ticket, $ticket_datetimes, $all_dtts, $default, $all_tickets,
1300 1300
             $this->_is_creating_event);
1301 1301
         
1302
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_row.template.php';
1302
+        $template = PRICING_TEMPLATE_PATH.'event_tickets_datetime_ticket_row.template.php';
1303 1303
         
1304 1304
         return EEH_Template::display_template($template, $template_args, true);
1305 1305
     }
@@ -1308,7 +1308,7 @@  discard block
 block discarded – undo
1308 1308
     protected function _get_tax_rows($tktrow, $ticket)
1309 1309
     {
1310 1310
         $tax_rows      = '';
1311
-        $template      = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_tax_row.template.php';
1311
+        $template      = PRICING_TEMPLATE_PATH.'event_tickets_datetime_ticket_tax_row.template.php';
1312 1312
         $template_args = array();
1313 1313
         $taxes         = empty($ticket) ? EE_Taxes::get_taxes_for_admin() : $ticket->get_ticket_taxes_for_admin();
1314 1314
         foreach ($taxes as $tax) {
@@ -1377,7 +1377,7 @@  discard block
 block discarded – undo
1377 1377
             $template_args, $tktrow, $prcrow, $price, $default, $ticket, $show_trash, $show_create,
1378 1378
             $this->_is_creating_event);
1379 1379
         
1380
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_price_row.template.php';
1380
+        $template = PRICING_TEMPLATE_PATH.'event_tickets_datetime_ticket_price_row.template.php';
1381 1381
         
1382 1382
         return EEH_Template::display_template($template, $template_args, true);
1383 1383
     }
@@ -1404,7 +1404,7 @@  discard block
 block discarded – undo
1404 1404
             'price_selected_operator'   => '+',
1405 1405
             'price_selected_is_percent' => 0
1406 1406
         );
1407
-        $template      = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_type_base.template.php';
1407
+        $template      = PRICING_TEMPLATE_PATH.'event_tickets_datetime_price_type_base.template.php';
1408 1408
         
1409 1409
         $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_base_price_template__template_args',
1410 1410
             $template_args, $tktrow, $prcrow, $price, $default, $this->_is_creating_event);
@@ -1415,7 +1415,7 @@  discard block
 block discarded – undo
1415 1415
     
1416 1416
     protected function _get_price_modifier_template($tktrow, $prcrow, $price, $default, $disabled = false)
1417 1417
     {
1418
-        $select_name                = $default && empty($price) ? 'edit_prices[TICKETNUM][PRICENUM][PRT_ID]' : 'edit_prices[' . $tktrow . '][' . $prcrow . '][PRT_ID]';
1418
+        $select_name                = $default && empty($price) ? 'edit_prices[TICKETNUM][PRICENUM][PRT_ID]' : 'edit_prices['.$tktrow.']['.$prcrow.'][PRT_ID]';
1419 1419
         $price_types                = EE_Registry::instance()->load_model('Price_Type')->get_all(array(
1420 1420
             array(
1421 1421
                 'OR' => array(
@@ -1424,7 +1424,7 @@  discard block
 block discarded – undo
1424 1424
                 )
1425 1425
             )
1426 1426
         ));
1427
-        $price_option_span_template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_option_span.template.php';
1427
+        $price_option_span_template = PRICING_TEMPLATE_PATH.'event_tickets_datetime_price_option_span.template.php';
1428 1428
         $all_price_types            = $default && empty($price) ? array(
1429 1429
             array(
1430 1430
                 'id'   => 0,
@@ -1451,7 +1451,7 @@  discard block
 block discarded – undo
1451 1451
         
1452 1452
         $select_params = $disabled ? 'style="width:auto;" disabled' : 'style="width:auto;"';
1453 1453
         $main_name     = $select_name;
1454
-        $select_name   = $disabled ? 'archive_price[' . $tktrow . '][' . $prcrow . '][PRT_ID]' : $main_name;
1454
+        $select_name   = $disabled ? 'archive_price['.$tktrow.']['.$prcrow.'][PRT_ID]' : $main_name;
1455 1455
         
1456 1456
         $template_args = array(
1457 1457
             'tkt_row'                   => $default ? 'TICKETNUM' : $tktrow,
@@ -1469,7 +1469,7 @@  discard block
 block discarded – undo
1469 1469
         $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_price_modifier_template__template_args',
1470 1470
             $template_args, $tktrow, $prcrow, $price, $default, $disabled, $this->_is_creating_event);
1471 1471
         
1472
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_modifier_selector.template.php';
1472
+        $template = PRICING_TEMPLATE_PATH.'event_tickets_datetime_price_modifier_selector.template.php';
1473 1473
         
1474 1474
         return EEH_Template::display_template($template, $template_args, true);
1475 1475
     }
@@ -1489,7 +1489,7 @@  discard block
 block discarded – undo
1489 1489
         
1490 1490
         $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_ticket_datetime_list_item__template_args',
1491 1491
             $template_args, $dttrow, $tktrow, $dtt, $ticket, $ticket_datetimes, $default, $this->_is_creating_event);
1492
-        $template      = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_datetimes_list_item.template.php';
1492
+        $template      = PRICING_TEMPLATE_PATH.'event_tickets_datetime_ticket_datetimes_list_item.template.php';
1493 1493
         
1494 1494
         return EEH_Template::display_template($template, $template_args, true);
1495 1495
     }
@@ -1554,7 +1554,7 @@  discard block
 block discarded – undo
1554 1554
         $template_args = apply_filters('FHEE__espresso_events_Pricing_Hooks___get_ticket_js_structure__template_args',
1555 1555
             $template_args, $all_dtts, $all_tickets, $this->_is_creating_event);
1556 1556
         
1557
-        $template = PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_js_structure.template.php';
1557
+        $template = PRICING_TEMPLATE_PATH.'event_tickets_datetime_ticket_js_structure.template.php';
1558 1558
         
1559 1559
         return EEH_Template::display_template($template, $template_args, true);
1560 1560
     }
Please login to merge, or discard this patch.
core/middleware/EE_Recommended_Versions.core.php 1 patch
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -18,150 +18,150 @@  discard block
 block discarded – undo
18 18
 {
19 19
 
20 20
 
21
-    /**
22
-     * converts a Request to a Response
23
-     *
24
-     * @param    EE_Request  $request
25
-     * @param    EE_Response $response
26
-     * @return    EE_Response
27
-     */
28
-    public function handle_request(EE_Request $request, EE_Response $response)
29
-    {
30
-        $this->_request = $request;
31
-        $this->_response = $response;
32
-        //$this->_response->add_output( "\n\t IN >>  " . __CLASS__ );
33
-        //$this->_response->set_notice( 1, 'hey look at this' );
34
-        // check required WP version
35
-        if ( ! $this->_minimum_wp_version_required()) {
36
-            $this->_request->un_set('activate', true);
37
-            add_action('admin_notices', array($this, 'minimum_wp_version_error'), 1);
38
-            //$this->_response->add_output( "\n<br />" . 'minimum_wp_version_error' );
39
-            $this->_response->terminate_request();
40
-            $this->_response->deactivate_plugin();
41
-        }
42
-        // check recommended PHP version
43
-        if ( ! $this->_minimum_php_version_recommended()) {
44
-            $this->_display_minimum_recommended_php_version_notice();
45
-        }
46
-        $this->_response = $this->process_request_stack($this->_request, $this->_response);
47
-        //$this->_response->add_output( "\n\t OUT << " . __CLASS__ );
48
-        return $this->_response;
49
-    }
50
-
51
-
52
-    /**
53
-     * Helper method to assess installed wp version against given values.
54
-     * By default this compares the required minimum version of WP for EE against the installed version of WP
55
-     *
56
-     * Note, $wp_version is the first parameter sent into the PHP version_compare function (what is being checked against)
57
-     * so consider that when sending in your values.
58
-     *
59
-     * @param string $version_to_check
60
-     * @param string $operator
61
-     * @return bool
62
-     */
63
-    public static function check_wp_version($version_to_check = EE_MIN_WP_VER_REQUIRED, $operator = '>=')
64
-    {
65
-        global $wp_version;
66
-        return version_compare(
67
-            //first account for wp_version being pre-release (like RC, beta etc which are usually in the format like
68
-            //4.7-RC3-39519
69
-            strpos($wp_version, '-') > 0 ? substr($wp_version, 0, strpos($wp_version, '-')) : $wp_version,
70
-            $version_to_check,
71
-            $operator
72
-        );
73
-    }
74
-
75
-
76
-
77
-    /**
78
-     *    _minimum_wp_version_required
79
-     *
80
-     * @access private
81
-     * @return boolean
82
-     */
83
-    private function _minimum_wp_version_required()
84
-    {
85
-        return self::check_wp_version();
86
-    }
87
-
88
-
89
-
90
-    /**
91
-     *    _check_php_version
92
-     *
93
-     * @access private
94
-     * @param string $min_version
95
-     * @return boolean
96
-     */
97
-    private function _check_php_version($min_version = EE_MIN_PHP_VER_RECOMMENDED)
98
-    {
99
-        return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
100
-    }
101
-
102
-
103
-
104
-    /**
105
-     *    _minimum_php_version_recommended
106
-     *
107
-     * @access private
108
-     * @return boolean
109
-     */
110
-    private function _minimum_php_version_recommended()
111
-    {
112
-        return $this->_check_php_version(EE_MIN_PHP_VER_RECOMMENDED);
113
-    }
114
-
115
-
116
-
117
-    /**
118
-     *    minimum_wp_version_error
119
-     *
120
-     * @return void
121
-     */
122
-    public function minimum_wp_version_error()
123
-    {
124
-        global $wp_version;
125
-        ?>
21
+	/**
22
+	 * converts a Request to a Response
23
+	 *
24
+	 * @param    EE_Request  $request
25
+	 * @param    EE_Response $response
26
+	 * @return    EE_Response
27
+	 */
28
+	public function handle_request(EE_Request $request, EE_Response $response)
29
+	{
30
+		$this->_request = $request;
31
+		$this->_response = $response;
32
+		//$this->_response->add_output( "\n\t IN >>  " . __CLASS__ );
33
+		//$this->_response->set_notice( 1, 'hey look at this' );
34
+		// check required WP version
35
+		if ( ! $this->_minimum_wp_version_required()) {
36
+			$this->_request->un_set('activate', true);
37
+			add_action('admin_notices', array($this, 'minimum_wp_version_error'), 1);
38
+			//$this->_response->add_output( "\n<br />" . 'minimum_wp_version_error' );
39
+			$this->_response->terminate_request();
40
+			$this->_response->deactivate_plugin();
41
+		}
42
+		// check recommended PHP version
43
+		if ( ! $this->_minimum_php_version_recommended()) {
44
+			$this->_display_minimum_recommended_php_version_notice();
45
+		}
46
+		$this->_response = $this->process_request_stack($this->_request, $this->_response);
47
+		//$this->_response->add_output( "\n\t OUT << " . __CLASS__ );
48
+		return $this->_response;
49
+	}
50
+
51
+
52
+	/**
53
+	 * Helper method to assess installed wp version against given values.
54
+	 * By default this compares the required minimum version of WP for EE against the installed version of WP
55
+	 *
56
+	 * Note, $wp_version is the first parameter sent into the PHP version_compare function (what is being checked against)
57
+	 * so consider that when sending in your values.
58
+	 *
59
+	 * @param string $version_to_check
60
+	 * @param string $operator
61
+	 * @return bool
62
+	 */
63
+	public static function check_wp_version($version_to_check = EE_MIN_WP_VER_REQUIRED, $operator = '>=')
64
+	{
65
+		global $wp_version;
66
+		return version_compare(
67
+			//first account for wp_version being pre-release (like RC, beta etc which are usually in the format like
68
+			//4.7-RC3-39519
69
+			strpos($wp_version, '-') > 0 ? substr($wp_version, 0, strpos($wp_version, '-')) : $wp_version,
70
+			$version_to_check,
71
+			$operator
72
+		);
73
+	}
74
+
75
+
76
+
77
+	/**
78
+	 *    _minimum_wp_version_required
79
+	 *
80
+	 * @access private
81
+	 * @return boolean
82
+	 */
83
+	private function _minimum_wp_version_required()
84
+	{
85
+		return self::check_wp_version();
86
+	}
87
+
88
+
89
+
90
+	/**
91
+	 *    _check_php_version
92
+	 *
93
+	 * @access private
94
+	 * @param string $min_version
95
+	 * @return boolean
96
+	 */
97
+	private function _check_php_version($min_version = EE_MIN_PHP_VER_RECOMMENDED)
98
+	{
99
+		return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
100
+	}
101
+
102
+
103
+
104
+	/**
105
+	 *    _minimum_php_version_recommended
106
+	 *
107
+	 * @access private
108
+	 * @return boolean
109
+	 */
110
+	private function _minimum_php_version_recommended()
111
+	{
112
+		return $this->_check_php_version(EE_MIN_PHP_VER_RECOMMENDED);
113
+	}
114
+
115
+
116
+
117
+	/**
118
+	 *    minimum_wp_version_error
119
+	 *
120
+	 * @return void
121
+	 */
122
+	public function minimum_wp_version_error()
123
+	{
124
+		global $wp_version;
125
+		?>
126 126
         <div class="error">
127 127
             <p>
128 128
                 <?php
129
-                printf(
130
-                        __('We\'re sorry, but Event Espresso requires WordPress version %1$s or greater in order to operate. You are currently running version %2$s.%3$sFor information on how to update your version of WordPress, please go to %4$s.',
131
-                                'event_espresso'),
132
-                        EE_MIN_WP_VER_REQUIRED,
133
-                        $wp_version,
134
-                        '<br/>',
135
-                        '<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
136
-                );
137
-                ?>
129
+				printf(
130
+						__('We\'re sorry, but Event Espresso requires WordPress version %1$s or greater in order to operate. You are currently running version %2$s.%3$sFor information on how to update your version of WordPress, please go to %4$s.',
131
+								'event_espresso'),
132
+						EE_MIN_WP_VER_REQUIRED,
133
+						$wp_version,
134
+						'<br/>',
135
+						'<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
136
+				);
137
+				?>
138 138
             </p>
139 139
         </div>
140 140
         <?php
141
-    }
142
-
143
-
144
-
145
-    /**
146
-     *    _display_minimum_recommended_php_version_notice
147
-     *
148
-     * @access private
149
-     * @return void
150
-     */
151
-    private function _display_minimum_recommended_php_version_notice()
152
-    {
153
-        EE_Error::add_persistent_admin_notice(
154
-                'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
155
-                sprintf(
156
-                        __('Event Espresso recommends PHP version %1$s or greater for optimal performance. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
157
-                                'event_espresso'),
158
-                        EE_MIN_PHP_VER_RECOMMENDED,
159
-                        PHP_VERSION,
160
-                        '<br/>',
161
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
162
-                )
163
-        );
164
-    }
141
+	}
142
+
143
+
144
+
145
+	/**
146
+	 *    _display_minimum_recommended_php_version_notice
147
+	 *
148
+	 * @access private
149
+	 * @return void
150
+	 */
151
+	private function _display_minimum_recommended_php_version_notice()
152
+	{
153
+		EE_Error::add_persistent_admin_notice(
154
+				'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
155
+				sprintf(
156
+						__('Event Espresso recommends PHP version %1$s or greater for optimal performance. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
157
+								'event_espresso'),
158
+						EE_MIN_PHP_VER_RECOMMENDED,
159
+						PHP_VERSION,
160
+						'<br/>',
161
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
162
+				)
163
+		);
164
+	}
165 165
 
166 166
 
167 167
 }
Please login to merge, or discard this patch.
core/libraries/rest_api/controllers/model/Read.php 2 patches
Indentation   +1116 added lines, -1116 removed lines patch added patch discarded remove patch
@@ -7,7 +7,7 @@  discard block
 block discarded – undo
7 7
 use EventEspresso\core\libraries\rest_api\Model_Data_Translator;
8 8
 
9 9
 if (! defined('EVENT_ESPRESSO_VERSION')) {
10
-    exit('No direct script access allowed');
10
+	exit('No direct script access allowed');
11 11
 }
12 12
 
13 13
 
@@ -25,1121 +25,1121 @@  discard block
 block discarded – undo
25 25
 
26 26
 
27 27
 
28
-    /**
29
-     * @var Calculated_Model_Fields
30
-     */
31
-    protected $_fields_calculator;
32
-
33
-
34
-
35
-    /**
36
-     * Read constructor.
37
-     */
38
-    public function __construct()
39
-    {
40
-        parent::__construct();
41
-        $this->_fields_calculator = new Calculated_Model_Fields();
42
-    }
43
-
44
-
45
-
46
-    /**
47
-     * Handles requests to get all (or a filtered subset) of entities for a particular model
48
-     *
49
-     * @param \WP_REST_Request $request
50
-     * @return \WP_REST_Response|\WP_Error
51
-     */
52
-    public static function handle_request_get_all(\WP_REST_Request $request)
53
-    {
54
-        $controller = new Read();
55
-        try {
56
-            $matches = $controller->parse_route(
57
-                $request->get_route(),
58
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)~',
59
-                array('version', 'model')
60
-            );
61
-            $controller->set_requested_version($matches['version']);
62
-            $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
63
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
64
-                return $controller->send_response(
65
-                    new \WP_Error(
66
-                        'endpoint_parsing_error',
67
-                        sprintf(
68
-                            __('There is no model for endpoint %s. Please contact event espresso support',
69
-                                'event_espresso'),
70
-                            $model_name_singular
71
-                        )
72
-                    )
73
-                );
74
-            }
75
-            return $controller->send_response(
76
-                $controller->get_entities_from_model(
77
-                    $controller->get_model_version_info()->load_model($model_name_singular),
78
-                    $request
79
-                )
80
-            );
81
-        } catch (\Exception $e) {
82
-            return $controller->send_response($e);
83
-        }
84
-    }
85
-
86
-
87
-
88
-    /**
89
-     * Gets a single entity related to the model indicated in the path and its id
90
-     *
91
-     * @param \WP_REST_Request $request
92
-     * @return \WP_REST_Response|\WP_Error
93
-     */
94
-    public static function handle_request_get_one(\WP_REST_Request $request)
95
-    {
96
-        $controller = new Read();
97
-        try {
98
-            $matches = $controller->parse_route(
99
-                $request->get_route(),
100
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)~',
101
-                array('version', 'model', 'id'));
102
-            $controller->set_requested_version($matches['version']);
103
-            $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
104
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
105
-                return $controller->send_response(
106
-                    new \WP_Error(
107
-                        'endpoint_parsing_error',
108
-                        sprintf(
109
-                            __('There is no model for endpoint %s. Please contact event espresso support',
110
-                                'event_espresso'),
111
-                            $model_name_singular
112
-                        )
113
-                    )
114
-                );
115
-            }
116
-            return $controller->send_response(
117
-                $controller->get_entity_from_model(
118
-                    $controller->get_model_version_info()->load_model($model_name_singular),
119
-                    $request
120
-                )
121
-            );
122
-        } catch (\Exception $e) {
123
-            return $controller->send_response($e);
124
-        }
125
-    }
126
-
127
-
128
-
129
-    /**
130
-     * Gets all the related entities (or if its a belongs-to relation just the one)
131
-     * to the item with the given id
132
-     *
133
-     * @param \WP_REST_Request $request
134
-     * @return \WP_REST_Response|\WP_Error
135
-     */
136
-    public static function handle_request_get_related(\WP_REST_Request $request)
137
-    {
138
-        $controller = new Read();
139
-        try {
140
-            $matches = $controller->parse_route(
141
-                $request->get_route(),
142
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)/(.*)~',
143
-                array('version', 'model', 'id', 'related_model')
144
-            );
145
-            $controller->set_requested_version($matches['version']);
146
-            $main_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
147
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
148
-                return $controller->send_response(
149
-                    new \WP_Error(
150
-                        'endpoint_parsing_error',
151
-                        sprintf(
152
-                            __('There is no model for endpoint %s. Please contact event espresso support',
153
-                                'event_espresso'),
154
-                            $main_model_name_singular
155
-                        )
156
-                    )
157
-                );
158
-            }
159
-            $main_model = $controller->get_model_version_info()->load_model($main_model_name_singular);
160
-            //assume the related model name is plural and try to find the model's name
161
-            $related_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['related_model']);
162
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
163
-                //so the word didn't singularize well. Maybe that's just because it's a singular word?
164
-                $related_model_name_singular = \EEH_Inflector::humanize($matches['related_model']);
165
-            }
166
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
167
-                return $controller->send_response(
168
-                    new \WP_Error(
169
-                        'endpoint_parsing_error',
170
-                        sprintf(
171
-                            __('There is no model for endpoint %s. Please contact event espresso support',
172
-                                'event_espresso'),
173
-                            $related_model_name_singular
174
-                        )
175
-                    )
176
-                );
177
-            }
178
-            return $controller->send_response(
179
-                $controller->get_entities_from_relation(
180
-                    $request->get_param('id'),
181
-                    $main_model->related_settings_for($related_model_name_singular),
182
-                    $request
183
-                )
184
-            );
185
-        } catch (\Exception $e) {
186
-            return $controller->send_response($e);
187
-        }
188
-    }
189
-
190
-
191
-
192
-    /**
193
-     * Gets a collection for the given model and filters
194
-     *
195
-     * @param \EEM_Base        $model
196
-     * @param \WP_REST_Request $request
197
-     * @return array|\WP_Error
198
-     */
199
-    public function get_entities_from_model($model, $request)
200
-    {
201
-        $query_params = $this->create_model_query_params($model, $request->get_params());
202
-        if (! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
203
-            $model_name_plural = \EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
204
-            return new \WP_Error(
205
-                sprintf('rest_%s_cannot_list', $model_name_plural),
206
-                sprintf(
207
-                    __('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
208
-                    $model_name_plural,
209
-                    Capabilities::get_missing_permissions_string($model, $query_params['caps'])
210
-                ),
211
-                array('status' => 403)
212
-            );
213
-        }
214
-        if (! $request->get_header('no_rest_headers')) {
215
-            $this->_set_headers_from_query_params($model, $query_params);
216
-        }
217
-        /** @type array $results */
218
-        $results = $model->get_all_wpdb_results($query_params);
219
-        $nice_results = array();
220
-        foreach ($results as $result) {
221
-            $nice_results[] = $this->create_entity_from_wpdb_result(
222
-                $model,
223
-                $result,
224
-                $request
225
-            );
226
-        }
227
-        return $nice_results;
228
-    }
229
-
230
-
231
-
232
-    /**
233
-     * @param array                   $primary_model_query_params query params for finding the item from which
234
-     *                                                            relations will be based
235
-     * @param \EE_Model_Relation_Base $relation
236
-     * @param \WP_REST_Request        $request
237
-     * @return \WP_Error|array
238
-     */
239
-    protected function _get_entities_from_relation($primary_model_query_params, $relation, $request)
240
-    {
241
-        $context = $this->validate_context($request->get_param('caps'));
242
-        $model = $relation->get_this_model();
243
-        $related_model = $relation->get_other_model();
244
-        if (! isset($primary_model_query_params[0])) {
245
-            $primary_model_query_params[0] = array();
246
-        }
247
-        //check if they can access the 1st model object
248
-        $primary_model_query_params = array(
249
-            0       => $primary_model_query_params[0],
250
-            'limit' => 1,
251
-        );
252
-        if ($model instanceof \EEM_Soft_Delete_Base) {
253
-            $primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($primary_model_query_params);
254
-        }
255
-        $restricted_query_params = $primary_model_query_params;
256
-        $restricted_query_params['caps'] = $context;
257
-        $this->_set_debug_info('main model query params', $restricted_query_params);
258
-        $this->_set_debug_info('missing caps', Capabilities::get_missing_permissions_string($related_model, $context));
259
-        if (
260
-        ! (
261
-            Capabilities::current_user_has_partial_access_to($related_model, $context)
262
-            && $model->exists($restricted_query_params)
263
-        )
264
-        ) {
265
-            if ($relation instanceof \EE_Belongs_To_Relation) {
266
-                $related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
267
-            } else {
268
-                $related_model_name_maybe_plural = \EEH_Inflector::pluralize_and_lower($related_model->get_this_model_name());
269
-            }
270
-            return new \WP_Error(
271
-                sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
272
-                sprintf(
273
-                    __('Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
274
-                        'event_espresso'),
275
-                    $related_model_name_maybe_plural,
276
-                    $relation->get_this_model()->get_this_model_name(),
277
-                    implode(
278
-                        ',',
279
-                        array_keys(
280
-                            Capabilities::get_missing_permissions($related_model, $context)
281
-                        )
282
-                    )
283
-                ),
284
-                array('status' => 403)
285
-            );
286
-        }
287
-        $query_params = $this->create_model_query_params($relation->get_other_model(), $request->get_params());
288
-        foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
289
-            $query_params[0][$relation->get_this_model()->get_this_model_name()
290
-                             . '.'
291
-                             . $where_condition_key] = $where_condition_value;
292
-        }
293
-        $query_params['default_where_conditions'] = 'none';
294
-        $query_params['caps'] = $context;
295
-        if (! $request->get_header('no_rest_headers')) {
296
-            $this->_set_headers_from_query_params($relation->get_other_model(), $query_params);
297
-        }
298
-        /** @type array $results */
299
-        $results = $relation->get_other_model()->get_all_wpdb_results($query_params);
300
-        $nice_results = array();
301
-        foreach ($results as $result) {
302
-            $nice_result = $this->create_entity_from_wpdb_result(
303
-                $relation->get_other_model(),
304
-                $result,
305
-                $request
306
-            );
307
-            if ($relation instanceof \EE_HABTM_Relation) {
308
-                //put the unusual stuff (properties from the HABTM relation) first, and make sure
309
-                //if there are conflicts we prefer the properties from the main model
310
-                $join_model_result = $this->create_entity_from_wpdb_result(
311
-                    $relation->get_join_model(),
312
-                    $result,
313
-                    $request
314
-                );
315
-                $joined_result = array_merge($nice_result, $join_model_result);
316
-                //but keep the meta stuff from the main model
317
-                if (isset($nice_result['meta'])) {
318
-                    $joined_result['meta'] = $nice_result['meta'];
319
-                }
320
-                $nice_result = $joined_result;
321
-            }
322
-            $nice_results[] = $nice_result;
323
-        }
324
-        if ($relation instanceof \EE_Belongs_To_Relation) {
325
-            return array_shift($nice_results);
326
-        } else {
327
-            return $nice_results;
328
-        }
329
-    }
330
-
331
-
332
-
333
-    /**
334
-     * Gets the collection for given relation object
335
-     * The same as Read::get_entities_from_model(), except if the relation
336
-     * is a HABTM relation, in which case it merges any non-foreign-key fields from
337
-     * the join-model-object into the results
338
-     *
339
-     * @param string                  $id the ID of the thing we are fetching related stuff from
340
-     * @param \EE_Model_Relation_Base $relation
341
-     * @param \WP_REST_Request        $request
342
-     * @return array|\WP_Error
343
-     * @throws \EE_Error
344
-     */
345
-    public function get_entities_from_relation($id, $relation, $request)
346
-    {
347
-        if (! $relation->get_this_model()->has_primary_key_field()) {
348
-            throw new \EE_Error(
349
-                sprintf(
350
-                    __('Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
351
-                        'event_espresso'),
352
-                    $relation->get_this_model()->get_this_model_name()
353
-                )
354
-            );
355
-        }
356
-        return $this->_get_entities_from_relation(
357
-            array(
358
-                array(
359
-                    $relation->get_this_model()->primary_key_name() => $id,
360
-                ),
361
-            ),
362
-            $relation,
363
-            $request
364
-        );
365
-    }
366
-
367
-
368
-
369
-    /**
370
-     * Sets the headers that are based on the model and query params,
371
-     * like the total records. This should only be called on the original request
372
-     * from the client, not on subsequent internal
373
-     *
374
-     * @param \EEM_Base $model
375
-     * @param array     $query_params
376
-     * @return void
377
-     */
378
-    protected function _set_headers_from_query_params($model, $query_params)
379
-    {
380
-        $this->_set_debug_info('model query params', $query_params);
381
-        $this->_set_debug_info('missing caps',
382
-            Capabilities::get_missing_permissions_string($model, $query_params['caps']));
383
-        //normally the limit to a 2-part array, where the 2nd item is the limit
384
-        if (! isset($query_params['limit'])) {
385
-            $query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
386
-        }
387
-        if (is_array($query_params['limit'])) {
388
-            $limit_parts = $query_params['limit'];
389
-        } else {
390
-            $limit_parts = explode(',', $query_params['limit']);
391
-            if (count($limit_parts) == 1) {
392
-                $limit_parts = array(0, $limit_parts[0]);
393
-            }
394
-        }
395
-        //remove the group by and having parts of the query, as those will
396
-        //make the sql query return an array of values, instead of just a single value
397
-        unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
398
-        $count = $model->count($query_params, null, true);
399
-        $pages = $count / $limit_parts[1];
400
-        $this->_set_response_header('Total', $count, false);
401
-        $this->_set_response_header('PageSize', $limit_parts[1], false);
402
-        $this->_set_response_header('TotalPages', ceil($pages), false);
403
-    }
404
-
405
-
406
-
407
-    /**
408
-     * Changes database results into REST API entities
409
-     *
410
-     * @param \EEM_Base        $model
411
-     * @param array            $db_row     like results from $wpdb->get_results()
412
-     * @param \WP_REST_Request $rest_request
413
-     * @param string           $deprecated no longer used
414
-     * @return array ready for being converted into json for sending to client
415
-     */
416
-    public function create_entity_from_wpdb_result($model, $db_row, $rest_request, $deprecated = null)
417
-    {
418
-        if (! $rest_request instanceof \WP_REST_Request) {
419
-            //ok so this was called in the old style, where the 3rd arg was
420
-            //$include, and the 4th arg was $context
421
-            //now setup the request just to avoid fatal errors, although we won't be able
422
-            //to truly make use of it because it's kinda devoid of info
423
-            $rest_request = new \WP_REST_Request();
424
-            $rest_request->set_param('include', $rest_request);
425
-            $rest_request->set_param('caps', $deprecated);
426
-        }
427
-        if ($rest_request->get_param('caps') == null) {
428
-            $rest_request->set_param('caps', \EEM_Base::caps_read);
429
-        }
430
-        $entity_array = $this->_create_bare_entity_from_wpdb_results($model, $db_row);
431
-        $entity_array = $this->_add_extra_fields($model, $db_row, $entity_array);
432
-        $entity_array['_links'] = $this->_get_entity_links($model, $db_row, $entity_array);
433
-        $entity_array['_calculated_fields'] = $this->_get_entity_calculations($model, $db_row, $rest_request);
434
-        $entity_array = $this->_include_requested_models($model, $rest_request, $entity_array, $db_row);
435
-        $entity_array = apply_filters(
436
-            'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
437
-            $entity_array,
438
-            $model,
439
-            $rest_request->get_param('caps'),
440
-            $rest_request,
441
-            $this
442
-        );
443
-        $result_without_inaccessible_fields = Capabilities::filter_out_inaccessible_entity_fields(
444
-            $entity_array,
445
-            $model,
446
-            $rest_request->get_param('caps'),
447
-            $this->get_model_version_info(),
448
-            $model->get_index_primary_key_string(
449
-                $model->deduce_fields_n_values_from_cols_n_values($db_row)
450
-            )
451
-        );
452
-        $this->_set_debug_info(
453
-            'inaccessible fields',
454
-            array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
455
-        );
456
-        return apply_filters(
457
-            'FHEE__Read__create_entity_from_wpdb_results__entity_return',
458
-            $result_without_inaccessible_fields,
459
-            $model,
460
-            $rest_request->get_param('caps')
461
-        );
462
-    }
463
-
464
-
465
-
466
-    /**
467
-     * Creates a REST entity array (JSON object we're going to return in the response, but
468
-     * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
469
-     * from $wpdb->get_row( $sql, ARRAY_A)
470
-     *
471
-     * @param \EEM_Base $model
472
-     * @param array     $db_row
473
-     * @return array entity mostly ready for converting to JSON and sending in the response
474
-     */
475
-    protected function _create_bare_entity_from_wpdb_results(\EEM_Base $model, $db_row)
476
-    {
477
-        $result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
478
-        $result = array_intersect_key($result,
479
-            $this->get_model_version_info()->fields_on_model_in_this_version($model));
480
-        foreach ($result as $field_name => $raw_field_value) {
481
-            $field_obj = $model->field_settings_for($field_name);
482
-            $field_value = $field_obj->prepare_for_set_from_db($raw_field_value);
483
-            if ($this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_ignored())) {
484
-                unset($result[$field_name]);
485
-            } elseif (
486
-            $this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_rendered_format())
487
-            ) {
488
-                $result[$field_name] = array(
489
-                    'raw'      => $field_obj->prepare_for_get($field_value),
490
-                    'rendered' => $field_obj->prepare_for_pretty_echoing($field_value),
491
-                );
492
-            } elseif (
493
-            $this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_pretty_format())
494
-            ) {
495
-                $result[$field_name] = array(
496
-                    'raw'    => $field_obj->prepare_for_get($field_value),
497
-                    'pretty' => $field_obj->prepare_for_pretty_echoing($field_value),
498
-                );
499
-            } elseif ($field_obj instanceof \EE_Datetime_Field) {
500
-                if ($field_value instanceof \DateTime) {
501
-                    $timezone = $field_value->getTimezone();
502
-                    $field_value->setTimezone(new \DateTimeZone('UTC'));
503
-                    $result[$field_name . '_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
504
-                        $field_obj,
505
-                        $field_value,
506
-                        $this->get_model_version_info()->requested_version()
507
-                    );
508
-                    $field_value->setTimezone($timezone);
509
-                    $result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
510
-                        $field_obj,
511
-                        $field_value,
512
-                        $this->get_model_version_info()->requested_version()
513
-                    );
514
-                }
515
-            } else {
516
-                $result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
517
-                    $field_obj,
518
-                    $field_obj->prepare_for_get($field_value),
519
-                    $this->get_model_version_info()->requested_version()
520
-                );
521
-            }
522
-        }
523
-        return $result;
524
-    }
525
-
526
-
527
-
528
-    /**
529
-     * Adds a few extra fields to the entity response
530
-     *
531
-     * @param \EEM_Base $model
532
-     * @param array     $db_row
533
-     * @param array     $entity_array
534
-     * @return array modified entity
535
-     */
536
-    protected function _add_extra_fields(\EEM_Base $model, $db_row, $entity_array)
537
-    {
538
-        if ($model instanceof \EEM_CPT_Base) {
539
-            $entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]);
540
-        }
541
-        return $entity_array;
542
-    }
543
-
544
-
545
-
546
-    /**
547
-     * Gets links we want to add to the response
548
-     *
549
-     * @global \WP_REST_Server $wp_rest_server
550
-     * @param \EEM_Base        $model
551
-     * @param array            $db_row
552
-     * @param array            $entity_array
553
-     * @return array the _links item in the entity
554
-     */
555
-    protected function _get_entity_links($model, $db_row, $entity_array)
556
-    {
557
-        //add basic links
558
-        $links = array();
559
-        if ($model->has_primary_key_field()) {
560
-            $links['self'] = array(
561
-                array(
562
-                    'href' => $this->get_versioned_link_to(
563
-                        \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
564
-                        . '/'
565
-                        . $entity_array[$model->primary_key_name()]
566
-                    ),
567
-                ),
568
-            );
569
-        }
570
-        $links['collection'] = array(
571
-            array(
572
-                'href' => $this->get_versioned_link_to(
573
-                    \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
574
-                ),
575
-            ),
576
-        );
577
-        //add link to the wp core endpoint, if wp api is active
578
-        global $wp_rest_server;
579
-        if ($model instanceof \EEM_CPT_Base
580
-            && $wp_rest_server instanceof \WP_REST_Server
581
-            && $wp_rest_server->get_route_options('/wp/v2/posts')
582
-            && $model->has_primary_key_field()
583
-        ) {
584
-            $links[\EED_Core_Rest_Api::ee_api_link_namespace . 'self_wp_post'] = array(
585
-                array(
586
-                    'href'   => rest_url('/wp/v2/posts/' . $db_row[$model->get_primary_key_field()
587
-                                                                         ->get_qualified_column()]),
588
-                    'single' => true,
589
-                ),
590
-            );
591
-        }
592
-        //add links to related models
593
-        if ($model->has_primary_key_field()) {
594
-            foreach ($this->get_model_version_info()->relation_settings($model) as $relation_name => $relation_obj) {
595
-                $related_model_part = Read::get_related_entity_name($relation_name, $relation_obj);
596
-                $links[\EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
597
-                    array(
598
-                        'href'   => $this->get_versioned_link_to(
599
-                            \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
600
-                            . '/'
601
-                            . $entity_array[$model->primary_key_name()]
602
-                            . '/'
603
-                            . $related_model_part
604
-                        ),
605
-                        'single' => $relation_obj instanceof \EE_Belongs_To_Relation ? true : false,
606
-                    ),
607
-                );
608
-            }
609
-        }
610
-        return $links;
611
-    }
612
-
613
-
614
-
615
-    /**
616
-     * Adds the included models indicated in the request to the entity provided
617
-     *
618
-     * @param \EEM_Base        $model
619
-     * @param \WP_REST_Request $rest_request
620
-     * @param array            $entity_array
621
-     * @param array            $db_row
622
-     * @return array the modified entity
623
-     */
624
-    protected function _include_requested_models(
625
-        \EEM_Base $model,
626
-        \WP_REST_Request $rest_request,
627
-        $entity_array,
628
-        $db_row = array()
629
-    ) {
630
-        //if $db_row not included, hope the entity array has what we need
631
-        if (! $db_row) {
632
-            $db_row = $entity_array;
633
-        }
634
-        $includes_for_this_model = $this->explode_and_get_items_prefixed_with($rest_request->get_param('include'), '');
635
-        $includes_for_this_model = $this->_remove_model_names_from_array($includes_for_this_model);
636
-        //if they passed in * or didn't specify any includes, return everything
637
-        if (! in_array('*', $includes_for_this_model)
638
-            && ! empty($includes_for_this_model)
639
-        ) {
640
-            if ($model->has_primary_key_field()) {
641
-                //always include the primary key. ya just gotta know that at least
642
-                $includes_for_this_model[] = $model->primary_key_name();
643
-            }
644
-            if ($this->explode_and_get_items_prefixed_with($rest_request->get_param('calculate'), '')) {
645
-                $includes_for_this_model[] = '_calculated_fields';
646
-            }
647
-            $entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
648
-        }
649
-        $relation_settings = $this->get_model_version_info()->relation_settings($model);
650
-        foreach ($relation_settings as $relation_name => $relation_obj) {
651
-            $related_fields_to_include = $this->explode_and_get_items_prefixed_with(
652
-                $rest_request->get_param('include'),
653
-                $relation_name
654
-            );
655
-            $related_fields_to_calculate = $this->explode_and_get_items_prefixed_with(
656
-                $rest_request->get_param('calculate'),
657
-                $relation_name
658
-            );
659
-            //did they specify they wanted to include a related model, or
660
-            //specific fields from a related model?
661
-            //or did they specify to calculate a field from a related model?
662
-            if ($related_fields_to_include || $related_fields_to_calculate) {
663
-                //if so, we should include at least some part of the related model
664
-                $pretend_related_request = new \WP_REST_Request();
665
-                $pretend_related_request->set_query_params(
666
-                    array(
667
-                        'caps'      => $rest_request->get_param('caps'),
668
-                        'include'   => $related_fields_to_include,
669
-                        'calculate' => $related_fields_to_calculate,
670
-                    )
671
-                );
672
-                $pretend_related_request->add_header('no_rest_headers', true);
673
-                $primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
674
-                    $model->get_index_primary_key_string(
675
-                        $model->deduce_fields_n_values_from_cols_n_values($db_row)
676
-                    )
677
-                );
678
-                $related_results = $this->_get_entities_from_relation(
679
-                    $primary_model_query_params,
680
-                    $relation_obj,
681
-                    $pretend_related_request
682
-                );
683
-                $entity_array[Read::get_related_entity_name($relation_name, $relation_obj)] = $related_results
684
-                                                                                              instanceof
685
-                                                                                              \WP_Error
686
-                    ? null
687
-                    : $related_results;
688
-            }
689
-        }
690
-        return $entity_array;
691
-    }
692
-
693
-
694
-
695
-    /**
696
-     * Returns a new array with all the names of models removed. Eg
697
-     * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
698
-     *
699
-     * @param array $arr
700
-     * @return array
701
-     */
702
-    private function _remove_model_names_from_array($arr)
703
-    {
704
-        return array_diff($arr, array_keys(\EE_Registry::instance()->non_abstract_db_models));
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     * Gets the calculated fields for the response
711
-     *
712
-     * @param \EEM_Base        $model
713
-     * @param array            $wpdb_row
714
-     * @param \WP_REST_Request $rest_request
715
-     * @return \stdClass the _calculations item in the entity
716
-     */
717
-    protected function _get_entity_calculations($model, $wpdb_row, $rest_request)
718
-    {
719
-        $calculated_fields = $this->explode_and_get_items_prefixed_with(
720
-            $rest_request->get_param('calculate'),
721
-            ''
722
-        );
723
-        //note: setting calculate=* doesn't do anything
724
-        $calculated_fields_to_return = new \stdClass();
725
-        foreach ($calculated_fields as $field_to_calculate) {
726
-            try {
727
-                $calculated_fields_to_return->$field_to_calculate = Model_Data_Translator::prepare_field_value_for_json(
728
-                    null,
729
-                    $this->_fields_calculator->retrieve_calculated_field_value(
730
-                        $model,
731
-                        $field_to_calculate,
732
-                        $wpdb_row,
733
-                        $rest_request,
734
-                        $this
735
-                    ),
736
-                    $this->get_model_version_info()->requested_version()
737
-                );
738
-            } catch (Rest_Exception $e) {
739
-                //if we don't have permission to read it, just leave it out. but let devs know about the problem
740
-                $this->_set_response_header(
741
-                    'Notices-Field-Calculation-Errors['
742
-                    . $e->get_string_code()
743
-                    . ']['
744
-                    . $model->get_this_model_name()
745
-                    . ']['
746
-                    . $field_to_calculate
747
-                    . ']',
748
-                    $e->getMessage(),
749
-                    true
750
-                );
751
-            }
752
-        }
753
-        return $calculated_fields_to_return;
754
-    }
755
-
756
-
757
-
758
-    /**
759
-     * Gets the full URL to the resource, taking the requested version into account
760
-     *
761
-     * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
762
-     * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
763
-     */
764
-    public function get_versioned_link_to($link_part_after_version_and_slash)
765
-    {
766
-        return rest_url(
767
-            \EED_Core_Rest_Api::ee_api_namespace
768
-            . $this->get_model_version_info()->requested_version()
769
-            . '/'
770
-            . $link_part_after_version_and_slash
771
-        );
772
-    }
773
-
774
-
775
-
776
-    /**
777
-     * Gets the correct lowercase name for the relation in the API according
778
-     * to the relation's type
779
-     *
780
-     * @param string                  $relation_name
781
-     * @param \EE_Model_Relation_Base $relation_obj
782
-     * @return string
783
-     */
784
-    public static function get_related_entity_name($relation_name, $relation_obj)
785
-    {
786
-        if ($relation_obj instanceof \EE_Belongs_To_Relation) {
787
-            return strtolower($relation_name);
788
-        } else {
789
-            return \EEH_Inflector::pluralize_and_lower($relation_name);
790
-        }
791
-    }
792
-
793
-
794
-
795
-    /**
796
-     * Gets the one model object with the specified id for the specified model
797
-     *
798
-     * @param \EEM_Base        $model
799
-     * @param \WP_REST_Request $request
800
-     * @return array|\WP_Error
801
-     */
802
-    public function get_entity_from_model($model, $request)
803
-    {
804
-        $query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
805
-        if ($model instanceof \EEM_Soft_Delete_Base) {
806
-            $query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
807
-        }
808
-        $restricted_query_params = $query_params;
809
-        $restricted_query_params['caps'] = $this->validate_context($request->get_param('caps'));
810
-        $this->_set_debug_info('model query params', $restricted_query_params);
811
-        $model_rows = $model->get_all_wpdb_results($restricted_query_params);
812
-        if (! empty ($model_rows)) {
813
-            return $this->create_entity_from_wpdb_result(
814
-                $model,
815
-                array_shift($model_rows),
816
-                $request);
817
-        } else {
818
-            //ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
819
-            $lowercase_model_name = strtolower($model->get_this_model_name());
820
-            $model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
821
-            if (! empty($model_rows_found_sans_restrictions)) {
822
-                //you got shafted- it existed but we didn't want to tell you!
823
-                return new \WP_Error(
824
-                    'rest_user_cannot_read',
825
-                    sprintf(
826
-                        __('Sorry, you cannot read this %1$s. Missing permissions are: %2$s', 'event_espresso'),
827
-                        strtolower($model->get_this_model_name()),
828
-                        Capabilities::get_missing_permissions_string(
829
-                            $model,
830
-                            $this->validate_context($request->get_param('caps')))
831
-                    ),
832
-                    array('status' => 403)
833
-                );
834
-            } else {
835
-                //it's not you. It just doesn't exist
836
-                return new \WP_Error(
837
-                    sprintf('rest_%s_invalid_id', $lowercase_model_name),
838
-                    sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
839
-                    array('status' => 404)
840
-                );
841
-            }
842
-        }
843
-    }
844
-
845
-
846
-
847
-    /**
848
-     * If a context is provided which isn't valid, maybe it was added in a future
849
-     * version so just treat it as a default read
850
-     *
851
-     * @param string $context
852
-     * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
853
-     */
854
-    public function validate_context($context)
855
-    {
856
-        if (! $context) {
857
-            $context = \EEM_Base::caps_read;
858
-        }
859
-        $valid_contexts = \EEM_Base::valid_cap_contexts();
860
-        if (in_array($context, $valid_contexts)) {
861
-            return $context;
862
-        } else {
863
-            return \EEM_Base::caps_read;
864
-        }
865
-    }
866
-
867
-
868
-
869
-    /**
870
-     * Verifies the passed in value is an allowable default where conditions value.
871
-     *
872
-     * @param $default_query_params
873
-     * @return string
874
-     */
875
-    public function validate_default_query_params($default_query_params)
876
-    {
877
-        $valid_default_where_conditions_for_api_calls = array(
878
-            \EEM_Base::default_where_conditions_all,
879
-            \EEM_Base::default_where_conditions_minimum_all,
880
-            \EEM_Base::default_where_conditions_minimum_others,
881
-        );
882
-        if (! $default_query_params) {
883
-            $default_query_params = \EEM_Base::default_where_conditions_all;
884
-        }
885
-        if (
886
-        in_array(
887
-            $default_query_params,
888
-            $valid_default_where_conditions_for_api_calls,
889
-            true
890
-        )
891
-        ) {
892
-            return $default_query_params;
893
-        } else {
894
-            return \EEM_Base::default_where_conditions_all;
895
-        }
896
-    }
897
-
898
-
899
-
900
-    /**
901
-     * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
902
-     * Note: right now the query parameter keys for fields (and related fields)
903
-     * can be left as-is, but it's quite possible this will change someday.
904
-     * Also, this method's contents might be candidate for moving to Model_Data_Translator
905
-     *
906
-     * @param \EEM_Base $model
907
-     * @param array     $query_parameters from $_GET parameter @see Read:handle_request_get_all
908
-     * @return array like what EEM_Base::get_all() expects or FALSE to indicate
909
-     *                                    that absolutely no results should be returned
910
-     * @throws \EE_Error
911
-     */
912
-    public function create_model_query_params($model, $query_parameters)
913
-    {
914
-        $model_query_params = array();
915
-        if (isset($query_parameters['where'])) {
916
-            $model_query_params[0] = Model_Data_Translator::prepare_conditions_query_params_for_models(
917
-                $query_parameters['where'],
918
-                $model,
919
-                $this->get_model_version_info()->requested_version()
920
-            );
921
-        }
922
-        if (isset($query_parameters['order_by'])) {
923
-            $order_by = $query_parameters['order_by'];
924
-        } elseif (isset($query_parameters['orderby'])) {
925
-            $order_by = $query_parameters['orderby'];
926
-        } else {
927
-            $order_by = null;
928
-        }
929
-        if ($order_by !== null) {
930
-            if (is_array($order_by)) {
931
-                $order_by = Model_Data_Translator::prepare_field_names_in_array_keys_from_json($order_by);
932
-            } else {
933
-                //it's a single item
934
-                $order_by = Model_Data_Translator::prepare_field_name_from_json($order_by);
935
-            }
936
-            $model_query_params['order_by'] = $order_by;
937
-        }
938
-        if (isset($query_parameters['group_by'])) {
939
-            $group_by = $query_parameters['group_by'];
940
-        } elseif (isset($query_parameters['groupby'])) {
941
-            $group_by = $query_parameters['groupby'];
942
-        } else {
943
-            $group_by = array_keys($model->get_combined_primary_key_fields());
944
-        }
945
-        //make sure they're all real names
946
-        if (is_array($group_by)) {
947
-            $group_by = Model_Data_Translator::prepare_field_names_from_json($group_by);
948
-        }
949
-        if ($group_by !== null) {
950
-            $model_query_params['group_by'] = $group_by;
951
-        }
952
-        if (isset($query_parameters['having'])) {
953
-            $model_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_models(
954
-                $query_parameters['having'],
955
-                $model,
956
-                $this->get_model_version_info()->requested_version()
957
-            );
958
-        }
959
-        if (isset($query_parameters['order'])) {
960
-            $model_query_params['order'] = $query_parameters['order'];
961
-        }
962
-        if (isset($query_parameters['mine'])) {
963
-            $model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
964
-        }
965
-        if (isset($query_parameters['limit'])) {
966
-            //limit should be either a string like '23' or '23,43', or an array with two items in it
967
-            if (! is_array($query_parameters['limit'])) {
968
-                $limit_array = explode(',', (string)$query_parameters['limit']);
969
-            } else {
970
-                $limit_array = $query_parameters['limit'];
971
-            }
972
-            $sanitized_limit = array();
973
-            foreach ($limit_array as $key => $limit_part) {
974
-                if ($this->_debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
975
-                    throw new \EE_Error(
976
-                        sprintf(
977
-                            __('An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.',
978
-                                'event_espresso'),
979
-                            wp_json_encode($query_parameters['limit'])
980
-                        )
981
-                    );
982
-                }
983
-                $sanitized_limit[] = (int)$limit_part;
984
-            }
985
-            $model_query_params['limit'] = implode(',', $sanitized_limit);
986
-        } else {
987
-            $model_query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
988
-        }
989
-        if (isset($query_parameters['caps'])) {
990
-            $model_query_params['caps'] = $this->validate_context($query_parameters['caps']);
991
-        } else {
992
-            $model_query_params['caps'] = \EEM_Base::caps_read;
993
-        }
994
-        if (isset($query_parameters['default_where_conditions'])) {
995
-            $model_query_params['default_where_conditions'] = $this->validate_default_query_params($query_parameters['default_where_conditions']);
996
-        }
997
-        return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
998
-    }
999
-
1000
-
1001
-
1002
-    /**
1003
-     * Changes the REST-style query params for use in the models
1004
-     *
1005
-     * @deprecated
1006
-     * @param \EEM_Base $model
1007
-     * @param array     $query_params sub-array from @see EEM_Base::get_all()
1008
-     * @return array
1009
-     */
1010
-    public function prepare_rest_query_params_key_for_models($model, $query_params)
1011
-    {
1012
-        $model_ready_query_params = array();
1013
-        foreach ($query_params as $key => $value) {
1014
-            if (is_array($value)) {
1015
-                $model_ready_query_params[$key] = $this->prepare_rest_query_params_key_for_models($model, $value);
1016
-            } else {
1017
-                $model_ready_query_params[$key] = $value;
1018
-            }
1019
-        }
1020
-        return $model_ready_query_params;
1021
-    }
1022
-
1023
-
1024
-
1025
-    /**
1026
-     * @deprecated
1027
-     * @param $model
1028
-     * @param $query_params
1029
-     * @return array
1030
-     */
1031
-    public function prepare_rest_query_params_values_for_models($model, $query_params)
1032
-    {
1033
-        $model_ready_query_params = array();
1034
-        foreach ($query_params as $key => $value) {
1035
-            if (is_array($value)) {
1036
-                $model_ready_query_params[$key] = $this->prepare_rest_query_params_values_for_models($model, $value);
1037
-            } else {
1038
-                $model_ready_query_params[$key] = $value;
1039
-            }
1040
-        }
1041
-        return $model_ready_query_params;
1042
-    }
1043
-
1044
-
1045
-
1046
-    /**
1047
-     * Explodes the string on commas, and only returns items with $prefix followed by a period.
1048
-     * If no prefix is specified, returns items with no period.
1049
-     *
1050
-     * @param string|array $string_to_explode eg "jibba,jabba, blah, blaabla" or array('jibba', 'jabba' )
1051
-     * @param string       $prefix            "Event" or "foobar"
1052
-     * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1053
-     *                                        we only return strings starting with that and a period; if no prefix was
1054
-     *                                        specified we return all items containing NO periods
1055
-     */
1056
-    public function explode_and_get_items_prefixed_with($string_to_explode, $prefix)
1057
-    {
1058
-        if (is_string($string_to_explode)) {
1059
-            $exploded_contents = explode(',', $string_to_explode);
1060
-        } else if (is_array($string_to_explode)) {
1061
-            $exploded_contents = $string_to_explode;
1062
-        } else {
1063
-            $exploded_contents = array();
1064
-        }
1065
-        //if the string was empty, we want an empty array
1066
-        $exploded_contents = array_filter($exploded_contents);
1067
-        $contents_with_prefix = array();
1068
-        foreach ($exploded_contents as $item) {
1069
-            $item = trim($item);
1070
-            //if no prefix was provided, so we look for items with no "." in them
1071
-            if (! $prefix) {
1072
-                //does this item have a period?
1073
-                if (strpos($item, '.') === false) {
1074
-                    //if not, then its what we're looking for
1075
-                    $contents_with_prefix[] = $item;
1076
-                }
1077
-            } else if (strpos($item, $prefix . '.') === 0) {
1078
-                //this item has the prefix and a period, grab it
1079
-                $contents_with_prefix[] = substr(
1080
-                    $item,
1081
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1082
-                );
1083
-            } else if ($item === $prefix) {
1084
-                //this item is JUST the prefix
1085
-                //so let's grab everything after, which is a blank string
1086
-                $contents_with_prefix[] = '';
1087
-            }
1088
-        }
1089
-        return $contents_with_prefix;
1090
-    }
1091
-
1092
-
1093
-
1094
-    /**
1095
-     * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1096
-     * Deprecated because its return values were really quite confusing- sometimes it returned
1097
-     * an empty array (when the include string was blank or '*') or sometimes it returned
1098
-     * array('*') (when you provided a model and a model of that kind was found).
1099
-     * Parses the $include_string so we fetch all the field names relating to THIS model
1100
-     * (ie have NO period in them), or for the provided model (ie start with the model
1101
-     * name and then a period).
1102
-     * @param string $include_string @see Read:handle_request_get_all
1103
-     * @param string $model_name
1104
-     * @return array of fields for this model. If $model_name is provided, then
1105
-     *                               the fields for that model, with the model's name removed from each.
1106
-     *                               If $include_string was blank or '*' returns an empty array
1107
-     */
1108
-    public function extract_includes_for_this_model($include_string, $model_name = null)
1109
-    {
1110
-        if (is_array($include_string)) {
1111
-            $include_string = implode(',', $include_string);
1112
-        }
1113
-        if ($include_string === '*' || $include_string === '') {
1114
-            return array();
1115
-        }
1116
-        $includes = explode(',', $include_string);
1117
-        $extracted_fields_to_include = array();
1118
-        if ($model_name) {
1119
-            foreach ($includes as $field_to_include) {
1120
-                $field_to_include = trim($field_to_include);
1121
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1122
-                    //found the model name at the exact start
1123
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1124
-                    $extracted_fields_to_include[] = $field_sans_model_name;
1125
-                } elseif ($field_to_include == $model_name) {
1126
-                    $extracted_fields_to_include[] = '*';
1127
-                }
1128
-            }
1129
-        } else {
1130
-            //look for ones with no period
1131
-            foreach ($includes as $field_to_include) {
1132
-                $field_to_include = trim($field_to_include);
1133
-                if (
1134
-                    strpos($field_to_include, '.') === false
1135
-                    && ! $this->get_model_version_info()->is_model_name_in_this_version($field_to_include)
1136
-                ) {
1137
-                    $extracted_fields_to_include[] = $field_to_include;
1138
-                }
1139
-            }
1140
-        }
1141
-        return $extracted_fields_to_include;
1142
-    }
28
+	/**
29
+	 * @var Calculated_Model_Fields
30
+	 */
31
+	protected $_fields_calculator;
32
+
33
+
34
+
35
+	/**
36
+	 * Read constructor.
37
+	 */
38
+	public function __construct()
39
+	{
40
+		parent::__construct();
41
+		$this->_fields_calculator = new Calculated_Model_Fields();
42
+	}
43
+
44
+
45
+
46
+	/**
47
+	 * Handles requests to get all (or a filtered subset) of entities for a particular model
48
+	 *
49
+	 * @param \WP_REST_Request $request
50
+	 * @return \WP_REST_Response|\WP_Error
51
+	 */
52
+	public static function handle_request_get_all(\WP_REST_Request $request)
53
+	{
54
+		$controller = new Read();
55
+		try {
56
+			$matches = $controller->parse_route(
57
+				$request->get_route(),
58
+				'~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)~',
59
+				array('version', 'model')
60
+			);
61
+			$controller->set_requested_version($matches['version']);
62
+			$model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
63
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
64
+				return $controller->send_response(
65
+					new \WP_Error(
66
+						'endpoint_parsing_error',
67
+						sprintf(
68
+							__('There is no model for endpoint %s. Please contact event espresso support',
69
+								'event_espresso'),
70
+							$model_name_singular
71
+						)
72
+					)
73
+				);
74
+			}
75
+			return $controller->send_response(
76
+				$controller->get_entities_from_model(
77
+					$controller->get_model_version_info()->load_model($model_name_singular),
78
+					$request
79
+				)
80
+			);
81
+		} catch (\Exception $e) {
82
+			return $controller->send_response($e);
83
+		}
84
+	}
85
+
86
+
87
+
88
+	/**
89
+	 * Gets a single entity related to the model indicated in the path and its id
90
+	 *
91
+	 * @param \WP_REST_Request $request
92
+	 * @return \WP_REST_Response|\WP_Error
93
+	 */
94
+	public static function handle_request_get_one(\WP_REST_Request $request)
95
+	{
96
+		$controller = new Read();
97
+		try {
98
+			$matches = $controller->parse_route(
99
+				$request->get_route(),
100
+				'~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)~',
101
+				array('version', 'model', 'id'));
102
+			$controller->set_requested_version($matches['version']);
103
+			$model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
104
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
105
+				return $controller->send_response(
106
+					new \WP_Error(
107
+						'endpoint_parsing_error',
108
+						sprintf(
109
+							__('There is no model for endpoint %s. Please contact event espresso support',
110
+								'event_espresso'),
111
+							$model_name_singular
112
+						)
113
+					)
114
+				);
115
+			}
116
+			return $controller->send_response(
117
+				$controller->get_entity_from_model(
118
+					$controller->get_model_version_info()->load_model($model_name_singular),
119
+					$request
120
+				)
121
+			);
122
+		} catch (\Exception $e) {
123
+			return $controller->send_response($e);
124
+		}
125
+	}
126
+
127
+
128
+
129
+	/**
130
+	 * Gets all the related entities (or if its a belongs-to relation just the one)
131
+	 * to the item with the given id
132
+	 *
133
+	 * @param \WP_REST_Request $request
134
+	 * @return \WP_REST_Response|\WP_Error
135
+	 */
136
+	public static function handle_request_get_related(\WP_REST_Request $request)
137
+	{
138
+		$controller = new Read();
139
+		try {
140
+			$matches = $controller->parse_route(
141
+				$request->get_route(),
142
+				'~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)/(.*)~',
143
+				array('version', 'model', 'id', 'related_model')
144
+			);
145
+			$controller->set_requested_version($matches['version']);
146
+			$main_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
147
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
148
+				return $controller->send_response(
149
+					new \WP_Error(
150
+						'endpoint_parsing_error',
151
+						sprintf(
152
+							__('There is no model for endpoint %s. Please contact event espresso support',
153
+								'event_espresso'),
154
+							$main_model_name_singular
155
+						)
156
+					)
157
+				);
158
+			}
159
+			$main_model = $controller->get_model_version_info()->load_model($main_model_name_singular);
160
+			//assume the related model name is plural and try to find the model's name
161
+			$related_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['related_model']);
162
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
163
+				//so the word didn't singularize well. Maybe that's just because it's a singular word?
164
+				$related_model_name_singular = \EEH_Inflector::humanize($matches['related_model']);
165
+			}
166
+			if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
167
+				return $controller->send_response(
168
+					new \WP_Error(
169
+						'endpoint_parsing_error',
170
+						sprintf(
171
+							__('There is no model for endpoint %s. Please contact event espresso support',
172
+								'event_espresso'),
173
+							$related_model_name_singular
174
+						)
175
+					)
176
+				);
177
+			}
178
+			return $controller->send_response(
179
+				$controller->get_entities_from_relation(
180
+					$request->get_param('id'),
181
+					$main_model->related_settings_for($related_model_name_singular),
182
+					$request
183
+				)
184
+			);
185
+		} catch (\Exception $e) {
186
+			return $controller->send_response($e);
187
+		}
188
+	}
189
+
190
+
191
+
192
+	/**
193
+	 * Gets a collection for the given model and filters
194
+	 *
195
+	 * @param \EEM_Base        $model
196
+	 * @param \WP_REST_Request $request
197
+	 * @return array|\WP_Error
198
+	 */
199
+	public function get_entities_from_model($model, $request)
200
+	{
201
+		$query_params = $this->create_model_query_params($model, $request->get_params());
202
+		if (! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
203
+			$model_name_plural = \EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
204
+			return new \WP_Error(
205
+				sprintf('rest_%s_cannot_list', $model_name_plural),
206
+				sprintf(
207
+					__('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
208
+					$model_name_plural,
209
+					Capabilities::get_missing_permissions_string($model, $query_params['caps'])
210
+				),
211
+				array('status' => 403)
212
+			);
213
+		}
214
+		if (! $request->get_header('no_rest_headers')) {
215
+			$this->_set_headers_from_query_params($model, $query_params);
216
+		}
217
+		/** @type array $results */
218
+		$results = $model->get_all_wpdb_results($query_params);
219
+		$nice_results = array();
220
+		foreach ($results as $result) {
221
+			$nice_results[] = $this->create_entity_from_wpdb_result(
222
+				$model,
223
+				$result,
224
+				$request
225
+			);
226
+		}
227
+		return $nice_results;
228
+	}
229
+
230
+
231
+
232
+	/**
233
+	 * @param array                   $primary_model_query_params query params for finding the item from which
234
+	 *                                                            relations will be based
235
+	 * @param \EE_Model_Relation_Base $relation
236
+	 * @param \WP_REST_Request        $request
237
+	 * @return \WP_Error|array
238
+	 */
239
+	protected function _get_entities_from_relation($primary_model_query_params, $relation, $request)
240
+	{
241
+		$context = $this->validate_context($request->get_param('caps'));
242
+		$model = $relation->get_this_model();
243
+		$related_model = $relation->get_other_model();
244
+		if (! isset($primary_model_query_params[0])) {
245
+			$primary_model_query_params[0] = array();
246
+		}
247
+		//check if they can access the 1st model object
248
+		$primary_model_query_params = array(
249
+			0       => $primary_model_query_params[0],
250
+			'limit' => 1,
251
+		);
252
+		if ($model instanceof \EEM_Soft_Delete_Base) {
253
+			$primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($primary_model_query_params);
254
+		}
255
+		$restricted_query_params = $primary_model_query_params;
256
+		$restricted_query_params['caps'] = $context;
257
+		$this->_set_debug_info('main model query params', $restricted_query_params);
258
+		$this->_set_debug_info('missing caps', Capabilities::get_missing_permissions_string($related_model, $context));
259
+		if (
260
+		! (
261
+			Capabilities::current_user_has_partial_access_to($related_model, $context)
262
+			&& $model->exists($restricted_query_params)
263
+		)
264
+		) {
265
+			if ($relation instanceof \EE_Belongs_To_Relation) {
266
+				$related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
267
+			} else {
268
+				$related_model_name_maybe_plural = \EEH_Inflector::pluralize_and_lower($related_model->get_this_model_name());
269
+			}
270
+			return new \WP_Error(
271
+				sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
272
+				sprintf(
273
+					__('Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
274
+						'event_espresso'),
275
+					$related_model_name_maybe_plural,
276
+					$relation->get_this_model()->get_this_model_name(),
277
+					implode(
278
+						',',
279
+						array_keys(
280
+							Capabilities::get_missing_permissions($related_model, $context)
281
+						)
282
+					)
283
+				),
284
+				array('status' => 403)
285
+			);
286
+		}
287
+		$query_params = $this->create_model_query_params($relation->get_other_model(), $request->get_params());
288
+		foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
289
+			$query_params[0][$relation->get_this_model()->get_this_model_name()
290
+							 . '.'
291
+							 . $where_condition_key] = $where_condition_value;
292
+		}
293
+		$query_params['default_where_conditions'] = 'none';
294
+		$query_params['caps'] = $context;
295
+		if (! $request->get_header('no_rest_headers')) {
296
+			$this->_set_headers_from_query_params($relation->get_other_model(), $query_params);
297
+		}
298
+		/** @type array $results */
299
+		$results = $relation->get_other_model()->get_all_wpdb_results($query_params);
300
+		$nice_results = array();
301
+		foreach ($results as $result) {
302
+			$nice_result = $this->create_entity_from_wpdb_result(
303
+				$relation->get_other_model(),
304
+				$result,
305
+				$request
306
+			);
307
+			if ($relation instanceof \EE_HABTM_Relation) {
308
+				//put the unusual stuff (properties from the HABTM relation) first, and make sure
309
+				//if there are conflicts we prefer the properties from the main model
310
+				$join_model_result = $this->create_entity_from_wpdb_result(
311
+					$relation->get_join_model(),
312
+					$result,
313
+					$request
314
+				);
315
+				$joined_result = array_merge($nice_result, $join_model_result);
316
+				//but keep the meta stuff from the main model
317
+				if (isset($nice_result['meta'])) {
318
+					$joined_result['meta'] = $nice_result['meta'];
319
+				}
320
+				$nice_result = $joined_result;
321
+			}
322
+			$nice_results[] = $nice_result;
323
+		}
324
+		if ($relation instanceof \EE_Belongs_To_Relation) {
325
+			return array_shift($nice_results);
326
+		} else {
327
+			return $nice_results;
328
+		}
329
+	}
330
+
331
+
332
+
333
+	/**
334
+	 * Gets the collection for given relation object
335
+	 * The same as Read::get_entities_from_model(), except if the relation
336
+	 * is a HABTM relation, in which case it merges any non-foreign-key fields from
337
+	 * the join-model-object into the results
338
+	 *
339
+	 * @param string                  $id the ID of the thing we are fetching related stuff from
340
+	 * @param \EE_Model_Relation_Base $relation
341
+	 * @param \WP_REST_Request        $request
342
+	 * @return array|\WP_Error
343
+	 * @throws \EE_Error
344
+	 */
345
+	public function get_entities_from_relation($id, $relation, $request)
346
+	{
347
+		if (! $relation->get_this_model()->has_primary_key_field()) {
348
+			throw new \EE_Error(
349
+				sprintf(
350
+					__('Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
351
+						'event_espresso'),
352
+					$relation->get_this_model()->get_this_model_name()
353
+				)
354
+			);
355
+		}
356
+		return $this->_get_entities_from_relation(
357
+			array(
358
+				array(
359
+					$relation->get_this_model()->primary_key_name() => $id,
360
+				),
361
+			),
362
+			$relation,
363
+			$request
364
+		);
365
+	}
366
+
367
+
368
+
369
+	/**
370
+	 * Sets the headers that are based on the model and query params,
371
+	 * like the total records. This should only be called on the original request
372
+	 * from the client, not on subsequent internal
373
+	 *
374
+	 * @param \EEM_Base $model
375
+	 * @param array     $query_params
376
+	 * @return void
377
+	 */
378
+	protected function _set_headers_from_query_params($model, $query_params)
379
+	{
380
+		$this->_set_debug_info('model query params', $query_params);
381
+		$this->_set_debug_info('missing caps',
382
+			Capabilities::get_missing_permissions_string($model, $query_params['caps']));
383
+		//normally the limit to a 2-part array, where the 2nd item is the limit
384
+		if (! isset($query_params['limit'])) {
385
+			$query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
386
+		}
387
+		if (is_array($query_params['limit'])) {
388
+			$limit_parts = $query_params['limit'];
389
+		} else {
390
+			$limit_parts = explode(',', $query_params['limit']);
391
+			if (count($limit_parts) == 1) {
392
+				$limit_parts = array(0, $limit_parts[0]);
393
+			}
394
+		}
395
+		//remove the group by and having parts of the query, as those will
396
+		//make the sql query return an array of values, instead of just a single value
397
+		unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
398
+		$count = $model->count($query_params, null, true);
399
+		$pages = $count / $limit_parts[1];
400
+		$this->_set_response_header('Total', $count, false);
401
+		$this->_set_response_header('PageSize', $limit_parts[1], false);
402
+		$this->_set_response_header('TotalPages', ceil($pages), false);
403
+	}
404
+
405
+
406
+
407
+	/**
408
+	 * Changes database results into REST API entities
409
+	 *
410
+	 * @param \EEM_Base        $model
411
+	 * @param array            $db_row     like results from $wpdb->get_results()
412
+	 * @param \WP_REST_Request $rest_request
413
+	 * @param string           $deprecated no longer used
414
+	 * @return array ready for being converted into json for sending to client
415
+	 */
416
+	public function create_entity_from_wpdb_result($model, $db_row, $rest_request, $deprecated = null)
417
+	{
418
+		if (! $rest_request instanceof \WP_REST_Request) {
419
+			//ok so this was called in the old style, where the 3rd arg was
420
+			//$include, and the 4th arg was $context
421
+			//now setup the request just to avoid fatal errors, although we won't be able
422
+			//to truly make use of it because it's kinda devoid of info
423
+			$rest_request = new \WP_REST_Request();
424
+			$rest_request->set_param('include', $rest_request);
425
+			$rest_request->set_param('caps', $deprecated);
426
+		}
427
+		if ($rest_request->get_param('caps') == null) {
428
+			$rest_request->set_param('caps', \EEM_Base::caps_read);
429
+		}
430
+		$entity_array = $this->_create_bare_entity_from_wpdb_results($model, $db_row);
431
+		$entity_array = $this->_add_extra_fields($model, $db_row, $entity_array);
432
+		$entity_array['_links'] = $this->_get_entity_links($model, $db_row, $entity_array);
433
+		$entity_array['_calculated_fields'] = $this->_get_entity_calculations($model, $db_row, $rest_request);
434
+		$entity_array = $this->_include_requested_models($model, $rest_request, $entity_array, $db_row);
435
+		$entity_array = apply_filters(
436
+			'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
437
+			$entity_array,
438
+			$model,
439
+			$rest_request->get_param('caps'),
440
+			$rest_request,
441
+			$this
442
+		);
443
+		$result_without_inaccessible_fields = Capabilities::filter_out_inaccessible_entity_fields(
444
+			$entity_array,
445
+			$model,
446
+			$rest_request->get_param('caps'),
447
+			$this->get_model_version_info(),
448
+			$model->get_index_primary_key_string(
449
+				$model->deduce_fields_n_values_from_cols_n_values($db_row)
450
+			)
451
+		);
452
+		$this->_set_debug_info(
453
+			'inaccessible fields',
454
+			array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
455
+		);
456
+		return apply_filters(
457
+			'FHEE__Read__create_entity_from_wpdb_results__entity_return',
458
+			$result_without_inaccessible_fields,
459
+			$model,
460
+			$rest_request->get_param('caps')
461
+		);
462
+	}
463
+
464
+
465
+
466
+	/**
467
+	 * Creates a REST entity array (JSON object we're going to return in the response, but
468
+	 * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
469
+	 * from $wpdb->get_row( $sql, ARRAY_A)
470
+	 *
471
+	 * @param \EEM_Base $model
472
+	 * @param array     $db_row
473
+	 * @return array entity mostly ready for converting to JSON and sending in the response
474
+	 */
475
+	protected function _create_bare_entity_from_wpdb_results(\EEM_Base $model, $db_row)
476
+	{
477
+		$result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
478
+		$result = array_intersect_key($result,
479
+			$this->get_model_version_info()->fields_on_model_in_this_version($model));
480
+		foreach ($result as $field_name => $raw_field_value) {
481
+			$field_obj = $model->field_settings_for($field_name);
482
+			$field_value = $field_obj->prepare_for_set_from_db($raw_field_value);
483
+			if ($this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_ignored())) {
484
+				unset($result[$field_name]);
485
+			} elseif (
486
+			$this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_rendered_format())
487
+			) {
488
+				$result[$field_name] = array(
489
+					'raw'      => $field_obj->prepare_for_get($field_value),
490
+					'rendered' => $field_obj->prepare_for_pretty_echoing($field_value),
491
+				);
492
+			} elseif (
493
+			$this->is_subclass_of_one($field_obj, $this->get_model_version_info()->fields_that_have_pretty_format())
494
+			) {
495
+				$result[$field_name] = array(
496
+					'raw'    => $field_obj->prepare_for_get($field_value),
497
+					'pretty' => $field_obj->prepare_for_pretty_echoing($field_value),
498
+				);
499
+			} elseif ($field_obj instanceof \EE_Datetime_Field) {
500
+				if ($field_value instanceof \DateTime) {
501
+					$timezone = $field_value->getTimezone();
502
+					$field_value->setTimezone(new \DateTimeZone('UTC'));
503
+					$result[$field_name . '_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
504
+						$field_obj,
505
+						$field_value,
506
+						$this->get_model_version_info()->requested_version()
507
+					);
508
+					$field_value->setTimezone($timezone);
509
+					$result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
510
+						$field_obj,
511
+						$field_value,
512
+						$this->get_model_version_info()->requested_version()
513
+					);
514
+				}
515
+			} else {
516
+				$result[$field_name] = Model_Data_Translator::prepare_field_value_for_json(
517
+					$field_obj,
518
+					$field_obj->prepare_for_get($field_value),
519
+					$this->get_model_version_info()->requested_version()
520
+				);
521
+			}
522
+		}
523
+		return $result;
524
+	}
525
+
526
+
527
+
528
+	/**
529
+	 * Adds a few extra fields to the entity response
530
+	 *
531
+	 * @param \EEM_Base $model
532
+	 * @param array     $db_row
533
+	 * @param array     $entity_array
534
+	 * @return array modified entity
535
+	 */
536
+	protected function _add_extra_fields(\EEM_Base $model, $db_row, $entity_array)
537
+	{
538
+		if ($model instanceof \EEM_CPT_Base) {
539
+			$entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]);
540
+		}
541
+		return $entity_array;
542
+	}
543
+
544
+
545
+
546
+	/**
547
+	 * Gets links we want to add to the response
548
+	 *
549
+	 * @global \WP_REST_Server $wp_rest_server
550
+	 * @param \EEM_Base        $model
551
+	 * @param array            $db_row
552
+	 * @param array            $entity_array
553
+	 * @return array the _links item in the entity
554
+	 */
555
+	protected function _get_entity_links($model, $db_row, $entity_array)
556
+	{
557
+		//add basic links
558
+		$links = array();
559
+		if ($model->has_primary_key_field()) {
560
+			$links['self'] = array(
561
+				array(
562
+					'href' => $this->get_versioned_link_to(
563
+						\EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
564
+						. '/'
565
+						. $entity_array[$model->primary_key_name()]
566
+					),
567
+				),
568
+			);
569
+		}
570
+		$links['collection'] = array(
571
+			array(
572
+				'href' => $this->get_versioned_link_to(
573
+					\EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
574
+				),
575
+			),
576
+		);
577
+		//add link to the wp core endpoint, if wp api is active
578
+		global $wp_rest_server;
579
+		if ($model instanceof \EEM_CPT_Base
580
+			&& $wp_rest_server instanceof \WP_REST_Server
581
+			&& $wp_rest_server->get_route_options('/wp/v2/posts')
582
+			&& $model->has_primary_key_field()
583
+		) {
584
+			$links[\EED_Core_Rest_Api::ee_api_link_namespace . 'self_wp_post'] = array(
585
+				array(
586
+					'href'   => rest_url('/wp/v2/posts/' . $db_row[$model->get_primary_key_field()
587
+																		 ->get_qualified_column()]),
588
+					'single' => true,
589
+				),
590
+			);
591
+		}
592
+		//add links to related models
593
+		if ($model->has_primary_key_field()) {
594
+			foreach ($this->get_model_version_info()->relation_settings($model) as $relation_name => $relation_obj) {
595
+				$related_model_part = Read::get_related_entity_name($relation_name, $relation_obj);
596
+				$links[\EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
597
+					array(
598
+						'href'   => $this->get_versioned_link_to(
599
+							\EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
600
+							. '/'
601
+							. $entity_array[$model->primary_key_name()]
602
+							. '/'
603
+							. $related_model_part
604
+						),
605
+						'single' => $relation_obj instanceof \EE_Belongs_To_Relation ? true : false,
606
+					),
607
+				);
608
+			}
609
+		}
610
+		return $links;
611
+	}
612
+
613
+
614
+
615
+	/**
616
+	 * Adds the included models indicated in the request to the entity provided
617
+	 *
618
+	 * @param \EEM_Base        $model
619
+	 * @param \WP_REST_Request $rest_request
620
+	 * @param array            $entity_array
621
+	 * @param array            $db_row
622
+	 * @return array the modified entity
623
+	 */
624
+	protected function _include_requested_models(
625
+		\EEM_Base $model,
626
+		\WP_REST_Request $rest_request,
627
+		$entity_array,
628
+		$db_row = array()
629
+	) {
630
+		//if $db_row not included, hope the entity array has what we need
631
+		if (! $db_row) {
632
+			$db_row = $entity_array;
633
+		}
634
+		$includes_for_this_model = $this->explode_and_get_items_prefixed_with($rest_request->get_param('include'), '');
635
+		$includes_for_this_model = $this->_remove_model_names_from_array($includes_for_this_model);
636
+		//if they passed in * or didn't specify any includes, return everything
637
+		if (! in_array('*', $includes_for_this_model)
638
+			&& ! empty($includes_for_this_model)
639
+		) {
640
+			if ($model->has_primary_key_field()) {
641
+				//always include the primary key. ya just gotta know that at least
642
+				$includes_for_this_model[] = $model->primary_key_name();
643
+			}
644
+			if ($this->explode_and_get_items_prefixed_with($rest_request->get_param('calculate'), '')) {
645
+				$includes_for_this_model[] = '_calculated_fields';
646
+			}
647
+			$entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
648
+		}
649
+		$relation_settings = $this->get_model_version_info()->relation_settings($model);
650
+		foreach ($relation_settings as $relation_name => $relation_obj) {
651
+			$related_fields_to_include = $this->explode_and_get_items_prefixed_with(
652
+				$rest_request->get_param('include'),
653
+				$relation_name
654
+			);
655
+			$related_fields_to_calculate = $this->explode_and_get_items_prefixed_with(
656
+				$rest_request->get_param('calculate'),
657
+				$relation_name
658
+			);
659
+			//did they specify they wanted to include a related model, or
660
+			//specific fields from a related model?
661
+			//or did they specify to calculate a field from a related model?
662
+			if ($related_fields_to_include || $related_fields_to_calculate) {
663
+				//if so, we should include at least some part of the related model
664
+				$pretend_related_request = new \WP_REST_Request();
665
+				$pretend_related_request->set_query_params(
666
+					array(
667
+						'caps'      => $rest_request->get_param('caps'),
668
+						'include'   => $related_fields_to_include,
669
+						'calculate' => $related_fields_to_calculate,
670
+					)
671
+				);
672
+				$pretend_related_request->add_header('no_rest_headers', true);
673
+				$primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
674
+					$model->get_index_primary_key_string(
675
+						$model->deduce_fields_n_values_from_cols_n_values($db_row)
676
+					)
677
+				);
678
+				$related_results = $this->_get_entities_from_relation(
679
+					$primary_model_query_params,
680
+					$relation_obj,
681
+					$pretend_related_request
682
+				);
683
+				$entity_array[Read::get_related_entity_name($relation_name, $relation_obj)] = $related_results
684
+																							  instanceof
685
+																							  \WP_Error
686
+					? null
687
+					: $related_results;
688
+			}
689
+		}
690
+		return $entity_array;
691
+	}
692
+
693
+
694
+
695
+	/**
696
+	 * Returns a new array with all the names of models removed. Eg
697
+	 * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
698
+	 *
699
+	 * @param array $arr
700
+	 * @return array
701
+	 */
702
+	private function _remove_model_names_from_array($arr)
703
+	{
704
+		return array_diff($arr, array_keys(\EE_Registry::instance()->non_abstract_db_models));
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 * Gets the calculated fields for the response
711
+	 *
712
+	 * @param \EEM_Base        $model
713
+	 * @param array            $wpdb_row
714
+	 * @param \WP_REST_Request $rest_request
715
+	 * @return \stdClass the _calculations item in the entity
716
+	 */
717
+	protected function _get_entity_calculations($model, $wpdb_row, $rest_request)
718
+	{
719
+		$calculated_fields = $this->explode_and_get_items_prefixed_with(
720
+			$rest_request->get_param('calculate'),
721
+			''
722
+		);
723
+		//note: setting calculate=* doesn't do anything
724
+		$calculated_fields_to_return = new \stdClass();
725
+		foreach ($calculated_fields as $field_to_calculate) {
726
+			try {
727
+				$calculated_fields_to_return->$field_to_calculate = Model_Data_Translator::prepare_field_value_for_json(
728
+					null,
729
+					$this->_fields_calculator->retrieve_calculated_field_value(
730
+						$model,
731
+						$field_to_calculate,
732
+						$wpdb_row,
733
+						$rest_request,
734
+						$this
735
+					),
736
+					$this->get_model_version_info()->requested_version()
737
+				);
738
+			} catch (Rest_Exception $e) {
739
+				//if we don't have permission to read it, just leave it out. but let devs know about the problem
740
+				$this->_set_response_header(
741
+					'Notices-Field-Calculation-Errors['
742
+					. $e->get_string_code()
743
+					. ']['
744
+					. $model->get_this_model_name()
745
+					. ']['
746
+					. $field_to_calculate
747
+					. ']',
748
+					$e->getMessage(),
749
+					true
750
+				);
751
+			}
752
+		}
753
+		return $calculated_fields_to_return;
754
+	}
755
+
756
+
757
+
758
+	/**
759
+	 * Gets the full URL to the resource, taking the requested version into account
760
+	 *
761
+	 * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
762
+	 * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
763
+	 */
764
+	public function get_versioned_link_to($link_part_after_version_and_slash)
765
+	{
766
+		return rest_url(
767
+			\EED_Core_Rest_Api::ee_api_namespace
768
+			. $this->get_model_version_info()->requested_version()
769
+			. '/'
770
+			. $link_part_after_version_and_slash
771
+		);
772
+	}
773
+
774
+
775
+
776
+	/**
777
+	 * Gets the correct lowercase name for the relation in the API according
778
+	 * to the relation's type
779
+	 *
780
+	 * @param string                  $relation_name
781
+	 * @param \EE_Model_Relation_Base $relation_obj
782
+	 * @return string
783
+	 */
784
+	public static function get_related_entity_name($relation_name, $relation_obj)
785
+	{
786
+		if ($relation_obj instanceof \EE_Belongs_To_Relation) {
787
+			return strtolower($relation_name);
788
+		} else {
789
+			return \EEH_Inflector::pluralize_and_lower($relation_name);
790
+		}
791
+	}
792
+
793
+
794
+
795
+	/**
796
+	 * Gets the one model object with the specified id for the specified model
797
+	 *
798
+	 * @param \EEM_Base        $model
799
+	 * @param \WP_REST_Request $request
800
+	 * @return array|\WP_Error
801
+	 */
802
+	public function get_entity_from_model($model, $request)
803
+	{
804
+		$query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
805
+		if ($model instanceof \EEM_Soft_Delete_Base) {
806
+			$query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
807
+		}
808
+		$restricted_query_params = $query_params;
809
+		$restricted_query_params['caps'] = $this->validate_context($request->get_param('caps'));
810
+		$this->_set_debug_info('model query params', $restricted_query_params);
811
+		$model_rows = $model->get_all_wpdb_results($restricted_query_params);
812
+		if (! empty ($model_rows)) {
813
+			return $this->create_entity_from_wpdb_result(
814
+				$model,
815
+				array_shift($model_rows),
816
+				$request);
817
+		} else {
818
+			//ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
819
+			$lowercase_model_name = strtolower($model->get_this_model_name());
820
+			$model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
821
+			if (! empty($model_rows_found_sans_restrictions)) {
822
+				//you got shafted- it existed but we didn't want to tell you!
823
+				return new \WP_Error(
824
+					'rest_user_cannot_read',
825
+					sprintf(
826
+						__('Sorry, you cannot read this %1$s. Missing permissions are: %2$s', 'event_espresso'),
827
+						strtolower($model->get_this_model_name()),
828
+						Capabilities::get_missing_permissions_string(
829
+							$model,
830
+							$this->validate_context($request->get_param('caps')))
831
+					),
832
+					array('status' => 403)
833
+				);
834
+			} else {
835
+				//it's not you. It just doesn't exist
836
+				return new \WP_Error(
837
+					sprintf('rest_%s_invalid_id', $lowercase_model_name),
838
+					sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
839
+					array('status' => 404)
840
+				);
841
+			}
842
+		}
843
+	}
844
+
845
+
846
+
847
+	/**
848
+	 * If a context is provided which isn't valid, maybe it was added in a future
849
+	 * version so just treat it as a default read
850
+	 *
851
+	 * @param string $context
852
+	 * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
853
+	 */
854
+	public function validate_context($context)
855
+	{
856
+		if (! $context) {
857
+			$context = \EEM_Base::caps_read;
858
+		}
859
+		$valid_contexts = \EEM_Base::valid_cap_contexts();
860
+		if (in_array($context, $valid_contexts)) {
861
+			return $context;
862
+		} else {
863
+			return \EEM_Base::caps_read;
864
+		}
865
+	}
866
+
867
+
868
+
869
+	/**
870
+	 * Verifies the passed in value is an allowable default where conditions value.
871
+	 *
872
+	 * @param $default_query_params
873
+	 * @return string
874
+	 */
875
+	public function validate_default_query_params($default_query_params)
876
+	{
877
+		$valid_default_where_conditions_for_api_calls = array(
878
+			\EEM_Base::default_where_conditions_all,
879
+			\EEM_Base::default_where_conditions_minimum_all,
880
+			\EEM_Base::default_where_conditions_minimum_others,
881
+		);
882
+		if (! $default_query_params) {
883
+			$default_query_params = \EEM_Base::default_where_conditions_all;
884
+		}
885
+		if (
886
+		in_array(
887
+			$default_query_params,
888
+			$valid_default_where_conditions_for_api_calls,
889
+			true
890
+		)
891
+		) {
892
+			return $default_query_params;
893
+		} else {
894
+			return \EEM_Base::default_where_conditions_all;
895
+		}
896
+	}
897
+
898
+
899
+
900
+	/**
901
+	 * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
902
+	 * Note: right now the query parameter keys for fields (and related fields)
903
+	 * can be left as-is, but it's quite possible this will change someday.
904
+	 * Also, this method's contents might be candidate for moving to Model_Data_Translator
905
+	 *
906
+	 * @param \EEM_Base $model
907
+	 * @param array     $query_parameters from $_GET parameter @see Read:handle_request_get_all
908
+	 * @return array like what EEM_Base::get_all() expects or FALSE to indicate
909
+	 *                                    that absolutely no results should be returned
910
+	 * @throws \EE_Error
911
+	 */
912
+	public function create_model_query_params($model, $query_parameters)
913
+	{
914
+		$model_query_params = array();
915
+		if (isset($query_parameters['where'])) {
916
+			$model_query_params[0] = Model_Data_Translator::prepare_conditions_query_params_for_models(
917
+				$query_parameters['where'],
918
+				$model,
919
+				$this->get_model_version_info()->requested_version()
920
+			);
921
+		}
922
+		if (isset($query_parameters['order_by'])) {
923
+			$order_by = $query_parameters['order_by'];
924
+		} elseif (isset($query_parameters['orderby'])) {
925
+			$order_by = $query_parameters['orderby'];
926
+		} else {
927
+			$order_by = null;
928
+		}
929
+		if ($order_by !== null) {
930
+			if (is_array($order_by)) {
931
+				$order_by = Model_Data_Translator::prepare_field_names_in_array_keys_from_json($order_by);
932
+			} else {
933
+				//it's a single item
934
+				$order_by = Model_Data_Translator::prepare_field_name_from_json($order_by);
935
+			}
936
+			$model_query_params['order_by'] = $order_by;
937
+		}
938
+		if (isset($query_parameters['group_by'])) {
939
+			$group_by = $query_parameters['group_by'];
940
+		} elseif (isset($query_parameters['groupby'])) {
941
+			$group_by = $query_parameters['groupby'];
942
+		} else {
943
+			$group_by = array_keys($model->get_combined_primary_key_fields());
944
+		}
945
+		//make sure they're all real names
946
+		if (is_array($group_by)) {
947
+			$group_by = Model_Data_Translator::prepare_field_names_from_json($group_by);
948
+		}
949
+		if ($group_by !== null) {
950
+			$model_query_params['group_by'] = $group_by;
951
+		}
952
+		if (isset($query_parameters['having'])) {
953
+			$model_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_models(
954
+				$query_parameters['having'],
955
+				$model,
956
+				$this->get_model_version_info()->requested_version()
957
+			);
958
+		}
959
+		if (isset($query_parameters['order'])) {
960
+			$model_query_params['order'] = $query_parameters['order'];
961
+		}
962
+		if (isset($query_parameters['mine'])) {
963
+			$model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
964
+		}
965
+		if (isset($query_parameters['limit'])) {
966
+			//limit should be either a string like '23' or '23,43', or an array with two items in it
967
+			if (! is_array($query_parameters['limit'])) {
968
+				$limit_array = explode(',', (string)$query_parameters['limit']);
969
+			} else {
970
+				$limit_array = $query_parameters['limit'];
971
+			}
972
+			$sanitized_limit = array();
973
+			foreach ($limit_array as $key => $limit_part) {
974
+				if ($this->_debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
975
+					throw new \EE_Error(
976
+						sprintf(
977
+							__('An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.',
978
+								'event_espresso'),
979
+							wp_json_encode($query_parameters['limit'])
980
+						)
981
+					);
982
+				}
983
+				$sanitized_limit[] = (int)$limit_part;
984
+			}
985
+			$model_query_params['limit'] = implode(',', $sanitized_limit);
986
+		} else {
987
+			$model_query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
988
+		}
989
+		if (isset($query_parameters['caps'])) {
990
+			$model_query_params['caps'] = $this->validate_context($query_parameters['caps']);
991
+		} else {
992
+			$model_query_params['caps'] = \EEM_Base::caps_read;
993
+		}
994
+		if (isset($query_parameters['default_where_conditions'])) {
995
+			$model_query_params['default_where_conditions'] = $this->validate_default_query_params($query_parameters['default_where_conditions']);
996
+		}
997
+		return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
998
+	}
999
+
1000
+
1001
+
1002
+	/**
1003
+	 * Changes the REST-style query params for use in the models
1004
+	 *
1005
+	 * @deprecated
1006
+	 * @param \EEM_Base $model
1007
+	 * @param array     $query_params sub-array from @see EEM_Base::get_all()
1008
+	 * @return array
1009
+	 */
1010
+	public function prepare_rest_query_params_key_for_models($model, $query_params)
1011
+	{
1012
+		$model_ready_query_params = array();
1013
+		foreach ($query_params as $key => $value) {
1014
+			if (is_array($value)) {
1015
+				$model_ready_query_params[$key] = $this->prepare_rest_query_params_key_for_models($model, $value);
1016
+			} else {
1017
+				$model_ready_query_params[$key] = $value;
1018
+			}
1019
+		}
1020
+		return $model_ready_query_params;
1021
+	}
1022
+
1023
+
1024
+
1025
+	/**
1026
+	 * @deprecated
1027
+	 * @param $model
1028
+	 * @param $query_params
1029
+	 * @return array
1030
+	 */
1031
+	public function prepare_rest_query_params_values_for_models($model, $query_params)
1032
+	{
1033
+		$model_ready_query_params = array();
1034
+		foreach ($query_params as $key => $value) {
1035
+			if (is_array($value)) {
1036
+				$model_ready_query_params[$key] = $this->prepare_rest_query_params_values_for_models($model, $value);
1037
+			} else {
1038
+				$model_ready_query_params[$key] = $value;
1039
+			}
1040
+		}
1041
+		return $model_ready_query_params;
1042
+	}
1043
+
1044
+
1045
+
1046
+	/**
1047
+	 * Explodes the string on commas, and only returns items with $prefix followed by a period.
1048
+	 * If no prefix is specified, returns items with no period.
1049
+	 *
1050
+	 * @param string|array $string_to_explode eg "jibba,jabba, blah, blaabla" or array('jibba', 'jabba' )
1051
+	 * @param string       $prefix            "Event" or "foobar"
1052
+	 * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1053
+	 *                                        we only return strings starting with that and a period; if no prefix was
1054
+	 *                                        specified we return all items containing NO periods
1055
+	 */
1056
+	public function explode_and_get_items_prefixed_with($string_to_explode, $prefix)
1057
+	{
1058
+		if (is_string($string_to_explode)) {
1059
+			$exploded_contents = explode(',', $string_to_explode);
1060
+		} else if (is_array($string_to_explode)) {
1061
+			$exploded_contents = $string_to_explode;
1062
+		} else {
1063
+			$exploded_contents = array();
1064
+		}
1065
+		//if the string was empty, we want an empty array
1066
+		$exploded_contents = array_filter($exploded_contents);
1067
+		$contents_with_prefix = array();
1068
+		foreach ($exploded_contents as $item) {
1069
+			$item = trim($item);
1070
+			//if no prefix was provided, so we look for items with no "." in them
1071
+			if (! $prefix) {
1072
+				//does this item have a period?
1073
+				if (strpos($item, '.') === false) {
1074
+					//if not, then its what we're looking for
1075
+					$contents_with_prefix[] = $item;
1076
+				}
1077
+			} else if (strpos($item, $prefix . '.') === 0) {
1078
+				//this item has the prefix and a period, grab it
1079
+				$contents_with_prefix[] = substr(
1080
+					$item,
1081
+					strpos($item, $prefix . '.') + strlen($prefix . '.')
1082
+				);
1083
+			} else if ($item === $prefix) {
1084
+				//this item is JUST the prefix
1085
+				//so let's grab everything after, which is a blank string
1086
+				$contents_with_prefix[] = '';
1087
+			}
1088
+		}
1089
+		return $contents_with_prefix;
1090
+	}
1091
+
1092
+
1093
+
1094
+	/**
1095
+	 * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1096
+	 * Deprecated because its return values were really quite confusing- sometimes it returned
1097
+	 * an empty array (when the include string was blank or '*') or sometimes it returned
1098
+	 * array('*') (when you provided a model and a model of that kind was found).
1099
+	 * Parses the $include_string so we fetch all the field names relating to THIS model
1100
+	 * (ie have NO period in them), or for the provided model (ie start with the model
1101
+	 * name and then a period).
1102
+	 * @param string $include_string @see Read:handle_request_get_all
1103
+	 * @param string $model_name
1104
+	 * @return array of fields for this model. If $model_name is provided, then
1105
+	 *                               the fields for that model, with the model's name removed from each.
1106
+	 *                               If $include_string was blank or '*' returns an empty array
1107
+	 */
1108
+	public function extract_includes_for_this_model($include_string, $model_name = null)
1109
+	{
1110
+		if (is_array($include_string)) {
1111
+			$include_string = implode(',', $include_string);
1112
+		}
1113
+		if ($include_string === '*' || $include_string === '') {
1114
+			return array();
1115
+		}
1116
+		$includes = explode(',', $include_string);
1117
+		$extracted_fields_to_include = array();
1118
+		if ($model_name) {
1119
+			foreach ($includes as $field_to_include) {
1120
+				$field_to_include = trim($field_to_include);
1121
+				if (strpos($field_to_include, $model_name . '.') === 0) {
1122
+					//found the model name at the exact start
1123
+					$field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1124
+					$extracted_fields_to_include[] = $field_sans_model_name;
1125
+				} elseif ($field_to_include == $model_name) {
1126
+					$extracted_fields_to_include[] = '*';
1127
+				}
1128
+			}
1129
+		} else {
1130
+			//look for ones with no period
1131
+			foreach ($includes as $field_to_include) {
1132
+				$field_to_include = trim($field_to_include);
1133
+				if (
1134
+					strpos($field_to_include, '.') === false
1135
+					&& ! $this->get_model_version_info()->is_model_name_in_this_version($field_to_include)
1136
+				) {
1137
+					$extracted_fields_to_include[] = $field_to_include;
1138
+				}
1139
+			}
1140
+		}
1141
+		return $extracted_fields_to_include;
1142
+	}
1143 1143
 }
1144 1144
 
1145 1145
 
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -6,7 +6,7 @@  discard block
 block discarded – undo
6 6
 use EventEspresso\core\libraries\rest_api\Rest_Exception;
7 7
 use EventEspresso\core\libraries\rest_api\Model_Data_Translator;
8 8
 
9
-if (! defined('EVENT_ESPRESSO_VERSION')) {
9
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
10 10
     exit('No direct script access allowed');
11 11
 }
12 12
 
@@ -55,12 +55,12 @@  discard block
 block discarded – undo
55 55
         try {
56 56
             $matches = $controller->parse_route(
57 57
                 $request->get_route(),
58
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)~',
58
+                '~'.\EED_Core_Rest_Api::ee_api_namespace_for_regex.'(.*)~',
59 59
                 array('version', 'model')
60 60
             );
61 61
             $controller->set_requested_version($matches['version']);
62 62
             $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
63
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
63
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
64 64
                 return $controller->send_response(
65 65
                     new \WP_Error(
66 66
                         'endpoint_parsing_error',
@@ -97,11 +97,11 @@  discard block
 block discarded – undo
97 97
         try {
98 98
             $matches = $controller->parse_route(
99 99
                 $request->get_route(),
100
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)~',
100
+                '~'.\EED_Core_Rest_Api::ee_api_namespace_for_regex.'(.*)/(.*)~',
101 101
                 array('version', 'model', 'id'));
102 102
             $controller->set_requested_version($matches['version']);
103 103
             $model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
104
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
104
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($model_name_singular)) {
105 105
                 return $controller->send_response(
106 106
                     new \WP_Error(
107 107
                         'endpoint_parsing_error',
@@ -139,12 +139,12 @@  discard block
 block discarded – undo
139 139
         try {
140 140
             $matches = $controller->parse_route(
141 141
                 $request->get_route(),
142
-                '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . '(.*)/(.*)/(.*)~',
142
+                '~'.\EED_Core_Rest_Api::ee_api_namespace_for_regex.'(.*)/(.*)/(.*)~',
143 143
                 array('version', 'model', 'id', 'related_model')
144 144
             );
145 145
             $controller->set_requested_version($matches['version']);
146 146
             $main_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['model']);
147
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
147
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($main_model_name_singular)) {
148 148
                 return $controller->send_response(
149 149
                     new \WP_Error(
150 150
                         'endpoint_parsing_error',
@@ -159,11 +159,11 @@  discard block
 block discarded – undo
159 159
             $main_model = $controller->get_model_version_info()->load_model($main_model_name_singular);
160 160
             //assume the related model name is plural and try to find the model's name
161 161
             $related_model_name_singular = \EEH_Inflector::singularize_and_upper($matches['related_model']);
162
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
162
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
163 163
                 //so the word didn't singularize well. Maybe that's just because it's a singular word?
164 164
                 $related_model_name_singular = \EEH_Inflector::humanize($matches['related_model']);
165 165
             }
166
-            if (! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
166
+            if ( ! $controller->get_model_version_info()->is_model_name_in_this_version($related_model_name_singular)) {
167 167
                 return $controller->send_response(
168 168
                     new \WP_Error(
169 169
                         'endpoint_parsing_error',
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
     public function get_entities_from_model($model, $request)
200 200
     {
201 201
         $query_params = $this->create_model_query_params($model, $request->get_params());
202
-        if (! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
202
+        if ( ! Capabilities::current_user_has_partial_access_to($model, $query_params['caps'])) {
203 203
             $model_name_plural = \EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
204 204
             return new \WP_Error(
205 205
                 sprintf('rest_%s_cannot_list', $model_name_plural),
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
                 array('status' => 403)
212 212
             );
213 213
         }
214
-        if (! $request->get_header('no_rest_headers')) {
214
+        if ( ! $request->get_header('no_rest_headers')) {
215 215
             $this->_set_headers_from_query_params($model, $query_params);
216 216
         }
217 217
         /** @type array $results */
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
         $context = $this->validate_context($request->get_param('caps'));
242 242
         $model = $relation->get_this_model();
243 243
         $related_model = $relation->get_other_model();
244
-        if (! isset($primary_model_query_params[0])) {
244
+        if ( ! isset($primary_model_query_params[0])) {
245 245
             $primary_model_query_params[0] = array();
246 246
         }
247 247
         //check if they can access the 1st model object
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
         }
293 293
         $query_params['default_where_conditions'] = 'none';
294 294
         $query_params['caps'] = $context;
295
-        if (! $request->get_header('no_rest_headers')) {
295
+        if ( ! $request->get_header('no_rest_headers')) {
296 296
             $this->_set_headers_from_query_params($relation->get_other_model(), $query_params);
297 297
         }
298 298
         /** @type array $results */
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
      */
345 345
     public function get_entities_from_relation($id, $relation, $request)
346 346
     {
347
-        if (! $relation->get_this_model()->has_primary_key_field()) {
347
+        if ( ! $relation->get_this_model()->has_primary_key_field()) {
348 348
             throw new \EE_Error(
349 349
                 sprintf(
350 350
                     __('Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
@@ -381,7 +381,7 @@  discard block
 block discarded – undo
381 381
         $this->_set_debug_info('missing caps',
382 382
             Capabilities::get_missing_permissions_string($model, $query_params['caps']));
383 383
         //normally the limit to a 2-part array, where the 2nd item is the limit
384
-        if (! isset($query_params['limit'])) {
384
+        if ( ! isset($query_params['limit'])) {
385 385
             $query_params['limit'] = \EED_Core_Rest_Api::get_default_query_limit();
386 386
         }
387 387
         if (is_array($query_params['limit'])) {
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
      */
416 416
     public function create_entity_from_wpdb_result($model, $db_row, $rest_request, $deprecated = null)
417 417
     {
418
-        if (! $rest_request instanceof \WP_REST_Request) {
418
+        if ( ! $rest_request instanceof \WP_REST_Request) {
419 419
             //ok so this was called in the old style, where the 3rd arg was
420 420
             //$include, and the 4th arg was $context
421 421
             //now setup the request just to avoid fatal errors, although we won't be able
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
                 if ($field_value instanceof \DateTime) {
501 501
                     $timezone = $field_value->getTimezone();
502 502
                     $field_value->setTimezone(new \DateTimeZone('UTC'));
503
-                    $result[$field_name . '_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
503
+                    $result[$field_name.'_gmt'] = Model_Data_Translator::prepare_field_value_for_json(
504 504
                         $field_obj,
505 505
                         $field_value,
506 506
                         $this->get_model_version_info()->requested_version()
@@ -581,9 +581,9 @@  discard block
 block discarded – undo
581 581
             && $wp_rest_server->get_route_options('/wp/v2/posts')
582 582
             && $model->has_primary_key_field()
583 583
         ) {
584
-            $links[\EED_Core_Rest_Api::ee_api_link_namespace . 'self_wp_post'] = array(
584
+            $links[\EED_Core_Rest_Api::ee_api_link_namespace.'self_wp_post'] = array(
585 585
                 array(
586
-                    'href'   => rest_url('/wp/v2/posts/' . $db_row[$model->get_primary_key_field()
586
+                    'href'   => rest_url('/wp/v2/posts/'.$db_row[$model->get_primary_key_field()
587 587
                                                                          ->get_qualified_column()]),
588 588
                     'single' => true,
589 589
                 ),
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
         if ($model->has_primary_key_field()) {
594 594
             foreach ($this->get_model_version_info()->relation_settings($model) as $relation_name => $relation_obj) {
595 595
                 $related_model_part = Read::get_related_entity_name($relation_name, $relation_obj);
596
-                $links[\EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part] = array(
596
+                $links[\EED_Core_Rest_Api::ee_api_link_namespace.$related_model_part] = array(
597 597
                     array(
598 598
                         'href'   => $this->get_versioned_link_to(
599 599
                             \EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
@@ -628,13 +628,13 @@  discard block
 block discarded – undo
628 628
         $db_row = array()
629 629
     ) {
630 630
         //if $db_row not included, hope the entity array has what we need
631
-        if (! $db_row) {
631
+        if ( ! $db_row) {
632 632
             $db_row = $entity_array;
633 633
         }
634 634
         $includes_for_this_model = $this->explode_and_get_items_prefixed_with($rest_request->get_param('include'), '');
635 635
         $includes_for_this_model = $this->_remove_model_names_from_array($includes_for_this_model);
636 636
         //if they passed in * or didn't specify any includes, return everything
637
-        if (! in_array('*', $includes_for_this_model)
637
+        if ( ! in_array('*', $includes_for_this_model)
638 638
             && ! empty($includes_for_this_model)
639 639
         ) {
640 640
             if ($model->has_primary_key_field()) {
@@ -809,7 +809,7 @@  discard block
 block discarded – undo
809 809
         $restricted_query_params['caps'] = $this->validate_context($request->get_param('caps'));
810 810
         $this->_set_debug_info('model query params', $restricted_query_params);
811 811
         $model_rows = $model->get_all_wpdb_results($restricted_query_params);
812
-        if (! empty ($model_rows)) {
812
+        if ( ! empty ($model_rows)) {
813 813
             return $this->create_entity_from_wpdb_result(
814 814
                 $model,
815 815
                 array_shift($model_rows),
@@ -818,7 +818,7 @@  discard block
 block discarded – undo
818 818
             //ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
819 819
             $lowercase_model_name = strtolower($model->get_this_model_name());
820 820
             $model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
821
-            if (! empty($model_rows_found_sans_restrictions)) {
821
+            if ( ! empty($model_rows_found_sans_restrictions)) {
822 822
                 //you got shafted- it existed but we didn't want to tell you!
823 823
                 return new \WP_Error(
824 824
                     'rest_user_cannot_read',
@@ -853,7 +853,7 @@  discard block
 block discarded – undo
853 853
      */
854 854
     public function validate_context($context)
855 855
     {
856
-        if (! $context) {
856
+        if ( ! $context) {
857 857
             $context = \EEM_Base::caps_read;
858 858
         }
859 859
         $valid_contexts = \EEM_Base::valid_cap_contexts();
@@ -879,7 +879,7 @@  discard block
 block discarded – undo
879 879
             \EEM_Base::default_where_conditions_minimum_all,
880 880
             \EEM_Base::default_where_conditions_minimum_others,
881 881
         );
882
-        if (! $default_query_params) {
882
+        if ( ! $default_query_params) {
883 883
             $default_query_params = \EEM_Base::default_where_conditions_all;
884 884
         }
885 885
         if (
@@ -964,14 +964,14 @@  discard block
 block discarded – undo
964 964
         }
965 965
         if (isset($query_parameters['limit'])) {
966 966
             //limit should be either a string like '23' or '23,43', or an array with two items in it
967
-            if (! is_array($query_parameters['limit'])) {
968
-                $limit_array = explode(',', (string)$query_parameters['limit']);
967
+            if ( ! is_array($query_parameters['limit'])) {
968
+                $limit_array = explode(',', (string) $query_parameters['limit']);
969 969
             } else {
970 970
                 $limit_array = $query_parameters['limit'];
971 971
             }
972 972
             $sanitized_limit = array();
973 973
             foreach ($limit_array as $key => $limit_part) {
974
-                if ($this->_debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
974
+                if ($this->_debug_mode && ( ! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
975 975
                     throw new \EE_Error(
976 976
                         sprintf(
977 977
                             __('An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.',
@@ -980,7 +980,7 @@  discard block
 block discarded – undo
980 980
                         )
981 981
                     );
982 982
                 }
983
-                $sanitized_limit[] = (int)$limit_part;
983
+                $sanitized_limit[] = (int) $limit_part;
984 984
             }
985 985
             $model_query_params['limit'] = implode(',', $sanitized_limit);
986 986
         } else {
@@ -1068,17 +1068,17 @@  discard block
 block discarded – undo
1068 1068
         foreach ($exploded_contents as $item) {
1069 1069
             $item = trim($item);
1070 1070
             //if no prefix was provided, so we look for items with no "." in them
1071
-            if (! $prefix) {
1071
+            if ( ! $prefix) {
1072 1072
                 //does this item have a period?
1073 1073
                 if (strpos($item, '.') === false) {
1074 1074
                     //if not, then its what we're looking for
1075 1075
                     $contents_with_prefix[] = $item;
1076 1076
                 }
1077
-            } else if (strpos($item, $prefix . '.') === 0) {
1077
+            } else if (strpos($item, $prefix.'.') === 0) {
1078 1078
                 //this item has the prefix and a period, grab it
1079 1079
                 $contents_with_prefix[] = substr(
1080 1080
                     $item,
1081
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1081
+                    strpos($item, $prefix.'.') + strlen($prefix.'.')
1082 1082
                 );
1083 1083
             } else if ($item === $prefix) {
1084 1084
                 //this item is JUST the prefix
@@ -1118,9 +1118,9 @@  discard block
 block discarded – undo
1118 1118
         if ($model_name) {
1119 1119
             foreach ($includes as $field_to_include) {
1120 1120
                 $field_to_include = trim($field_to_include);
1121
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1121
+                if (strpos($field_to_include, $model_name.'.') === 0) {
1122 1122
                     //found the model name at the exact start
1123
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1123
+                    $field_sans_model_name = str_replace($model_name.'.', '', $field_to_include);
1124 1124
                     $extracted_fields_to_include[] = $field_sans_model_name;
1125 1125
                 } elseif ($field_to_include == $model_name) {
1126 1126
                     $extracted_fields_to_include[] = '*';
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +18 added lines, -16 removed lines patch added patch discarded remove patch
@@ -961,7 +961,7 @@  discard block
 block discarded – undo
961 961
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
962 962
      * foreign key to the WP_User table)
963 963
      *
964
-     * @return string|boolean string on success, boolean false when there is no
964
+     * @return string|false string on success, boolean false when there is no
965 965
      * foreign key to the WP_User table
966 966
      */
967 967
     public function wp_user_field_name()
@@ -1067,7 +1067,7 @@  discard block
 block discarded – undo
1067 1067
      *
1068 1068
      * @param array  $query_params      like EEM_Base::get_all's $query_params
1069 1069
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1070
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1071 1071
      *                                  fields on the model, and the models we joined to in the query. However, you can
1072 1072
      *                                  override this and set the select to "*", or a specific column name, like
1073 1073
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1459,7 +1459,7 @@  discard block
 block discarded – undo
1459 1459
      * @param string $field_name The name of the field the formats are being retrieved for.
1460 1460
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1461 1461
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1462
-     * @return array formats in an array with the date format first, and the time format last.
1462
+     * @return string[] formats in an array with the date format first, and the time format last.
1463 1463
      */
1464 1464
     public function get_formats_for($field_name, $pretty = false)
1465 1465
     {
@@ -1492,7 +1492,7 @@  discard block
 block discarded – undo
1492 1492
      *                                 be returned.
1493 1493
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1494 1494
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1495
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1495
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1496 1496
      *                                 exception is triggered.
1497 1497
      */
1498 1498
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1830,7 +1830,7 @@  discard block
 block discarded – undo
1830 1830
      * Wrapper for EEM_Base::delete_permanently()
1831 1831
      *
1832 1832
      * @param mixed $id
1833
-     * @return boolean whether the row got deleted or not
1833
+     * @return integer whether the row got deleted or not
1834 1834
      * @throws \EE_Error
1835 1835
      */
1836 1836
     public function delete_permanently_by_ID($id)
@@ -1850,7 +1850,7 @@  discard block
 block discarded – undo
1850 1850
      * Wrapper for EEM_Base::delete()
1851 1851
      *
1852 1852
      * @param mixed $id
1853
-     * @return boolean whether the row got deleted or not
1853
+     * @return integer whether the row got deleted or not
1854 1854
      * @throws \EE_Error
1855 1855
      */
1856 1856
     public function delete_by_ID($id)
@@ -2300,7 +2300,7 @@  discard block
 block discarded – undo
2300 2300
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2301 2301
      * EEM_Base::$_db_verification_level
2302 2302
      *
2303
-     * @param $wpdb_method
2303
+     * @param string $wpdb_method
2304 2304
      * @param $arguments_to_provide
2305 2305
      * @return string
2306 2306
      */
@@ -2424,6 +2424,7 @@  discard block
 block discarded – undo
2424 2424
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2425 2425
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2426 2426
      *                             because these will be inserted in any new rows created as well.
2427
+     * @param EE_Base_Class $id_or_obj
2427 2428
      */
2428 2429
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2429 2430
     {
@@ -2434,7 +2435,7 @@  discard block
 block discarded – undo
2434 2435
 
2435 2436
 
2436 2437
     /**
2437
-     * @param mixed           $id_or_obj
2438
+     * @param EE_Base_Class           $id_or_obj
2438 2439
      * @param string          $relationName
2439 2440
      * @param array           $where_query_params
2440 2441
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2475,7 +2476,7 @@  discard block
 block discarded – undo
2475 2476
      * However, if the model objects can't be deleted because of blocking related model objects, then
2476 2477
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2477 2478
      *
2478
-     * @param EE_Base_Class|int|string $id_or_obj
2479
+     * @param EE_Base_Class $id_or_obj
2479 2480
      * @param string                   $model_name
2480 2481
      * @param array                    $query_params
2481 2482
      * @return int how many deleted
@@ -2496,7 +2497,7 @@  discard block
 block discarded – undo
2496 2497
      * the model objects can't be hard deleted because of blocking related model objects,
2497 2498
      * just does a soft-delete on them instead.
2498 2499
      *
2499
-     * @param EE_Base_Class|int|string $id_or_obj
2500
+     * @param EE_Base_Class $id_or_obj
2500 2501
      * @param string                   $model_name
2501 2502
      * @param array                    $query_params
2502 2503
      * @return int how many deleted
@@ -2553,6 +2554,7 @@  discard block
 block discarded – undo
2553 2554
      * @param string $model_name   like 'Event', or 'Registration'
2554 2555
      * @param array  $query_params like EEM_Base::get_all's
2555 2556
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2557
+     * @param EE_Base_Class $id_or_obj
2556 2558
      * @return float
2557 2559
      * @throws \EE_Error
2558 2560
      */
@@ -3023,7 +3025,7 @@  discard block
 block discarded – undo
3023 3025
      * Finds all the fields that correspond to the given table
3024 3026
      *
3025 3027
      * @param string $table_alias , array key in EEM_Base::_tables
3026
-     * @return EE_Model_Field_Base[]
3028
+     * @return EE_Model_Field_Base
3027 3029
      */
3028 3030
     public function _get_fields_for_table($table_alias)
3029 3031
     {
@@ -3508,7 +3510,7 @@  discard block
 block discarded – undo
3508 3510
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3509 3511
      * We should use default where conditions on related models when they requested to use default where conditions
3510 3512
      * on all models, or specifically just on other related models
3511
-     * @param      $default_where_conditions_value
3513
+     * @param      string $default_where_conditions_value
3512 3514
      * @param bool $for_this_model false means this is for OTHER related models
3513 3515
      * @return bool
3514 3516
      */
@@ -3546,7 +3548,7 @@  discard block
 block discarded – undo
3546 3548
      * where conditions.
3547 3549
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3548 3550
      * on this model or others
3549
-     * @param      $default_where_conditions_value
3551
+     * @param      string $default_where_conditions_value
3550 3552
      * @param bool $for_this_model false means this is for OTHER related models
3551 3553
      * @return bool
3552 3554
      */
@@ -4536,7 +4538,7 @@  discard block
 block discarded – undo
4536 4538
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4537 4539
      * Eg, on EE_Answer that would be ANS_ID field object
4538 4540
      *
4539
-     * @param $field_obj
4541
+     * @param EE_Model_Field_Base $field_obj
4540 4542
      * @return boolean
4541 4543
      */
4542 4544
     public function is_primary_key_field($field_obj)
@@ -4647,7 +4649,7 @@  discard block
 block discarded – undo
4647 4649
      * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4648 4650
      *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4649 4651
      *                            Either one works
4650
-     * @return EE_Table_Base
4652
+     * @return string
4651 4653
      */
4652 4654
     public function get_table_for_alias($table_alias)
4653 4655
     {
@@ -5258,7 +5260,7 @@  discard block
 block discarded – undo
5258 5260
     /**
5259 5261
      * Read comments for assume_values_already_prepared_by_model_object()
5260 5262
      *
5261
-     * @return int
5263
+     * @return boolean
5262 5264
      */
5263 5265
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5264 5266
     {
Please login to merge, or discard this patch.
Indentation   +5719 added lines, -5719 removed lines patch added patch discarded remove patch
@@ -29,5727 +29,5727 @@
 block discarded – undo
29 29
 abstract class EEM_Base extends EE_Base
30 30
 {
31 31
 
32
-    //admin posty
33
-    //basic -> grants access to mine -> if they don't have it, select none
34
-    //*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
-    //*_published -> grants access to published -> if they dont have it, select non-published
37
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
39
-    //frontend posty
40
-    //by default has access to published
41
-    //basic -> grants access to mine that arent published, and all published
42
-    //*_others ->grants access to others that arent private, all mine
43
-    //*_private -> grants full access
44
-    //frontend non-posty
45
-    //like admin posty
46
-    //category-y
47
-    //assign -> grants access to join-table
48
-    //(delete, edit)
49
-    //payment-method-y
50
-    //for each registered payment method,
51
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
-    /**
53
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
-     * They almost always WILL NOT, but it's not necessarily a requirement.
56
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
-     *
58
-     * @var boolean
59
-     */
60
-    private $_values_already_prepared_by_model_object = 0;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the data is just like form input that needs to have the model fields'
65
-     * prepare_for_set and prepare_for_use_in_db called on it
66
-     */
67
-    const not_prepared_by_model_object = 0;
68
-
69
-    /**
70
-     * when $_values_already_prepared_by_model_object equals this, we
71
-     * assume this value is coming from a model object and doesn't need to have
72
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
73
-     */
74
-    const prepared_by_model_object = 1;
75
-
76
-    /**
77
-     * when $_values_already_prepared_by_model_object equals this, we assume
78
-     * the values are already to be used in the database (ie no processing is done
79
-     * on them by the model's fields)
80
-     */
81
-    const prepared_for_use_in_db = 2;
82
-
83
-
84
-    protected $singular_item = 'Item';
85
-
86
-    protected $plural_item   = 'Items';
87
-
88
-    /**
89
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
-     */
91
-    protected $_tables;
92
-
93
-    /**
94
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
-     *
98
-     * @var \EE_Model_Field_Base[] $_fields
99
-     */
100
-    protected $_fields;
101
-
102
-    /**
103
-     * array of different kinds of relations
104
-     *
105
-     * @var \EE_Model_Relation_Base[] $_model_relations
106
-     */
107
-    protected $_model_relations;
108
-
109
-    /**
110
-     * @var \EE_Index[] $_indexes
111
-     */
112
-    protected $_indexes = array();
113
-
114
-    /**
115
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
116
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
-     * by setting the same columns as used in these queries in the query yourself.
118
-     *
119
-     * @var EE_Default_Where_Conditions
120
-     */
121
-    protected $_default_where_conditions_strategy;
122
-
123
-    /**
124
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
-     * This is particularly useful when you want something between 'none' and 'default'
126
-     *
127
-     * @var EE_Default_Where_Conditions
128
-     */
129
-    protected $_minimum_where_conditions_strategy;
130
-
131
-    /**
132
-     * String describing how to find the "owner" of this model's objects.
133
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
-     * But when there isn't, this indicates which related model, or transiently-related model,
135
-     * has the foreign key to the wp_users table.
136
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
-     * related to events, and events have a foreign key to wp_users.
138
-     * On EEM_Transaction, this would be 'Transaction.Event'
139
-     *
140
-     * @var string
141
-     */
142
-    protected $_model_chain_to_wp_user = '';
143
-
144
-    /**
145
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
-     * don't need it (particularly CPT models)
147
-     *
148
-     * @var bool
149
-     */
150
-    protected $_ignore_where_strategy = false;
151
-
152
-    /**
153
-     * String used in caps relating to this model. Eg, if the caps relating to this
154
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
-     *
156
-     * @var string. If null it hasn't been initialized yet. If false then we
157
-     * have indicated capabilities don't apply to this
158
-     */
159
-    protected $_caps_slug = null;
160
-
161
-    /**
162
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
-     * and next-level keys are capability names, and each's value is a
164
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
-     * they specify which context to use (ie, frontend, backend, edit or delete)
166
-     * and then each capability in the corresponding sub-array that they're missing
167
-     * adds the where conditions onto the query.
168
-     *
169
-     * @var array
170
-     */
171
-    protected $_cap_restrictions = array(
172
-        self::caps_read       => array(),
173
-        self::caps_read_admin => array(),
174
-        self::caps_edit       => array(),
175
-        self::caps_delete     => array(),
176
-    );
177
-
178
-    /**
179
-     * Array defining which cap restriction generators to use to create default
180
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
181
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
-     * automatically set this to false (not just null).
184
-     *
185
-     * @var EE_Restriction_Generator_Base[]
186
-     */
187
-    protected $_cap_restriction_generators = array();
188
-
189
-    /**
190
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
-     */
192
-    const caps_read       = 'read';
193
-
194
-    const caps_read_admin = 'read_admin';
195
-
196
-    const caps_edit       = 'edit';
197
-
198
-    const caps_delete     = 'delete';
199
-
200
-    /**
201
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
-     * maps to 'read' because when looking for relevant permissions we're going to use
204
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
205
-     *
206
-     * @var array
207
-     */
208
-    protected $_cap_contexts_to_cap_action_map = array(
209
-        self::caps_read       => 'read',
210
-        self::caps_read_admin => 'read',
211
-        self::caps_edit       => 'edit',
212
-        self::caps_delete     => 'delete',
213
-    );
214
-
215
-    /**
216
-     * Timezone
217
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
-     * EE_Datetime_Field data type will have access to it.
221
-     *
222
-     * @var string
223
-     */
224
-    protected $_timezone;
225
-
226
-
227
-    /**
228
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
-     * multisite.
230
-     *
231
-     * @var int
232
-     */
233
-    protected static $_model_query_blog_id;
234
-
235
-    /**
236
-     * A copy of _fields, except the array keys are the model names pointed to by
237
-     * the field
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cache_foreign_key_to_fields = array();
242
-
243
-    /**
244
-     * Cached list of all the fields on the model, indexed by their name
245
-     *
246
-     * @var EE_Model_Field_Base[]
247
-     */
248
-    private $_cached_fields = null;
249
-
250
-    /**
251
-     * Cached list of all the fields on the model, except those that are
252
-     * marked as only pertinent to the database
253
-     *
254
-     * @var EE_Model_Field_Base[]
255
-     */
256
-    private $_cached_fields_non_db_only = null;
257
-
258
-    /**
259
-     * A cached reference to the primary key for quick lookup
260
-     *
261
-     * @var EE_Model_Field_Base
262
-     */
263
-    private $_primary_key_field = null;
264
-
265
-    /**
266
-     * Flag indicating whether this model has a primary key or not
267
-     *
268
-     * @var boolean
269
-     */
270
-    protected $_has_primary_key_field = null;
271
-
272
-    /**
273
-     * Whether or not this model is based off a table in WP core only (CPTs should set
274
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
-     *
276
-     * @var boolean
277
-     */
278
-    protected $_wp_core_model = false;
279
-
280
-    /**
281
-     *    List of valid operators that can be used for querying.
282
-     * The keys are all operators we'll accept, the values are the real SQL
283
-     * operators used
284
-     *
285
-     * @var array
286
-     */
287
-    protected $_valid_operators = array(
288
-        '='           => '=',
289
-        '<='          => '<=',
290
-        '<'           => '<',
291
-        '>='          => '>=',
292
-        '>'           => '>',
293
-        '!='          => '!=',
294
-        'LIKE'        => 'LIKE',
295
-        'like'        => 'LIKE',
296
-        'NOT_LIKE'    => 'NOT LIKE',
297
-        'not_like'    => 'NOT LIKE',
298
-        'NOT LIKE'    => 'NOT LIKE',
299
-        'not like'    => 'NOT LIKE',
300
-        'IN'          => 'IN',
301
-        'in'          => 'IN',
302
-        'NOT_IN'      => 'NOT IN',
303
-        'not_in'      => 'NOT IN',
304
-        'NOT IN'      => 'NOT IN',
305
-        'not in'      => 'NOT IN',
306
-        'between'     => 'BETWEEN',
307
-        'BETWEEN'     => 'BETWEEN',
308
-        'IS_NOT_NULL' => 'IS NOT NULL',
309
-        'is_not_null' => 'IS NOT NULL',
310
-        'IS NOT NULL' => 'IS NOT NULL',
311
-        'is not null' => 'IS NOT NULL',
312
-        'IS_NULL'     => 'IS NULL',
313
-        'is_null'     => 'IS NULL',
314
-        'IS NULL'     => 'IS NULL',
315
-        'is null'     => 'IS NULL',
316
-        'REGEXP'      => 'REGEXP',
317
-        'regexp'      => 'REGEXP',
318
-        'NOT_REGEXP'  => 'NOT REGEXP',
319
-        'not_regexp'  => 'NOT REGEXP',
320
-        'NOT REGEXP'  => 'NOT REGEXP',
321
-        'not regexp'  => 'NOT REGEXP',
322
-    );
323
-
324
-    /**
325
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
-     *
327
-     * @var array
328
-     */
329
-    protected $_in_style_operators = array('IN', 'NOT IN');
330
-
331
-    /**
332
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
-     * '12-31-2012'"
334
-     *
335
-     * @var array
336
-     */
337
-    protected $_between_style_operators = array('BETWEEN');
338
-
339
-    /**
340
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
-     * on a join table.
342
-     *
343
-     * @var array
344
-     */
345
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
-
347
-    /**
348
-     * Allowed values for $query_params['order'] for ordering in queries
349
-     *
350
-     * @var array
351
-     */
352
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
-
354
-    /**
355
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
357
-     *
358
-     * @var array
359
-     */
360
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
-
362
-    /**
363
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
365
-     *
366
-     * @var array
367
-     */
368
-    private $_allowed_query_params = array(
369
-        0,
370
-        'limit',
371
-        'order_by',
372
-        'group_by',
373
-        'having',
374
-        'force_join',
375
-        'order',
376
-        'on_join_limit',
377
-        'default_where_conditions',
378
-        'caps',
379
-    );
380
-
381
-    /**
382
-     * All the data types that can be used in $wpdb->prepare statements.
383
-     *
384
-     * @var array
385
-     */
386
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
-
388
-    /**
389
-     *    EE_Registry Object
390
-     *
391
-     * @var    object
392
-     * @access    protected
393
-     */
394
-    protected $EE = null;
395
-
396
-
397
-    /**
398
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
-     *
400
-     * @var int
401
-     */
402
-    protected $_show_next_x_db_queries = 0;
403
-
404
-    /**
405
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
-     *
408
-     * @var array
409
-     */
410
-    protected $_custom_selections = array();
411
-
412
-    /**
413
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
-     * caches every model object we've fetched from the DB on this request
415
-     *
416
-     * @var array
417
-     */
418
-    protected $_entity_map;
419
-
420
-    /**
421
-     * constant used to show EEM_Base has not yet verified the db on this http request
422
-     */
423
-    const db_verified_none = 0;
424
-
425
-    /**
426
-     * constant used to show EEM_Base has verified the EE core db on this http request,
427
-     * but not the addons' dbs
428
-     */
429
-    const db_verified_core = 1;
430
-
431
-    /**
432
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
-     * the EE core db too)
434
-     */
435
-    const db_verified_addons = 2;
436
-
437
-    /**
438
-     * indicates whether an EEM_Base child has already re-verified the DB
439
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
440
-     * looking like EEM_Base::db_verified_*
441
-     *
442
-     * @var int - 0 = none, 1 = core, 2 = addons
443
-     */
444
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
445
-
446
-    /**
447
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
448
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
449
-     *        registrations for non-trashed tickets for non-trashed datetimes)
450
-     */
451
-    const default_where_conditions_all = 'all';
452
-
453
-    /**
454
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
455
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
456
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
457
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
458
-     *        models which share tables with other models, this can return data for the wrong model.
459
-     */
460
-    const default_where_conditions_this_only = 'this_model_only';
461
-
462
-    /**
463
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
464
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
465
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
466
-     */
467
-    const default_where_conditions_others_only = 'other_models_only';
468
-
469
-    /**
470
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
471
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
472
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
473
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
474
-     *        (regardless of whether those events and venues are trashed)
475
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
476
-     *        events.
477
-     */
478
-    const default_where_conditions_minimum_all = 'minimum';
479
-
480
-    /**
481
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
482
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
483
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
484
-     *        not)
485
-     */
486
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
487
-
488
-    /**
489
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
490
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
491
-     *        it's possible it will return table entries for other models. You should use
492
-     *        EEM_Base::default_where_conditions_minimum_all instead.
493
-     */
494
-    const default_where_conditions_none = 'none';
495
-
496
-
497
-
498
-    /**
499
-     * About all child constructors:
500
-     * they should define the _tables, _fields and _model_relations arrays.
501
-     * Should ALWAYS be called after child constructor.
502
-     * In order to make the child constructors to be as simple as possible, this parent constructor
503
-     * finalizes constructing all the object's attributes.
504
-     * Generally, rather than requiring a child to code
505
-     * $this->_tables = array(
506
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
507
-     *        ...);
508
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
509
-     * each EE_Table has a function to set the table's alias after the constructor, using
510
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
511
-     * do something similar.
512
-     *
513
-     * @param null $timezone
514
-     * @throws \EE_Error
515
-     */
516
-    protected function __construct($timezone = null)
517
-    {
518
-        // check that the model has not been loaded too soon
519
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
520
-            throw new EE_Error (
521
-                sprintf(
522
-                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
523
-                        'event_espresso'),
524
-                    get_class($this)
525
-                )
526
-            );
527
-        }
528
-        /**
529
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
530
-         */
531
-        if (empty(EEM_Base::$_model_query_blog_id)) {
532
-            EEM_Base::set_model_query_blog_id();
533
-        }
534
-        /**
535
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
536
-         * just use EE_Register_Model_Extension
537
-         *
538
-         * @var EE_Table_Base[] $_tables
539
-         */
540
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
541
-        foreach ($this->_tables as $table_alias => $table_obj) {
542
-            /** @var $table_obj EE_Table_Base */
543
-            $table_obj->_construct_finalize_with_alias($table_alias);
544
-            if ($table_obj instanceof EE_Secondary_Table) {
545
-                /** @var $table_obj EE_Secondary_Table */
546
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
547
-            }
548
-        }
549
-        /**
550
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
551
-         * EE_Register_Model_Extension
552
-         *
553
-         * @param EE_Model_Field_Base[] $_fields
554
-         */
555
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
556
-        $this->_invalidate_field_caches();
557
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
558
-            if (! array_key_exists($table_alias, $this->_tables)) {
559
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
560
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
561
-            }
562
-            foreach ($fields_for_table as $field_name => $field_obj) {
563
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
564
-                //primary key field base has a slightly different _construct_finalize
565
-                /** @var $field_obj EE_Model_Field_Base */
566
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
567
-            }
568
-        }
569
-        // everything is related to Extra_Meta
570
-        if (get_class($this) !== 'EEM_Extra_Meta') {
571
-            //make extra meta related to everything, but don't block deleting things just
572
-            //because they have related extra meta info. For now just orphan those extra meta
573
-            //in the future we should automatically delete them
574
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
575
-        }
576
-        //and change logs
577
-        if (get_class($this) !== 'EEM_Change_Log') {
578
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
579
-        }
580
-        /**
581
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
582
-         * EE_Register_Model_Extension
583
-         *
584
-         * @param EE_Model_Relation_Base[] $_model_relations
585
-         */
586
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
587
-            $this->_model_relations);
588
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
589
-            /** @var $relation_obj EE_Model_Relation_Base */
590
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
591
-        }
592
-        foreach ($this->_indexes as $index_name => $index_obj) {
593
-            /** @var $index_obj EE_Index */
594
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
595
-        }
596
-        $this->set_timezone($timezone);
597
-        //finalize default where condition strategy, or set default
598
-        if (! $this->_default_where_conditions_strategy) {
599
-            //nothing was set during child constructor, so set default
600
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
601
-        }
602
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
603
-        if (! $this->_minimum_where_conditions_strategy) {
604
-            //nothing was set during child constructor, so set default
605
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
606
-        }
607
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
608
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
609
-        //to indicate to NOT set it, set it to the logical default
610
-        if ($this->_caps_slug === null) {
611
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
612
-        }
613
-        //initialize the standard cap restriction generators if none were specified by the child constructor
614
-        if ($this->_cap_restriction_generators !== false) {
615
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
616
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
617
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
618
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
619
-                        new EE_Restriction_Generator_Protected(),
620
-                        $cap_context,
621
-                        $this
622
-                    );
623
-                }
624
-            }
625
-        }
626
-        //if there are cap restriction generators, use them to make the default cap restrictions
627
-        if ($this->_cap_restriction_generators !== false) {
628
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
629
-                if (! $generator_object) {
630
-                    continue;
631
-                }
632
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
633
-                    throw new EE_Error(
634
-                        sprintf(
635
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
636
-                                'event_espresso'),
637
-                            $context,
638
-                            $this->get_this_model_name()
639
-                        )
640
-                    );
641
-                }
642
-                $action = $this->cap_action_for_context($context);
643
-                if (! $generator_object->construction_finalized()) {
644
-                    $generator_object->_construct_finalize($this, $action);
645
-                }
646
-            }
647
-        }
648
-        do_action('AHEE__' . get_class($this) . '__construct__end');
649
-    }
650
-
651
-
652
-
653
-    /**
654
-     * Generates the cap restrictions for the given context, or if they were
655
-     * already generated just gets what's cached
656
-     *
657
-     * @param string $context one of EEM_Base::valid_cap_contexts()
658
-     * @return EE_Default_Where_Conditions[]
659
-     */
660
-    protected function _generate_cap_restrictions($context)
661
-    {
662
-        if (isset($this->_cap_restriction_generators[$context])
663
-            && $this->_cap_restriction_generators[$context]
664
-               instanceof
665
-               EE_Restriction_Generator_Base
666
-        ) {
667
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
668
-        } else {
669
-            return array();
670
-        }
671
-    }
672
-
673
-
674
-
675
-    /**
676
-     * Used to set the $_model_query_blog_id static property.
677
-     *
678
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
679
-     *                      value for get_current_blog_id() will be used.
680
-     */
681
-    public static function set_model_query_blog_id($blog_id = 0)
682
-    {
683
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
684
-    }
685
-
686
-
687
-
688
-    /**
689
-     * Returns whatever is set as the internal $model_query_blog_id.
690
-     *
691
-     * @return int
692
-     */
693
-    public static function get_model_query_blog_id()
694
-    {
695
-        return EEM_Base::$_model_query_blog_id;
696
-    }
697
-
698
-
699
-
700
-    /**
701
-     *        This function is a singleton method used to instantiate the Espresso_model object
702
-     *
703
-     * @access public
704
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
705
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
706
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
707
-     *                         timezone in the 'timezone_string' wp option)
708
-     * @return static (as in the concrete child class)
709
-     */
710
-    public static function instance($timezone = null)
711
-    {
712
-        // check if instance of Espresso_model already exists
713
-        if (! static::$_instance instanceof static) {
714
-            // instantiate Espresso_model
715
-            static::$_instance = new static($timezone);
716
-        }
717
-        //we might have a timezone set, let set_timezone decide what to do with it
718
-        static::$_instance->set_timezone($timezone);
719
-        // Espresso_model object
720
-        return static::$_instance;
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * resets the model and returns it
727
-     *
728
-     * @param null | string $timezone
729
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
730
-     * all its properties reset; if it wasn't instantiated, returns null)
731
-     */
732
-    public static function reset($timezone = null)
733
-    {
734
-        if (static::$_instance instanceof EEM_Base) {
735
-            //let's try to NOT swap out the current instance for a new one
736
-            //because if someone has a reference to it, we can't remove their reference
737
-            //so it's best to keep using the same reference, but change the original object
738
-            //reset all its properties to their original values as defined in the class
739
-            $r = new ReflectionClass(get_class(static::$_instance));
740
-            $static_properties = $r->getStaticProperties();
741
-            foreach ($r->getDefaultProperties() as $property => $value) {
742
-                //don't set instance to null like it was originally,
743
-                //but it's static anyways, and we're ignoring static properties (for now at least)
744
-                if (! isset($static_properties[$property])) {
745
-                    static::$_instance->{$property} = $value;
746
-                }
747
-            }
748
-            //and then directly call its constructor again, like we would if we
749
-            //were creating a new one
750
-            static::$_instance->__construct($timezone);
751
-            return self::instance();
752
-        }
753
-        return null;
754
-    }
755
-
756
-
757
-
758
-    /**
759
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
760
-     *
761
-     * @param  boolean $translated return localized strings or JUST the array.
762
-     * @return array
763
-     * @throws \EE_Error
764
-     */
765
-    public function status_array($translated = false)
766
-    {
767
-        if (! array_key_exists('Status', $this->_model_relations)) {
768
-            return array();
769
-        }
770
-        $model_name = $this->get_this_model_name();
771
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
772
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
773
-        $status_array = array();
774
-        foreach ($stati as $status) {
775
-            $status_array[$status->ID()] = $status->get('STS_code');
776
-        }
777
-        return $translated
778
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
779
-            : $status_array;
780
-    }
781
-
782
-
783
-
784
-    /**
785
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
786
-     *
787
-     * @param array $query_params             {
788
-     * @var array $0 (where) array {
789
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
790
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
791
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
792
-     *                                        conditions based on related models (and even
793
-     *                                        models-related-to-related-models) prepend the model's name onto the field
794
-     *                                        name. Eg,
795
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
796
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
797
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
798
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
799
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
800
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
801
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
802
-     *                                        to Venues (even when each of those models actually consisted of two
803
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
804
-     *                                        just having
805
-     *                                        "Venue.VNU_ID", you could have
806
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
807
-     *                                        events are related to Registrations, which are related to Attendees). You
808
-     *                                        can take it even further with
809
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
810
-     *                                        (from the default of '='), change the value to an numerically-indexed
811
-     *                                        array, where the first item in the list is the operator. eg: array(
812
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
813
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
814
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
815
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
816
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
817
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
818
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
819
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
820
-     *                                        the value is a field, simply provide a third array item (true) to the
821
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
822
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
823
-     *                                        Note: you can also use related model field names like you would any other
824
-     *                                        field name. eg:
825
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
826
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
827
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
828
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
829
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
830
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
831
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
832
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
833
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
834
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
835
-     *                                        "stick" until you specify an AND. eg
836
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
837
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
838
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
839
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
840
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
841
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
842
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
843
-     *                                        too, eg:
844
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
845
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
846
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
847
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
848
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
849
-     *                                        the OFFSET, the 2nd is the LIMIT
850
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
851
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
852
-     *                                        following format array('on_join_limit'
853
-     *                                        => array( 'table_alias', array(1,2) ) ).
854
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
855
-     *                                        values are either 'ASC' or 'DESC'.
856
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
857
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
858
-     *                                        DESC..." respectively. Like the
859
-     *                                        'where' conditions, these fields can be on related models. Eg
860
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
861
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
862
-     *                                        Attendee, Price, Datetime, etc.)
863
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
864
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
865
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
866
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
867
-     *                                        order by the primary key. Eg,
868
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
869
-     *                                        //(will join with the Datetime model's table(s) and order by its field
870
-     *                                        DTT_EVT_start) or
871
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
872
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
873
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
874
-     *                                        'group_by'=>'VNU_ID', or
875
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
876
-     *                                        if no
877
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
878
-     *                                        model's primary key (or combined primary keys). This avoids some
879
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
880
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
881
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
882
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
883
-     *                                        results)
884
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
885
-     *                                        array where values are models to be joined in the query.Eg
886
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
887
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
888
-     *                                        probably only want to do this in hopes of increasing efficiency, as
889
-     *                                        related models which belongs to the current model
890
-     *                                        (ie, the current model has a foreign key to them, like how Registration
891
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
892
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
893
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
894
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
895
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
896
-     *                                        default where conditions set it to 'other_models_only'. If you only want
897
-     *                                        this model's default where conditions added to the query, use
898
-     *                                        'this_model_only'. If you want to use all default where conditions
899
-     *                                        (default), set to 'all'.
900
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
901
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
902
-     *                                        everything? Or should we only show the current user items they should be
903
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
904
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
905
-     *                                        }
906
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
907
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
908
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
909
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
910
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
911
-     *                                        array( array(
912
-     *                                        'OR'=>array(
913
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
914
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
915
-     *                                        )
916
-     *                                        ),
917
-     *                                        'limit'=>10,
918
-     *                                        'group_by'=>'TXN_ID'
919
-     *                                        ));
920
-     *                                        get all the answers to the question titled "shirt size" for event with id
921
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
922
-     *                                        'Question.QST_display_text'=>'shirt size',
923
-     *                                        'Registration.Event.EVT_ID'=>12
924
-     *                                        ),
925
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
926
-     *                                        ));
927
-     * @throws \EE_Error
928
-     */
929
-    public function get_all($query_params = array())
930
-    {
931
-        if (isset($query_params['limit'])
932
-            && ! isset($query_params['group_by'])
933
-        ) {
934
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
935
-        }
936
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
937
-    }
938
-
939
-
940
-
941
-    /**
942
-     * Modifies the query parameters so we only get back model objects
943
-     * that "belong" to the current user
944
-     *
945
-     * @param array $query_params @see EEM_Base::get_all()
946
-     * @return array like EEM_Base::get_all
947
-     */
948
-    public function alter_query_params_to_only_include_mine($query_params = array())
949
-    {
950
-        $wp_user_field_name = $this->wp_user_field_name();
951
-        if ($wp_user_field_name) {
952
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
953
-        }
954
-        return $query_params;
955
-    }
956
-
957
-
958
-
959
-    /**
960
-     * Returns the name of the field's name that points to the WP_User table
961
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
962
-     * foreign key to the WP_User table)
963
-     *
964
-     * @return string|boolean string on success, boolean false when there is no
965
-     * foreign key to the WP_User table
966
-     */
967
-    public function wp_user_field_name()
968
-    {
969
-        try {
970
-            if (! empty($this->_model_chain_to_wp_user)) {
971
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
972
-                $last_model_name = end($models_to_follow_to_wp_users);
973
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
974
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
975
-            } else {
976
-                $model_with_fk_to_wp_users = $this;
977
-                $model_chain_to_wp_user = '';
978
-            }
979
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
980
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
981
-        } catch (EE_Error $e) {
982
-            return false;
983
-        }
984
-    }
985
-
986
-
987
-
988
-    /**
989
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
990
-     * (or transiently-related model) has a foreign key to the wp_users table;
991
-     * useful for finding if model objects of this type are 'owned' by the current user.
992
-     * This is an empty string when the foreign key is on this model and when it isn't,
993
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
994
-     * (or transiently-related model)
995
-     *
996
-     * @return string
997
-     */
998
-    public function model_chain_to_wp_user()
999
-    {
1000
-        return $this->_model_chain_to_wp_user;
1001
-    }
1002
-
1003
-
1004
-
1005
-    /**
1006
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1007
-     * like how registrations don't have a foreign key to wp_users, but the
1008
-     * events they are for are), or is unrelated to wp users.
1009
-     * generally available
1010
-     *
1011
-     * @return boolean
1012
-     */
1013
-    public function is_owned()
1014
-    {
1015
-        if ($this->model_chain_to_wp_user()) {
1016
-            return true;
1017
-        } else {
1018
-            try {
1019
-                $this->get_foreign_key_to('WP_User');
1020
-                return true;
1021
-            } catch (EE_Error $e) {
1022
-                return false;
1023
-            }
1024
-        }
1025
-    }
1026
-
1027
-
1028
-
1029
-    /**
1030
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1031
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1032
-     * the model)
1033
-     *
1034
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1035
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1037
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1038
-     *                                  override this and set the select to "*", or a specific column name, like
1039
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
-     *                                  the aliases used to refer to this selection, and values are to be
1042
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
-     * @throws \EE_Error
1046
-     */
1047
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1048
-    {
1049
-        // remember the custom selections, if any, and type cast as array
1050
-        // (unless $columns_to_select is an object, then just set as an empty array)
1051
-        // Note: (array) 'some string' === array( 'some string' )
1052
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1053
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1054
-        $select_expressions = $columns_to_select !== null
1055
-            ? $this->_construct_select_from_input($columns_to_select)
1056
-            : $this->_construct_default_select_sql($model_query_info);
1057
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1058
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1059
-    }
1060
-
1061
-
1062
-
1063
-    /**
1064
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1065
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1066
-     * take care of joins, field preparation etc.
1067
-     *
1068
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1069
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1070
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1071
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1072
-     *                                  override this and set the select to "*", or a specific column name, like
1073
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1074
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1075
-     *                                  the aliases used to refer to this selection, and values are to be
1076
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1077
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1078
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1079
-     * @throws \EE_Error
1080
-     */
1081
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1082
-    {
1083
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1084
-    }
1085
-
1086
-
1087
-
1088
-    /**
1089
-     * For creating a custom select statement
1090
-     *
1091
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1092
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1093
-     *                                 SQL, and 1=>is the datatype
1094
-     * @throws EE_Error
1095
-     * @return string
1096
-     */
1097
-    private function _construct_select_from_input($columns_to_select)
1098
-    {
1099
-        if (is_array($columns_to_select)) {
1100
-            $select_sql_array = array();
1101
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1102
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1103
-                    throw new EE_Error(
1104
-                        sprintf(
1105
-                            __(
1106
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1107
-                                "event_espresso"
1108
-                            ),
1109
-                            $selection_and_datatype,
1110
-                            $alias
1111
-                        )
1112
-                    );
1113
-                }
1114
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1115
-                    throw new EE_Error(
1116
-                        sprintf(
1117
-                            __(
1118
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1119
-                                "event_espresso"
1120
-                            ),
1121
-                            $selection_and_datatype[1],
1122
-                            $selection_and_datatype[0],
1123
-                            $alias,
1124
-                            implode(",", $this->_valid_wpdb_data_types)
1125
-                        )
1126
-                    );
1127
-                }
1128
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1129
-            }
1130
-            $columns_to_select_string = implode(", ", $select_sql_array);
1131
-        } else {
1132
-            $columns_to_select_string = $columns_to_select;
1133
-        }
1134
-        return $columns_to_select_string;
1135
-    }
1136
-
1137
-
1138
-
1139
-    /**
1140
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1141
-     *
1142
-     * @return string
1143
-     * @throws \EE_Error
1144
-     */
1145
-    public function primary_key_name()
1146
-    {
1147
-        return $this->get_primary_key_field()->get_name();
1148
-    }
1149
-
1150
-
1151
-
1152
-    /**
1153
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1154
-     * If there is no primary key on this model, $id is treated as primary key string
1155
-     *
1156
-     * @param mixed $id int or string, depending on the type of the model's primary key
1157
-     * @return EE_Base_Class
1158
-     */
1159
-    public function get_one_by_ID($id)
1160
-    {
1161
-        if ($this->get_from_entity_map($id)) {
1162
-            return $this->get_from_entity_map($id);
1163
-        }
1164
-        return $this->get_one(
1165
-            $this->alter_query_params_to_restrict_by_ID(
1166
-                $id,
1167
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1168
-            )
1169
-        );
1170
-    }
1171
-
1172
-
1173
-
1174
-    /**
1175
-     * Alters query parameters to only get items with this ID are returned.
1176
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1177
-     * or could just be a simple primary key ID
1178
-     *
1179
-     * @param int   $id
1180
-     * @param array $query_params
1181
-     * @return array of normal query params, @see EEM_Base::get_all
1182
-     * @throws \EE_Error
1183
-     */
1184
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1185
-    {
1186
-        if (! isset($query_params[0])) {
1187
-            $query_params[0] = array();
1188
-        }
1189
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1190
-        if ($conditions_from_id === null) {
1191
-            $query_params[0][$this->primary_key_name()] = $id;
1192
-        } else {
1193
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1194
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1195
-        }
1196
-        return $query_params;
1197
-    }
1198
-
1199
-
1200
-
1201
-    /**
1202
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1203
-     * array. If no item is found, null is returned.
1204
-     *
1205
-     * @param array $query_params like EEM_Base's $query_params variable.
1206
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1207
-     * @throws \EE_Error
1208
-     */
1209
-    public function get_one($query_params = array())
1210
-    {
1211
-        if (! is_array($query_params)) {
1212
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1213
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1214
-                    gettype($query_params)), '4.6.0');
1215
-            $query_params = array();
1216
-        }
1217
-        $query_params['limit'] = 1;
1218
-        $items = $this->get_all($query_params);
1219
-        if (empty($items)) {
1220
-            return null;
1221
-        } else {
1222
-            return array_shift($items);
1223
-        }
1224
-    }
1225
-
1226
-
1227
-
1228
-    /**
1229
-     * Returns the next x number of items in sequence from the given value as
1230
-     * found in the database matching the given query conditions.
1231
-     *
1232
-     * @param mixed $current_field_value    Value used for the reference point.
1233
-     * @param null  $field_to_order_by      What field is used for the
1234
-     *                                      reference point.
1235
-     * @param int   $limit                  How many to return.
1236
-     * @param array $query_params           Extra conditions on the query.
1237
-     * @param null  $columns_to_select      If left null, then an array of
1238
-     *                                      EE_Base_Class objects is returned,
1239
-     *                                      otherwise you can indicate just the
1240
-     *                                      columns you want returned.
1241
-     * @return EE_Base_Class[]|array
1242
-     * @throws \EE_Error
1243
-     */
1244
-    public function next_x(
1245
-        $current_field_value,
1246
-        $field_to_order_by = null,
1247
-        $limit = 1,
1248
-        $query_params = array(),
1249
-        $columns_to_select = null
1250
-    ) {
1251
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1252
-            $columns_to_select);
1253
-    }
1254
-
1255
-
1256
-
1257
-    /**
1258
-     * Returns the previous x number of items in sequence from the given value
1259
-     * as found in the database matching the given query conditions.
1260
-     *
1261
-     * @param mixed $current_field_value    Value used for the reference point.
1262
-     * @param null  $field_to_order_by      What field is used for the
1263
-     *                                      reference point.
1264
-     * @param int   $limit                  How many to return.
1265
-     * @param array $query_params           Extra conditions on the query.
1266
-     * @param null  $columns_to_select      If left null, then an array of
1267
-     *                                      EE_Base_Class objects is returned,
1268
-     *                                      otherwise you can indicate just the
1269
-     *                                      columns you want returned.
1270
-     * @return EE_Base_Class[]|array
1271
-     * @throws \EE_Error
1272
-     */
1273
-    public function previous_x(
1274
-        $current_field_value,
1275
-        $field_to_order_by = null,
1276
-        $limit = 1,
1277
-        $query_params = array(),
1278
-        $columns_to_select = null
1279
-    ) {
1280
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1281
-            $columns_to_select);
1282
-    }
1283
-
1284
-
1285
-
1286
-    /**
1287
-     * Returns the next item in sequence from the given value as found in the
1288
-     * database matching the given query conditions.
1289
-     *
1290
-     * @param mixed $current_field_value    Value used for the reference point.
1291
-     * @param null  $field_to_order_by      What field is used for the
1292
-     *                                      reference point.
1293
-     * @param array $query_params           Extra conditions on the query.
1294
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1295
-     *                                      object is returned, otherwise you
1296
-     *                                      can indicate just the columns you
1297
-     *                                      want and a single array indexed by
1298
-     *                                      the columns will be returned.
1299
-     * @return EE_Base_Class|null|array()
1300
-     * @throws \EE_Error
1301
-     */
1302
-    public function next(
1303
-        $current_field_value,
1304
-        $field_to_order_by = null,
1305
-        $query_params = array(),
1306
-        $columns_to_select = null
1307
-    ) {
1308
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1309
-            $columns_to_select);
1310
-        return empty($results) ? null : reset($results);
1311
-    }
1312
-
1313
-
1314
-
1315
-    /**
1316
-     * Returns the previous item in sequence from the given value as found in
1317
-     * the database matching the given query conditions.
1318
-     *
1319
-     * @param mixed $current_field_value    Value used for the reference point.
1320
-     * @param null  $field_to_order_by      What field is used for the
1321
-     *                                      reference point.
1322
-     * @param array $query_params           Extra conditions on the query.
1323
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1324
-     *                                      object is returned, otherwise you
1325
-     *                                      can indicate just the columns you
1326
-     *                                      want and a single array indexed by
1327
-     *                                      the columns will be returned.
1328
-     * @return EE_Base_Class|null|array()
1329
-     * @throws EE_Error
1330
-     */
1331
-    public function previous(
1332
-        $current_field_value,
1333
-        $field_to_order_by = null,
1334
-        $query_params = array(),
1335
-        $columns_to_select = null
1336
-    ) {
1337
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1338
-            $columns_to_select);
1339
-        return empty($results) ? null : reset($results);
1340
-    }
1341
-
1342
-
1343
-
1344
-    /**
1345
-     * Returns the a consecutive number of items in sequence from the given
1346
-     * value as found in the database matching the given query conditions.
1347
-     *
1348
-     * @param mixed  $current_field_value   Value used for the reference point.
1349
-     * @param string $operand               What operand is used for the sequence.
1350
-     * @param string $field_to_order_by     What field is used for the reference point.
1351
-     * @param int    $limit                 How many to return.
1352
-     * @param array  $query_params          Extra conditions on the query.
1353
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1354
-     *                                      otherwise you can indicate just the columns you want returned.
1355
-     * @return EE_Base_Class[]|array
1356
-     * @throws EE_Error
1357
-     */
1358
-    protected function _get_consecutive(
1359
-        $current_field_value,
1360
-        $operand = '>',
1361
-        $field_to_order_by = null,
1362
-        $limit = 1,
1363
-        $query_params = array(),
1364
-        $columns_to_select = null
1365
-    ) {
1366
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1367
-        if (empty($field_to_order_by)) {
1368
-            if ($this->has_primary_key_field()) {
1369
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1370
-            } else {
1371
-                if (WP_DEBUG) {
1372
-                    throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1373
-                        'event_espresso'));
1374
-                }
1375
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1376
-                return array();
1377
-            }
1378
-        }
1379
-        if (! is_array($query_params)) {
1380
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1381
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1382
-                    gettype($query_params)), '4.6.0');
1383
-            $query_params = array();
1384
-        }
1385
-        //let's add the where query param for consecutive look up.
1386
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1387
-        $query_params['limit'] = $limit;
1388
-        //set direction
1389
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1390
-        $query_params['order_by'] = $operand === '>'
1391
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1392
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1393
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1394
-        if (empty($columns_to_select)) {
1395
-            return $this->get_all($query_params);
1396
-        } else {
1397
-            //getting just the fields
1398
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1399
-        }
1400
-    }
1401
-
1402
-
1403
-
1404
-    /**
1405
-     * This sets the _timezone property after model object has been instantiated.
1406
-     *
1407
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1408
-     */
1409
-    public function set_timezone($timezone)
1410
-    {
1411
-        if ($timezone !== null) {
1412
-            $this->_timezone = $timezone;
1413
-        }
1414
-        //note we need to loop through relations and set the timezone on those objects as well.
1415
-        foreach ($this->_model_relations as $relation) {
1416
-            $relation->set_timezone($timezone);
1417
-        }
1418
-        //and finally we do the same for any datetime fields
1419
-        foreach ($this->_fields as $field) {
1420
-            if ($field instanceof EE_Datetime_Field) {
1421
-                $field->set_timezone($timezone);
1422
-            }
1423
-        }
1424
-    }
1425
-
1426
-
1427
-
1428
-    /**
1429
-     * This just returns whatever is set for the current timezone.
1430
-     *
1431
-     * @access public
1432
-     * @return string
1433
-     */
1434
-    public function get_timezone()
1435
-    {
1436
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1437
-        if (empty($this->_timezone)) {
1438
-            foreach ($this->_fields as $field) {
1439
-                if ($field instanceof EE_Datetime_Field) {
1440
-                    $this->set_timezone($field->get_timezone());
1441
-                    break;
1442
-                }
1443
-            }
1444
-        }
1445
-        //if timezone STILL empty then return the default timezone for the site.
1446
-        if (empty($this->_timezone)) {
1447
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1448
-        }
1449
-        return $this->_timezone;
1450
-    }
1451
-
1452
-
1453
-
1454
-    /**
1455
-     * This returns the date formats set for the given field name and also ensures that
1456
-     * $this->_timezone property is set correctly.
1457
-     *
1458
-     * @since 4.6.x
1459
-     * @param string $field_name The name of the field the formats are being retrieved for.
1460
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1461
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1462
-     * @return array formats in an array with the date format first, and the time format last.
1463
-     */
1464
-    public function get_formats_for($field_name, $pretty = false)
1465
-    {
1466
-        $field_settings = $this->field_settings_for($field_name);
1467
-        //if not a valid EE_Datetime_Field then throw error
1468
-        if (! $field_settings instanceof EE_Datetime_Field) {
1469
-            throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1470
-                'event_espresso'), $field_name));
1471
-        }
1472
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1473
-        //the field.
1474
-        $this->_timezone = $field_settings->get_timezone();
1475
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1476
-    }
1477
-
1478
-
1479
-
1480
-    /**
1481
-     * This returns the current time in a format setup for a query on this model.
1482
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1483
-     * it will return:
1484
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1485
-     *  NOW
1486
-     *  - or a unix timestamp (equivalent to time())
1487
-     *
1488
-     * @since 4.6.x
1489
-     * @param string $field_name       The field the current time is needed for.
1490
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1491
-     *                                 formatted string matching the set format for the field in the set timezone will
1492
-     *                                 be returned.
1493
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1494
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1495
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1496
-     *                                 exception is triggered.
1497
-     */
1498
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1499
-    {
1500
-        $formats = $this->get_formats_for($field_name);
1501
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1502
-        if ($timestamp) {
1503
-            return $DateTime->format('U');
1504
-        }
1505
-        //not returning timestamp, so return formatted string in timezone.
1506
-        switch ($what) {
1507
-            case 'time' :
1508
-                return $DateTime->format($formats[1]);
1509
-                break;
1510
-            case 'date' :
1511
-                return $DateTime->format($formats[0]);
1512
-                break;
1513
-            default :
1514
-                return $DateTime->format(implode(' ', $formats));
1515
-                break;
1516
-        }
1517
-    }
1518
-
1519
-
1520
-
1521
-    /**
1522
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1523
-     * for the model are.  Returns a DateTime object.
1524
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1525
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1526
-     * ignored.
1527
-     *
1528
-     * @param string $field_name      The field being setup.
1529
-     * @param string $timestring      The date time string being used.
1530
-     * @param string $incoming_format The format for the time string.
1531
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1532
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1533
-     *                                format is
1534
-     *                                'U', this is ignored.
1535
-     * @return DateTime
1536
-     * @throws \EE_Error
1537
-     */
1538
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1539
-    {
1540
-        //just using this to ensure the timezone is set correctly internally
1541
-        $this->get_formats_for($field_name);
1542
-        //load EEH_DTT_Helper
1543
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1544
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1545
-        return $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1546
-    }
1547
-
1548
-
1549
-
1550
-    /**
1551
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1552
-     *
1553
-     * @return EE_Table_Base[]
1554
-     */
1555
-    public function get_tables()
1556
-    {
1557
-        return $this->_tables;
1558
-    }
1559
-
1560
-
1561
-
1562
-    /**
1563
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1564
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1565
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1566
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1567
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1568
-     * model object with EVT_ID = 1
1569
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1570
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1571
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1572
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1573
-     * are not specified)
1574
-     *
1575
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1576
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1577
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1578
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1579
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1580
-     *                                         ID=34, we'd use this method as follows:
1581
-     *                                         EEM_Transaction::instance()->update(
1582
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1583
-     *                                         array(array('TXN_ID'=>34)));
1584
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1585
-     *                                         in client code into what's expected to be stored on each field. Eg,
1586
-     *                                         consider updating Question's QST_admin_label field is of type
1587
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1588
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1589
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1590
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1591
-     *                                         TRUE, it is assumed that you've already called
1592
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1593
-     *                                         malicious javascript. However, if
1594
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1595
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1596
-     *                                         and every other field, before insertion. We provide this parameter
1597
-     *                                         because model objects perform their prepare_for_set function on all
1598
-     *                                         their values, and so don't need to be called again (and in many cases,
1599
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1600
-     *                                         prepare_for_set method...)
1601
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1602
-     *                                         in this model's entity map according to $fields_n_values that match
1603
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1604
-     *                                         by setting this to FALSE, but be aware that model objects being used
1605
-     *                                         could get out-of-sync with the database
1606
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1607
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1608
-     *                                         bad)
1609
-     * @throws \EE_Error
1610
-     */
1611
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1612
-    {
1613
-        if (! is_array($query_params)) {
1614
-            EE_Error::doing_it_wrong('EEM_Base::update',
1615
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1616
-                    gettype($query_params)), '4.6.0');
1617
-            $query_params = array();
1618
-        }
1619
-        /**
1620
-         * Action called before a model update call has been made.
1621
-         *
1622
-         * @param EEM_Base $model
1623
-         * @param array    $fields_n_values the updated fields and their new values
1624
-         * @param array    $query_params    @see EEM_Base::get_all()
1625
-         */
1626
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1627
-        /**
1628
-         * Filters the fields about to be updated given the query parameters. You can provide the
1629
-         * $query_params to $this->get_all() to find exactly which records will be updated
1630
-         *
1631
-         * @param array    $fields_n_values fields and their new values
1632
-         * @param EEM_Base $model           the model being queried
1633
-         * @param array    $query_params    see EEM_Base::get_all()
1634
-         */
1635
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1636
-            $query_params);
1637
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1638
-        //to do that, for each table, verify that it's PK isn't null.
1639
-        $tables = $this->get_tables();
1640
-        //and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1641
-        //NOTE: we should make this code more efficient by NOT querying twice
1642
-        //before the real update, but that needs to first go through ALPHA testing
1643
-        //as it's dangerous. says Mike August 8 2014
1644
-        //we want to make sure the default_where strategy is ignored
1645
-        $this->_ignore_where_strategy = true;
1646
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1647
-        foreach ($wpdb_select_results as $wpdb_result) {
1648
-            // type cast stdClass as array
1649
-            $wpdb_result = (array)$wpdb_result;
1650
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1651
-            if ($this->has_primary_key_field()) {
1652
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1653
-            } else {
1654
-                //if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1655
-                $main_table_pk_value = null;
1656
-            }
1657
-            //if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1658
-            //and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1659
-            if (count($tables) > 1) {
1660
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1661
-                //in that table, and so we'll want to insert one
1662
-                foreach ($tables as $table_obj) {
1663
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1664
-                    //if there is no private key for this table on the results, it means there's no entry
1665
-                    //in this table, right? so insert a row in the current table, using any fields available
1666
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1667
-                           && $wpdb_result[$this_table_pk_column])
1668
-                    ) {
1669
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1670
-                            $main_table_pk_value);
1671
-                        //if we died here, report the error
1672
-                        if (! $success) {
1673
-                            return false;
1674
-                        }
1675
-                    }
1676
-                }
1677
-            }
1678
-            //				//and now check that if we have cached any models by that ID on the model, that
1679
-            //				//they also get updated properly
1680
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1681
-            //				if( $model_object ){
1682
-            //					foreach( $fields_n_values as $field => $value ){
1683
-            //						$model_object->set($field, $value);
1684
-            //let's make sure default_where strategy is followed now
1685
-            $this->_ignore_where_strategy = false;
1686
-        }
1687
-        //if we want to keep model objects in sync, AND
1688
-        //if this wasn't called from a model object (to update itself)
1689
-        //then we want to make sure we keep all the existing
1690
-        //model objects in sync with the db
1691
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1692
-            if ($this->has_primary_key_field()) {
1693
-                $model_objs_affected_ids = $this->get_col($query_params);
1694
-            } else {
1695
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1696
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1697
-                $model_objs_affected_ids = array();
1698
-                foreach ($models_affected_key_columns as $row) {
1699
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1700
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1701
-                }
1702
-            }
1703
-            if (! $model_objs_affected_ids) {
1704
-                //wait wait wait- if nothing was affected let's stop here
1705
-                return 0;
1706
-            }
1707
-            foreach ($model_objs_affected_ids as $id) {
1708
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1709
-                if ($model_obj_in_entity_map) {
1710
-                    foreach ($fields_n_values as $field => $new_value) {
1711
-                        $model_obj_in_entity_map->set($field, $new_value);
1712
-                    }
1713
-                }
1714
-            }
1715
-            //if there is a primary key on this model, we can now do a slight optimization
1716
-            if ($this->has_primary_key_field()) {
1717
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1718
-                $query_params = array(
1719
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1720
-                    'limit'                    => count($model_objs_affected_ids),
1721
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1722
-                );
1723
-            }
1724
-        }
1725
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1726
-        $SQL = "UPDATE "
1727
-               . $model_query_info->get_full_join_sql()
1728
-               . " SET "
1729
-               . $this->_construct_update_sql($fields_n_values)
1730
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1731
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1732
-        /**
1733
-         * Action called after a model update call has been made.
1734
-         *
1735
-         * @param EEM_Base $model
1736
-         * @param array    $fields_n_values the updated fields and their new values
1737
-         * @param array    $query_params    @see EEM_Base::get_all()
1738
-         * @param int      $rows_affected
1739
-         */
1740
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1741
-        return $rows_affected;//how many supposedly got updated
1742
-    }
1743
-
1744
-
1745
-
1746
-    /**
1747
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1748
-     * are teh values of the field specified (or by default the primary key field)
1749
-     * that matched the query params. Note that you should pass the name of the
1750
-     * model FIELD, not the database table's column name.
1751
-     *
1752
-     * @param array  $query_params @see EEM_Base::get_all()
1753
-     * @param string $field_to_select
1754
-     * @return array just like $wpdb->get_col()
1755
-     * @throws \EE_Error
1756
-     */
1757
-    public function get_col($query_params = array(), $field_to_select = null)
1758
-    {
1759
-        if ($field_to_select) {
1760
-            $field = $this->field_settings_for($field_to_select);
1761
-        } elseif ($this->has_primary_key_field()) {
1762
-            $field = $this->get_primary_key_field();
1763
-        } else {
1764
-            //no primary key, just grab the first column
1765
-            $field = reset($this->field_settings());
1766
-        }
1767
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1768
-        $select_expressions = $field->get_qualified_column();
1769
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1770
-        return $this->_do_wpdb_query('get_col', array($SQL));
1771
-    }
1772
-
1773
-
1774
-
1775
-    /**
1776
-     * Returns a single column value for a single row from the database
1777
-     *
1778
-     * @param array  $query_params    @see EEM_Base::get_all()
1779
-     * @param string $field_to_select @see EEM_Base::get_col()
1780
-     * @return string
1781
-     * @throws \EE_Error
1782
-     */
1783
-    public function get_var($query_params = array(), $field_to_select = null)
1784
-    {
1785
-        $query_params['limit'] = 1;
1786
-        $col = $this->get_col($query_params, $field_to_select);
1787
-        if (! empty($col)) {
1788
-            return reset($col);
1789
-        } else {
1790
-            return null;
1791
-        }
1792
-    }
1793
-
1794
-
1795
-
1796
-    /**
1797
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1798
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1799
-     * injection, but currently no further filtering is done
1800
-     *
1801
-     * @global      $wpdb
1802
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1803
-     *                               be updated to in the DB
1804
-     * @return string of SQL
1805
-     * @throws \EE_Error
1806
-     */
1807
-    public function _construct_update_sql($fields_n_values)
1808
-    {
1809
-        /** @type WPDB $wpdb */
1810
-        global $wpdb;
1811
-        $cols_n_values = array();
1812
-        foreach ($fields_n_values as $field_name => $value) {
1813
-            $field_obj = $this->field_settings_for($field_name);
1814
-            //if the value is NULL, we want to assign the value to that.
1815
-            //wpdb->prepare doesn't really handle that properly
1816
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1817
-            $value_sql = $prepared_value === null ? 'NULL'
1818
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1819
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1820
-        }
1821
-        return implode(",", $cols_n_values);
1822
-    }
1823
-
1824
-
1825
-
1826
-    /**
1827
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1828
-     * Performs a HARD delete, meaning the database row should always be removed,
1829
-     * not just have a flag field on it switched
1830
-     * Wrapper for EEM_Base::delete_permanently()
1831
-     *
1832
-     * @param mixed $id
1833
-     * @return boolean whether the row got deleted or not
1834
-     * @throws \EE_Error
1835
-     */
1836
-    public function delete_permanently_by_ID($id)
1837
-    {
1838
-        return $this->delete_permanently(
1839
-            array(
1840
-                array($this->get_primary_key_field()->get_name() => $id),
1841
-                'limit' => 1,
1842
-            )
1843
-        );
1844
-    }
1845
-
1846
-
1847
-
1848
-    /**
1849
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1850
-     * Wrapper for EEM_Base::delete()
1851
-     *
1852
-     * @param mixed $id
1853
-     * @return boolean whether the row got deleted or not
1854
-     * @throws \EE_Error
1855
-     */
1856
-    public function delete_by_ID($id)
1857
-    {
1858
-        return $this->delete(
1859
-            array(
1860
-                array($this->get_primary_key_field()->get_name() => $id),
1861
-                'limit' => 1,
1862
-            )
1863
-        );
1864
-    }
1865
-
1866
-
1867
-
1868
-    /**
1869
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1870
-     * meaning if the model has a field that indicates its been "trashed" or
1871
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1872
-     *
1873
-     * @see EEM_Base::delete_permanently
1874
-     * @param array   $query_params
1875
-     * @param boolean $allow_blocking
1876
-     * @return int how many rows got deleted
1877
-     * @throws \EE_Error
1878
-     */
1879
-    public function delete($query_params, $allow_blocking = true)
1880
-    {
1881
-        return $this->delete_permanently($query_params, $allow_blocking);
1882
-    }
1883
-
1884
-
1885
-
1886
-    /**
1887
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1888
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1889
-     * as archived, not actually deleted
1890
-     *
1891
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1892
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1893
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1894
-     *                                deletes regardless of other objects which may depend on it. Its generally
1895
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1896
-     *                                DB
1897
-     * @return int how many rows got deleted
1898
-     * @throws \EE_Error
1899
-     */
1900
-    public function delete_permanently($query_params, $allow_blocking = true)
1901
-    {
1902
-        /**
1903
-         * Action called just before performing a real deletion query. You can use the
1904
-         * model and its $query_params to find exactly which items will be deleted
1905
-         *
1906
-         * @param EEM_Base $model
1907
-         * @param array    $query_params   @see EEM_Base::get_all()
1908
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1909
-         *                                 to block (prevent) this deletion
1910
-         */
1911
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1912
-        //some MySQL databases may be running safe mode, which may restrict
1913
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1914
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1915
-        //to delete them
1916
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1917
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1918
-        if ($deletion_where) {
1919
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1920
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1921
-            $table_aliases = array_keys($this->_tables);
1922
-            $SQL = "DELETE "
1923
-                   . implode(", ", $table_aliases)
1924
-                   . " FROM "
1925
-                   . $model_query_info->get_full_join_sql()
1926
-                   . " WHERE "
1927
-                   . $deletion_where;
1928
-            //		/echo "delete sql:$SQL";
1929
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1930
-        } else {
1931
-            $rows_deleted = 0;
1932
-        }
1933
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1934
-        if ($this->has_primary_key_field()) {
1935
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1936
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1937
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1938
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1939
-                }
1940
-            }
1941
-        }
1942
-        /**
1943
-         * Action called just after performing a real deletion query. Although at this point the
1944
-         * items should have been deleted
1945
-         *
1946
-         * @param EEM_Base $model
1947
-         * @param array    $query_params @see EEM_Base::get_all()
1948
-         * @param int      $rows_deleted
1949
-         */
1950
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1951
-        return $rows_deleted;//how many supposedly got deleted
1952
-    }
1953
-
1954
-
1955
-
1956
-    /**
1957
-     * Checks all the relations that throw error messages when there are blocking related objects
1958
-     * for related model objects. If there are any related model objects on those relations,
1959
-     * adds an EE_Error, and return true
1960
-     *
1961
-     * @param EE_Base_Class|int $this_model_obj_or_id
1962
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1963
-     *                                                 should be ignored when determining whether there are related
1964
-     *                                                 model objects which block this model object's deletion. Useful
1965
-     *                                                 if you know A is related to B and are considering deleting A,
1966
-     *                                                 but want to see if A has any other objects blocking its deletion
1967
-     *                                                 before removing the relation between A and B
1968
-     * @return boolean
1969
-     * @throws \EE_Error
1970
-     */
1971
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1972
-    {
1973
-        //first, if $ignore_this_model_obj was supplied, get its model
1974
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1975
-            $ignored_model = $ignore_this_model_obj->get_model();
1976
-        } else {
1977
-            $ignored_model = null;
1978
-        }
1979
-        //now check all the relations of $this_model_obj_or_id and see if there
1980
-        //are any related model objects blocking it?
1981
-        $is_blocked = false;
1982
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1983
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1984
-                //if $ignore_this_model_obj was supplied, then for the query
1985
-                //on that model needs to be told to ignore $ignore_this_model_obj
1986
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1987
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1988
-                        array(
1989
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1990
-                                '!=',
1991
-                                $ignore_this_model_obj->ID(),
1992
-                            ),
1993
-                        ),
1994
-                    ));
1995
-                } else {
1996
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1997
-                }
1998
-                if ($related_model_objects) {
1999
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2000
-                    $is_blocked = true;
2001
-                }
2002
-            }
2003
-        }
2004
-        return $is_blocked;
2005
-    }
2006
-
2007
-
2008
-
2009
-    /**
2010
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2011
-     * well.
2012
-     *
2013
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2014
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2015
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
2016
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
2017
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
2018
-     *                                      easily corrupt your DB
2019
-     * @throws EE_Error
2020
-     * @return string    everything that comes after the WHERE statement.
2021
-     */
2022
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2023
-    {
2024
-        if ($this->has_primary_key_field()) {
2025
-            $primary_table = $this->_get_main_table();
2026
-            $other_tables = $this->_get_other_tables();
2027
-            $deletes = $query = array();
2028
-            foreach ($objects_for_deletion as $delete_object) {
2029
-                //before we mark this object for deletion,
2030
-                //make sure there's no related objects blocking its deletion (if we're checking)
2031
-                if (
2032
-                    $allow_blocking
2033
-                    && $this->delete_is_blocked_by_related_models(
2034
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
2035
-                    )
2036
-                ) {
2037
-                    continue;
2038
-                }
2039
-                //primary table deletes
2040
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2041
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2042
-                }
2043
-                //other tables
2044
-                if (! empty($other_tables)) {
2045
-                    foreach ($other_tables as $ot) {
2046
-                        //first check if we've got the foreign key column here.
2047
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2048
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2049
-                        }
2050
-                        // wait! it's entirely possible that we'll have a the primary key
2051
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
2052
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2053
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2054
-                        }
2055
-                        // finally, it is possible that the fk for this table is found
2056
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
2057
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2058
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2059
-                        }
2060
-                    }
2061
-                }
2062
-            }
2063
-            //we should have deletes now, so let's just go through and setup the where statement
2064
-            foreach ($deletes as $column => $values) {
2065
-                //make sure we have unique $values;
2066
-                $values = array_unique($values);
2067
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2068
-            }
2069
-            return ! empty($query) ? implode(' AND ', $query) : '';
2070
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2071
-            $ways_to_identify_a_row = array();
2072
-            $fields = $this->get_combined_primary_key_fields();
2073
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2074
-            foreach ($objects_for_deletion as $delete_object) {
2075
-                $values_for_each_cpk_for_a_row = array();
2076
-                foreach ($fields as $cpk_field) {
2077
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2078
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2079
-                                                           . "="
2080
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
2081
-                    }
2082
-                }
2083
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2084
-            }
2085
-            return implode(" OR ", $ways_to_identify_a_row);
2086
-        } else {
2087
-            //so there's no primary key and no combined key...
2088
-            //sorry, can't help you
2089
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2090
-                "event_espresso"), get_class($this)));
2091
-        }
2092
-    }
2093
-
2094
-
2095
-
2096
-    /**
2097
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2098
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2099
-     * column
2100
-     *
2101
-     * @param array  $query_params   like EEM_Base::get_all's
2102
-     * @param string $field_to_count field on model to count by (not column name)
2103
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2104
-     *                               that by the setting $distinct to TRUE;
2105
-     * @return int
2106
-     * @throws \EE_Error
2107
-     */
2108
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2109
-    {
2110
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2111
-        if ($field_to_count) {
2112
-            $field_obj = $this->field_settings_for($field_to_count);
2113
-            $column_to_count = $field_obj->get_qualified_column();
2114
-        } elseif ($this->has_primary_key_field()) {
2115
-            $pk_field_obj = $this->get_primary_key_field();
2116
-            $column_to_count = $pk_field_obj->get_qualified_column();
2117
-        } else {
2118
-            //there's no primary key
2119
-            //if we're counting distinct items, and there's no primary key,
2120
-            //we need to list out the columns for distinction;
2121
-            //otherwise we can just use star
2122
-            if ($distinct) {
2123
-                $columns_to_use = array();
2124
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2125
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2126
-                }
2127
-                $column_to_count = implode(',', $columns_to_use);
2128
-            } else {
2129
-                $column_to_count = '*';
2130
-            }
2131
-        }
2132
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2133
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2134
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2135
-    }
2136
-
2137
-
2138
-
2139
-    /**
2140
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2141
-     *
2142
-     * @param array  $query_params like EEM_Base::get_all
2143
-     * @param string $field_to_sum name of field (array key in $_fields array)
2144
-     * @return float
2145
-     * @throws \EE_Error
2146
-     */
2147
-    public function sum($query_params, $field_to_sum = null)
2148
-    {
2149
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2150
-        if ($field_to_sum) {
2151
-            $field_obj = $this->field_settings_for($field_to_sum);
2152
-        } else {
2153
-            $field_obj = $this->get_primary_key_field();
2154
-        }
2155
-        $column_to_count = $field_obj->get_qualified_column();
2156
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2157
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2158
-        $data_type = $field_obj->get_wpdb_data_type();
2159
-        if ($data_type === '%d' || $data_type === '%s') {
2160
-            return (float)$return_value;
2161
-        } else {//must be %f
2162
-            return (float)$return_value;
2163
-        }
2164
-    }
2165
-
2166
-
2167
-
2168
-    /**
2169
-     * Just calls the specified method on $wpdb with the given arguments
2170
-     * Consolidates a little extra error handling code
2171
-     *
2172
-     * @param string $wpdb_method
2173
-     * @param array  $arguments_to_provide
2174
-     * @throws EE_Error
2175
-     * @global wpdb  $wpdb
2176
-     * @return mixed
2177
-     */
2178
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2179
-    {
2180
-        //if we're in maintenance mode level 2, DON'T run any queries
2181
-        //because level 2 indicates the database needs updating and
2182
-        //is probably out of sync with the code
2183
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2184
-            throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2185
-                "event_espresso")));
2186
-        }
2187
-        /** @type WPDB $wpdb */
2188
-        global $wpdb;
2189
-        if (! method_exists($wpdb, $wpdb_method)) {
2190
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2191
-                'event_espresso'), $wpdb_method));
2192
-        }
2193
-        if (WP_DEBUG) {
2194
-            $old_show_errors_value = $wpdb->show_errors;
2195
-            $wpdb->show_errors(false);
2196
-        }
2197
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2198
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2199
-        if (WP_DEBUG) {
2200
-            $wpdb->show_errors($old_show_errors_value);
2201
-            if (! empty($wpdb->last_error)) {
2202
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2203
-            } elseif ($result === false) {
2204
-                throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2205
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2206
-            }
2207
-        } elseif ($result === false) {
2208
-            EE_Error::add_error(
2209
-                sprintf(
2210
-                    __('A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2211
-                        'event_espresso'),
2212
-                    $wpdb_method,
2213
-                    var_export($arguments_to_provide, true),
2214
-                    $wpdb->last_error
2215
-                ),
2216
-                __FILE__,
2217
-                __FUNCTION__,
2218
-                __LINE__
2219
-            );
2220
-        }
2221
-        return $result;
2222
-    }
2223
-
2224
-
2225
-
2226
-    /**
2227
-     * Attempts to run the indicated WPDB method with the provided arguments,
2228
-     * and if there's an error tries to verify the DB is correct. Uses
2229
-     * the static property EEM_Base::$_db_verification_level to determine whether
2230
-     * we should try to fix the EE core db, the addons, or just give up
2231
-     *
2232
-     * @param string $wpdb_method
2233
-     * @param array  $arguments_to_provide
2234
-     * @return mixed
2235
-     */
2236
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2237
-    {
2238
-        /** @type WPDB $wpdb */
2239
-        global $wpdb;
2240
-        $wpdb->last_error = null;
2241
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2242
-        // was there an error running the query? but we don't care on new activations
2243
-        // (we're going to setup the DB anyway on new activations)
2244
-        if (($result === false || ! empty($wpdb->last_error))
2245
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2246
-        ) {
2247
-            switch (EEM_Base::$_db_verification_level) {
2248
-                case EEM_Base::db_verified_none :
2249
-                    // let's double-check core's DB
2250
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2251
-                    break;
2252
-                case EEM_Base::db_verified_core :
2253
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2254
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2255
-                    break;
2256
-                case EEM_Base::db_verified_addons :
2257
-                    // ummmm... you in trouble
2258
-                    return $result;
2259
-                    break;
2260
-            }
2261
-            if (! empty($error_message)) {
2262
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2263
-                trigger_error($error_message);
2264
-            }
2265
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2266
-        }
2267
-        return $result;
2268
-    }
2269
-
2270
-
2271
-
2272
-    /**
2273
-     * Verifies the EE core database is up-to-date and records that we've done it on
2274
-     * EEM_Base::$_db_verification_level
2275
-     *
2276
-     * @param string $wpdb_method
2277
-     * @param array  $arguments_to_provide
2278
-     * @return string
2279
-     */
2280
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2281
-    {
2282
-        /** @type WPDB $wpdb */
2283
-        global $wpdb;
2284
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2285
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2286
-        $error_message = sprintf(
2287
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2288
-                'event_espresso'),
2289
-            $wpdb->last_error,
2290
-            $wpdb_method,
2291
-            wp_json_encode($arguments_to_provide)
2292
-        );
2293
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2294
-        return $error_message;
2295
-    }
2296
-
2297
-
2298
-
2299
-    /**
2300
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2301
-     * EEM_Base::$_db_verification_level
2302
-     *
2303
-     * @param $wpdb_method
2304
-     * @param $arguments_to_provide
2305
-     * @return string
2306
-     */
2307
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2308
-    {
2309
-        /** @type WPDB $wpdb */
2310
-        global $wpdb;
2311
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2312
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2313
-        $error_message = sprintf(
2314
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2315
-                'event_espresso'),
2316
-            $wpdb->last_error,
2317
-            $wpdb_method,
2318
-            wp_json_encode($arguments_to_provide)
2319
-        );
2320
-        EE_System::instance()->initialize_addons();
2321
-        return $error_message;
2322
-    }
2323
-
2324
-
2325
-
2326
-    /**
2327
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2328
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2329
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2330
-     * ..."
2331
-     *
2332
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2333
-     * @return string
2334
-     */
2335
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2336
-    {
2337
-        return " FROM " . $model_query_info->get_full_join_sql() .
2338
-               $model_query_info->get_where_sql() .
2339
-               $model_query_info->get_group_by_sql() .
2340
-               $model_query_info->get_having_sql() .
2341
-               $model_query_info->get_order_by_sql() .
2342
-               $model_query_info->get_limit_sql();
2343
-    }
2344
-
2345
-
2346
-
2347
-    /**
2348
-     * Set to easily debug the next X queries ran from this model.
2349
-     *
2350
-     * @param int $count
2351
-     */
2352
-    public function show_next_x_db_queries($count = 1)
2353
-    {
2354
-        $this->_show_next_x_db_queries = $count;
2355
-    }
2356
-
2357
-
2358
-
2359
-    /**
2360
-     * @param $sql_query
2361
-     */
2362
-    public function show_db_query_if_previously_requested($sql_query)
2363
-    {
2364
-        if ($this->_show_next_x_db_queries > 0) {
2365
-            echo $sql_query;
2366
-            $this->_show_next_x_db_queries--;
2367
-        }
2368
-    }
2369
-
2370
-
2371
-
2372
-    /**
2373
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2374
-     * There are the 3 cases:
2375
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2376
-     * $otherModelObject has no ID, it is first saved.
2377
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2378
-     * has no ID, it is first saved.
2379
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2380
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2381
-     * join table
2382
-     *
2383
-     * @param        EE_Base_Class                     /int $thisModelObject
2384
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2385
-     * @param string $relationName                     , key in EEM_Base::_relations
2386
-     *                                                 an attendee to a group, you also want to specify which role they
2387
-     *                                                 will have in that group. So you would use this parameter to
2388
-     *                                                 specify array('role-column-name'=>'role-id')
2389
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2390
-     *                                                 to for relation to methods that allow you to further specify
2391
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2392
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2393
-     *                                                 because these will be inserted in any new rows created as well.
2394
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2395
-     * @throws \EE_Error
2396
-     */
2397
-    public function add_relationship_to(
2398
-        $id_or_obj,
2399
-        $other_model_id_or_obj,
2400
-        $relationName,
2401
-        $extra_join_model_fields_n_values = array()
2402
-    ) {
2403
-        $relation_obj = $this->related_settings_for($relationName);
2404
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2405
-    }
2406
-
2407
-
2408
-
2409
-    /**
2410
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2411
-     * There are the 3 cases:
2412
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2413
-     * error
2414
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2415
-     * an error
2416
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2417
-     *
2418
-     * @param        EE_Base_Class /int $id_or_obj
2419
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2420
-     * @param string $relationName key in EEM_Base::_relations
2421
-     * @return boolean of success
2422
-     * @throws \EE_Error
2423
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2424
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2425
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2426
-     *                             because these will be inserted in any new rows created as well.
2427
-     */
2428
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2429
-    {
2430
-        $relation_obj = $this->related_settings_for($relationName);
2431
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2432
-    }
2433
-
2434
-
2435
-
2436
-    /**
2437
-     * @param mixed           $id_or_obj
2438
-     * @param string          $relationName
2439
-     * @param array           $where_query_params
2440
-     * @param EE_Base_Class[] objects to which relations were removed
2441
-     * @return \EE_Base_Class[]
2442
-     * @throws \EE_Error
2443
-     */
2444
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2445
-    {
2446
-        $relation_obj = $this->related_settings_for($relationName);
2447
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2448
-    }
2449
-
2450
-
2451
-
2452
-    /**
2453
-     * Gets all the related items of the specified $model_name, using $query_params.
2454
-     * Note: by default, we remove the "default query params"
2455
-     * because we want to get even deleted items etc.
2456
-     *
2457
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2458
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2459
-     * @param array  $query_params like EEM_Base::get_all
2460
-     * @return EE_Base_Class[]
2461
-     * @throws \EE_Error
2462
-     */
2463
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2464
-    {
2465
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2466
-        $relation_settings = $this->related_settings_for($model_name);
2467
-        return $relation_settings->get_all_related($model_obj, $query_params);
2468
-    }
2469
-
2470
-
2471
-
2472
-    /**
2473
-     * Deletes all the model objects across the relation indicated by $model_name
2474
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2475
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2476
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2477
-     *
2478
-     * @param EE_Base_Class|int|string $id_or_obj
2479
-     * @param string                   $model_name
2480
-     * @param array                    $query_params
2481
-     * @return int how many deleted
2482
-     * @throws \EE_Error
2483
-     */
2484
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2485
-    {
2486
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2487
-        $relation_settings = $this->related_settings_for($model_name);
2488
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2489
-    }
2490
-
2491
-
2492
-
2493
-    /**
2494
-     * Hard deletes all the model objects across the relation indicated by $model_name
2495
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2496
-     * the model objects can't be hard deleted because of blocking related model objects,
2497
-     * just does a soft-delete on them instead.
2498
-     *
2499
-     * @param EE_Base_Class|int|string $id_or_obj
2500
-     * @param string                   $model_name
2501
-     * @param array                    $query_params
2502
-     * @return int how many deleted
2503
-     * @throws \EE_Error
2504
-     */
2505
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2506
-    {
2507
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2508
-        $relation_settings = $this->related_settings_for($model_name);
2509
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2510
-    }
2511
-
2512
-
2513
-
2514
-    /**
2515
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2516
-     * unless otherwise specified in the $query_params
2517
-     *
2518
-     * @param        int             /EE_Base_Class $id_or_obj
2519
-     * @param string $model_name     like 'Event', or 'Registration'
2520
-     * @param array  $query_params   like EEM_Base::get_all's
2521
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2522
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2523
-     *                               that by the setting $distinct to TRUE;
2524
-     * @return int
2525
-     * @throws \EE_Error
2526
-     */
2527
-    public function count_related(
2528
-        $id_or_obj,
2529
-        $model_name,
2530
-        $query_params = array(),
2531
-        $field_to_count = null,
2532
-        $distinct = false
2533
-    ) {
2534
-        $related_model = $this->get_related_model_obj($model_name);
2535
-        //we're just going to use the query params on the related model's normal get_all query,
2536
-        //except add a condition to say to match the current mod
2537
-        if (! isset($query_params['default_where_conditions'])) {
2538
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2539
-        }
2540
-        $this_model_name = $this->get_this_model_name();
2541
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2542
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2543
-        return $related_model->count($query_params, $field_to_count, $distinct);
2544
-    }
2545
-
2546
-
2547
-
2548
-    /**
2549
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2550
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2551
-     *
2552
-     * @param        int           /EE_Base_Class $id_or_obj
2553
-     * @param string $model_name   like 'Event', or 'Registration'
2554
-     * @param array  $query_params like EEM_Base::get_all's
2555
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2556
-     * @return float
2557
-     * @throws \EE_Error
2558
-     */
2559
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2560
-    {
2561
-        $related_model = $this->get_related_model_obj($model_name);
2562
-        if (! is_array($query_params)) {
2563
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2564
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2565
-                    gettype($query_params)), '4.6.0');
2566
-            $query_params = array();
2567
-        }
2568
-        //we're just going to use the query params on the related model's normal get_all query,
2569
-        //except add a condition to say to match the current mod
2570
-        if (! isset($query_params['default_where_conditions'])) {
2571
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2572
-        }
2573
-        $this_model_name = $this->get_this_model_name();
2574
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2575
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2576
-        return $related_model->sum($query_params, $field_to_sum);
2577
-    }
2578
-
2579
-
2580
-
2581
-    /**
2582
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2583
-     * $modelObject
2584
-     *
2585
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2586
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2587
-     * @param array               $query_params     like EEM_Base::get_all's
2588
-     * @return EE_Base_Class
2589
-     * @throws \EE_Error
2590
-     */
2591
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2592
-    {
2593
-        $query_params['limit'] = 1;
2594
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2595
-        if ($results) {
2596
-            return array_shift($results);
2597
-        } else {
2598
-            return null;
2599
-        }
2600
-    }
2601
-
2602
-
2603
-
2604
-    /**
2605
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2606
-     *
2607
-     * @return string
2608
-     */
2609
-    public function get_this_model_name()
2610
-    {
2611
-        return str_replace("EEM_", "", get_class($this));
2612
-    }
2613
-
2614
-
2615
-
2616
-    /**
2617
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2618
-     *
2619
-     * @return EE_Any_Foreign_Model_Name_Field
2620
-     * @throws EE_Error
2621
-     */
2622
-    public function get_field_containing_related_model_name()
2623
-    {
2624
-        foreach ($this->field_settings(true) as $field) {
2625
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2626
-                $field_with_model_name = $field;
2627
-            }
2628
-        }
2629
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2630
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2631
-                $this->get_this_model_name()));
2632
-        }
2633
-        return $field_with_model_name;
2634
-    }
2635
-
2636
-
2637
-
2638
-    /**
2639
-     * Inserts a new entry into the database, for each table.
2640
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2641
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2642
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2643
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2644
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2645
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2646
-     *
2647
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2648
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2649
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2650
-     *                              of EEM_Base)
2651
-     * @return int new primary key on main table that got inserted
2652
-     * @throws EE_Error
2653
-     */
2654
-    public function insert($field_n_values)
2655
-    {
2656
-        /**
2657
-         * Filters the fields and their values before inserting an item using the models
2658
-         *
2659
-         * @param array    $fields_n_values keys are the fields and values are their new values
2660
-         * @param EEM_Base $model           the model used
2661
-         */
2662
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2663
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2664
-            $main_table = $this->_get_main_table();
2665
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2666
-            if ($new_id !== false) {
2667
-                foreach ($this->_get_other_tables() as $other_table) {
2668
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2669
-                }
2670
-            }
2671
-            /**
2672
-             * Done just after attempting to insert a new model object
2673
-             *
2674
-             * @param EEM_Base   $model           used
2675
-             * @param array      $fields_n_values fields and their values
2676
-             * @param int|string the              ID of the newly-inserted model object
2677
-             */
2678
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2679
-            return $new_id;
2680
-        } else {
2681
-            return false;
2682
-        }
2683
-    }
2684
-
2685
-
2686
-
2687
-    /**
2688
-     * Checks that the result would satisfy the unique indexes on this model
2689
-     *
2690
-     * @param array  $field_n_values
2691
-     * @param string $action
2692
-     * @return boolean
2693
-     * @throws \EE_Error
2694
-     */
2695
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2696
-    {
2697
-        foreach ($this->unique_indexes() as $index_name => $index) {
2698
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2699
-            if ($this->exists(array($uniqueness_where_params))) {
2700
-                EE_Error::add_error(
2701
-                    sprintf(
2702
-                        __(
2703
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2704
-                            "event_espresso"
2705
-                        ),
2706
-                        $action,
2707
-                        $this->_get_class_name(),
2708
-                        $index_name,
2709
-                        implode(",", $index->field_names()),
2710
-                        http_build_query($uniqueness_where_params)
2711
-                    ),
2712
-                    __FILE__,
2713
-                    __FUNCTION__,
2714
-                    __LINE__
2715
-                );
2716
-                return false;
2717
-            }
2718
-        }
2719
-        return true;
2720
-    }
2721
-
2722
-
2723
-
2724
-    /**
2725
-     * Checks the database for an item that conflicts (ie, if this item were
2726
-     * saved to the DB would break some uniqueness requirement, like a primary key
2727
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2728
-     * can be either an EE_Base_Class or an array of fields n values
2729
-     *
2730
-     * @param EE_Base_Class|array $obj_or_fields_array
2731
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2732
-     *                                                 when looking for conflicts
2733
-     *                                                 (ie, if false, we ignore the model object's primary key
2734
-     *                                                 when finding "conflicts". If true, it's also considered).
2735
-     *                                                 Only works for INT primary key,
2736
-     *                                                 STRING primary keys cannot be ignored
2737
-     * @throws EE_Error
2738
-     * @return EE_Base_Class|array
2739
-     */
2740
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2741
-    {
2742
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2743
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2744
-        } elseif (is_array($obj_or_fields_array)) {
2745
-            $fields_n_values = $obj_or_fields_array;
2746
-        } else {
2747
-            throw new EE_Error(
2748
-                sprintf(
2749
-                    __(
2750
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2751
-                        "event_espresso"
2752
-                    ),
2753
-                    get_class($this),
2754
-                    $obj_or_fields_array
2755
-                )
2756
-            );
2757
-        }
2758
-        $query_params = array();
2759
-        if ($this->has_primary_key_field()
2760
-            && ($include_primary_key
2761
-                || $this->get_primary_key_field()
2762
-                   instanceof
2763
-                   EE_Primary_Key_String_Field)
2764
-            && isset($fields_n_values[$this->primary_key_name()])
2765
-        ) {
2766
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2767
-        }
2768
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2769
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2770
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2771
-        }
2772
-        //if there is nothing to base this search on, then we shouldn't find anything
2773
-        if (empty($query_params)) {
2774
-            return array();
2775
-        } else {
2776
-            return $this->get_one($query_params);
2777
-        }
2778
-    }
2779
-
2780
-
2781
-
2782
-    /**
2783
-     * Like count, but is optimized and returns a boolean instead of an int
2784
-     *
2785
-     * @param array $query_params
2786
-     * @return boolean
2787
-     * @throws \EE_Error
2788
-     */
2789
-    public function exists($query_params)
2790
-    {
2791
-        $query_params['limit'] = 1;
2792
-        return $this->count($query_params) > 0;
2793
-    }
2794
-
2795
-
2796
-
2797
-    /**
2798
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2799
-     *
2800
-     * @param int|string $id
2801
-     * @return boolean
2802
-     * @throws \EE_Error
2803
-     */
2804
-    public function exists_by_ID($id)
2805
-    {
2806
-        return $this->exists(
2807
-            array(
2808
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2809
-                array(
2810
-                    $this->primary_key_name() => $id,
2811
-                ),
2812
-            )
2813
-        );
2814
-    }
2815
-
2816
-
2817
-
2818
-    /**
2819
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2820
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2821
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2822
-     * on the main table)
2823
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2824
-     * cases where we want to call it directly rather than via insert().
2825
-     *
2826
-     * @access   protected
2827
-     * @param EE_Table_Base $table
2828
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2829
-     *                                       float
2830
-     * @param int           $new_id          for now we assume only int keys
2831
-     * @throws EE_Error
2832
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2833
-     * @return int ID of new row inserted, or FALSE on failure
2834
-     */
2835
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2836
-    {
2837
-        global $wpdb;
2838
-        $insertion_col_n_values = array();
2839
-        $format_for_insertion = array();
2840
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2841
-        foreach ($fields_on_table as $field_name => $field_obj) {
2842
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2843
-            if ($field_obj->is_auto_increment()) {
2844
-                continue;
2845
-            }
2846
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2847
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2848
-            if ($prepared_value !== null) {
2849
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2850
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2851
-            }
2852
-        }
2853
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2854
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2855
-            //so add the fk to the main table as a column
2856
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2857
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2858
-        }
2859
-        //insert the new entry
2860
-        $result = $this->_do_wpdb_query('insert',
2861
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2862
-        if ($result === false) {
2863
-            return false;
2864
-        }
2865
-        //ok, now what do we return for the ID of the newly-inserted thing?
2866
-        if ($this->has_primary_key_field()) {
2867
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2868
-                return $wpdb->insert_id;
2869
-            } else {
2870
-                //it's not an auto-increment primary key, so
2871
-                //it must have been supplied
2872
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2873
-            }
2874
-        } else {
2875
-            //we can't return a  primary key because there is none. instead return
2876
-            //a unique string indicating this model
2877
-            return $this->get_index_primary_key_string($fields_n_values);
2878
-        }
2879
-    }
2880
-
2881
-
2882
-
2883
-    /**
2884
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2885
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2886
-     * and there is no default, we pass it along. WPDB will take care of it)
2887
-     *
2888
-     * @param EE_Model_Field_Base $field_obj
2889
-     * @param array               $fields_n_values
2890
-     * @return mixed string|int|float depending on what the table column will be expecting
2891
-     * @throws \EE_Error
2892
-     */
2893
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2894
-    {
2895
-        //if this field doesn't allow nullable, don't allow it
2896
-        if (! $field_obj->is_nullable()
2897
-            && (
2898
-                ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2899
-        ) {
2900
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2901
-        }
2902
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2903
-            : null;
2904
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2905
-    }
2906
-
2907
-
2908
-
2909
-    /**
2910
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2911
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2912
-     * the field's prepare_for_set() method.
2913
-     *
2914
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2915
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2916
-     *                                   top of file)
2917
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2918
-     *                                   $value is a custom selection
2919
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2920
-     */
2921
-    private function _prepare_value_for_use_in_db($value, $field)
2922
-    {
2923
-        if ($field && $field instanceof EE_Model_Field_Base) {
2924
-            switch ($this->_values_already_prepared_by_model_object) {
2925
-                /** @noinspection PhpMissingBreakStatementInspection */
2926
-                case self::not_prepared_by_model_object:
2927
-                    $value = $field->prepare_for_set($value);
2928
-                //purposefully left out "return"
2929
-                case self::prepared_by_model_object:
2930
-                    $value = $field->prepare_for_use_in_db($value);
2931
-                case self::prepared_for_use_in_db:
2932
-                    //leave the value alone
2933
-            }
2934
-            return $value;
2935
-        } else {
2936
-            return $value;
2937
-        }
2938
-    }
2939
-
2940
-
2941
-
2942
-    /**
2943
-     * Returns the main table on this model
2944
-     *
2945
-     * @return EE_Primary_Table
2946
-     * @throws EE_Error
2947
-     */
2948
-    protected function _get_main_table()
2949
-    {
2950
-        foreach ($this->_tables as $table) {
2951
-            if ($table instanceof EE_Primary_Table) {
2952
-                return $table;
2953
-            }
2954
-        }
2955
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2956
-            'event_espresso'), get_class($this)));
2957
-    }
2958
-
2959
-
2960
-
2961
-    /**
2962
-     * table
2963
-     * returns EE_Primary_Table table name
2964
-     *
2965
-     * @return string
2966
-     * @throws \EE_Error
2967
-     */
2968
-    public function table()
2969
-    {
2970
-        return $this->_get_main_table()->get_table_name();
2971
-    }
2972
-
2973
-
2974
-
2975
-    /**
2976
-     * table
2977
-     * returns first EE_Secondary_Table table name
2978
-     *
2979
-     * @return string
2980
-     */
2981
-    public function second_table()
2982
-    {
2983
-        // grab second table from tables array
2984
-        $second_table = end($this->_tables);
2985
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2986
-    }
2987
-
2988
-
2989
-
2990
-    /**
2991
-     * get_table_obj_by_alias
2992
-     * returns table name given it's alias
2993
-     *
2994
-     * @param string $table_alias
2995
-     * @return EE_Primary_Table | EE_Secondary_Table
2996
-     */
2997
-    public function get_table_obj_by_alias($table_alias = '')
2998
-    {
2999
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3000
-    }
3001
-
3002
-
3003
-
3004
-    /**
3005
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3006
-     *
3007
-     * @return EE_Secondary_Table[]
3008
-     */
3009
-    protected function _get_other_tables()
3010
-    {
3011
-        $other_tables = array();
3012
-        foreach ($this->_tables as $table_alias => $table) {
3013
-            if ($table instanceof EE_Secondary_Table) {
3014
-                $other_tables[$table_alias] = $table;
3015
-            }
3016
-        }
3017
-        return $other_tables;
3018
-    }
3019
-
3020
-
3021
-
3022
-    /**
3023
-     * Finds all the fields that correspond to the given table
3024
-     *
3025
-     * @param string $table_alias , array key in EEM_Base::_tables
3026
-     * @return EE_Model_Field_Base[]
3027
-     */
3028
-    public function _get_fields_for_table($table_alias)
3029
-    {
3030
-        return $this->_fields[$table_alias];
3031
-    }
3032
-
3033
-
3034
-
3035
-    /**
3036
-     * Recurses through all the where parameters, and finds all the related models we'll need
3037
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3038
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3039
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3040
-     * related Registration, Transaction, and Payment models.
3041
-     *
3042
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3043
-     * @return EE_Model_Query_Info_Carrier
3044
-     * @throws \EE_Error
3045
-     */
3046
-    public function _extract_related_models_from_query($query_params)
3047
-    {
3048
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3049
-        if (array_key_exists(0, $query_params)) {
3050
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3051
-        }
3052
-        if (array_key_exists('group_by', $query_params)) {
3053
-            if (is_array($query_params['group_by'])) {
3054
-                $this->_extract_related_models_from_sub_params_array_values(
3055
-                    $query_params['group_by'],
3056
-                    $query_info_carrier,
3057
-                    'group_by'
3058
-                );
3059
-            } elseif (! empty ($query_params['group_by'])) {
3060
-                $this->_extract_related_model_info_from_query_param(
3061
-                    $query_params['group_by'],
3062
-                    $query_info_carrier,
3063
-                    'group_by'
3064
-                );
3065
-            }
3066
-        }
3067
-        if (array_key_exists('having', $query_params)) {
3068
-            $this->_extract_related_models_from_sub_params_array_keys(
3069
-                $query_params[0],
3070
-                $query_info_carrier,
3071
-                'having'
3072
-            );
3073
-        }
3074
-        if (array_key_exists('order_by', $query_params)) {
3075
-            if (is_array($query_params['order_by'])) {
3076
-                $this->_extract_related_models_from_sub_params_array_keys(
3077
-                    $query_params['order_by'],
3078
-                    $query_info_carrier,
3079
-                    'order_by'
3080
-                );
3081
-            } elseif (! empty($query_params['order_by'])) {
3082
-                $this->_extract_related_model_info_from_query_param(
3083
-                    $query_params['order_by'],
3084
-                    $query_info_carrier,
3085
-                    'order_by'
3086
-                );
3087
-            }
3088
-        }
3089
-        if (array_key_exists('force_join', $query_params)) {
3090
-            $this->_extract_related_models_from_sub_params_array_values(
3091
-                $query_params['force_join'],
3092
-                $query_info_carrier,
3093
-                'force_join'
3094
-            );
3095
-        }
3096
-        return $query_info_carrier;
3097
-    }
3098
-
3099
-
3100
-
3101
-    /**
3102
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3103
-     *
3104
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3105
-     *                                                      $query_params['having']
3106
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3107
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3108
-     * @throws EE_Error
3109
-     * @return \EE_Model_Query_Info_Carrier
3110
-     */
3111
-    private function _extract_related_models_from_sub_params_array_keys(
3112
-        $sub_query_params,
3113
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3114
-        $query_param_type
3115
-    ) {
3116
-        if (! empty($sub_query_params)) {
3117
-            $sub_query_params = (array)$sub_query_params;
3118
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3119
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3120
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3121
-                    $query_param_type);
3122
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3123
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3124
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3125
-                //of array('Registration.TXN_ID'=>23)
3126
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3127
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3128
-                    if (! is_array($possibly_array_of_params)) {
3129
-                        throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3130
-                            "event_espresso"),
3131
-                            $param, $possibly_array_of_params));
3132
-                    } else {
3133
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3134
-                            $model_query_info_carrier, $query_param_type);
3135
-                    }
3136
-                } elseif ($query_param_type === 0 //ie WHERE
3137
-                          && is_array($possibly_array_of_params)
3138
-                          && isset($possibly_array_of_params[2])
3139
-                          && $possibly_array_of_params[2] == true
3140
-                ) {
3141
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3142
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3143
-                    //from which we should extract query parameters!
3144
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3145
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3146
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3147
-                    }
3148
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3149
-                        $model_query_info_carrier, $query_param_type);
3150
-                }
3151
-            }
3152
-        }
3153
-        return $model_query_info_carrier;
3154
-    }
3155
-
3156
-
3157
-
3158
-    /**
3159
-     * For extracting related models from forced_joins, where the array values contain the info about what
3160
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3161
-     *
3162
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3163
-     *                                                      $query_params['having']
3164
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3165
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3166
-     * @throws EE_Error
3167
-     * @return \EE_Model_Query_Info_Carrier
3168
-     */
3169
-    private function _extract_related_models_from_sub_params_array_values(
3170
-        $sub_query_params,
3171
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3172
-        $query_param_type
3173
-    ) {
3174
-        if (! empty($sub_query_params)) {
3175
-            if (! is_array($sub_query_params)) {
3176
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3177
-                    $sub_query_params));
3178
-            }
3179
-            foreach ($sub_query_params as $param) {
3180
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3181
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3182
-                    $query_param_type);
3183
-            }
3184
-        }
3185
-        return $model_query_info_carrier;
3186
-    }
3187
-
3188
-
3189
-
3190
-    /**
3191
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3192
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3193
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3194
-     * but use them in a different order. Eg, we need to know what models we are querying
3195
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3196
-     * other models before we can finalize the where clause SQL.
3197
-     *
3198
-     * @param array $query_params
3199
-     * @throws EE_Error
3200
-     * @return EE_Model_Query_Info_Carrier
3201
-     */
3202
-    public function _create_model_query_info_carrier($query_params)
3203
-    {
3204
-        if (! is_array($query_params)) {
3205
-            EE_Error::doing_it_wrong(
3206
-                'EEM_Base::_create_model_query_info_carrier',
3207
-                sprintf(
3208
-                    __(
3209
-                        '$query_params should be an array, you passed a variable of type %s',
3210
-                        'event_espresso'
3211
-                    ),
3212
-                    gettype($query_params)
3213
-                ),
3214
-                '4.6.0'
3215
-            );
3216
-            $query_params = array();
3217
-        }
3218
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3219
-        //first check if we should alter the query to account for caps or not
3220
-        //because the caps might require us to do extra joins
3221
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3222
-            $query_params[0] = $where_query_params = array_replace_recursive(
3223
-                $where_query_params,
3224
-                $this->caps_where_conditions(
3225
-                    $query_params['caps']
3226
-                )
3227
-            );
3228
-        }
3229
-        $query_object = $this->_extract_related_models_from_query($query_params);
3230
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3231
-        foreach ($where_query_params as $key => $value) {
3232
-            if (is_int($key)) {
3233
-                throw new EE_Error(
3234
-                    sprintf(
3235
-                        __(
3236
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3237
-                            "event_espresso"
3238
-                        ),
3239
-                        $key,
3240
-                        var_export($value, true),
3241
-                        var_export($query_params, true),
3242
-                        get_class($this)
3243
-                    )
3244
-                );
3245
-            }
3246
-        }
3247
-        if (
3248
-            array_key_exists('default_where_conditions', $query_params)
3249
-            && ! empty($query_params['default_where_conditions'])
3250
-        ) {
3251
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3252
-        } else {
3253
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3254
-        }
3255
-        $where_query_params = array_merge(
3256
-            $this->_get_default_where_conditions_for_models_in_query(
3257
-                $query_object,
3258
-                $use_default_where_conditions,
3259
-                $where_query_params
3260
-            ),
3261
-            $where_query_params
3262
-        );
3263
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3264
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3265
-        // So we need to setup a subquery and use that for the main join.
3266
-        // Note for now this only works on the primary table for the model.
3267
-        // So for instance, you could set the limit array like this:
3268
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3269
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3270
-            $query_object->set_main_model_join_sql(
3271
-                $this->_construct_limit_join_select(
3272
-                    $query_params['on_join_limit'][0],
3273
-                    $query_params['on_join_limit'][1]
3274
-                )
3275
-            );
3276
-        }
3277
-        //set limit
3278
-        if (array_key_exists('limit', $query_params)) {
3279
-            if (is_array($query_params['limit'])) {
3280
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3281
-                    $e = sprintf(
3282
-                        __(
3283
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3284
-                            "event_espresso"
3285
-                        ),
3286
-                        http_build_query($query_params['limit'])
3287
-                    );
3288
-                    throw new EE_Error($e . "|" . $e);
3289
-                }
3290
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3291
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3292
-            } elseif (! empty ($query_params['limit'])) {
3293
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3294
-            }
3295
-        }
3296
-        //set order by
3297
-        if (array_key_exists('order_by', $query_params)) {
3298
-            if (is_array($query_params['order_by'])) {
3299
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3300
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3301
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3302
-                if (array_key_exists('order', $query_params)) {
3303
-                    throw new EE_Error(
3304
-                        sprintf(
3305
-                            __(
3306
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3307
-                                "event_espresso"
3308
-                            ),
3309
-                            get_class($this),
3310
-                            implode(", ", array_keys($query_params['order_by'])),
3311
-                            implode(", ", $query_params['order_by']),
3312
-                            $query_params['order']
3313
-                        )
3314
-                    );
3315
-                }
3316
-                $this->_extract_related_models_from_sub_params_array_keys(
3317
-                    $query_params['order_by'],
3318
-                    $query_object,
3319
-                    'order_by'
3320
-                );
3321
-                //assume it's an array of fields to order by
3322
-                $order_array = array();
3323
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3324
-                    $order = $this->_extract_order($order);
3325
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3326
-                }
3327
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3328
-            } elseif (! empty ($query_params['order_by'])) {
3329
-                $this->_extract_related_model_info_from_query_param(
3330
-                    $query_params['order_by'],
3331
-                    $query_object,
3332
-                    'order',
3333
-                    $query_params['order_by']
3334
-                );
3335
-                $order = isset($query_params['order'])
3336
-                    ? $this->_extract_order($query_params['order'])
3337
-                    : 'DESC';
3338
-                $query_object->set_order_by_sql(
3339
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3340
-                );
3341
-            }
3342
-        }
3343
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3344
-        if (! array_key_exists('order_by', $query_params)
3345
-            && array_key_exists('order', $query_params)
3346
-            && ! empty($query_params['order'])
3347
-        ) {
3348
-            $pk_field = $this->get_primary_key_field();
3349
-            $order = $this->_extract_order($query_params['order']);
3350
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3351
-        }
3352
-        //set group by
3353
-        if (array_key_exists('group_by', $query_params)) {
3354
-            if (is_array($query_params['group_by'])) {
3355
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3356
-                $group_by_array = array();
3357
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3358
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3359
-                }
3360
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3361
-            } elseif (! empty ($query_params['group_by'])) {
3362
-                $query_object->set_group_by_sql(
3363
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3364
-                );
3365
-            }
3366
-        }
3367
-        //set having
3368
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3369
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3370
-        }
3371
-        //now, just verify they didn't pass anything wack
3372
-        foreach ($query_params as $query_key => $query_value) {
3373
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3374
-                throw new EE_Error(
3375
-                    sprintf(
3376
-                        __(
3377
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3378
-                            'event_espresso'
3379
-                        ),
3380
-                        $query_key,
3381
-                        get_class($this),
3382
-                        //						print_r( $this->_allowed_query_params, TRUE )
3383
-                        implode(',', $this->_allowed_query_params)
3384
-                    )
3385
-                );
3386
-            }
3387
-        }
3388
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3389
-        if (empty($main_model_join_sql)) {
3390
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3391
-        }
3392
-        return $query_object;
3393
-    }
3394
-
3395
-
3396
-
3397
-    /**
3398
-     * Gets the where conditions that should be imposed on the query based on the
3399
-     * context (eg reading frontend, backend, edit or delete).
3400
-     *
3401
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3402
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3403
-     * @throws \EE_Error
3404
-     */
3405
-    public function caps_where_conditions($context = self::caps_read)
3406
-    {
3407
-        EEM_Base::verify_is_valid_cap_context($context);
3408
-        $cap_where_conditions = array();
3409
-        $cap_restrictions = $this->caps_missing($context);
3410
-        /**
3411
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3412
-         */
3413
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3414
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3415
-                $restriction_if_no_cap->get_default_where_conditions());
3416
-        }
3417
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3418
-            $cap_restrictions);
3419
-    }
3420
-
3421
-
3422
-
3423
-    /**
3424
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3425
-     * otherwise throws an exception
3426
-     *
3427
-     * @param string $should_be_order_string
3428
-     * @return string either ASC, asc, DESC or desc
3429
-     * @throws EE_Error
3430
-     */
3431
-    private function _extract_order($should_be_order_string)
3432
-    {
3433
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3434
-            return $should_be_order_string;
3435
-        } else {
3436
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3437
-                "event_espresso"), get_class($this), $should_be_order_string));
3438
-        }
3439
-    }
3440
-
3441
-
3442
-
3443
-    /**
3444
-     * Looks at all the models which are included in this query, and asks each
3445
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3446
-     * so they can be merged
3447
-     *
3448
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3449
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3450
-     *                                                                  'none' means NO default where conditions will
3451
-     *                                                                  be used AT ALL during this query.
3452
-     *                                                                  'other_models_only' means default where
3453
-     *                                                                  conditions from other models will be used, but
3454
-     *                                                                  not for this primary model. 'all', the default,
3455
-     *                                                                  means default where conditions will apply as
3456
-     *                                                                  normal
3457
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3458
-     * @throws EE_Error
3459
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3460
-     */
3461
-    private function _get_default_where_conditions_for_models_in_query(
3462
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3463
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3464
-        $where_query_params = array()
3465
-    ) {
3466
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3467
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3468
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3469
-                "event_espresso"), $use_default_where_conditions,
3470
-                implode(", ", $allowed_used_default_where_conditions_values)));
3471
-        }
3472
-        $universal_query_params = array();
3473
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3474
-            $universal_query_params = $this->_get_default_where_conditions();
3475
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3476
-            $universal_query_params = $this->_get_minimum_where_conditions();
3477
-        }
3478
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3479
-            $related_model = $this->get_related_model_obj($model_name);
3480
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3481
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3482
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3483
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3484
-            } else {
3485
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3486
-                continue;
3487
-            }
3488
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3489
-                $related_model_universal_where_params,
3490
-                $where_query_params,
3491
-                $related_model,
3492
-                $model_relation_path
3493
-            );
3494
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3495
-                $universal_query_params,
3496
-                $overrides
3497
-            );
3498
-        }
3499
-        return $universal_query_params;
3500
-    }
3501
-
3502
-
3503
-
3504
-    /**
3505
-     * Determines whether or not we should use default where conditions for the model in question
3506
-     * (this model, or other related models).
3507
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3508
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3509
-     * We should use default where conditions on related models when they requested to use default where conditions
3510
-     * on all models, or specifically just on other related models
3511
-     * @param      $default_where_conditions_value
3512
-     * @param bool $for_this_model false means this is for OTHER related models
3513
-     * @return bool
3514
-     */
3515
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3516
-    {
3517
-        return (
3518
-                   $for_this_model
3519
-                   && in_array(
3520
-                       $default_where_conditions_value,
3521
-                       array(
3522
-                           EEM_Base::default_where_conditions_all,
3523
-                           EEM_Base::default_where_conditions_this_only,
3524
-                           EEM_Base::default_where_conditions_minimum_others,
3525
-                       ),
3526
-                       true
3527
-                   )
3528
-               )
3529
-               || (
3530
-                   ! $for_this_model
3531
-                   && in_array(
3532
-                       $default_where_conditions_value,
3533
-                       array(
3534
-                           EEM_Base::default_where_conditions_all,
3535
-                           EEM_Base::default_where_conditions_others_only,
3536
-                       ),
3537
-                       true
3538
-                   )
3539
-               );
3540
-    }
3541
-
3542
-    /**
3543
-     * Determines whether or not we should use default minimum conditions for the model in question
3544
-     * (this model, or other related models).
3545
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3546
-     * where conditions.
3547
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3548
-     * on this model or others
3549
-     * @param      $default_where_conditions_value
3550
-     * @param bool $for_this_model false means this is for OTHER related models
3551
-     * @return bool
3552
-     */
3553
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3554
-    {
3555
-        return (
3556
-                   $for_this_model
3557
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3558
-               )
3559
-               || (
3560
-                   ! $for_this_model
3561
-                   && in_array(
3562
-                       $default_where_conditions_value,
3563
-                       array(
3564
-                           EEM_Base::default_where_conditions_minimum_others,
3565
-                           EEM_Base::default_where_conditions_minimum_all,
3566
-                       ),
3567
-                       true
3568
-                   )
3569
-               );
3570
-    }
3571
-
3572
-
3573
-    /**
3574
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3575
-     * then we also add a special where condition which allows for that model's primary key
3576
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3577
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3578
-     *
3579
-     * @param array    $default_where_conditions
3580
-     * @param array    $provided_where_conditions
3581
-     * @param EEM_Base $model
3582
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3583
-     * @return array like EEM_Base::get_all's $query_params[0]
3584
-     * @throws \EE_Error
3585
-     */
3586
-    private function _override_defaults_or_make_null_friendly(
3587
-        $default_where_conditions,
3588
-        $provided_where_conditions,
3589
-        $model,
3590
-        $model_relation_path
3591
-    ) {
3592
-        $null_friendly_where_conditions = array();
3593
-        $none_overridden = true;
3594
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3595
-        foreach ($default_where_conditions as $key => $val) {
3596
-            if (isset($provided_where_conditions[$key])) {
3597
-                $none_overridden = false;
3598
-            } else {
3599
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3600
-            }
3601
-        }
3602
-        if ($none_overridden && $default_where_conditions) {
3603
-            if ($model->has_primary_key_field()) {
3604
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3605
-                                                                                . "."
3606
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3607
-            }/*else{
32
+	//admin posty
33
+	//basic -> grants access to mine -> if they don't have it, select none
34
+	//*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
+	//*_published -> grants access to published -> if they dont have it, select non-published
37
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
39
+	//frontend posty
40
+	//by default has access to published
41
+	//basic -> grants access to mine that arent published, and all published
42
+	//*_others ->grants access to others that arent private, all mine
43
+	//*_private -> grants full access
44
+	//frontend non-posty
45
+	//like admin posty
46
+	//category-y
47
+	//assign -> grants access to join-table
48
+	//(delete, edit)
49
+	//payment-method-y
50
+	//for each registered payment method,
51
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
+	/**
53
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
56
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
+	 *
58
+	 * @var boolean
59
+	 */
60
+	private $_values_already_prepared_by_model_object = 0;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the data is just like form input that needs to have the model fields'
65
+	 * prepare_for_set and prepare_for_use_in_db called on it
66
+	 */
67
+	const not_prepared_by_model_object = 0;
68
+
69
+	/**
70
+	 * when $_values_already_prepared_by_model_object equals this, we
71
+	 * assume this value is coming from a model object and doesn't need to have
72
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
73
+	 */
74
+	const prepared_by_model_object = 1;
75
+
76
+	/**
77
+	 * when $_values_already_prepared_by_model_object equals this, we assume
78
+	 * the values are already to be used in the database (ie no processing is done
79
+	 * on them by the model's fields)
80
+	 */
81
+	const prepared_for_use_in_db = 2;
82
+
83
+
84
+	protected $singular_item = 'Item';
85
+
86
+	protected $plural_item   = 'Items';
87
+
88
+	/**
89
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
+	 */
91
+	protected $_tables;
92
+
93
+	/**
94
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
+	 *
98
+	 * @var \EE_Model_Field_Base[] $_fields
99
+	 */
100
+	protected $_fields;
101
+
102
+	/**
103
+	 * array of different kinds of relations
104
+	 *
105
+	 * @var \EE_Model_Relation_Base[] $_model_relations
106
+	 */
107
+	protected $_model_relations;
108
+
109
+	/**
110
+	 * @var \EE_Index[] $_indexes
111
+	 */
112
+	protected $_indexes = array();
113
+
114
+	/**
115
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
116
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
+	 * by setting the same columns as used in these queries in the query yourself.
118
+	 *
119
+	 * @var EE_Default_Where_Conditions
120
+	 */
121
+	protected $_default_where_conditions_strategy;
122
+
123
+	/**
124
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
+	 * This is particularly useful when you want something between 'none' and 'default'
126
+	 *
127
+	 * @var EE_Default_Where_Conditions
128
+	 */
129
+	protected $_minimum_where_conditions_strategy;
130
+
131
+	/**
132
+	 * String describing how to find the "owner" of this model's objects.
133
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
+	 * But when there isn't, this indicates which related model, or transiently-related model,
135
+	 * has the foreign key to the wp_users table.
136
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
+	 * related to events, and events have a foreign key to wp_users.
138
+	 * On EEM_Transaction, this would be 'Transaction.Event'
139
+	 *
140
+	 * @var string
141
+	 */
142
+	protected $_model_chain_to_wp_user = '';
143
+
144
+	/**
145
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
+	 * don't need it (particularly CPT models)
147
+	 *
148
+	 * @var bool
149
+	 */
150
+	protected $_ignore_where_strategy = false;
151
+
152
+	/**
153
+	 * String used in caps relating to this model. Eg, if the caps relating to this
154
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
+	 *
156
+	 * @var string. If null it hasn't been initialized yet. If false then we
157
+	 * have indicated capabilities don't apply to this
158
+	 */
159
+	protected $_caps_slug = null;
160
+
161
+	/**
162
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
+	 * and next-level keys are capability names, and each's value is a
164
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
166
+	 * and then each capability in the corresponding sub-array that they're missing
167
+	 * adds the where conditions onto the query.
168
+	 *
169
+	 * @var array
170
+	 */
171
+	protected $_cap_restrictions = array(
172
+		self::caps_read       => array(),
173
+		self::caps_read_admin => array(),
174
+		self::caps_edit       => array(),
175
+		self::caps_delete     => array(),
176
+	);
177
+
178
+	/**
179
+	 * Array defining which cap restriction generators to use to create default
180
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
181
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
+	 * automatically set this to false (not just null).
184
+	 *
185
+	 * @var EE_Restriction_Generator_Base[]
186
+	 */
187
+	protected $_cap_restriction_generators = array();
188
+
189
+	/**
190
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
+	 */
192
+	const caps_read       = 'read';
193
+
194
+	const caps_read_admin = 'read_admin';
195
+
196
+	const caps_edit       = 'edit';
197
+
198
+	const caps_delete     = 'delete';
199
+
200
+	/**
201
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
+	 * maps to 'read' because when looking for relevant permissions we're going to use
204
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
205
+	 *
206
+	 * @var array
207
+	 */
208
+	protected $_cap_contexts_to_cap_action_map = array(
209
+		self::caps_read       => 'read',
210
+		self::caps_read_admin => 'read',
211
+		self::caps_edit       => 'edit',
212
+		self::caps_delete     => 'delete',
213
+	);
214
+
215
+	/**
216
+	 * Timezone
217
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
+	 * EE_Datetime_Field data type will have access to it.
221
+	 *
222
+	 * @var string
223
+	 */
224
+	protected $_timezone;
225
+
226
+
227
+	/**
228
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
+	 * multisite.
230
+	 *
231
+	 * @var int
232
+	 */
233
+	protected static $_model_query_blog_id;
234
+
235
+	/**
236
+	 * A copy of _fields, except the array keys are the model names pointed to by
237
+	 * the field
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cache_foreign_key_to_fields = array();
242
+
243
+	/**
244
+	 * Cached list of all the fields on the model, indexed by their name
245
+	 *
246
+	 * @var EE_Model_Field_Base[]
247
+	 */
248
+	private $_cached_fields = null;
249
+
250
+	/**
251
+	 * Cached list of all the fields on the model, except those that are
252
+	 * marked as only pertinent to the database
253
+	 *
254
+	 * @var EE_Model_Field_Base[]
255
+	 */
256
+	private $_cached_fields_non_db_only = null;
257
+
258
+	/**
259
+	 * A cached reference to the primary key for quick lookup
260
+	 *
261
+	 * @var EE_Model_Field_Base
262
+	 */
263
+	private $_primary_key_field = null;
264
+
265
+	/**
266
+	 * Flag indicating whether this model has a primary key or not
267
+	 *
268
+	 * @var boolean
269
+	 */
270
+	protected $_has_primary_key_field = null;
271
+
272
+	/**
273
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
274
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
+	 *
276
+	 * @var boolean
277
+	 */
278
+	protected $_wp_core_model = false;
279
+
280
+	/**
281
+	 *    List of valid operators that can be used for querying.
282
+	 * The keys are all operators we'll accept, the values are the real SQL
283
+	 * operators used
284
+	 *
285
+	 * @var array
286
+	 */
287
+	protected $_valid_operators = array(
288
+		'='           => '=',
289
+		'<='          => '<=',
290
+		'<'           => '<',
291
+		'>='          => '>=',
292
+		'>'           => '>',
293
+		'!='          => '!=',
294
+		'LIKE'        => 'LIKE',
295
+		'like'        => 'LIKE',
296
+		'NOT_LIKE'    => 'NOT LIKE',
297
+		'not_like'    => 'NOT LIKE',
298
+		'NOT LIKE'    => 'NOT LIKE',
299
+		'not like'    => 'NOT LIKE',
300
+		'IN'          => 'IN',
301
+		'in'          => 'IN',
302
+		'NOT_IN'      => 'NOT IN',
303
+		'not_in'      => 'NOT IN',
304
+		'NOT IN'      => 'NOT IN',
305
+		'not in'      => 'NOT IN',
306
+		'between'     => 'BETWEEN',
307
+		'BETWEEN'     => 'BETWEEN',
308
+		'IS_NOT_NULL' => 'IS NOT NULL',
309
+		'is_not_null' => 'IS NOT NULL',
310
+		'IS NOT NULL' => 'IS NOT NULL',
311
+		'is not null' => 'IS NOT NULL',
312
+		'IS_NULL'     => 'IS NULL',
313
+		'is_null'     => 'IS NULL',
314
+		'IS NULL'     => 'IS NULL',
315
+		'is null'     => 'IS NULL',
316
+		'REGEXP'      => 'REGEXP',
317
+		'regexp'      => 'REGEXP',
318
+		'NOT_REGEXP'  => 'NOT REGEXP',
319
+		'not_regexp'  => 'NOT REGEXP',
320
+		'NOT REGEXP'  => 'NOT REGEXP',
321
+		'not regexp'  => 'NOT REGEXP',
322
+	);
323
+
324
+	/**
325
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
+	 *
327
+	 * @var array
328
+	 */
329
+	protected $_in_style_operators = array('IN', 'NOT IN');
330
+
331
+	/**
332
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
+	 * '12-31-2012'"
334
+	 *
335
+	 * @var array
336
+	 */
337
+	protected $_between_style_operators = array('BETWEEN');
338
+
339
+	/**
340
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
+	 * on a join table.
342
+	 *
343
+	 * @var array
344
+	 */
345
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
+
347
+	/**
348
+	 * Allowed values for $query_params['order'] for ordering in queries
349
+	 *
350
+	 * @var array
351
+	 */
352
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
+
354
+	/**
355
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
357
+	 *
358
+	 * @var array
359
+	 */
360
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
+
362
+	/**
363
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
365
+	 *
366
+	 * @var array
367
+	 */
368
+	private $_allowed_query_params = array(
369
+		0,
370
+		'limit',
371
+		'order_by',
372
+		'group_by',
373
+		'having',
374
+		'force_join',
375
+		'order',
376
+		'on_join_limit',
377
+		'default_where_conditions',
378
+		'caps',
379
+	);
380
+
381
+	/**
382
+	 * All the data types that can be used in $wpdb->prepare statements.
383
+	 *
384
+	 * @var array
385
+	 */
386
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
+
388
+	/**
389
+	 *    EE_Registry Object
390
+	 *
391
+	 * @var    object
392
+	 * @access    protected
393
+	 */
394
+	protected $EE = null;
395
+
396
+
397
+	/**
398
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
+	 *
400
+	 * @var int
401
+	 */
402
+	protected $_show_next_x_db_queries = 0;
403
+
404
+	/**
405
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
+	 *
408
+	 * @var array
409
+	 */
410
+	protected $_custom_selections = array();
411
+
412
+	/**
413
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
+	 * caches every model object we've fetched from the DB on this request
415
+	 *
416
+	 * @var array
417
+	 */
418
+	protected $_entity_map;
419
+
420
+	/**
421
+	 * constant used to show EEM_Base has not yet verified the db on this http request
422
+	 */
423
+	const db_verified_none = 0;
424
+
425
+	/**
426
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
427
+	 * but not the addons' dbs
428
+	 */
429
+	const db_verified_core = 1;
430
+
431
+	/**
432
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
+	 * the EE core db too)
434
+	 */
435
+	const db_verified_addons = 2;
436
+
437
+	/**
438
+	 * indicates whether an EEM_Base child has already re-verified the DB
439
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
440
+	 * looking like EEM_Base::db_verified_*
441
+	 *
442
+	 * @var int - 0 = none, 1 = core, 2 = addons
443
+	 */
444
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
445
+
446
+	/**
447
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
448
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
449
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
450
+	 */
451
+	const default_where_conditions_all = 'all';
452
+
453
+	/**
454
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
455
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
456
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
457
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
458
+	 *        models which share tables with other models, this can return data for the wrong model.
459
+	 */
460
+	const default_where_conditions_this_only = 'this_model_only';
461
+
462
+	/**
463
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
464
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
465
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
466
+	 */
467
+	const default_where_conditions_others_only = 'other_models_only';
468
+
469
+	/**
470
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
471
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
472
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
473
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
474
+	 *        (regardless of whether those events and venues are trashed)
475
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
476
+	 *        events.
477
+	 */
478
+	const default_where_conditions_minimum_all = 'minimum';
479
+
480
+	/**
481
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
482
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
483
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
484
+	 *        not)
485
+	 */
486
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
487
+
488
+	/**
489
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
490
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
491
+	 *        it's possible it will return table entries for other models. You should use
492
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
493
+	 */
494
+	const default_where_conditions_none = 'none';
495
+
496
+
497
+
498
+	/**
499
+	 * About all child constructors:
500
+	 * they should define the _tables, _fields and _model_relations arrays.
501
+	 * Should ALWAYS be called after child constructor.
502
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
503
+	 * finalizes constructing all the object's attributes.
504
+	 * Generally, rather than requiring a child to code
505
+	 * $this->_tables = array(
506
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
507
+	 *        ...);
508
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
509
+	 * each EE_Table has a function to set the table's alias after the constructor, using
510
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
511
+	 * do something similar.
512
+	 *
513
+	 * @param null $timezone
514
+	 * @throws \EE_Error
515
+	 */
516
+	protected function __construct($timezone = null)
517
+	{
518
+		// check that the model has not been loaded too soon
519
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
520
+			throw new EE_Error (
521
+				sprintf(
522
+					__('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
523
+						'event_espresso'),
524
+					get_class($this)
525
+				)
526
+			);
527
+		}
528
+		/**
529
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
530
+		 */
531
+		if (empty(EEM_Base::$_model_query_blog_id)) {
532
+			EEM_Base::set_model_query_blog_id();
533
+		}
534
+		/**
535
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
536
+		 * just use EE_Register_Model_Extension
537
+		 *
538
+		 * @var EE_Table_Base[] $_tables
539
+		 */
540
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
541
+		foreach ($this->_tables as $table_alias => $table_obj) {
542
+			/** @var $table_obj EE_Table_Base */
543
+			$table_obj->_construct_finalize_with_alias($table_alias);
544
+			if ($table_obj instanceof EE_Secondary_Table) {
545
+				/** @var $table_obj EE_Secondary_Table */
546
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
547
+			}
548
+		}
549
+		/**
550
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
551
+		 * EE_Register_Model_Extension
552
+		 *
553
+		 * @param EE_Model_Field_Base[] $_fields
554
+		 */
555
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
556
+		$this->_invalidate_field_caches();
557
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
558
+			if (! array_key_exists($table_alias, $this->_tables)) {
559
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
560
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
561
+			}
562
+			foreach ($fields_for_table as $field_name => $field_obj) {
563
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
564
+				//primary key field base has a slightly different _construct_finalize
565
+				/** @var $field_obj EE_Model_Field_Base */
566
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
567
+			}
568
+		}
569
+		// everything is related to Extra_Meta
570
+		if (get_class($this) !== 'EEM_Extra_Meta') {
571
+			//make extra meta related to everything, but don't block deleting things just
572
+			//because they have related extra meta info. For now just orphan those extra meta
573
+			//in the future we should automatically delete them
574
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
575
+		}
576
+		//and change logs
577
+		if (get_class($this) !== 'EEM_Change_Log') {
578
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
579
+		}
580
+		/**
581
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
582
+		 * EE_Register_Model_Extension
583
+		 *
584
+		 * @param EE_Model_Relation_Base[] $_model_relations
585
+		 */
586
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
587
+			$this->_model_relations);
588
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
589
+			/** @var $relation_obj EE_Model_Relation_Base */
590
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
591
+		}
592
+		foreach ($this->_indexes as $index_name => $index_obj) {
593
+			/** @var $index_obj EE_Index */
594
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
595
+		}
596
+		$this->set_timezone($timezone);
597
+		//finalize default where condition strategy, or set default
598
+		if (! $this->_default_where_conditions_strategy) {
599
+			//nothing was set during child constructor, so set default
600
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
601
+		}
602
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
603
+		if (! $this->_minimum_where_conditions_strategy) {
604
+			//nothing was set during child constructor, so set default
605
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
606
+		}
607
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
608
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
609
+		//to indicate to NOT set it, set it to the logical default
610
+		if ($this->_caps_slug === null) {
611
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
612
+		}
613
+		//initialize the standard cap restriction generators if none were specified by the child constructor
614
+		if ($this->_cap_restriction_generators !== false) {
615
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
616
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
617
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
618
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
619
+						new EE_Restriction_Generator_Protected(),
620
+						$cap_context,
621
+						$this
622
+					);
623
+				}
624
+			}
625
+		}
626
+		//if there are cap restriction generators, use them to make the default cap restrictions
627
+		if ($this->_cap_restriction_generators !== false) {
628
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
629
+				if (! $generator_object) {
630
+					continue;
631
+				}
632
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
633
+					throw new EE_Error(
634
+						sprintf(
635
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
636
+								'event_espresso'),
637
+							$context,
638
+							$this->get_this_model_name()
639
+						)
640
+					);
641
+				}
642
+				$action = $this->cap_action_for_context($context);
643
+				if (! $generator_object->construction_finalized()) {
644
+					$generator_object->_construct_finalize($this, $action);
645
+				}
646
+			}
647
+		}
648
+		do_action('AHEE__' . get_class($this) . '__construct__end');
649
+	}
650
+
651
+
652
+
653
+	/**
654
+	 * Generates the cap restrictions for the given context, or if they were
655
+	 * already generated just gets what's cached
656
+	 *
657
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
658
+	 * @return EE_Default_Where_Conditions[]
659
+	 */
660
+	protected function _generate_cap_restrictions($context)
661
+	{
662
+		if (isset($this->_cap_restriction_generators[$context])
663
+			&& $this->_cap_restriction_generators[$context]
664
+			   instanceof
665
+			   EE_Restriction_Generator_Base
666
+		) {
667
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
668
+		} else {
669
+			return array();
670
+		}
671
+	}
672
+
673
+
674
+
675
+	/**
676
+	 * Used to set the $_model_query_blog_id static property.
677
+	 *
678
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
679
+	 *                      value for get_current_blog_id() will be used.
680
+	 */
681
+	public static function set_model_query_blog_id($blog_id = 0)
682
+	{
683
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
684
+	}
685
+
686
+
687
+
688
+	/**
689
+	 * Returns whatever is set as the internal $model_query_blog_id.
690
+	 *
691
+	 * @return int
692
+	 */
693
+	public static function get_model_query_blog_id()
694
+	{
695
+		return EEM_Base::$_model_query_blog_id;
696
+	}
697
+
698
+
699
+
700
+	/**
701
+	 *        This function is a singleton method used to instantiate the Espresso_model object
702
+	 *
703
+	 * @access public
704
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
705
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
706
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
707
+	 *                         timezone in the 'timezone_string' wp option)
708
+	 * @return static (as in the concrete child class)
709
+	 */
710
+	public static function instance($timezone = null)
711
+	{
712
+		// check if instance of Espresso_model already exists
713
+		if (! static::$_instance instanceof static) {
714
+			// instantiate Espresso_model
715
+			static::$_instance = new static($timezone);
716
+		}
717
+		//we might have a timezone set, let set_timezone decide what to do with it
718
+		static::$_instance->set_timezone($timezone);
719
+		// Espresso_model object
720
+		return static::$_instance;
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * resets the model and returns it
727
+	 *
728
+	 * @param null | string $timezone
729
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
730
+	 * all its properties reset; if it wasn't instantiated, returns null)
731
+	 */
732
+	public static function reset($timezone = null)
733
+	{
734
+		if (static::$_instance instanceof EEM_Base) {
735
+			//let's try to NOT swap out the current instance for a new one
736
+			//because if someone has a reference to it, we can't remove their reference
737
+			//so it's best to keep using the same reference, but change the original object
738
+			//reset all its properties to their original values as defined in the class
739
+			$r = new ReflectionClass(get_class(static::$_instance));
740
+			$static_properties = $r->getStaticProperties();
741
+			foreach ($r->getDefaultProperties() as $property => $value) {
742
+				//don't set instance to null like it was originally,
743
+				//but it's static anyways, and we're ignoring static properties (for now at least)
744
+				if (! isset($static_properties[$property])) {
745
+					static::$_instance->{$property} = $value;
746
+				}
747
+			}
748
+			//and then directly call its constructor again, like we would if we
749
+			//were creating a new one
750
+			static::$_instance->__construct($timezone);
751
+			return self::instance();
752
+		}
753
+		return null;
754
+	}
755
+
756
+
757
+
758
+	/**
759
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
760
+	 *
761
+	 * @param  boolean $translated return localized strings or JUST the array.
762
+	 * @return array
763
+	 * @throws \EE_Error
764
+	 */
765
+	public function status_array($translated = false)
766
+	{
767
+		if (! array_key_exists('Status', $this->_model_relations)) {
768
+			return array();
769
+		}
770
+		$model_name = $this->get_this_model_name();
771
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
772
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
773
+		$status_array = array();
774
+		foreach ($stati as $status) {
775
+			$status_array[$status->ID()] = $status->get('STS_code');
776
+		}
777
+		return $translated
778
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
779
+			: $status_array;
780
+	}
781
+
782
+
783
+
784
+	/**
785
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
786
+	 *
787
+	 * @param array $query_params             {
788
+	 * @var array $0 (where) array {
789
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
790
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
791
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
792
+	 *                                        conditions based on related models (and even
793
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
794
+	 *                                        name. Eg,
795
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
796
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
797
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
798
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
799
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
800
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
801
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
802
+	 *                                        to Venues (even when each of those models actually consisted of two
803
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
804
+	 *                                        just having
805
+	 *                                        "Venue.VNU_ID", you could have
806
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
807
+	 *                                        events are related to Registrations, which are related to Attendees). You
808
+	 *                                        can take it even further with
809
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
810
+	 *                                        (from the default of '='), change the value to an numerically-indexed
811
+	 *                                        array, where the first item in the list is the operator. eg: array(
812
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
813
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
814
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
815
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
816
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
817
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
818
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
819
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
820
+	 *                                        the value is a field, simply provide a third array item (true) to the
821
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
822
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
823
+	 *                                        Note: you can also use related model field names like you would any other
824
+	 *                                        field name. eg:
825
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
826
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
827
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
828
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
829
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
830
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
831
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
832
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
833
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
834
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
835
+	 *                                        "stick" until you specify an AND. eg
836
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
837
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
838
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
839
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
840
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
841
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
842
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
843
+	 *                                        too, eg:
844
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
845
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
846
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
847
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
848
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
849
+	 *                                        the OFFSET, the 2nd is the LIMIT
850
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
851
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
852
+	 *                                        following format array('on_join_limit'
853
+	 *                                        => array( 'table_alias', array(1,2) ) ).
854
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
855
+	 *                                        values are either 'ASC' or 'DESC'.
856
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
857
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
858
+	 *                                        DESC..." respectively. Like the
859
+	 *                                        'where' conditions, these fields can be on related models. Eg
860
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
861
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
862
+	 *                                        Attendee, Price, Datetime, etc.)
863
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
864
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
865
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
866
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
867
+	 *                                        order by the primary key. Eg,
868
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
869
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
870
+	 *                                        DTT_EVT_start) or
871
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
872
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
873
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
874
+	 *                                        'group_by'=>'VNU_ID', or
875
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
876
+	 *                                        if no
877
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
878
+	 *                                        model's primary key (or combined primary keys). This avoids some
879
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
880
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
881
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
882
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
883
+	 *                                        results)
884
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
885
+	 *                                        array where values are models to be joined in the query.Eg
886
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
887
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
888
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
889
+	 *                                        related models which belongs to the current model
890
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
891
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
892
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
893
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
894
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
895
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
896
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
897
+	 *                                        this model's default where conditions added to the query, use
898
+	 *                                        'this_model_only'. If you want to use all default where conditions
899
+	 *                                        (default), set to 'all'.
900
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
901
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
902
+	 *                                        everything? Or should we only show the current user items they should be
903
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
904
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
905
+	 *                                        }
906
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
907
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
908
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
909
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
910
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
911
+	 *                                        array( array(
912
+	 *                                        'OR'=>array(
913
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
914
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
915
+	 *                                        )
916
+	 *                                        ),
917
+	 *                                        'limit'=>10,
918
+	 *                                        'group_by'=>'TXN_ID'
919
+	 *                                        ));
920
+	 *                                        get all the answers to the question titled "shirt size" for event with id
921
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
922
+	 *                                        'Question.QST_display_text'=>'shirt size',
923
+	 *                                        'Registration.Event.EVT_ID'=>12
924
+	 *                                        ),
925
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
926
+	 *                                        ));
927
+	 * @throws \EE_Error
928
+	 */
929
+	public function get_all($query_params = array())
930
+	{
931
+		if (isset($query_params['limit'])
932
+			&& ! isset($query_params['group_by'])
933
+		) {
934
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
935
+		}
936
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
937
+	}
938
+
939
+
940
+
941
+	/**
942
+	 * Modifies the query parameters so we only get back model objects
943
+	 * that "belong" to the current user
944
+	 *
945
+	 * @param array $query_params @see EEM_Base::get_all()
946
+	 * @return array like EEM_Base::get_all
947
+	 */
948
+	public function alter_query_params_to_only_include_mine($query_params = array())
949
+	{
950
+		$wp_user_field_name = $this->wp_user_field_name();
951
+		if ($wp_user_field_name) {
952
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
953
+		}
954
+		return $query_params;
955
+	}
956
+
957
+
958
+
959
+	/**
960
+	 * Returns the name of the field's name that points to the WP_User table
961
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
962
+	 * foreign key to the WP_User table)
963
+	 *
964
+	 * @return string|boolean string on success, boolean false when there is no
965
+	 * foreign key to the WP_User table
966
+	 */
967
+	public function wp_user_field_name()
968
+	{
969
+		try {
970
+			if (! empty($this->_model_chain_to_wp_user)) {
971
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
972
+				$last_model_name = end($models_to_follow_to_wp_users);
973
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
974
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
975
+			} else {
976
+				$model_with_fk_to_wp_users = $this;
977
+				$model_chain_to_wp_user = '';
978
+			}
979
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
980
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
981
+		} catch (EE_Error $e) {
982
+			return false;
983
+		}
984
+	}
985
+
986
+
987
+
988
+	/**
989
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
990
+	 * (or transiently-related model) has a foreign key to the wp_users table;
991
+	 * useful for finding if model objects of this type are 'owned' by the current user.
992
+	 * This is an empty string when the foreign key is on this model and when it isn't,
993
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
994
+	 * (or transiently-related model)
995
+	 *
996
+	 * @return string
997
+	 */
998
+	public function model_chain_to_wp_user()
999
+	{
1000
+		return $this->_model_chain_to_wp_user;
1001
+	}
1002
+
1003
+
1004
+
1005
+	/**
1006
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1007
+	 * like how registrations don't have a foreign key to wp_users, but the
1008
+	 * events they are for are), or is unrelated to wp users.
1009
+	 * generally available
1010
+	 *
1011
+	 * @return boolean
1012
+	 */
1013
+	public function is_owned()
1014
+	{
1015
+		if ($this->model_chain_to_wp_user()) {
1016
+			return true;
1017
+		} else {
1018
+			try {
1019
+				$this->get_foreign_key_to('WP_User');
1020
+				return true;
1021
+			} catch (EE_Error $e) {
1022
+				return false;
1023
+			}
1024
+		}
1025
+	}
1026
+
1027
+
1028
+
1029
+	/**
1030
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1031
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1032
+	 * the model)
1033
+	 *
1034
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1035
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1037
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1038
+	 *                                  override this and set the select to "*", or a specific column name, like
1039
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
+	 *                                  the aliases used to refer to this selection, and values are to be
1042
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
+	 * @throws \EE_Error
1046
+	 */
1047
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1048
+	{
1049
+		// remember the custom selections, if any, and type cast as array
1050
+		// (unless $columns_to_select is an object, then just set as an empty array)
1051
+		// Note: (array) 'some string' === array( 'some string' )
1052
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1053
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1054
+		$select_expressions = $columns_to_select !== null
1055
+			? $this->_construct_select_from_input($columns_to_select)
1056
+			: $this->_construct_default_select_sql($model_query_info);
1057
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1058
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1059
+	}
1060
+
1061
+
1062
+
1063
+	/**
1064
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1065
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1066
+	 * take care of joins, field preparation etc.
1067
+	 *
1068
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1069
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1070
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1071
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1072
+	 *                                  override this and set the select to "*", or a specific column name, like
1073
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1074
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1075
+	 *                                  the aliases used to refer to this selection, and values are to be
1076
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1077
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1078
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1079
+	 * @throws \EE_Error
1080
+	 */
1081
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1082
+	{
1083
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1084
+	}
1085
+
1086
+
1087
+
1088
+	/**
1089
+	 * For creating a custom select statement
1090
+	 *
1091
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1092
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1093
+	 *                                 SQL, and 1=>is the datatype
1094
+	 * @throws EE_Error
1095
+	 * @return string
1096
+	 */
1097
+	private function _construct_select_from_input($columns_to_select)
1098
+	{
1099
+		if (is_array($columns_to_select)) {
1100
+			$select_sql_array = array();
1101
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1102
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1103
+					throw new EE_Error(
1104
+						sprintf(
1105
+							__(
1106
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1107
+								"event_espresso"
1108
+							),
1109
+							$selection_and_datatype,
1110
+							$alias
1111
+						)
1112
+					);
1113
+				}
1114
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1115
+					throw new EE_Error(
1116
+						sprintf(
1117
+							__(
1118
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1119
+								"event_espresso"
1120
+							),
1121
+							$selection_and_datatype[1],
1122
+							$selection_and_datatype[0],
1123
+							$alias,
1124
+							implode(",", $this->_valid_wpdb_data_types)
1125
+						)
1126
+					);
1127
+				}
1128
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1129
+			}
1130
+			$columns_to_select_string = implode(", ", $select_sql_array);
1131
+		} else {
1132
+			$columns_to_select_string = $columns_to_select;
1133
+		}
1134
+		return $columns_to_select_string;
1135
+	}
1136
+
1137
+
1138
+
1139
+	/**
1140
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1141
+	 *
1142
+	 * @return string
1143
+	 * @throws \EE_Error
1144
+	 */
1145
+	public function primary_key_name()
1146
+	{
1147
+		return $this->get_primary_key_field()->get_name();
1148
+	}
1149
+
1150
+
1151
+
1152
+	/**
1153
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1154
+	 * If there is no primary key on this model, $id is treated as primary key string
1155
+	 *
1156
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1157
+	 * @return EE_Base_Class
1158
+	 */
1159
+	public function get_one_by_ID($id)
1160
+	{
1161
+		if ($this->get_from_entity_map($id)) {
1162
+			return $this->get_from_entity_map($id);
1163
+		}
1164
+		return $this->get_one(
1165
+			$this->alter_query_params_to_restrict_by_ID(
1166
+				$id,
1167
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1168
+			)
1169
+		);
1170
+	}
1171
+
1172
+
1173
+
1174
+	/**
1175
+	 * Alters query parameters to only get items with this ID are returned.
1176
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1177
+	 * or could just be a simple primary key ID
1178
+	 *
1179
+	 * @param int   $id
1180
+	 * @param array $query_params
1181
+	 * @return array of normal query params, @see EEM_Base::get_all
1182
+	 * @throws \EE_Error
1183
+	 */
1184
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1185
+	{
1186
+		if (! isset($query_params[0])) {
1187
+			$query_params[0] = array();
1188
+		}
1189
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1190
+		if ($conditions_from_id === null) {
1191
+			$query_params[0][$this->primary_key_name()] = $id;
1192
+		} else {
1193
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1194
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1195
+		}
1196
+		return $query_params;
1197
+	}
1198
+
1199
+
1200
+
1201
+	/**
1202
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1203
+	 * array. If no item is found, null is returned.
1204
+	 *
1205
+	 * @param array $query_params like EEM_Base's $query_params variable.
1206
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1207
+	 * @throws \EE_Error
1208
+	 */
1209
+	public function get_one($query_params = array())
1210
+	{
1211
+		if (! is_array($query_params)) {
1212
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1213
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1214
+					gettype($query_params)), '4.6.0');
1215
+			$query_params = array();
1216
+		}
1217
+		$query_params['limit'] = 1;
1218
+		$items = $this->get_all($query_params);
1219
+		if (empty($items)) {
1220
+			return null;
1221
+		} else {
1222
+			return array_shift($items);
1223
+		}
1224
+	}
1225
+
1226
+
1227
+
1228
+	/**
1229
+	 * Returns the next x number of items in sequence from the given value as
1230
+	 * found in the database matching the given query conditions.
1231
+	 *
1232
+	 * @param mixed $current_field_value    Value used for the reference point.
1233
+	 * @param null  $field_to_order_by      What field is used for the
1234
+	 *                                      reference point.
1235
+	 * @param int   $limit                  How many to return.
1236
+	 * @param array $query_params           Extra conditions on the query.
1237
+	 * @param null  $columns_to_select      If left null, then an array of
1238
+	 *                                      EE_Base_Class objects is returned,
1239
+	 *                                      otherwise you can indicate just the
1240
+	 *                                      columns you want returned.
1241
+	 * @return EE_Base_Class[]|array
1242
+	 * @throws \EE_Error
1243
+	 */
1244
+	public function next_x(
1245
+		$current_field_value,
1246
+		$field_to_order_by = null,
1247
+		$limit = 1,
1248
+		$query_params = array(),
1249
+		$columns_to_select = null
1250
+	) {
1251
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1252
+			$columns_to_select);
1253
+	}
1254
+
1255
+
1256
+
1257
+	/**
1258
+	 * Returns the previous x number of items in sequence from the given value
1259
+	 * as found in the database matching the given query conditions.
1260
+	 *
1261
+	 * @param mixed $current_field_value    Value used for the reference point.
1262
+	 * @param null  $field_to_order_by      What field is used for the
1263
+	 *                                      reference point.
1264
+	 * @param int   $limit                  How many to return.
1265
+	 * @param array $query_params           Extra conditions on the query.
1266
+	 * @param null  $columns_to_select      If left null, then an array of
1267
+	 *                                      EE_Base_Class objects is returned,
1268
+	 *                                      otherwise you can indicate just the
1269
+	 *                                      columns you want returned.
1270
+	 * @return EE_Base_Class[]|array
1271
+	 * @throws \EE_Error
1272
+	 */
1273
+	public function previous_x(
1274
+		$current_field_value,
1275
+		$field_to_order_by = null,
1276
+		$limit = 1,
1277
+		$query_params = array(),
1278
+		$columns_to_select = null
1279
+	) {
1280
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1281
+			$columns_to_select);
1282
+	}
1283
+
1284
+
1285
+
1286
+	/**
1287
+	 * Returns the next item in sequence from the given value as found in the
1288
+	 * database matching the given query conditions.
1289
+	 *
1290
+	 * @param mixed $current_field_value    Value used for the reference point.
1291
+	 * @param null  $field_to_order_by      What field is used for the
1292
+	 *                                      reference point.
1293
+	 * @param array $query_params           Extra conditions on the query.
1294
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1295
+	 *                                      object is returned, otherwise you
1296
+	 *                                      can indicate just the columns you
1297
+	 *                                      want and a single array indexed by
1298
+	 *                                      the columns will be returned.
1299
+	 * @return EE_Base_Class|null|array()
1300
+	 * @throws \EE_Error
1301
+	 */
1302
+	public function next(
1303
+		$current_field_value,
1304
+		$field_to_order_by = null,
1305
+		$query_params = array(),
1306
+		$columns_to_select = null
1307
+	) {
1308
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1309
+			$columns_to_select);
1310
+		return empty($results) ? null : reset($results);
1311
+	}
1312
+
1313
+
1314
+
1315
+	/**
1316
+	 * Returns the previous item in sequence from the given value as found in
1317
+	 * the database matching the given query conditions.
1318
+	 *
1319
+	 * @param mixed $current_field_value    Value used for the reference point.
1320
+	 * @param null  $field_to_order_by      What field is used for the
1321
+	 *                                      reference point.
1322
+	 * @param array $query_params           Extra conditions on the query.
1323
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1324
+	 *                                      object is returned, otherwise you
1325
+	 *                                      can indicate just the columns you
1326
+	 *                                      want and a single array indexed by
1327
+	 *                                      the columns will be returned.
1328
+	 * @return EE_Base_Class|null|array()
1329
+	 * @throws EE_Error
1330
+	 */
1331
+	public function previous(
1332
+		$current_field_value,
1333
+		$field_to_order_by = null,
1334
+		$query_params = array(),
1335
+		$columns_to_select = null
1336
+	) {
1337
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1338
+			$columns_to_select);
1339
+		return empty($results) ? null : reset($results);
1340
+	}
1341
+
1342
+
1343
+
1344
+	/**
1345
+	 * Returns the a consecutive number of items in sequence from the given
1346
+	 * value as found in the database matching the given query conditions.
1347
+	 *
1348
+	 * @param mixed  $current_field_value   Value used for the reference point.
1349
+	 * @param string $operand               What operand is used for the sequence.
1350
+	 * @param string $field_to_order_by     What field is used for the reference point.
1351
+	 * @param int    $limit                 How many to return.
1352
+	 * @param array  $query_params          Extra conditions on the query.
1353
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1354
+	 *                                      otherwise you can indicate just the columns you want returned.
1355
+	 * @return EE_Base_Class[]|array
1356
+	 * @throws EE_Error
1357
+	 */
1358
+	protected function _get_consecutive(
1359
+		$current_field_value,
1360
+		$operand = '>',
1361
+		$field_to_order_by = null,
1362
+		$limit = 1,
1363
+		$query_params = array(),
1364
+		$columns_to_select = null
1365
+	) {
1366
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1367
+		if (empty($field_to_order_by)) {
1368
+			if ($this->has_primary_key_field()) {
1369
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1370
+			} else {
1371
+				if (WP_DEBUG) {
1372
+					throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1373
+						'event_espresso'));
1374
+				}
1375
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1376
+				return array();
1377
+			}
1378
+		}
1379
+		if (! is_array($query_params)) {
1380
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1381
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1382
+					gettype($query_params)), '4.6.0');
1383
+			$query_params = array();
1384
+		}
1385
+		//let's add the where query param for consecutive look up.
1386
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1387
+		$query_params['limit'] = $limit;
1388
+		//set direction
1389
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1390
+		$query_params['order_by'] = $operand === '>'
1391
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1392
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1393
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1394
+		if (empty($columns_to_select)) {
1395
+			return $this->get_all($query_params);
1396
+		} else {
1397
+			//getting just the fields
1398
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1399
+		}
1400
+	}
1401
+
1402
+
1403
+
1404
+	/**
1405
+	 * This sets the _timezone property after model object has been instantiated.
1406
+	 *
1407
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1408
+	 */
1409
+	public function set_timezone($timezone)
1410
+	{
1411
+		if ($timezone !== null) {
1412
+			$this->_timezone = $timezone;
1413
+		}
1414
+		//note we need to loop through relations and set the timezone on those objects as well.
1415
+		foreach ($this->_model_relations as $relation) {
1416
+			$relation->set_timezone($timezone);
1417
+		}
1418
+		//and finally we do the same for any datetime fields
1419
+		foreach ($this->_fields as $field) {
1420
+			if ($field instanceof EE_Datetime_Field) {
1421
+				$field->set_timezone($timezone);
1422
+			}
1423
+		}
1424
+	}
1425
+
1426
+
1427
+
1428
+	/**
1429
+	 * This just returns whatever is set for the current timezone.
1430
+	 *
1431
+	 * @access public
1432
+	 * @return string
1433
+	 */
1434
+	public function get_timezone()
1435
+	{
1436
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1437
+		if (empty($this->_timezone)) {
1438
+			foreach ($this->_fields as $field) {
1439
+				if ($field instanceof EE_Datetime_Field) {
1440
+					$this->set_timezone($field->get_timezone());
1441
+					break;
1442
+				}
1443
+			}
1444
+		}
1445
+		//if timezone STILL empty then return the default timezone for the site.
1446
+		if (empty($this->_timezone)) {
1447
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1448
+		}
1449
+		return $this->_timezone;
1450
+	}
1451
+
1452
+
1453
+
1454
+	/**
1455
+	 * This returns the date formats set for the given field name and also ensures that
1456
+	 * $this->_timezone property is set correctly.
1457
+	 *
1458
+	 * @since 4.6.x
1459
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1460
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1461
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1462
+	 * @return array formats in an array with the date format first, and the time format last.
1463
+	 */
1464
+	public function get_formats_for($field_name, $pretty = false)
1465
+	{
1466
+		$field_settings = $this->field_settings_for($field_name);
1467
+		//if not a valid EE_Datetime_Field then throw error
1468
+		if (! $field_settings instanceof EE_Datetime_Field) {
1469
+			throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1470
+				'event_espresso'), $field_name));
1471
+		}
1472
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1473
+		//the field.
1474
+		$this->_timezone = $field_settings->get_timezone();
1475
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1476
+	}
1477
+
1478
+
1479
+
1480
+	/**
1481
+	 * This returns the current time in a format setup for a query on this model.
1482
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1483
+	 * it will return:
1484
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1485
+	 *  NOW
1486
+	 *  - or a unix timestamp (equivalent to time())
1487
+	 *
1488
+	 * @since 4.6.x
1489
+	 * @param string $field_name       The field the current time is needed for.
1490
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1491
+	 *                                 formatted string matching the set format for the field in the set timezone will
1492
+	 *                                 be returned.
1493
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1494
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1495
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1496
+	 *                                 exception is triggered.
1497
+	 */
1498
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1499
+	{
1500
+		$formats = $this->get_formats_for($field_name);
1501
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1502
+		if ($timestamp) {
1503
+			return $DateTime->format('U');
1504
+		}
1505
+		//not returning timestamp, so return formatted string in timezone.
1506
+		switch ($what) {
1507
+			case 'time' :
1508
+				return $DateTime->format($formats[1]);
1509
+				break;
1510
+			case 'date' :
1511
+				return $DateTime->format($formats[0]);
1512
+				break;
1513
+			default :
1514
+				return $DateTime->format(implode(' ', $formats));
1515
+				break;
1516
+		}
1517
+	}
1518
+
1519
+
1520
+
1521
+	/**
1522
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1523
+	 * for the model are.  Returns a DateTime object.
1524
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1525
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1526
+	 * ignored.
1527
+	 *
1528
+	 * @param string $field_name      The field being setup.
1529
+	 * @param string $timestring      The date time string being used.
1530
+	 * @param string $incoming_format The format for the time string.
1531
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1532
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1533
+	 *                                format is
1534
+	 *                                'U', this is ignored.
1535
+	 * @return DateTime
1536
+	 * @throws \EE_Error
1537
+	 */
1538
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1539
+	{
1540
+		//just using this to ensure the timezone is set correctly internally
1541
+		$this->get_formats_for($field_name);
1542
+		//load EEH_DTT_Helper
1543
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1544
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1545
+		return $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1546
+	}
1547
+
1548
+
1549
+
1550
+	/**
1551
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1552
+	 *
1553
+	 * @return EE_Table_Base[]
1554
+	 */
1555
+	public function get_tables()
1556
+	{
1557
+		return $this->_tables;
1558
+	}
1559
+
1560
+
1561
+
1562
+	/**
1563
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1564
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1565
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1566
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1567
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1568
+	 * model object with EVT_ID = 1
1569
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1570
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1571
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1572
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1573
+	 * are not specified)
1574
+	 *
1575
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1576
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1577
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1578
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1579
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1580
+	 *                                         ID=34, we'd use this method as follows:
1581
+	 *                                         EEM_Transaction::instance()->update(
1582
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1583
+	 *                                         array(array('TXN_ID'=>34)));
1584
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1585
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1586
+	 *                                         consider updating Question's QST_admin_label field is of type
1587
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1588
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1589
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1590
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1591
+	 *                                         TRUE, it is assumed that you've already called
1592
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1593
+	 *                                         malicious javascript. However, if
1594
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1595
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1596
+	 *                                         and every other field, before insertion. We provide this parameter
1597
+	 *                                         because model objects perform their prepare_for_set function on all
1598
+	 *                                         their values, and so don't need to be called again (and in many cases,
1599
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1600
+	 *                                         prepare_for_set method...)
1601
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1602
+	 *                                         in this model's entity map according to $fields_n_values that match
1603
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1604
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1605
+	 *                                         could get out-of-sync with the database
1606
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1607
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1608
+	 *                                         bad)
1609
+	 * @throws \EE_Error
1610
+	 */
1611
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1612
+	{
1613
+		if (! is_array($query_params)) {
1614
+			EE_Error::doing_it_wrong('EEM_Base::update',
1615
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1616
+					gettype($query_params)), '4.6.0');
1617
+			$query_params = array();
1618
+		}
1619
+		/**
1620
+		 * Action called before a model update call has been made.
1621
+		 *
1622
+		 * @param EEM_Base $model
1623
+		 * @param array    $fields_n_values the updated fields and their new values
1624
+		 * @param array    $query_params    @see EEM_Base::get_all()
1625
+		 */
1626
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1627
+		/**
1628
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1629
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1630
+		 *
1631
+		 * @param array    $fields_n_values fields and their new values
1632
+		 * @param EEM_Base $model           the model being queried
1633
+		 * @param array    $query_params    see EEM_Base::get_all()
1634
+		 */
1635
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1636
+			$query_params);
1637
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1638
+		//to do that, for each table, verify that it's PK isn't null.
1639
+		$tables = $this->get_tables();
1640
+		//and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1641
+		//NOTE: we should make this code more efficient by NOT querying twice
1642
+		//before the real update, but that needs to first go through ALPHA testing
1643
+		//as it's dangerous. says Mike August 8 2014
1644
+		//we want to make sure the default_where strategy is ignored
1645
+		$this->_ignore_where_strategy = true;
1646
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1647
+		foreach ($wpdb_select_results as $wpdb_result) {
1648
+			// type cast stdClass as array
1649
+			$wpdb_result = (array)$wpdb_result;
1650
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1651
+			if ($this->has_primary_key_field()) {
1652
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1653
+			} else {
1654
+				//if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1655
+				$main_table_pk_value = null;
1656
+			}
1657
+			//if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1658
+			//and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1659
+			if (count($tables) > 1) {
1660
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1661
+				//in that table, and so we'll want to insert one
1662
+				foreach ($tables as $table_obj) {
1663
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1664
+					//if there is no private key for this table on the results, it means there's no entry
1665
+					//in this table, right? so insert a row in the current table, using any fields available
1666
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1667
+						   && $wpdb_result[$this_table_pk_column])
1668
+					) {
1669
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1670
+							$main_table_pk_value);
1671
+						//if we died here, report the error
1672
+						if (! $success) {
1673
+							return false;
1674
+						}
1675
+					}
1676
+				}
1677
+			}
1678
+			//				//and now check that if we have cached any models by that ID on the model, that
1679
+			//				//they also get updated properly
1680
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1681
+			//				if( $model_object ){
1682
+			//					foreach( $fields_n_values as $field => $value ){
1683
+			//						$model_object->set($field, $value);
1684
+			//let's make sure default_where strategy is followed now
1685
+			$this->_ignore_where_strategy = false;
1686
+		}
1687
+		//if we want to keep model objects in sync, AND
1688
+		//if this wasn't called from a model object (to update itself)
1689
+		//then we want to make sure we keep all the existing
1690
+		//model objects in sync with the db
1691
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1692
+			if ($this->has_primary_key_field()) {
1693
+				$model_objs_affected_ids = $this->get_col($query_params);
1694
+			} else {
1695
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1696
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1697
+				$model_objs_affected_ids = array();
1698
+				foreach ($models_affected_key_columns as $row) {
1699
+					$combined_index_key = $this->get_index_primary_key_string($row);
1700
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1701
+				}
1702
+			}
1703
+			if (! $model_objs_affected_ids) {
1704
+				//wait wait wait- if nothing was affected let's stop here
1705
+				return 0;
1706
+			}
1707
+			foreach ($model_objs_affected_ids as $id) {
1708
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1709
+				if ($model_obj_in_entity_map) {
1710
+					foreach ($fields_n_values as $field => $new_value) {
1711
+						$model_obj_in_entity_map->set($field, $new_value);
1712
+					}
1713
+				}
1714
+			}
1715
+			//if there is a primary key on this model, we can now do a slight optimization
1716
+			if ($this->has_primary_key_field()) {
1717
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1718
+				$query_params = array(
1719
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1720
+					'limit'                    => count($model_objs_affected_ids),
1721
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1722
+				);
1723
+			}
1724
+		}
1725
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1726
+		$SQL = "UPDATE "
1727
+			   . $model_query_info->get_full_join_sql()
1728
+			   . " SET "
1729
+			   . $this->_construct_update_sql($fields_n_values)
1730
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1731
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1732
+		/**
1733
+		 * Action called after a model update call has been made.
1734
+		 *
1735
+		 * @param EEM_Base $model
1736
+		 * @param array    $fields_n_values the updated fields and their new values
1737
+		 * @param array    $query_params    @see EEM_Base::get_all()
1738
+		 * @param int      $rows_affected
1739
+		 */
1740
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1741
+		return $rows_affected;//how many supposedly got updated
1742
+	}
1743
+
1744
+
1745
+
1746
+	/**
1747
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1748
+	 * are teh values of the field specified (or by default the primary key field)
1749
+	 * that matched the query params. Note that you should pass the name of the
1750
+	 * model FIELD, not the database table's column name.
1751
+	 *
1752
+	 * @param array  $query_params @see EEM_Base::get_all()
1753
+	 * @param string $field_to_select
1754
+	 * @return array just like $wpdb->get_col()
1755
+	 * @throws \EE_Error
1756
+	 */
1757
+	public function get_col($query_params = array(), $field_to_select = null)
1758
+	{
1759
+		if ($field_to_select) {
1760
+			$field = $this->field_settings_for($field_to_select);
1761
+		} elseif ($this->has_primary_key_field()) {
1762
+			$field = $this->get_primary_key_field();
1763
+		} else {
1764
+			//no primary key, just grab the first column
1765
+			$field = reset($this->field_settings());
1766
+		}
1767
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1768
+		$select_expressions = $field->get_qualified_column();
1769
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1770
+		return $this->_do_wpdb_query('get_col', array($SQL));
1771
+	}
1772
+
1773
+
1774
+
1775
+	/**
1776
+	 * Returns a single column value for a single row from the database
1777
+	 *
1778
+	 * @param array  $query_params    @see EEM_Base::get_all()
1779
+	 * @param string $field_to_select @see EEM_Base::get_col()
1780
+	 * @return string
1781
+	 * @throws \EE_Error
1782
+	 */
1783
+	public function get_var($query_params = array(), $field_to_select = null)
1784
+	{
1785
+		$query_params['limit'] = 1;
1786
+		$col = $this->get_col($query_params, $field_to_select);
1787
+		if (! empty($col)) {
1788
+			return reset($col);
1789
+		} else {
1790
+			return null;
1791
+		}
1792
+	}
1793
+
1794
+
1795
+
1796
+	/**
1797
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1798
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1799
+	 * injection, but currently no further filtering is done
1800
+	 *
1801
+	 * @global      $wpdb
1802
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1803
+	 *                               be updated to in the DB
1804
+	 * @return string of SQL
1805
+	 * @throws \EE_Error
1806
+	 */
1807
+	public function _construct_update_sql($fields_n_values)
1808
+	{
1809
+		/** @type WPDB $wpdb */
1810
+		global $wpdb;
1811
+		$cols_n_values = array();
1812
+		foreach ($fields_n_values as $field_name => $value) {
1813
+			$field_obj = $this->field_settings_for($field_name);
1814
+			//if the value is NULL, we want to assign the value to that.
1815
+			//wpdb->prepare doesn't really handle that properly
1816
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1817
+			$value_sql = $prepared_value === null ? 'NULL'
1818
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1819
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1820
+		}
1821
+		return implode(",", $cols_n_values);
1822
+	}
1823
+
1824
+
1825
+
1826
+	/**
1827
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1828
+	 * Performs a HARD delete, meaning the database row should always be removed,
1829
+	 * not just have a flag field on it switched
1830
+	 * Wrapper for EEM_Base::delete_permanently()
1831
+	 *
1832
+	 * @param mixed $id
1833
+	 * @return boolean whether the row got deleted or not
1834
+	 * @throws \EE_Error
1835
+	 */
1836
+	public function delete_permanently_by_ID($id)
1837
+	{
1838
+		return $this->delete_permanently(
1839
+			array(
1840
+				array($this->get_primary_key_field()->get_name() => $id),
1841
+				'limit' => 1,
1842
+			)
1843
+		);
1844
+	}
1845
+
1846
+
1847
+
1848
+	/**
1849
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1850
+	 * Wrapper for EEM_Base::delete()
1851
+	 *
1852
+	 * @param mixed $id
1853
+	 * @return boolean whether the row got deleted or not
1854
+	 * @throws \EE_Error
1855
+	 */
1856
+	public function delete_by_ID($id)
1857
+	{
1858
+		return $this->delete(
1859
+			array(
1860
+				array($this->get_primary_key_field()->get_name() => $id),
1861
+				'limit' => 1,
1862
+			)
1863
+		);
1864
+	}
1865
+
1866
+
1867
+
1868
+	/**
1869
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1870
+	 * meaning if the model has a field that indicates its been "trashed" or
1871
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1872
+	 *
1873
+	 * @see EEM_Base::delete_permanently
1874
+	 * @param array   $query_params
1875
+	 * @param boolean $allow_blocking
1876
+	 * @return int how many rows got deleted
1877
+	 * @throws \EE_Error
1878
+	 */
1879
+	public function delete($query_params, $allow_blocking = true)
1880
+	{
1881
+		return $this->delete_permanently($query_params, $allow_blocking);
1882
+	}
1883
+
1884
+
1885
+
1886
+	/**
1887
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1888
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1889
+	 * as archived, not actually deleted
1890
+	 *
1891
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1892
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1893
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1894
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1895
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1896
+	 *                                DB
1897
+	 * @return int how many rows got deleted
1898
+	 * @throws \EE_Error
1899
+	 */
1900
+	public function delete_permanently($query_params, $allow_blocking = true)
1901
+	{
1902
+		/**
1903
+		 * Action called just before performing a real deletion query. You can use the
1904
+		 * model and its $query_params to find exactly which items will be deleted
1905
+		 *
1906
+		 * @param EEM_Base $model
1907
+		 * @param array    $query_params   @see EEM_Base::get_all()
1908
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1909
+		 *                                 to block (prevent) this deletion
1910
+		 */
1911
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1912
+		//some MySQL databases may be running safe mode, which may restrict
1913
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1914
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1915
+		//to delete them
1916
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1917
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1918
+		if ($deletion_where) {
1919
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1920
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1921
+			$table_aliases = array_keys($this->_tables);
1922
+			$SQL = "DELETE "
1923
+				   . implode(", ", $table_aliases)
1924
+				   . " FROM "
1925
+				   . $model_query_info->get_full_join_sql()
1926
+				   . " WHERE "
1927
+				   . $deletion_where;
1928
+			//		/echo "delete sql:$SQL";
1929
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1930
+		} else {
1931
+			$rows_deleted = 0;
1932
+		}
1933
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1934
+		if ($this->has_primary_key_field()) {
1935
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1936
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1937
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1938
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1939
+				}
1940
+			}
1941
+		}
1942
+		/**
1943
+		 * Action called just after performing a real deletion query. Although at this point the
1944
+		 * items should have been deleted
1945
+		 *
1946
+		 * @param EEM_Base $model
1947
+		 * @param array    $query_params @see EEM_Base::get_all()
1948
+		 * @param int      $rows_deleted
1949
+		 */
1950
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1951
+		return $rows_deleted;//how many supposedly got deleted
1952
+	}
1953
+
1954
+
1955
+
1956
+	/**
1957
+	 * Checks all the relations that throw error messages when there are blocking related objects
1958
+	 * for related model objects. If there are any related model objects on those relations,
1959
+	 * adds an EE_Error, and return true
1960
+	 *
1961
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1962
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1963
+	 *                                                 should be ignored when determining whether there are related
1964
+	 *                                                 model objects which block this model object's deletion. Useful
1965
+	 *                                                 if you know A is related to B and are considering deleting A,
1966
+	 *                                                 but want to see if A has any other objects blocking its deletion
1967
+	 *                                                 before removing the relation between A and B
1968
+	 * @return boolean
1969
+	 * @throws \EE_Error
1970
+	 */
1971
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1972
+	{
1973
+		//first, if $ignore_this_model_obj was supplied, get its model
1974
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1975
+			$ignored_model = $ignore_this_model_obj->get_model();
1976
+		} else {
1977
+			$ignored_model = null;
1978
+		}
1979
+		//now check all the relations of $this_model_obj_or_id and see if there
1980
+		//are any related model objects blocking it?
1981
+		$is_blocked = false;
1982
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1983
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1984
+				//if $ignore_this_model_obj was supplied, then for the query
1985
+				//on that model needs to be told to ignore $ignore_this_model_obj
1986
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1987
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1988
+						array(
1989
+							$ignored_model->get_primary_key_field()->get_name() => array(
1990
+								'!=',
1991
+								$ignore_this_model_obj->ID(),
1992
+							),
1993
+						),
1994
+					));
1995
+				} else {
1996
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1997
+				}
1998
+				if ($related_model_objects) {
1999
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2000
+					$is_blocked = true;
2001
+				}
2002
+			}
2003
+		}
2004
+		return $is_blocked;
2005
+	}
2006
+
2007
+
2008
+
2009
+	/**
2010
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2011
+	 * well.
2012
+	 *
2013
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2014
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2015
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
2016
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
2017
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
2018
+	 *                                      easily corrupt your DB
2019
+	 * @throws EE_Error
2020
+	 * @return string    everything that comes after the WHERE statement.
2021
+	 */
2022
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2023
+	{
2024
+		if ($this->has_primary_key_field()) {
2025
+			$primary_table = $this->_get_main_table();
2026
+			$other_tables = $this->_get_other_tables();
2027
+			$deletes = $query = array();
2028
+			foreach ($objects_for_deletion as $delete_object) {
2029
+				//before we mark this object for deletion,
2030
+				//make sure there's no related objects blocking its deletion (if we're checking)
2031
+				if (
2032
+					$allow_blocking
2033
+					&& $this->delete_is_blocked_by_related_models(
2034
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
2035
+					)
2036
+				) {
2037
+					continue;
2038
+				}
2039
+				//primary table deletes
2040
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2041
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2042
+				}
2043
+				//other tables
2044
+				if (! empty($other_tables)) {
2045
+					foreach ($other_tables as $ot) {
2046
+						//first check if we've got the foreign key column here.
2047
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2048
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2049
+						}
2050
+						// wait! it's entirely possible that we'll have a the primary key
2051
+						// for this table in here, if it's a foreign key for one of the other secondary tables
2052
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2053
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2054
+						}
2055
+						// finally, it is possible that the fk for this table is found
2056
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
2057
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2058
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2059
+						}
2060
+					}
2061
+				}
2062
+			}
2063
+			//we should have deletes now, so let's just go through and setup the where statement
2064
+			foreach ($deletes as $column => $values) {
2065
+				//make sure we have unique $values;
2066
+				$values = array_unique($values);
2067
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
2068
+			}
2069
+			return ! empty($query) ? implode(' AND ', $query) : '';
2070
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2071
+			$ways_to_identify_a_row = array();
2072
+			$fields = $this->get_combined_primary_key_fields();
2073
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2074
+			foreach ($objects_for_deletion as $delete_object) {
2075
+				$values_for_each_cpk_for_a_row = array();
2076
+				foreach ($fields as $cpk_field) {
2077
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2078
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2079
+														   . "="
2080
+														   . $delete_object[$cpk_field->get_qualified_column()];
2081
+					}
2082
+				}
2083
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2084
+			}
2085
+			return implode(" OR ", $ways_to_identify_a_row);
2086
+		} else {
2087
+			//so there's no primary key and no combined key...
2088
+			//sorry, can't help you
2089
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2090
+				"event_espresso"), get_class($this)));
2091
+		}
2092
+	}
2093
+
2094
+
2095
+
2096
+	/**
2097
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2098
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2099
+	 * column
2100
+	 *
2101
+	 * @param array  $query_params   like EEM_Base::get_all's
2102
+	 * @param string $field_to_count field on model to count by (not column name)
2103
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2104
+	 *                               that by the setting $distinct to TRUE;
2105
+	 * @return int
2106
+	 * @throws \EE_Error
2107
+	 */
2108
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2109
+	{
2110
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2111
+		if ($field_to_count) {
2112
+			$field_obj = $this->field_settings_for($field_to_count);
2113
+			$column_to_count = $field_obj->get_qualified_column();
2114
+		} elseif ($this->has_primary_key_field()) {
2115
+			$pk_field_obj = $this->get_primary_key_field();
2116
+			$column_to_count = $pk_field_obj->get_qualified_column();
2117
+		} else {
2118
+			//there's no primary key
2119
+			//if we're counting distinct items, and there's no primary key,
2120
+			//we need to list out the columns for distinction;
2121
+			//otherwise we can just use star
2122
+			if ($distinct) {
2123
+				$columns_to_use = array();
2124
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2125
+					$columns_to_use[] = $field_obj->get_qualified_column();
2126
+				}
2127
+				$column_to_count = implode(',', $columns_to_use);
2128
+			} else {
2129
+				$column_to_count = '*';
2130
+			}
2131
+		}
2132
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2133
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2134
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2135
+	}
2136
+
2137
+
2138
+
2139
+	/**
2140
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2141
+	 *
2142
+	 * @param array  $query_params like EEM_Base::get_all
2143
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2144
+	 * @return float
2145
+	 * @throws \EE_Error
2146
+	 */
2147
+	public function sum($query_params, $field_to_sum = null)
2148
+	{
2149
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2150
+		if ($field_to_sum) {
2151
+			$field_obj = $this->field_settings_for($field_to_sum);
2152
+		} else {
2153
+			$field_obj = $this->get_primary_key_field();
2154
+		}
2155
+		$column_to_count = $field_obj->get_qualified_column();
2156
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2157
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2158
+		$data_type = $field_obj->get_wpdb_data_type();
2159
+		if ($data_type === '%d' || $data_type === '%s') {
2160
+			return (float)$return_value;
2161
+		} else {//must be %f
2162
+			return (float)$return_value;
2163
+		}
2164
+	}
2165
+
2166
+
2167
+
2168
+	/**
2169
+	 * Just calls the specified method on $wpdb with the given arguments
2170
+	 * Consolidates a little extra error handling code
2171
+	 *
2172
+	 * @param string $wpdb_method
2173
+	 * @param array  $arguments_to_provide
2174
+	 * @throws EE_Error
2175
+	 * @global wpdb  $wpdb
2176
+	 * @return mixed
2177
+	 */
2178
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2179
+	{
2180
+		//if we're in maintenance mode level 2, DON'T run any queries
2181
+		//because level 2 indicates the database needs updating and
2182
+		//is probably out of sync with the code
2183
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2184
+			throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2185
+				"event_espresso")));
2186
+		}
2187
+		/** @type WPDB $wpdb */
2188
+		global $wpdb;
2189
+		if (! method_exists($wpdb, $wpdb_method)) {
2190
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2191
+				'event_espresso'), $wpdb_method));
2192
+		}
2193
+		if (WP_DEBUG) {
2194
+			$old_show_errors_value = $wpdb->show_errors;
2195
+			$wpdb->show_errors(false);
2196
+		}
2197
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2198
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2199
+		if (WP_DEBUG) {
2200
+			$wpdb->show_errors($old_show_errors_value);
2201
+			if (! empty($wpdb->last_error)) {
2202
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2203
+			} elseif ($result === false) {
2204
+				throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2205
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2206
+			}
2207
+		} elseif ($result === false) {
2208
+			EE_Error::add_error(
2209
+				sprintf(
2210
+					__('A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2211
+						'event_espresso'),
2212
+					$wpdb_method,
2213
+					var_export($arguments_to_provide, true),
2214
+					$wpdb->last_error
2215
+				),
2216
+				__FILE__,
2217
+				__FUNCTION__,
2218
+				__LINE__
2219
+			);
2220
+		}
2221
+		return $result;
2222
+	}
2223
+
2224
+
2225
+
2226
+	/**
2227
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2228
+	 * and if there's an error tries to verify the DB is correct. Uses
2229
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2230
+	 * we should try to fix the EE core db, the addons, or just give up
2231
+	 *
2232
+	 * @param string $wpdb_method
2233
+	 * @param array  $arguments_to_provide
2234
+	 * @return mixed
2235
+	 */
2236
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2237
+	{
2238
+		/** @type WPDB $wpdb */
2239
+		global $wpdb;
2240
+		$wpdb->last_error = null;
2241
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2242
+		// was there an error running the query? but we don't care on new activations
2243
+		// (we're going to setup the DB anyway on new activations)
2244
+		if (($result === false || ! empty($wpdb->last_error))
2245
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2246
+		) {
2247
+			switch (EEM_Base::$_db_verification_level) {
2248
+				case EEM_Base::db_verified_none :
2249
+					// let's double-check core's DB
2250
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2251
+					break;
2252
+				case EEM_Base::db_verified_core :
2253
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2254
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2255
+					break;
2256
+				case EEM_Base::db_verified_addons :
2257
+					// ummmm... you in trouble
2258
+					return $result;
2259
+					break;
2260
+			}
2261
+			if (! empty($error_message)) {
2262
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2263
+				trigger_error($error_message);
2264
+			}
2265
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2266
+		}
2267
+		return $result;
2268
+	}
2269
+
2270
+
2271
+
2272
+	/**
2273
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2274
+	 * EEM_Base::$_db_verification_level
2275
+	 *
2276
+	 * @param string $wpdb_method
2277
+	 * @param array  $arguments_to_provide
2278
+	 * @return string
2279
+	 */
2280
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2281
+	{
2282
+		/** @type WPDB $wpdb */
2283
+		global $wpdb;
2284
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2285
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2286
+		$error_message = sprintf(
2287
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2288
+				'event_espresso'),
2289
+			$wpdb->last_error,
2290
+			$wpdb_method,
2291
+			wp_json_encode($arguments_to_provide)
2292
+		);
2293
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2294
+		return $error_message;
2295
+	}
2296
+
2297
+
2298
+
2299
+	/**
2300
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2301
+	 * EEM_Base::$_db_verification_level
2302
+	 *
2303
+	 * @param $wpdb_method
2304
+	 * @param $arguments_to_provide
2305
+	 * @return string
2306
+	 */
2307
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2308
+	{
2309
+		/** @type WPDB $wpdb */
2310
+		global $wpdb;
2311
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2312
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2313
+		$error_message = sprintf(
2314
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2315
+				'event_espresso'),
2316
+			$wpdb->last_error,
2317
+			$wpdb_method,
2318
+			wp_json_encode($arguments_to_provide)
2319
+		);
2320
+		EE_System::instance()->initialize_addons();
2321
+		return $error_message;
2322
+	}
2323
+
2324
+
2325
+
2326
+	/**
2327
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2328
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2329
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2330
+	 * ..."
2331
+	 *
2332
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2333
+	 * @return string
2334
+	 */
2335
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2336
+	{
2337
+		return " FROM " . $model_query_info->get_full_join_sql() .
2338
+			   $model_query_info->get_where_sql() .
2339
+			   $model_query_info->get_group_by_sql() .
2340
+			   $model_query_info->get_having_sql() .
2341
+			   $model_query_info->get_order_by_sql() .
2342
+			   $model_query_info->get_limit_sql();
2343
+	}
2344
+
2345
+
2346
+
2347
+	/**
2348
+	 * Set to easily debug the next X queries ran from this model.
2349
+	 *
2350
+	 * @param int $count
2351
+	 */
2352
+	public function show_next_x_db_queries($count = 1)
2353
+	{
2354
+		$this->_show_next_x_db_queries = $count;
2355
+	}
2356
+
2357
+
2358
+
2359
+	/**
2360
+	 * @param $sql_query
2361
+	 */
2362
+	public function show_db_query_if_previously_requested($sql_query)
2363
+	{
2364
+		if ($this->_show_next_x_db_queries > 0) {
2365
+			echo $sql_query;
2366
+			$this->_show_next_x_db_queries--;
2367
+		}
2368
+	}
2369
+
2370
+
2371
+
2372
+	/**
2373
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2374
+	 * There are the 3 cases:
2375
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2376
+	 * $otherModelObject has no ID, it is first saved.
2377
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2378
+	 * has no ID, it is first saved.
2379
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2380
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2381
+	 * join table
2382
+	 *
2383
+	 * @param        EE_Base_Class                     /int $thisModelObject
2384
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2385
+	 * @param string $relationName                     , key in EEM_Base::_relations
2386
+	 *                                                 an attendee to a group, you also want to specify which role they
2387
+	 *                                                 will have in that group. So you would use this parameter to
2388
+	 *                                                 specify array('role-column-name'=>'role-id')
2389
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2390
+	 *                                                 to for relation to methods that allow you to further specify
2391
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2392
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2393
+	 *                                                 because these will be inserted in any new rows created as well.
2394
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2395
+	 * @throws \EE_Error
2396
+	 */
2397
+	public function add_relationship_to(
2398
+		$id_or_obj,
2399
+		$other_model_id_or_obj,
2400
+		$relationName,
2401
+		$extra_join_model_fields_n_values = array()
2402
+	) {
2403
+		$relation_obj = $this->related_settings_for($relationName);
2404
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2405
+	}
2406
+
2407
+
2408
+
2409
+	/**
2410
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2411
+	 * There are the 3 cases:
2412
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2413
+	 * error
2414
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2415
+	 * an error
2416
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2417
+	 *
2418
+	 * @param        EE_Base_Class /int $id_or_obj
2419
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2420
+	 * @param string $relationName key in EEM_Base::_relations
2421
+	 * @return boolean of success
2422
+	 * @throws \EE_Error
2423
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2424
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2425
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2426
+	 *                             because these will be inserted in any new rows created as well.
2427
+	 */
2428
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2429
+	{
2430
+		$relation_obj = $this->related_settings_for($relationName);
2431
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2432
+	}
2433
+
2434
+
2435
+
2436
+	/**
2437
+	 * @param mixed           $id_or_obj
2438
+	 * @param string          $relationName
2439
+	 * @param array           $where_query_params
2440
+	 * @param EE_Base_Class[] objects to which relations were removed
2441
+	 * @return \EE_Base_Class[]
2442
+	 * @throws \EE_Error
2443
+	 */
2444
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2445
+	{
2446
+		$relation_obj = $this->related_settings_for($relationName);
2447
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2448
+	}
2449
+
2450
+
2451
+
2452
+	/**
2453
+	 * Gets all the related items of the specified $model_name, using $query_params.
2454
+	 * Note: by default, we remove the "default query params"
2455
+	 * because we want to get even deleted items etc.
2456
+	 *
2457
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2458
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2459
+	 * @param array  $query_params like EEM_Base::get_all
2460
+	 * @return EE_Base_Class[]
2461
+	 * @throws \EE_Error
2462
+	 */
2463
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2464
+	{
2465
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2466
+		$relation_settings = $this->related_settings_for($model_name);
2467
+		return $relation_settings->get_all_related($model_obj, $query_params);
2468
+	}
2469
+
2470
+
2471
+
2472
+	/**
2473
+	 * Deletes all the model objects across the relation indicated by $model_name
2474
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2475
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2476
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2477
+	 *
2478
+	 * @param EE_Base_Class|int|string $id_or_obj
2479
+	 * @param string                   $model_name
2480
+	 * @param array                    $query_params
2481
+	 * @return int how many deleted
2482
+	 * @throws \EE_Error
2483
+	 */
2484
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2485
+	{
2486
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2487
+		$relation_settings = $this->related_settings_for($model_name);
2488
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2489
+	}
2490
+
2491
+
2492
+
2493
+	/**
2494
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2495
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2496
+	 * the model objects can't be hard deleted because of blocking related model objects,
2497
+	 * just does a soft-delete on them instead.
2498
+	 *
2499
+	 * @param EE_Base_Class|int|string $id_or_obj
2500
+	 * @param string                   $model_name
2501
+	 * @param array                    $query_params
2502
+	 * @return int how many deleted
2503
+	 * @throws \EE_Error
2504
+	 */
2505
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2506
+	{
2507
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2508
+		$relation_settings = $this->related_settings_for($model_name);
2509
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2510
+	}
2511
+
2512
+
2513
+
2514
+	/**
2515
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2516
+	 * unless otherwise specified in the $query_params
2517
+	 *
2518
+	 * @param        int             /EE_Base_Class $id_or_obj
2519
+	 * @param string $model_name     like 'Event', or 'Registration'
2520
+	 * @param array  $query_params   like EEM_Base::get_all's
2521
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2522
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2523
+	 *                               that by the setting $distinct to TRUE;
2524
+	 * @return int
2525
+	 * @throws \EE_Error
2526
+	 */
2527
+	public function count_related(
2528
+		$id_or_obj,
2529
+		$model_name,
2530
+		$query_params = array(),
2531
+		$field_to_count = null,
2532
+		$distinct = false
2533
+	) {
2534
+		$related_model = $this->get_related_model_obj($model_name);
2535
+		//we're just going to use the query params on the related model's normal get_all query,
2536
+		//except add a condition to say to match the current mod
2537
+		if (! isset($query_params['default_where_conditions'])) {
2538
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2539
+		}
2540
+		$this_model_name = $this->get_this_model_name();
2541
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2542
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2543
+		return $related_model->count($query_params, $field_to_count, $distinct);
2544
+	}
2545
+
2546
+
2547
+
2548
+	/**
2549
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2550
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2551
+	 *
2552
+	 * @param        int           /EE_Base_Class $id_or_obj
2553
+	 * @param string $model_name   like 'Event', or 'Registration'
2554
+	 * @param array  $query_params like EEM_Base::get_all's
2555
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2556
+	 * @return float
2557
+	 * @throws \EE_Error
2558
+	 */
2559
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2560
+	{
2561
+		$related_model = $this->get_related_model_obj($model_name);
2562
+		if (! is_array($query_params)) {
2563
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2564
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2565
+					gettype($query_params)), '4.6.0');
2566
+			$query_params = array();
2567
+		}
2568
+		//we're just going to use the query params on the related model's normal get_all query,
2569
+		//except add a condition to say to match the current mod
2570
+		if (! isset($query_params['default_where_conditions'])) {
2571
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2572
+		}
2573
+		$this_model_name = $this->get_this_model_name();
2574
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2575
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2576
+		return $related_model->sum($query_params, $field_to_sum);
2577
+	}
2578
+
2579
+
2580
+
2581
+	/**
2582
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2583
+	 * $modelObject
2584
+	 *
2585
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2586
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2587
+	 * @param array               $query_params     like EEM_Base::get_all's
2588
+	 * @return EE_Base_Class
2589
+	 * @throws \EE_Error
2590
+	 */
2591
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2592
+	{
2593
+		$query_params['limit'] = 1;
2594
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2595
+		if ($results) {
2596
+			return array_shift($results);
2597
+		} else {
2598
+			return null;
2599
+		}
2600
+	}
2601
+
2602
+
2603
+
2604
+	/**
2605
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2606
+	 *
2607
+	 * @return string
2608
+	 */
2609
+	public function get_this_model_name()
2610
+	{
2611
+		return str_replace("EEM_", "", get_class($this));
2612
+	}
2613
+
2614
+
2615
+
2616
+	/**
2617
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2618
+	 *
2619
+	 * @return EE_Any_Foreign_Model_Name_Field
2620
+	 * @throws EE_Error
2621
+	 */
2622
+	public function get_field_containing_related_model_name()
2623
+	{
2624
+		foreach ($this->field_settings(true) as $field) {
2625
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2626
+				$field_with_model_name = $field;
2627
+			}
2628
+		}
2629
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2630
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2631
+				$this->get_this_model_name()));
2632
+		}
2633
+		return $field_with_model_name;
2634
+	}
2635
+
2636
+
2637
+
2638
+	/**
2639
+	 * Inserts a new entry into the database, for each table.
2640
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2641
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2642
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2643
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2644
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2645
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2646
+	 *
2647
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2648
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2649
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2650
+	 *                              of EEM_Base)
2651
+	 * @return int new primary key on main table that got inserted
2652
+	 * @throws EE_Error
2653
+	 */
2654
+	public function insert($field_n_values)
2655
+	{
2656
+		/**
2657
+		 * Filters the fields and their values before inserting an item using the models
2658
+		 *
2659
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2660
+		 * @param EEM_Base $model           the model used
2661
+		 */
2662
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2663
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2664
+			$main_table = $this->_get_main_table();
2665
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2666
+			if ($new_id !== false) {
2667
+				foreach ($this->_get_other_tables() as $other_table) {
2668
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2669
+				}
2670
+			}
2671
+			/**
2672
+			 * Done just after attempting to insert a new model object
2673
+			 *
2674
+			 * @param EEM_Base   $model           used
2675
+			 * @param array      $fields_n_values fields and their values
2676
+			 * @param int|string the              ID of the newly-inserted model object
2677
+			 */
2678
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2679
+			return $new_id;
2680
+		} else {
2681
+			return false;
2682
+		}
2683
+	}
2684
+
2685
+
2686
+
2687
+	/**
2688
+	 * Checks that the result would satisfy the unique indexes on this model
2689
+	 *
2690
+	 * @param array  $field_n_values
2691
+	 * @param string $action
2692
+	 * @return boolean
2693
+	 * @throws \EE_Error
2694
+	 */
2695
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2696
+	{
2697
+		foreach ($this->unique_indexes() as $index_name => $index) {
2698
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2699
+			if ($this->exists(array($uniqueness_where_params))) {
2700
+				EE_Error::add_error(
2701
+					sprintf(
2702
+						__(
2703
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2704
+							"event_espresso"
2705
+						),
2706
+						$action,
2707
+						$this->_get_class_name(),
2708
+						$index_name,
2709
+						implode(",", $index->field_names()),
2710
+						http_build_query($uniqueness_where_params)
2711
+					),
2712
+					__FILE__,
2713
+					__FUNCTION__,
2714
+					__LINE__
2715
+				);
2716
+				return false;
2717
+			}
2718
+		}
2719
+		return true;
2720
+	}
2721
+
2722
+
2723
+
2724
+	/**
2725
+	 * Checks the database for an item that conflicts (ie, if this item were
2726
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2727
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2728
+	 * can be either an EE_Base_Class or an array of fields n values
2729
+	 *
2730
+	 * @param EE_Base_Class|array $obj_or_fields_array
2731
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2732
+	 *                                                 when looking for conflicts
2733
+	 *                                                 (ie, if false, we ignore the model object's primary key
2734
+	 *                                                 when finding "conflicts". If true, it's also considered).
2735
+	 *                                                 Only works for INT primary key,
2736
+	 *                                                 STRING primary keys cannot be ignored
2737
+	 * @throws EE_Error
2738
+	 * @return EE_Base_Class|array
2739
+	 */
2740
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2741
+	{
2742
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2743
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2744
+		} elseif (is_array($obj_or_fields_array)) {
2745
+			$fields_n_values = $obj_or_fields_array;
2746
+		} else {
2747
+			throw new EE_Error(
2748
+				sprintf(
2749
+					__(
2750
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2751
+						"event_espresso"
2752
+					),
2753
+					get_class($this),
2754
+					$obj_or_fields_array
2755
+				)
2756
+			);
2757
+		}
2758
+		$query_params = array();
2759
+		if ($this->has_primary_key_field()
2760
+			&& ($include_primary_key
2761
+				|| $this->get_primary_key_field()
2762
+				   instanceof
2763
+				   EE_Primary_Key_String_Field)
2764
+			&& isset($fields_n_values[$this->primary_key_name()])
2765
+		) {
2766
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2767
+		}
2768
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2769
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2770
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2771
+		}
2772
+		//if there is nothing to base this search on, then we shouldn't find anything
2773
+		if (empty($query_params)) {
2774
+			return array();
2775
+		} else {
2776
+			return $this->get_one($query_params);
2777
+		}
2778
+	}
2779
+
2780
+
2781
+
2782
+	/**
2783
+	 * Like count, but is optimized and returns a boolean instead of an int
2784
+	 *
2785
+	 * @param array $query_params
2786
+	 * @return boolean
2787
+	 * @throws \EE_Error
2788
+	 */
2789
+	public function exists($query_params)
2790
+	{
2791
+		$query_params['limit'] = 1;
2792
+		return $this->count($query_params) > 0;
2793
+	}
2794
+
2795
+
2796
+
2797
+	/**
2798
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2799
+	 *
2800
+	 * @param int|string $id
2801
+	 * @return boolean
2802
+	 * @throws \EE_Error
2803
+	 */
2804
+	public function exists_by_ID($id)
2805
+	{
2806
+		return $this->exists(
2807
+			array(
2808
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2809
+				array(
2810
+					$this->primary_key_name() => $id,
2811
+				),
2812
+			)
2813
+		);
2814
+	}
2815
+
2816
+
2817
+
2818
+	/**
2819
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2820
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2821
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2822
+	 * on the main table)
2823
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2824
+	 * cases where we want to call it directly rather than via insert().
2825
+	 *
2826
+	 * @access   protected
2827
+	 * @param EE_Table_Base $table
2828
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2829
+	 *                                       float
2830
+	 * @param int           $new_id          for now we assume only int keys
2831
+	 * @throws EE_Error
2832
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2833
+	 * @return int ID of new row inserted, or FALSE on failure
2834
+	 */
2835
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2836
+	{
2837
+		global $wpdb;
2838
+		$insertion_col_n_values = array();
2839
+		$format_for_insertion = array();
2840
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2841
+		foreach ($fields_on_table as $field_name => $field_obj) {
2842
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2843
+			if ($field_obj->is_auto_increment()) {
2844
+				continue;
2845
+			}
2846
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2847
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2848
+			if ($prepared_value !== null) {
2849
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2850
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2851
+			}
2852
+		}
2853
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2854
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2855
+			//so add the fk to the main table as a column
2856
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2857
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2858
+		}
2859
+		//insert the new entry
2860
+		$result = $this->_do_wpdb_query('insert',
2861
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2862
+		if ($result === false) {
2863
+			return false;
2864
+		}
2865
+		//ok, now what do we return for the ID of the newly-inserted thing?
2866
+		if ($this->has_primary_key_field()) {
2867
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2868
+				return $wpdb->insert_id;
2869
+			} else {
2870
+				//it's not an auto-increment primary key, so
2871
+				//it must have been supplied
2872
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2873
+			}
2874
+		} else {
2875
+			//we can't return a  primary key because there is none. instead return
2876
+			//a unique string indicating this model
2877
+			return $this->get_index_primary_key_string($fields_n_values);
2878
+		}
2879
+	}
2880
+
2881
+
2882
+
2883
+	/**
2884
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2885
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2886
+	 * and there is no default, we pass it along. WPDB will take care of it)
2887
+	 *
2888
+	 * @param EE_Model_Field_Base $field_obj
2889
+	 * @param array               $fields_n_values
2890
+	 * @return mixed string|int|float depending on what the table column will be expecting
2891
+	 * @throws \EE_Error
2892
+	 */
2893
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2894
+	{
2895
+		//if this field doesn't allow nullable, don't allow it
2896
+		if (! $field_obj->is_nullable()
2897
+			&& (
2898
+				! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2899
+		) {
2900
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2901
+		}
2902
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2903
+			: null;
2904
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2905
+	}
2906
+
2907
+
2908
+
2909
+	/**
2910
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2911
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2912
+	 * the field's prepare_for_set() method.
2913
+	 *
2914
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2915
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2916
+	 *                                   top of file)
2917
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2918
+	 *                                   $value is a custom selection
2919
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2920
+	 */
2921
+	private function _prepare_value_for_use_in_db($value, $field)
2922
+	{
2923
+		if ($field && $field instanceof EE_Model_Field_Base) {
2924
+			switch ($this->_values_already_prepared_by_model_object) {
2925
+				/** @noinspection PhpMissingBreakStatementInspection */
2926
+				case self::not_prepared_by_model_object:
2927
+					$value = $field->prepare_for_set($value);
2928
+				//purposefully left out "return"
2929
+				case self::prepared_by_model_object:
2930
+					$value = $field->prepare_for_use_in_db($value);
2931
+				case self::prepared_for_use_in_db:
2932
+					//leave the value alone
2933
+			}
2934
+			return $value;
2935
+		} else {
2936
+			return $value;
2937
+		}
2938
+	}
2939
+
2940
+
2941
+
2942
+	/**
2943
+	 * Returns the main table on this model
2944
+	 *
2945
+	 * @return EE_Primary_Table
2946
+	 * @throws EE_Error
2947
+	 */
2948
+	protected function _get_main_table()
2949
+	{
2950
+		foreach ($this->_tables as $table) {
2951
+			if ($table instanceof EE_Primary_Table) {
2952
+				return $table;
2953
+			}
2954
+		}
2955
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2956
+			'event_espresso'), get_class($this)));
2957
+	}
2958
+
2959
+
2960
+
2961
+	/**
2962
+	 * table
2963
+	 * returns EE_Primary_Table table name
2964
+	 *
2965
+	 * @return string
2966
+	 * @throws \EE_Error
2967
+	 */
2968
+	public function table()
2969
+	{
2970
+		return $this->_get_main_table()->get_table_name();
2971
+	}
2972
+
2973
+
2974
+
2975
+	/**
2976
+	 * table
2977
+	 * returns first EE_Secondary_Table table name
2978
+	 *
2979
+	 * @return string
2980
+	 */
2981
+	public function second_table()
2982
+	{
2983
+		// grab second table from tables array
2984
+		$second_table = end($this->_tables);
2985
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2986
+	}
2987
+
2988
+
2989
+
2990
+	/**
2991
+	 * get_table_obj_by_alias
2992
+	 * returns table name given it's alias
2993
+	 *
2994
+	 * @param string $table_alias
2995
+	 * @return EE_Primary_Table | EE_Secondary_Table
2996
+	 */
2997
+	public function get_table_obj_by_alias($table_alias = '')
2998
+	{
2999
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3000
+	}
3001
+
3002
+
3003
+
3004
+	/**
3005
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3006
+	 *
3007
+	 * @return EE_Secondary_Table[]
3008
+	 */
3009
+	protected function _get_other_tables()
3010
+	{
3011
+		$other_tables = array();
3012
+		foreach ($this->_tables as $table_alias => $table) {
3013
+			if ($table instanceof EE_Secondary_Table) {
3014
+				$other_tables[$table_alias] = $table;
3015
+			}
3016
+		}
3017
+		return $other_tables;
3018
+	}
3019
+
3020
+
3021
+
3022
+	/**
3023
+	 * Finds all the fields that correspond to the given table
3024
+	 *
3025
+	 * @param string $table_alias , array key in EEM_Base::_tables
3026
+	 * @return EE_Model_Field_Base[]
3027
+	 */
3028
+	public function _get_fields_for_table($table_alias)
3029
+	{
3030
+		return $this->_fields[$table_alias];
3031
+	}
3032
+
3033
+
3034
+
3035
+	/**
3036
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3037
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3038
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3039
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3040
+	 * related Registration, Transaction, and Payment models.
3041
+	 *
3042
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3043
+	 * @return EE_Model_Query_Info_Carrier
3044
+	 * @throws \EE_Error
3045
+	 */
3046
+	public function _extract_related_models_from_query($query_params)
3047
+	{
3048
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3049
+		if (array_key_exists(0, $query_params)) {
3050
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3051
+		}
3052
+		if (array_key_exists('group_by', $query_params)) {
3053
+			if (is_array($query_params['group_by'])) {
3054
+				$this->_extract_related_models_from_sub_params_array_values(
3055
+					$query_params['group_by'],
3056
+					$query_info_carrier,
3057
+					'group_by'
3058
+				);
3059
+			} elseif (! empty ($query_params['group_by'])) {
3060
+				$this->_extract_related_model_info_from_query_param(
3061
+					$query_params['group_by'],
3062
+					$query_info_carrier,
3063
+					'group_by'
3064
+				);
3065
+			}
3066
+		}
3067
+		if (array_key_exists('having', $query_params)) {
3068
+			$this->_extract_related_models_from_sub_params_array_keys(
3069
+				$query_params[0],
3070
+				$query_info_carrier,
3071
+				'having'
3072
+			);
3073
+		}
3074
+		if (array_key_exists('order_by', $query_params)) {
3075
+			if (is_array($query_params['order_by'])) {
3076
+				$this->_extract_related_models_from_sub_params_array_keys(
3077
+					$query_params['order_by'],
3078
+					$query_info_carrier,
3079
+					'order_by'
3080
+				);
3081
+			} elseif (! empty($query_params['order_by'])) {
3082
+				$this->_extract_related_model_info_from_query_param(
3083
+					$query_params['order_by'],
3084
+					$query_info_carrier,
3085
+					'order_by'
3086
+				);
3087
+			}
3088
+		}
3089
+		if (array_key_exists('force_join', $query_params)) {
3090
+			$this->_extract_related_models_from_sub_params_array_values(
3091
+				$query_params['force_join'],
3092
+				$query_info_carrier,
3093
+				'force_join'
3094
+			);
3095
+		}
3096
+		return $query_info_carrier;
3097
+	}
3098
+
3099
+
3100
+
3101
+	/**
3102
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3103
+	 *
3104
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3105
+	 *                                                      $query_params['having']
3106
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3107
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3108
+	 * @throws EE_Error
3109
+	 * @return \EE_Model_Query_Info_Carrier
3110
+	 */
3111
+	private function _extract_related_models_from_sub_params_array_keys(
3112
+		$sub_query_params,
3113
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3114
+		$query_param_type
3115
+	) {
3116
+		if (! empty($sub_query_params)) {
3117
+			$sub_query_params = (array)$sub_query_params;
3118
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3119
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3120
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3121
+					$query_param_type);
3122
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3123
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3124
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3125
+				//of array('Registration.TXN_ID'=>23)
3126
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3127
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3128
+					if (! is_array($possibly_array_of_params)) {
3129
+						throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3130
+							"event_espresso"),
3131
+							$param, $possibly_array_of_params));
3132
+					} else {
3133
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3134
+							$model_query_info_carrier, $query_param_type);
3135
+					}
3136
+				} elseif ($query_param_type === 0 //ie WHERE
3137
+						  && is_array($possibly_array_of_params)
3138
+						  && isset($possibly_array_of_params[2])
3139
+						  && $possibly_array_of_params[2] == true
3140
+				) {
3141
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3142
+					//indicating that $possible_array_of_params[1] is actually a field name,
3143
+					//from which we should extract query parameters!
3144
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3145
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3146
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3147
+					}
3148
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3149
+						$model_query_info_carrier, $query_param_type);
3150
+				}
3151
+			}
3152
+		}
3153
+		return $model_query_info_carrier;
3154
+	}
3155
+
3156
+
3157
+
3158
+	/**
3159
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3160
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3161
+	 *
3162
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3163
+	 *                                                      $query_params['having']
3164
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3165
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3166
+	 * @throws EE_Error
3167
+	 * @return \EE_Model_Query_Info_Carrier
3168
+	 */
3169
+	private function _extract_related_models_from_sub_params_array_values(
3170
+		$sub_query_params,
3171
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3172
+		$query_param_type
3173
+	) {
3174
+		if (! empty($sub_query_params)) {
3175
+			if (! is_array($sub_query_params)) {
3176
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3177
+					$sub_query_params));
3178
+			}
3179
+			foreach ($sub_query_params as $param) {
3180
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3181
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3182
+					$query_param_type);
3183
+			}
3184
+		}
3185
+		return $model_query_info_carrier;
3186
+	}
3187
+
3188
+
3189
+
3190
+	/**
3191
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3192
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3193
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3194
+	 * but use them in a different order. Eg, we need to know what models we are querying
3195
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3196
+	 * other models before we can finalize the where clause SQL.
3197
+	 *
3198
+	 * @param array $query_params
3199
+	 * @throws EE_Error
3200
+	 * @return EE_Model_Query_Info_Carrier
3201
+	 */
3202
+	public function _create_model_query_info_carrier($query_params)
3203
+	{
3204
+		if (! is_array($query_params)) {
3205
+			EE_Error::doing_it_wrong(
3206
+				'EEM_Base::_create_model_query_info_carrier',
3207
+				sprintf(
3208
+					__(
3209
+						'$query_params should be an array, you passed a variable of type %s',
3210
+						'event_espresso'
3211
+					),
3212
+					gettype($query_params)
3213
+				),
3214
+				'4.6.0'
3215
+			);
3216
+			$query_params = array();
3217
+		}
3218
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3219
+		//first check if we should alter the query to account for caps or not
3220
+		//because the caps might require us to do extra joins
3221
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3222
+			$query_params[0] = $where_query_params = array_replace_recursive(
3223
+				$where_query_params,
3224
+				$this->caps_where_conditions(
3225
+					$query_params['caps']
3226
+				)
3227
+			);
3228
+		}
3229
+		$query_object = $this->_extract_related_models_from_query($query_params);
3230
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3231
+		foreach ($where_query_params as $key => $value) {
3232
+			if (is_int($key)) {
3233
+				throw new EE_Error(
3234
+					sprintf(
3235
+						__(
3236
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3237
+							"event_espresso"
3238
+						),
3239
+						$key,
3240
+						var_export($value, true),
3241
+						var_export($query_params, true),
3242
+						get_class($this)
3243
+					)
3244
+				);
3245
+			}
3246
+		}
3247
+		if (
3248
+			array_key_exists('default_where_conditions', $query_params)
3249
+			&& ! empty($query_params['default_where_conditions'])
3250
+		) {
3251
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3252
+		} else {
3253
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3254
+		}
3255
+		$where_query_params = array_merge(
3256
+			$this->_get_default_where_conditions_for_models_in_query(
3257
+				$query_object,
3258
+				$use_default_where_conditions,
3259
+				$where_query_params
3260
+			),
3261
+			$where_query_params
3262
+		);
3263
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3264
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3265
+		// So we need to setup a subquery and use that for the main join.
3266
+		// Note for now this only works on the primary table for the model.
3267
+		// So for instance, you could set the limit array like this:
3268
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3269
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3270
+			$query_object->set_main_model_join_sql(
3271
+				$this->_construct_limit_join_select(
3272
+					$query_params['on_join_limit'][0],
3273
+					$query_params['on_join_limit'][1]
3274
+				)
3275
+			);
3276
+		}
3277
+		//set limit
3278
+		if (array_key_exists('limit', $query_params)) {
3279
+			if (is_array($query_params['limit'])) {
3280
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3281
+					$e = sprintf(
3282
+						__(
3283
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3284
+							"event_espresso"
3285
+						),
3286
+						http_build_query($query_params['limit'])
3287
+					);
3288
+					throw new EE_Error($e . "|" . $e);
3289
+				}
3290
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3291
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3292
+			} elseif (! empty ($query_params['limit'])) {
3293
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3294
+			}
3295
+		}
3296
+		//set order by
3297
+		if (array_key_exists('order_by', $query_params)) {
3298
+			if (is_array($query_params['order_by'])) {
3299
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3300
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3301
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3302
+				if (array_key_exists('order', $query_params)) {
3303
+					throw new EE_Error(
3304
+						sprintf(
3305
+							__(
3306
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3307
+								"event_espresso"
3308
+							),
3309
+							get_class($this),
3310
+							implode(", ", array_keys($query_params['order_by'])),
3311
+							implode(", ", $query_params['order_by']),
3312
+							$query_params['order']
3313
+						)
3314
+					);
3315
+				}
3316
+				$this->_extract_related_models_from_sub_params_array_keys(
3317
+					$query_params['order_by'],
3318
+					$query_object,
3319
+					'order_by'
3320
+				);
3321
+				//assume it's an array of fields to order by
3322
+				$order_array = array();
3323
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3324
+					$order = $this->_extract_order($order);
3325
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3326
+				}
3327
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3328
+			} elseif (! empty ($query_params['order_by'])) {
3329
+				$this->_extract_related_model_info_from_query_param(
3330
+					$query_params['order_by'],
3331
+					$query_object,
3332
+					'order',
3333
+					$query_params['order_by']
3334
+				);
3335
+				$order = isset($query_params['order'])
3336
+					? $this->_extract_order($query_params['order'])
3337
+					: 'DESC';
3338
+				$query_object->set_order_by_sql(
3339
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3340
+				);
3341
+			}
3342
+		}
3343
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3344
+		if (! array_key_exists('order_by', $query_params)
3345
+			&& array_key_exists('order', $query_params)
3346
+			&& ! empty($query_params['order'])
3347
+		) {
3348
+			$pk_field = $this->get_primary_key_field();
3349
+			$order = $this->_extract_order($query_params['order']);
3350
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3351
+		}
3352
+		//set group by
3353
+		if (array_key_exists('group_by', $query_params)) {
3354
+			if (is_array($query_params['group_by'])) {
3355
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3356
+				$group_by_array = array();
3357
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3358
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3359
+				}
3360
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3361
+			} elseif (! empty ($query_params['group_by'])) {
3362
+				$query_object->set_group_by_sql(
3363
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3364
+				);
3365
+			}
3366
+		}
3367
+		//set having
3368
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3369
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3370
+		}
3371
+		//now, just verify they didn't pass anything wack
3372
+		foreach ($query_params as $query_key => $query_value) {
3373
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3374
+				throw new EE_Error(
3375
+					sprintf(
3376
+						__(
3377
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3378
+							'event_espresso'
3379
+						),
3380
+						$query_key,
3381
+						get_class($this),
3382
+						//						print_r( $this->_allowed_query_params, TRUE )
3383
+						implode(',', $this->_allowed_query_params)
3384
+					)
3385
+				);
3386
+			}
3387
+		}
3388
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3389
+		if (empty($main_model_join_sql)) {
3390
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3391
+		}
3392
+		return $query_object;
3393
+	}
3394
+
3395
+
3396
+
3397
+	/**
3398
+	 * Gets the where conditions that should be imposed on the query based on the
3399
+	 * context (eg reading frontend, backend, edit or delete).
3400
+	 *
3401
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3402
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3403
+	 * @throws \EE_Error
3404
+	 */
3405
+	public function caps_where_conditions($context = self::caps_read)
3406
+	{
3407
+		EEM_Base::verify_is_valid_cap_context($context);
3408
+		$cap_where_conditions = array();
3409
+		$cap_restrictions = $this->caps_missing($context);
3410
+		/**
3411
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3412
+		 */
3413
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3414
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3415
+				$restriction_if_no_cap->get_default_where_conditions());
3416
+		}
3417
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3418
+			$cap_restrictions);
3419
+	}
3420
+
3421
+
3422
+
3423
+	/**
3424
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3425
+	 * otherwise throws an exception
3426
+	 *
3427
+	 * @param string $should_be_order_string
3428
+	 * @return string either ASC, asc, DESC or desc
3429
+	 * @throws EE_Error
3430
+	 */
3431
+	private function _extract_order($should_be_order_string)
3432
+	{
3433
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3434
+			return $should_be_order_string;
3435
+		} else {
3436
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3437
+				"event_espresso"), get_class($this), $should_be_order_string));
3438
+		}
3439
+	}
3440
+
3441
+
3442
+
3443
+	/**
3444
+	 * Looks at all the models which are included in this query, and asks each
3445
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3446
+	 * so they can be merged
3447
+	 *
3448
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3449
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3450
+	 *                                                                  'none' means NO default where conditions will
3451
+	 *                                                                  be used AT ALL during this query.
3452
+	 *                                                                  'other_models_only' means default where
3453
+	 *                                                                  conditions from other models will be used, but
3454
+	 *                                                                  not for this primary model. 'all', the default,
3455
+	 *                                                                  means default where conditions will apply as
3456
+	 *                                                                  normal
3457
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3458
+	 * @throws EE_Error
3459
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3460
+	 */
3461
+	private function _get_default_where_conditions_for_models_in_query(
3462
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3463
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3464
+		$where_query_params = array()
3465
+	) {
3466
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3467
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3468
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3469
+				"event_espresso"), $use_default_where_conditions,
3470
+				implode(", ", $allowed_used_default_where_conditions_values)));
3471
+		}
3472
+		$universal_query_params = array();
3473
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3474
+			$universal_query_params = $this->_get_default_where_conditions();
3475
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3476
+			$universal_query_params = $this->_get_minimum_where_conditions();
3477
+		}
3478
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3479
+			$related_model = $this->get_related_model_obj($model_name);
3480
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3481
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3482
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3483
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3484
+			} else {
3485
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3486
+				continue;
3487
+			}
3488
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3489
+				$related_model_universal_where_params,
3490
+				$where_query_params,
3491
+				$related_model,
3492
+				$model_relation_path
3493
+			);
3494
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3495
+				$universal_query_params,
3496
+				$overrides
3497
+			);
3498
+		}
3499
+		return $universal_query_params;
3500
+	}
3501
+
3502
+
3503
+
3504
+	/**
3505
+	 * Determines whether or not we should use default where conditions for the model in question
3506
+	 * (this model, or other related models).
3507
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3508
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3509
+	 * We should use default where conditions on related models when they requested to use default where conditions
3510
+	 * on all models, or specifically just on other related models
3511
+	 * @param      $default_where_conditions_value
3512
+	 * @param bool $for_this_model false means this is for OTHER related models
3513
+	 * @return bool
3514
+	 */
3515
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3516
+	{
3517
+		return (
3518
+				   $for_this_model
3519
+				   && in_array(
3520
+					   $default_where_conditions_value,
3521
+					   array(
3522
+						   EEM_Base::default_where_conditions_all,
3523
+						   EEM_Base::default_where_conditions_this_only,
3524
+						   EEM_Base::default_where_conditions_minimum_others,
3525
+					   ),
3526
+					   true
3527
+				   )
3528
+			   )
3529
+			   || (
3530
+				   ! $for_this_model
3531
+				   && in_array(
3532
+					   $default_where_conditions_value,
3533
+					   array(
3534
+						   EEM_Base::default_where_conditions_all,
3535
+						   EEM_Base::default_where_conditions_others_only,
3536
+					   ),
3537
+					   true
3538
+				   )
3539
+			   );
3540
+	}
3541
+
3542
+	/**
3543
+	 * Determines whether or not we should use default minimum conditions for the model in question
3544
+	 * (this model, or other related models).
3545
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3546
+	 * where conditions.
3547
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3548
+	 * on this model or others
3549
+	 * @param      $default_where_conditions_value
3550
+	 * @param bool $for_this_model false means this is for OTHER related models
3551
+	 * @return bool
3552
+	 */
3553
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3554
+	{
3555
+		return (
3556
+				   $for_this_model
3557
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3558
+			   )
3559
+			   || (
3560
+				   ! $for_this_model
3561
+				   && in_array(
3562
+					   $default_where_conditions_value,
3563
+					   array(
3564
+						   EEM_Base::default_where_conditions_minimum_others,
3565
+						   EEM_Base::default_where_conditions_minimum_all,
3566
+					   ),
3567
+					   true
3568
+				   )
3569
+			   );
3570
+	}
3571
+
3572
+
3573
+	/**
3574
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3575
+	 * then we also add a special where condition which allows for that model's primary key
3576
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3577
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3578
+	 *
3579
+	 * @param array    $default_where_conditions
3580
+	 * @param array    $provided_where_conditions
3581
+	 * @param EEM_Base $model
3582
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3583
+	 * @return array like EEM_Base::get_all's $query_params[0]
3584
+	 * @throws \EE_Error
3585
+	 */
3586
+	private function _override_defaults_or_make_null_friendly(
3587
+		$default_where_conditions,
3588
+		$provided_where_conditions,
3589
+		$model,
3590
+		$model_relation_path
3591
+	) {
3592
+		$null_friendly_where_conditions = array();
3593
+		$none_overridden = true;
3594
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3595
+		foreach ($default_where_conditions as $key => $val) {
3596
+			if (isset($provided_where_conditions[$key])) {
3597
+				$none_overridden = false;
3598
+			} else {
3599
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3600
+			}
3601
+		}
3602
+		if ($none_overridden && $default_where_conditions) {
3603
+			if ($model->has_primary_key_field()) {
3604
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3605
+																				. "."
3606
+																				. $model->primary_key_name()] = array('IS NULL');
3607
+			}/*else{
3608 3608
 				//@todo NO PK, use other defaults
3609 3609
 			}*/
3610
-        }
3611
-        return $null_friendly_where_conditions;
3612
-    }
3613
-
3614
-
3615
-
3616
-    /**
3617
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3618
-     * default where conditions on all get_all, update, and delete queries done by this model.
3619
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3620
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3621
-     *
3622
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3623
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3624
-     */
3625
-    private function _get_default_where_conditions($model_relation_path = null)
3626
-    {
3627
-        if ($this->_ignore_where_strategy) {
3628
-            return array();
3629
-        }
3630
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3631
-    }
3632
-
3633
-
3634
-
3635
-    /**
3636
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3637
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3638
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3639
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3640
-     * Similar to _get_default_where_conditions
3641
-     *
3642
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3643
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3644
-     */
3645
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3646
-    {
3647
-        if ($this->_ignore_where_strategy) {
3648
-            return array();
3649
-        }
3650
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3651
-    }
3652
-
3653
-
3654
-
3655
-    /**
3656
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3657
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3658
-     *
3659
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3660
-     * @return string
3661
-     * @throws \EE_Error
3662
-     */
3663
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3664
-    {
3665
-        $selects = $this->_get_columns_to_select_for_this_model();
3666
-        foreach (
3667
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3668
-            $name_of_other_model_included
3669
-        ) {
3670
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3671
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3672
-            foreach ($other_model_selects as $key => $value) {
3673
-                $selects[] = $value;
3674
-            }
3675
-        }
3676
-        return implode(", ", $selects);
3677
-    }
3678
-
3679
-
3680
-
3681
-    /**
3682
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3683
-     * So that's going to be the columns for all the fields on the model
3684
-     *
3685
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3686
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3687
-     */
3688
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3689
-    {
3690
-        $fields = $this->field_settings();
3691
-        $selects = array();
3692
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3693
-            $this->get_this_model_name());
3694
-        foreach ($fields as $field_obj) {
3695
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3696
-                         . $field_obj->get_table_alias()
3697
-                         . "."
3698
-                         . $field_obj->get_table_column()
3699
-                         . " AS '"
3700
-                         . $table_alias_with_model_relation_chain_prefix
3701
-                         . $field_obj->get_table_alias()
3702
-                         . "."
3703
-                         . $field_obj->get_table_column()
3704
-                         . "'";
3705
-        }
3706
-        //make sure we are also getting the PKs of each table
3707
-        $tables = $this->get_tables();
3708
-        if (count($tables) > 1) {
3709
-            foreach ($tables as $table_obj) {
3710
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3711
-                                       . $table_obj->get_fully_qualified_pk_column();
3712
-                if (! in_array($qualified_pk_column, $selects)) {
3713
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3714
-                }
3715
-            }
3716
-        }
3717
-        return $selects;
3718
-    }
3719
-
3720
-
3721
-
3722
-    /**
3723
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3724
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3725
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3726
-     * SQL for joining, and the data types
3727
-     *
3728
-     * @param null|string                 $original_query_param
3729
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3730
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3731
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3732
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3733
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3734
-     *                                                          or 'Registration's
3735
-     * @param string                      $original_query_param what it originally was (eg
3736
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3737
-     *                                                          matches $query_param
3738
-     * @throws EE_Error
3739
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3740
-     */
3741
-    private function _extract_related_model_info_from_query_param(
3742
-        $query_param,
3743
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3744
-        $query_param_type,
3745
-        $original_query_param = null
3746
-    ) {
3747
-        if ($original_query_param === null) {
3748
-            $original_query_param = $query_param;
3749
-        }
3750
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3751
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3752
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3753
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3754
-        //check to see if we have a field on this model
3755
-        $this_model_fields = $this->field_settings(true);
3756
-        if (array_key_exists($query_param, $this_model_fields)) {
3757
-            if ($allow_fields) {
3758
-                return;
3759
-            } else {
3760
-                throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3761
-                    "event_espresso"),
3762
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3763
-            }
3764
-        } //check if this is a special logic query param
3765
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3766
-            if ($allow_logic_query_params) {
3767
-                return;
3768
-            } else {
3769
-                throw new EE_Error(
3770
-                    sprintf(
3771
-                        __('Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3772
-                            'event_espresso'),
3773
-                        implode('", "', $this->_logic_query_param_keys),
3774
-                        $query_param,
3775
-                        get_class($this),
3776
-                        '<br />',
3777
-                        "\t"
3778
-                        . ' $passed_in_query_info = <pre>'
3779
-                        . print_r($passed_in_query_info, true)
3780
-                        . '</pre>'
3781
-                        . "\n\t"
3782
-                        . ' $query_param_type = '
3783
-                        . $query_param_type
3784
-                        . "\n\t"
3785
-                        . ' $original_query_param = '
3786
-                        . $original_query_param
3787
-                    )
3788
-                );
3789
-            }
3790
-        } //check if it's a custom selection
3791
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3792
-            return;
3793
-        }
3794
-        //check if has a model name at the beginning
3795
-        //and
3796
-        //check if it's a field on a related model
3797
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3798
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3799
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3800
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3801
-                if ($query_param === '') {
3802
-                    //nothing left to $query_param
3803
-                    //we should actually end in a field name, not a model like this!
3804
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3805
-                        "event_espresso"),
3806
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3807
-                } else {
3808
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3809
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3810
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3811
-                    return;
3812
-                }
3813
-            } elseif ($query_param === $valid_related_model_name) {
3814
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3815
-                return;
3816
-            }
3817
-        }
3818
-        //ok so $query_param didn't start with a model name
3819
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3820
-        //it's wack, that's what it is
3821
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3822
-            "event_espresso"),
3823
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3824
-    }
3825
-
3826
-
3827
-
3828
-    /**
3829
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3830
-     * and store it on $passed_in_query_info
3831
-     *
3832
-     * @param string                      $model_name
3833
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3834
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3835
-     *                                                          model and $model_name. Eg, if we are querying Event,
3836
-     *                                                          and are adding a join to 'Payment' with the original
3837
-     *                                                          query param key
3838
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3839
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3840
-     *                                                          Payment wants to add default query params so that it
3841
-     *                                                          will know what models to prepend onto its default query
3842
-     *                                                          params or in case it wants to rename tables (in case
3843
-     *                                                          there are multiple joins to the same table)
3844
-     * @return void
3845
-     * @throws \EE_Error
3846
-     */
3847
-    private function _add_join_to_model(
3848
-        $model_name,
3849
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3850
-        $original_query_param
3851
-    ) {
3852
-        $relation_obj = $this->related_settings_for($model_name);
3853
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3854
-        //check if the relation is HABTM, because then we're essentially doing two joins
3855
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3856
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3857
-            $join_model_obj = $relation_obj->get_join_model();
3858
-            //replace the model specified with the join model for this relation chain, whi
3859
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3860
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3861
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3862
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3863
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3864
-            $passed_in_query_info->merge($new_query_info);
3865
-        }
3866
-        //now just join to the other table pointed to by the relation object, and add its data types
3867
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3868
-            array($model_relation_chain => $model_name),
3869
-            $relation_obj->get_join_statement($model_relation_chain));
3870
-        $passed_in_query_info->merge($new_query_info);
3871
-    }
3872
-
3873
-
3874
-
3875
-    /**
3876
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3877
-     *
3878
-     * @param array $where_params like EEM_Base::get_all
3879
-     * @return string of SQL
3880
-     * @throws \EE_Error
3881
-     */
3882
-    private function _construct_where_clause($where_params)
3883
-    {
3884
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3885
-        if ($SQL) {
3886
-            return " WHERE " . $SQL;
3887
-        } else {
3888
-            return '';
3889
-        }
3890
-    }
3891
-
3892
-
3893
-
3894
-    /**
3895
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3896
-     * and should be passed HAVING parameters, not WHERE parameters
3897
-     *
3898
-     * @param array $having_params
3899
-     * @return string
3900
-     * @throws \EE_Error
3901
-     */
3902
-    private function _construct_having_clause($having_params)
3903
-    {
3904
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3905
-        if ($SQL) {
3906
-            return " HAVING " . $SQL;
3907
-        } else {
3908
-            return '';
3909
-        }
3910
-    }
3911
-
3912
-
3913
-
3914
-    /**
3915
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3916
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3917
-     * EEM_Attendee.
3918
-     *
3919
-     * @param string $field_name
3920
-     * @param string $model_name
3921
-     * @return EE_Model_Field_Base
3922
-     * @throws EE_Error
3923
-     */
3924
-    protected function _get_field_on_model($field_name, $model_name)
3925
-    {
3926
-        $model_class = 'EEM_' . $model_name;
3927
-        $model_filepath = $model_class . ".model.php";
3928
-        if (is_readable($model_filepath)) {
3929
-            require_once($model_filepath);
3930
-            $model_instance = call_user_func($model_name . "::instance");
3931
-            /* @var $model_instance EEM_Base */
3932
-            return $model_instance->field_settings_for($field_name);
3933
-        } else {
3934
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3935
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3936
-        }
3937
-    }
3938
-
3939
-
3940
-
3941
-    /**
3942
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3943
-     * Event_Meta.meta_value = 'foo'))"
3944
-     *
3945
-     * @param array  $where_params see EEM_Base::get_all for documentation
3946
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3947
-     * @throws EE_Error
3948
-     * @return string of SQL
3949
-     */
3950
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3951
-    {
3952
-        $where_clauses = array();
3953
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3954
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3955
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3956
-                switch ($query_param) {
3957
-                    case 'not':
3958
-                    case 'NOT':
3959
-                        $where_clauses[] = "! ("
3960
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3961
-                                $glue)
3962
-                                           . ")";
3963
-                        break;
3964
-                    case 'and':
3965
-                    case 'AND':
3966
-                        $where_clauses[] = " ("
3967
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3968
-                                ' AND ')
3969
-                                           . ")";
3970
-                        break;
3971
-                    case 'or':
3972
-                    case 'OR':
3973
-                        $where_clauses[] = " ("
3974
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3975
-                                ' OR ')
3976
-                                           . ")";
3977
-                        break;
3978
-                }
3979
-            } else {
3980
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3981
-                //if it's not a normal field, maybe it's a custom selection?
3982
-                if (! $field_obj) {
3983
-                    if (isset($this->_custom_selections[$query_param][1])) {
3984
-                        $field_obj = $this->_custom_selections[$query_param][1];
3985
-                    } else {
3986
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3987
-                            "event_espresso"), $query_param));
3988
-                    }
3989
-                }
3990
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3991
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3992
-            }
3993
-        }
3994
-        return $where_clauses ? implode($glue, $where_clauses) : '';
3995
-    }
3996
-
3997
-
3998
-
3999
-    /**
4000
-     * Takes the input parameter and extract the table name (alias) and column name
4001
-     *
4002
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4003
-     * @throws EE_Error
4004
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4005
-     */
4006
-    private function _deduce_column_name_from_query_param($query_param)
4007
-    {
4008
-        $field = $this->_deduce_field_from_query_param($query_param);
4009
-        if ($field) {
4010
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4011
-                $query_param);
4012
-            return $table_alias_prefix . $field->get_qualified_column();
4013
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4014
-            //maybe it's custom selection item?
4015
-            //if so, just use it as the "column name"
4016
-            return $query_param;
4017
-        } else {
4018
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4019
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4020
-        }
4021
-    }
4022
-
4023
-
4024
-
4025
-    /**
4026
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4027
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4028
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4029
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4030
-     *
4031
-     * @param string $condition_query_param_key
4032
-     * @return string
4033
-     */
4034
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4035
-    {
4036
-        $pos_of_star = strpos($condition_query_param_key, '*');
4037
-        if ($pos_of_star === false) {
4038
-            return $condition_query_param_key;
4039
-        } else {
4040
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4041
-            return $condition_query_param_sans_star;
4042
-        }
4043
-    }
4044
-
4045
-
4046
-
4047
-    /**
4048
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4049
-     *
4050
-     * @param                            mixed      array | string    $op_and_value
4051
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4052
-     * @throws EE_Error
4053
-     * @return string
4054
-     */
4055
-    private function _construct_op_and_value($op_and_value, $field_obj)
4056
-    {
4057
-        if (is_array($op_and_value)) {
4058
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4059
-            if (! $operator) {
4060
-                $php_array_like_string = array();
4061
-                foreach ($op_and_value as $key => $value) {
4062
-                    $php_array_like_string[] = "$key=>$value";
4063
-                }
4064
-                throw new EE_Error(
4065
-                    sprintf(
4066
-                        __(
4067
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4068
-                            "event_espresso"
4069
-                        ),
4070
-                        implode(",", $php_array_like_string)
4071
-                    )
4072
-                );
4073
-            }
4074
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4075
-        } else {
4076
-            $operator = '=';
4077
-            $value = $op_and_value;
4078
-        }
4079
-        //check to see if the value is actually another field
4080
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4081
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4082
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4083
-            //in this case, the value should be an array, or at least a comma-separated list
4084
-            //it will need to handle a little differently
4085
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4086
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4087
-            return $operator . SP . $cleaned_value;
4088
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4089
-            //the value should be an array with count of two.
4090
-            if (count($value) !== 2) {
4091
-                throw new EE_Error(
4092
-                    sprintf(
4093
-                        __(
4094
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4095
-                            'event_espresso'
4096
-                        ),
4097
-                        "BETWEEN"
4098
-                    )
4099
-                );
4100
-            }
4101
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4102
-            return $operator . SP . $cleaned_value;
4103
-        } elseif (in_array($operator, $this->_null_style_operators)) {
4104
-            if ($value !== null) {
4105
-                throw new EE_Error(
4106
-                    sprintf(
4107
-                        __(
4108
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4109
-                            "event_espresso"
4110
-                        ),
4111
-                        $value,
4112
-                        $operator
4113
-                    )
4114
-                );
4115
-            }
4116
-            return $operator;
4117
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
4118
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4119
-            //remove other junk. So just treat it as a string.
4120
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4121
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4122
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4123
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4124
-            throw new EE_Error(
4125
-                sprintf(
4126
-                    __(
4127
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4128
-                        'event_espresso'
4129
-                    ),
4130
-                    $operator,
4131
-                    $operator
4132
-                )
4133
-            );
4134
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4135
-            throw new EE_Error(
4136
-                sprintf(
4137
-                    __(
4138
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4139
-                        'event_espresso'
4140
-                    ),
4141
-                    $operator,
4142
-                    $operator
4143
-                )
4144
-            );
4145
-        } else {
4146
-            throw new EE_Error(
4147
-                sprintf(
4148
-                    __(
4149
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4150
-                        "event_espresso"
4151
-                    ),
4152
-                    http_build_query($op_and_value)
4153
-                )
4154
-            );
4155
-        }
4156
-    }
4157
-
4158
-
4159
-
4160
-    /**
4161
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4162
-     *
4163
-     * @param array                      $values
4164
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4165
-     *                                              '%s'
4166
-     * @return string
4167
-     * @throws \EE_Error
4168
-     */
4169
-    public function _construct_between_value($values, $field_obj)
4170
-    {
4171
-        $cleaned_values = array();
4172
-        foreach ($values as $value) {
4173
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4174
-        }
4175
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4176
-    }
4177
-
4178
-
4179
-
4180
-    /**
4181
-     * Takes an array or a comma-separated list of $values and cleans them
4182
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4183
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4184
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4185
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4186
-     *
4187
-     * @param mixed                      $values    array or comma-separated string
4188
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4189
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4190
-     * @throws \EE_Error
4191
-     */
4192
-    public function _construct_in_value($values, $field_obj)
4193
-    {
4194
-        //check if the value is a CSV list
4195
-        if (is_string($values)) {
4196
-            //in which case, turn it into an array
4197
-            $values = explode(",", $values);
4198
-        }
4199
-        $cleaned_values = array();
4200
-        foreach ($values as $value) {
4201
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4202
-        }
4203
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4204
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4205
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4206
-        if (empty($cleaned_values)) {
4207
-            $all_fields = $this->field_settings();
4208
-            $a_field = array_shift($all_fields);
4209
-            $main_table = $this->_get_main_table();
4210
-            $cleaned_values[] = "SELECT "
4211
-                                . $a_field->get_table_column()
4212
-                                . " FROM "
4213
-                                . $main_table->get_table_name()
4214
-                                . " WHERE FALSE";
4215
-        }
4216
-        return "(" . implode(",", $cleaned_values) . ")";
4217
-    }
4218
-
4219
-
4220
-
4221
-    /**
4222
-     * @param mixed                      $value
4223
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4224
-     * @throws EE_Error
4225
-     * @return false|null|string
4226
-     */
4227
-    private function _wpdb_prepare_using_field($value, $field_obj)
4228
-    {
4229
-        /** @type WPDB $wpdb */
4230
-        global $wpdb;
4231
-        if ($field_obj instanceof EE_Model_Field_Base) {
4232
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4233
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4234
-        } else {//$field_obj should really just be a data type
4235
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4236
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4237
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4238
-            }
4239
-            return $wpdb->prepare($field_obj, $value);
4240
-        }
4241
-    }
4242
-
4243
-
4244
-
4245
-    /**
4246
-     * Takes the input parameter and finds the model field that it indicates.
4247
-     *
4248
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4249
-     * @throws EE_Error
4250
-     * @return EE_Model_Field_Base
4251
-     */
4252
-    protected function _deduce_field_from_query_param($query_param_name)
4253
-    {
4254
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4255
-        //which will help us find the database table and column
4256
-        $query_param_parts = explode(".", $query_param_name);
4257
-        if (empty($query_param_parts)) {
4258
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4259
-                'event_espresso'), $query_param_name));
4260
-        }
4261
-        $number_of_parts = count($query_param_parts);
4262
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4263
-        if ($number_of_parts === 1) {
4264
-            $field_name = $last_query_param_part;
4265
-            $model_obj = $this;
4266
-        } else {// $number_of_parts >= 2
4267
-            //the last part is the column name, and there are only 2parts. therefore...
4268
-            $field_name = $last_query_param_part;
4269
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4270
-        }
4271
-        try {
4272
-            return $model_obj->field_settings_for($field_name);
4273
-        } catch (EE_Error $e) {
4274
-            return null;
4275
-        }
4276
-    }
4277
-
4278
-
4279
-
4280
-    /**
4281
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4282
-     * alias and column which corresponds to it
4283
-     *
4284
-     * @param string $field_name
4285
-     * @throws EE_Error
4286
-     * @return string
4287
-     */
4288
-    public function _get_qualified_column_for_field($field_name)
4289
-    {
4290
-        $all_fields = $this->field_settings();
4291
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4292
-        if ($field) {
4293
-            return $field->get_qualified_column();
4294
-        } else {
4295
-            throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4296
-                'event_espresso'), $field_name, get_class($this)));
4297
-        }
4298
-    }
4299
-
4300
-
4301
-
4302
-    /**
4303
-     * constructs the select use on special limit joins
4304
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4305
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4306
-     * (as that is typically where the limits would be set).
4307
-     *
4308
-     * @param  string       $table_alias The table the select is being built for
4309
-     * @param  mixed|string $limit       The limit for this select
4310
-     * @return string                The final select join element for the query.
4311
-     */
4312
-    public function _construct_limit_join_select($table_alias, $limit)
4313
-    {
4314
-        $SQL = '';
4315
-        foreach ($this->_tables as $table_obj) {
4316
-            if ($table_obj instanceof EE_Primary_Table) {
4317
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4318
-                    ? $table_obj->get_select_join_limit($limit)
4319
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4320
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4321
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4322
-                    ? $table_obj->get_select_join_limit_join($limit)
4323
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4324
-            }
4325
-        }
4326
-        return $SQL;
4327
-    }
4328
-
4329
-
4330
-
4331
-    /**
4332
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4333
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4334
-     *
4335
-     * @return string SQL
4336
-     * @throws \EE_Error
4337
-     */
4338
-    public function _construct_internal_join()
4339
-    {
4340
-        $SQL = $this->_get_main_table()->get_table_sql();
4341
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4342
-        return $SQL;
4343
-    }
4344
-
4345
-
4346
-
4347
-    /**
4348
-     * Constructs the SQL for joining all the tables on this model.
4349
-     * Normally $alias should be the primary table's alias, but in cases where
4350
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4351
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4352
-     * alias, this will construct SQL like:
4353
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4354
-     * With $alias being a secondary table's alias, this will construct SQL like:
4355
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4356
-     *
4357
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4358
-     * @return string
4359
-     */
4360
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4361
-    {
4362
-        $SQL = '';
4363
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4364
-        foreach ($this->_tables as $table_obj) {
4365
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4366
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4367
-                    //so we're joining to this table, meaning the table is already in
4368
-                    //the FROM statement, BUT the primary table isn't. So we want
4369
-                    //to add the inverse join sql
4370
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4371
-                } else {
4372
-                    //just add a regular JOIN to this table from the primary table
4373
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4374
-                }
4375
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4376
-        }
4377
-        return $SQL;
4378
-    }
4379
-
4380
-
4381
-
4382
-    /**
4383
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4384
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4385
-     * their data type (eg, '%s', '%d', etc)
4386
-     *
4387
-     * @return array
4388
-     */
4389
-    public function _get_data_types()
4390
-    {
4391
-        $data_types = array();
4392
-        foreach ($this->field_settings() as $field_obj) {
4393
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4394
-            /** @var $field_obj EE_Model_Field_Base */
4395
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4396
-        }
4397
-        return $data_types;
4398
-    }
4399
-
4400
-
4401
-
4402
-    /**
4403
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4404
-     *
4405
-     * @param string $model_name
4406
-     * @throws EE_Error
4407
-     * @return EEM_Base
4408
-     */
4409
-    public function get_related_model_obj($model_name)
4410
-    {
4411
-        $model_classname = "EEM_" . $model_name;
4412
-        if (! class_exists($model_classname)) {
4413
-            throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4414
-                'event_espresso'), $model_name, $model_classname));
4415
-        }
4416
-        return call_user_func($model_classname . "::instance");
4417
-    }
4418
-
4419
-
4420
-
4421
-    /**
4422
-     * Returns the array of EE_ModelRelations for this model.
4423
-     *
4424
-     * @return EE_Model_Relation_Base[]
4425
-     */
4426
-    public function relation_settings()
4427
-    {
4428
-        return $this->_model_relations;
4429
-    }
4430
-
4431
-
4432
-
4433
-    /**
4434
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4435
-     * because without THOSE models, this model probably doesn't have much purpose.
4436
-     * (Eg, without an event, datetimes have little purpose.)
4437
-     *
4438
-     * @return EE_Belongs_To_Relation[]
4439
-     */
4440
-    public function belongs_to_relations()
4441
-    {
4442
-        $belongs_to_relations = array();
4443
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4444
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4445
-                $belongs_to_relations[$model_name] = $relation_obj;
4446
-            }
4447
-        }
4448
-        return $belongs_to_relations;
4449
-    }
4450
-
4451
-
4452
-
4453
-    /**
4454
-     * Returns the specified EE_Model_Relation, or throws an exception
4455
-     *
4456
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4457
-     * @throws EE_Error
4458
-     * @return EE_Model_Relation_Base
4459
-     */
4460
-    public function related_settings_for($relation_name)
4461
-    {
4462
-        $relatedModels = $this->relation_settings();
4463
-        if (! array_key_exists($relation_name, $relatedModels)) {
4464
-            throw new EE_Error(
4465
-                sprintf(
4466
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4467
-                        'event_espresso'),
4468
-                    $relation_name,
4469
-                    $this->_get_class_name(),
4470
-                    implode(', ', array_keys($relatedModels))
4471
-                )
4472
-            );
4473
-        }
4474
-        return $relatedModels[$relation_name];
4475
-    }
4476
-
4477
-
4478
-
4479
-    /**
4480
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4481
-     * fields
4482
-     *
4483
-     * @param string $fieldName
4484
-     * @throws EE_Error
4485
-     * @return EE_Model_Field_Base
4486
-     */
4487
-    public function field_settings_for($fieldName)
4488
-    {
4489
-        $fieldSettings = $this->field_settings(true);
4490
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4491
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4492
-                get_class($this)));
4493
-        }
4494
-        return $fieldSettings[$fieldName];
4495
-    }
4496
-
4497
-
4498
-
4499
-    /**
4500
-     * Checks if this field exists on this model
4501
-     *
4502
-     * @param string $fieldName a key in the model's _field_settings array
4503
-     * @return boolean
4504
-     */
4505
-    public function has_field($fieldName)
4506
-    {
4507
-        $fieldSettings = $this->field_settings(true);
4508
-        if (isset($fieldSettings[$fieldName])) {
4509
-            return true;
4510
-        } else {
4511
-            return false;
4512
-        }
4513
-    }
4514
-
4515
-
4516
-
4517
-    /**
4518
-     * Returns whether or not this model has a relation to the specified model
4519
-     *
4520
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4521
-     * @return boolean
4522
-     */
4523
-    public function has_relation($relation_name)
4524
-    {
4525
-        $relations = $this->relation_settings();
4526
-        if (isset($relations[$relation_name])) {
4527
-            return true;
4528
-        } else {
4529
-            return false;
4530
-        }
4531
-    }
4532
-
4533
-
4534
-
4535
-    /**
4536
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4537
-     * Eg, on EE_Answer that would be ANS_ID field object
4538
-     *
4539
-     * @param $field_obj
4540
-     * @return boolean
4541
-     */
4542
-    public function is_primary_key_field($field_obj)
4543
-    {
4544
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4545
-    }
4546
-
4547
-
4548
-
4549
-    /**
4550
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4551
-     * Eg, on EE_Answer that would be ANS_ID field object
4552
-     *
4553
-     * @return EE_Model_Field_Base
4554
-     * @throws EE_Error
4555
-     */
4556
-    public function get_primary_key_field()
4557
-    {
4558
-        if ($this->_primary_key_field === null) {
4559
-            foreach ($this->field_settings(true) as $field_obj) {
4560
-                if ($this->is_primary_key_field($field_obj)) {
4561
-                    $this->_primary_key_field = $field_obj;
4562
-                    break;
4563
-                }
4564
-            }
4565
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4566
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4567
-                    get_class($this)));
4568
-            }
4569
-        }
4570
-        return $this->_primary_key_field;
4571
-    }
4572
-
4573
-
4574
-
4575
-    /**
4576
-     * Returns whether or not not there is a primary key on this model.
4577
-     * Internally does some caching.
4578
-     *
4579
-     * @return boolean
4580
-     */
4581
-    public function has_primary_key_field()
4582
-    {
4583
-        if ($this->_has_primary_key_field === null) {
4584
-            try {
4585
-                $this->get_primary_key_field();
4586
-                $this->_has_primary_key_field = true;
4587
-            } catch (EE_Error $e) {
4588
-                $this->_has_primary_key_field = false;
4589
-            }
4590
-        }
4591
-        return $this->_has_primary_key_field;
4592
-    }
4593
-
4594
-
4595
-
4596
-    /**
4597
-     * Finds the first field of type $field_class_name.
4598
-     *
4599
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4600
-     *                                 EE_Foreign_Key_Field, etc
4601
-     * @return EE_Model_Field_Base or null if none is found
4602
-     */
4603
-    public function get_a_field_of_type($field_class_name)
4604
-    {
4605
-        foreach ($this->field_settings() as $field) {
4606
-            if ($field instanceof $field_class_name) {
4607
-                return $field;
4608
-            }
4609
-        }
4610
-        return null;
4611
-    }
4612
-
4613
-
4614
-
4615
-    /**
4616
-     * Gets a foreign key field pointing to model.
4617
-     *
4618
-     * @param string $model_name eg Event, Registration, not EEM_Event
4619
-     * @return EE_Foreign_Key_Field_Base
4620
-     * @throws EE_Error
4621
-     */
4622
-    public function get_foreign_key_to($model_name)
4623
-    {
4624
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4625
-            foreach ($this->field_settings() as $field) {
4626
-                if (
4627
-                    $field instanceof EE_Foreign_Key_Field_Base
4628
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4629
-                ) {
4630
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4631
-                    break;
4632
-                }
4633
-            }
4634
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4635
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4636
-                    'event_espresso'), $model_name, get_class($this)));
4637
-            }
4638
-        }
4639
-        return $this->_cache_foreign_key_to_fields[$model_name];
4640
-    }
4641
-
4642
-
4643
-
4644
-    /**
4645
-     * Gets the actual table for the table alias
4646
-     *
4647
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4648
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4649
-     *                            Either one works
4650
-     * @return EE_Table_Base
4651
-     */
4652
-    public function get_table_for_alias($table_alias)
4653
-    {
4654
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4655
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4656
-    }
4657
-
4658
-
4659
-
4660
-    /**
4661
-     * Returns a flat array of all field son this model, instead of organizing them
4662
-     * by table_alias as they are in the constructor.
4663
-     *
4664
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4665
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4666
-     */
4667
-    public function field_settings($include_db_only_fields = false)
4668
-    {
4669
-        if ($include_db_only_fields) {
4670
-            if ($this->_cached_fields === null) {
4671
-                $this->_cached_fields = array();
4672
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4673
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4674
-                        $this->_cached_fields[$field_name] = $field_obj;
4675
-                    }
4676
-                }
4677
-            }
4678
-            return $this->_cached_fields;
4679
-        } else {
4680
-            if ($this->_cached_fields_non_db_only === null) {
4681
-                $this->_cached_fields_non_db_only = array();
4682
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4683
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4684
-                        /** @var $field_obj EE_Model_Field_Base */
4685
-                        if (! $field_obj->is_db_only_field()) {
4686
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4687
-                        }
4688
-                    }
4689
-                }
4690
-            }
4691
-            return $this->_cached_fields_non_db_only;
4692
-        }
4693
-    }
4694
-
4695
-
4696
-
4697
-    /**
4698
-     *        cycle though array of attendees and create objects out of each item
4699
-     *
4700
-     * @access        private
4701
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4702
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4703
-     *                           numerically indexed)
4704
-     * @throws \EE_Error
4705
-     */
4706
-    protected function _create_objects($rows = array())
4707
-    {
4708
-        $array_of_objects = array();
4709
-        if (empty($rows)) {
4710
-            return array();
4711
-        }
4712
-        $count_if_model_has_no_primary_key = 0;
4713
-        $has_primary_key = $this->has_primary_key_field();
4714
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4715
-        foreach ((array)$rows as $row) {
4716
-            if (empty($row)) {
4717
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4718
-                return array();
4719
-            }
4720
-            //check if we've already set this object in the results array,
4721
-            //in which case there's no need to process it further (again)
4722
-            if ($has_primary_key) {
4723
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4724
-                    $row,
4725
-                    $primary_key_field->get_qualified_column(),
4726
-                    $primary_key_field->get_table_column()
4727
-                );
4728
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4729
-                    continue;
4730
-                }
4731
-            }
4732
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4733
-            if (! $classInstance) {
4734
-                throw new EE_Error(
4735
-                    sprintf(
4736
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4737
-                        $this->get_this_model_name(),
4738
-                        http_build_query($row)
4739
-                    )
4740
-                );
4741
-            }
4742
-            //set the timezone on the instantiated objects
4743
-            $classInstance->set_timezone($this->_timezone);
4744
-            //make sure if there is any timezone setting present that we set the timezone for the object
4745
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4746
-            $array_of_objects[$key] = $classInstance;
4747
-            //also, for all the relations of type BelongsTo, see if we can cache
4748
-            //those related models
4749
-            //(we could do this for other relations too, but if there are conditions
4750
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4751
-            //so it requires a little more thought than just caching them immediately...)
4752
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4753
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4754
-                    //check if this model's INFO is present. If so, cache it on the model
4755
-                    $other_model = $relation_obj->get_other_model();
4756
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4757
-                    //if we managed to make a model object from the results, cache it on the main model object
4758
-                    if ($other_model_obj_maybe) {
4759
-                        //set timezone on these other model objects if they are present
4760
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4761
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4762
-                    }
4763
-                }
4764
-            }
4765
-        }
4766
-        return $array_of_objects;
4767
-    }
4768
-
4769
-
4770
-
4771
-    /**
4772
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4773
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4774
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4775
-     * object (as set in the model_field!).
4776
-     *
4777
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4778
-     */
4779
-    public function create_default_object()
4780
-    {
4781
-        $this_model_fields_and_values = array();
4782
-        //setup the row using default values;
4783
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4784
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4785
-        }
4786
-        $className = $this->_get_class_name();
4787
-        $classInstance = EE_Registry::instance()
4788
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4789
-        return $classInstance;
4790
-    }
4791
-
4792
-
4793
-
4794
-    /**
4795
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4796
-     *                             or an stdClass where each property is the name of a column,
4797
-     * @return EE_Base_Class
4798
-     * @throws \EE_Error
4799
-     */
4800
-    public function instantiate_class_from_array_or_object($cols_n_values)
4801
-    {
4802
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4803
-            $cols_n_values = get_object_vars($cols_n_values);
4804
-        }
4805
-        $primary_key = null;
4806
-        //make sure the array only has keys that are fields/columns on this model
4807
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4808
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4809
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4810
-        }
4811
-        $className = $this->_get_class_name();
4812
-        //check we actually found results that we can use to build our model object
4813
-        //if not, return null
4814
-        if ($this->has_primary_key_field()) {
4815
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4816
-                return null;
4817
-            }
4818
-        } else if ($this->unique_indexes()) {
4819
-            $first_column = reset($this_model_fields_n_values);
4820
-            if (empty($first_column)) {
4821
-                return null;
4822
-            }
4823
-        }
4824
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4825
-        if ($primary_key) {
4826
-            $classInstance = $this->get_from_entity_map($primary_key);
4827
-            if (! $classInstance) {
4828
-                $classInstance = EE_Registry::instance()
4829
-                                            ->load_class($className,
4830
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4831
-                // add this new object to the entity map
4832
-                $classInstance = $this->add_to_entity_map($classInstance);
4833
-            }
4834
-        } else {
4835
-            $classInstance = EE_Registry::instance()
4836
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4837
-                                            true, false);
4838
-        }
4839
-        //it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4840
-        $this->set_timezone($classInstance->get_timezone());
4841
-        return $classInstance;
4842
-    }
4843
-
4844
-
4845
-
4846
-    /**
4847
-     * Gets the model object from the  entity map if it exists
4848
-     *
4849
-     * @param int|string $id the ID of the model object
4850
-     * @return EE_Base_Class
4851
-     */
4852
-    public function get_from_entity_map($id)
4853
-    {
4854
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4855
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4856
-    }
4857
-
4858
-
4859
-
4860
-    /**
4861
-     * add_to_entity_map
4862
-     * Adds the object to the model's entity mappings
4863
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4864
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4865
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4866
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4867
-     *        then this method should be called immediately after the update query
4868
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4869
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4870
-     *
4871
-     * @param    EE_Base_Class $object
4872
-     * @throws EE_Error
4873
-     * @return \EE_Base_Class
4874
-     */
4875
-    public function add_to_entity_map(EE_Base_Class $object)
4876
-    {
4877
-        $className = $this->_get_class_name();
4878
-        if (! $object instanceof $className) {
4879
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4880
-                is_object($object) ? get_class($object) : $object, $className));
4881
-        }
4882
-        /** @var $object EE_Base_Class */
4883
-        if (! $object->ID()) {
4884
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4885
-                "event_espresso"), get_class($this)));
4886
-        }
4887
-        // double check it's not already there
4888
-        $classInstance = $this->get_from_entity_map($object->ID());
4889
-        if ($classInstance) {
4890
-            return $classInstance;
4891
-        } else {
4892
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4893
-            return $object;
4894
-        }
4895
-    }
4896
-
4897
-
4898
-
4899
-    /**
4900
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4901
-     * if no identifier is provided, then the entire entity map is emptied
4902
-     *
4903
-     * @param int|string $id the ID of the model object
4904
-     * @return boolean
4905
-     */
4906
-    public function clear_entity_map($id = null)
4907
-    {
4908
-        if (empty($id)) {
4909
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4910
-            return true;
4911
-        }
4912
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4913
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4914
-            return true;
4915
-        }
4916
-        return false;
4917
-    }
4918
-
4919
-
4920
-
4921
-    /**
4922
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4923
-     * Given an array where keys are column (or column alias) names and values,
4924
-     * returns an array of their corresponding field names and database values
4925
-     *
4926
-     * @param array $cols_n_values
4927
-     * @return array
4928
-     */
4929
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4930
-    {
4931
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4932
-    }
4933
-
4934
-
4935
-
4936
-    /**
4937
-     * _deduce_fields_n_values_from_cols_n_values
4938
-     * Given an array where keys are column (or column alias) names and values,
4939
-     * returns an array of their corresponding field names and database values
4940
-     *
4941
-     * @param string $cols_n_values
4942
-     * @return array
4943
-     */
4944
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4945
-    {
4946
-        $this_model_fields_n_values = array();
4947
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
4948
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4949
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4950
-            //there is a primary key on this table and its not set. Use defaults for all its columns
4951
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
4952
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4953
-                    if (! $field_obj->is_db_only_field()) {
4954
-                        //prepare field as if its coming from db
4955
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4956
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4957
-                    }
4958
-                }
4959
-            } else {
4960
-                //the table's rows existed. Use their values
4961
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4962
-                    if (! $field_obj->is_db_only_field()) {
4963
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4964
-                            $cols_n_values, $field_obj->get_qualified_column(),
4965
-                            $field_obj->get_table_column()
4966
-                        );
4967
-                    }
4968
-                }
4969
-            }
4970
-        }
4971
-        return $this_model_fields_n_values;
4972
-    }
4973
-
4974
-
4975
-
4976
-    /**
4977
-     * @param $cols_n_values
4978
-     * @param $qualified_column
4979
-     * @param $regular_column
4980
-     * @return null
4981
-     */
4982
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4983
-    {
4984
-        $value = null;
4985
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4986
-        //does the field on the model relate to this column retrieved from the db?
4987
-        //or is it a db-only field? (not relating to the model)
4988
-        if (isset($cols_n_values[$qualified_column])) {
4989
-            $value = $cols_n_values[$qualified_column];
4990
-        } elseif (isset($cols_n_values[$regular_column])) {
4991
-            $value = $cols_n_values[$regular_column];
4992
-        }
4993
-        return $value;
4994
-    }
4995
-
4996
-
4997
-
4998
-    /**
4999
-     * refresh_entity_map_from_db
5000
-     * Makes sure the model object in the entity map at $id assumes the values
5001
-     * of the database (opposite of EE_base_Class::save())
5002
-     *
5003
-     * @param int|string $id
5004
-     * @return EE_Base_Class
5005
-     * @throws \EE_Error
5006
-     */
5007
-    public function refresh_entity_map_from_db($id)
5008
-    {
5009
-        $obj_in_map = $this->get_from_entity_map($id);
5010
-        if ($obj_in_map) {
5011
-            $wpdb_results = $this->_get_all_wpdb_results(
5012
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5013
-            );
5014
-            if ($wpdb_results && is_array($wpdb_results)) {
5015
-                $one_row = reset($wpdb_results);
5016
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5017
-                    $obj_in_map->set_from_db($field_name, $db_value);
5018
-                }
5019
-                //clear the cache of related model objects
5020
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5021
-                    $obj_in_map->clear_cache($relation_name, null, true);
5022
-                }
5023
-            }
5024
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5025
-            return $obj_in_map;
5026
-        } else {
5027
-            return $this->get_one_by_ID($id);
5028
-        }
5029
-    }
5030
-
5031
-
5032
-
5033
-    /**
5034
-     * refresh_entity_map_with
5035
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5036
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5037
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5038
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5039
-     *
5040
-     * @param int|string    $id
5041
-     * @param EE_Base_Class $replacing_model_obj
5042
-     * @return \EE_Base_Class
5043
-     * @throws \EE_Error
5044
-     */
5045
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5046
-    {
5047
-        $obj_in_map = $this->get_from_entity_map($id);
5048
-        if ($obj_in_map) {
5049
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5050
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5051
-                    $obj_in_map->set($field_name, $value);
5052
-                }
5053
-                //make the model object in the entity map's cache match the $replacing_model_obj
5054
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5055
-                    $obj_in_map->clear_cache($relation_name, null, true);
5056
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5057
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5058
-                    }
5059
-                }
5060
-            }
5061
-            return $obj_in_map;
5062
-        } else {
5063
-            $this->add_to_entity_map($replacing_model_obj);
5064
-            return $replacing_model_obj;
5065
-        }
5066
-    }
5067
-
5068
-
5069
-
5070
-    /**
5071
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5072
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5073
-     * require_once($this->_getClassName().".class.php");
5074
-     *
5075
-     * @return string
5076
-     */
5077
-    private function _get_class_name()
5078
-    {
5079
-        return "EE_" . $this->get_this_model_name();
5080
-    }
5081
-
5082
-
5083
-
5084
-    /**
5085
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5086
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5087
-     * it would be 'Events'.
5088
-     *
5089
-     * @param int $quantity
5090
-     * @return string
5091
-     */
5092
-    public function item_name($quantity = 1)
5093
-    {
5094
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5095
-    }
5096
-
5097
-
5098
-
5099
-    /**
5100
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5101
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5102
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5103
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5104
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5105
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5106
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5107
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5108
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5109
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5110
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5111
-     *        return $previousReturnValue.$returnString;
5112
-     * }
5113
-     * require('EEM_Answer.model.php');
5114
-     * $answer=EEM_Answer::instance();
5115
-     * echo $answer->my_callback('monkeys',100);
5116
-     * //will output "you called my_callback! and passed args:monkeys,100"
5117
-     *
5118
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5119
-     * @param array  $args       array of original arguments passed to the function
5120
-     * @throws EE_Error
5121
-     * @return mixed whatever the plugin which calls add_filter decides
5122
-     */
5123
-    public function __call($methodName, $args)
5124
-    {
5125
-        $className = get_class($this);
5126
-        $tagName = "FHEE__{$className}__{$methodName}";
5127
-        if (! has_filter($tagName)) {
5128
-            throw new EE_Error(
5129
-                sprintf(
5130
-                    __('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5131
-                        'event_espresso'),
5132
-                    $methodName,
5133
-                    $className,
5134
-                    $tagName,
5135
-                    '<br />'
5136
-                )
5137
-            );
5138
-        }
5139
-        return apply_filters($tagName, null, $this, $args);
5140
-    }
5141
-
5142
-
5143
-
5144
-    /**
5145
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5146
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5147
-     *
5148
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5149
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5150
-     *                                                       the object's class name
5151
-     *                                                       or object's ID
5152
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5153
-     *                                                       exists in the database. If it does not, we add it
5154
-     * @throws EE_Error
5155
-     * @return EE_Base_Class
5156
-     */
5157
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5158
-    {
5159
-        $className = $this->_get_class_name();
5160
-        if ($base_class_obj_or_id instanceof $className) {
5161
-            $model_object = $base_class_obj_or_id;
5162
-        } else {
5163
-            $primary_key_field = $this->get_primary_key_field();
5164
-            if (
5165
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5166
-                && (
5167
-                    is_int($base_class_obj_or_id)
5168
-                    || is_string($base_class_obj_or_id)
5169
-                )
5170
-            ) {
5171
-                // assume it's an ID.
5172
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5173
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5174
-            } else if (
5175
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5176
-                && is_string($base_class_obj_or_id)
5177
-            ) {
5178
-                // assume its a string representation of the object
5179
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5180
-            } else {
5181
-                throw new EE_Error(
5182
-                    sprintf(
5183
-                        __(
5184
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5185
-                            'event_espresso'
5186
-                        ),
5187
-                        $base_class_obj_or_id,
5188
-                        $this->_get_class_name(),
5189
-                        print_r($base_class_obj_or_id, true)
5190
-                    )
5191
-                );
5192
-            }
5193
-        }
5194
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5195
-            $model_object->save();
5196
-        }
5197
-        return $model_object;
5198
-    }
5199
-
5200
-
5201
-
5202
-    /**
5203
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5204
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5205
-     * returns it ID.
5206
-     *
5207
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5208
-     * @return int|string depending on the type of this model object's ID
5209
-     * @throws EE_Error
5210
-     */
5211
-    public function ensure_is_ID($base_class_obj_or_id)
5212
-    {
5213
-        $className = $this->_get_class_name();
5214
-        if ($base_class_obj_or_id instanceof $className) {
5215
-            /** @var $base_class_obj_or_id EE_Base_Class */
5216
-            $id = $base_class_obj_or_id->ID();
5217
-        } elseif (is_int($base_class_obj_or_id)) {
5218
-            //assume it's an ID
5219
-            $id = $base_class_obj_or_id;
5220
-        } elseif (is_string($base_class_obj_or_id)) {
5221
-            //assume its a string representation of the object
5222
-            $id = $base_class_obj_or_id;
5223
-        } else {
5224
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5225
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5226
-                print_r($base_class_obj_or_id, true)));
5227
-        }
5228
-        return $id;
5229
-    }
5230
-
5231
-
5232
-
5233
-    /**
5234
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5235
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5236
-     * been sanitized and converted into the appropriate domain.
5237
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5238
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5239
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5240
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5241
-     * $EVT = EEM_Event::instance(); $old_setting =
5242
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5243
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5244
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5245
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5246
-     *
5247
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5248
-     * @return void
5249
-     */
5250
-    public function assume_values_already_prepared_by_model_object(
5251
-        $values_already_prepared = self::not_prepared_by_model_object
5252
-    ) {
5253
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5254
-    }
5255
-
5256
-
5257
-
5258
-    /**
5259
-     * Read comments for assume_values_already_prepared_by_model_object()
5260
-     *
5261
-     * @return int
5262
-     */
5263
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5264
-    {
5265
-        return $this->_values_already_prepared_by_model_object;
5266
-    }
5267
-
5268
-
5269
-
5270
-    /**
5271
-     * Gets all the indexes on this model
5272
-     *
5273
-     * @return EE_Index[]
5274
-     */
5275
-    public function indexes()
5276
-    {
5277
-        return $this->_indexes;
5278
-    }
5279
-
5280
-
5281
-
5282
-    /**
5283
-     * Gets all the Unique Indexes on this model
5284
-     *
5285
-     * @return EE_Unique_Index[]
5286
-     */
5287
-    public function unique_indexes()
5288
-    {
5289
-        $unique_indexes = array();
5290
-        foreach ($this->_indexes as $name => $index) {
5291
-            if ($index instanceof EE_Unique_Index) {
5292
-                $unique_indexes [$name] = $index;
5293
-            }
5294
-        }
5295
-        return $unique_indexes;
5296
-    }
5297
-
5298
-
5299
-
5300
-    /**
5301
-     * Gets all the fields which, when combined, make the primary key.
5302
-     * This is usually just an array with 1 element (the primary key), but in cases
5303
-     * where there is no primary key, it's a combination of fields as defined
5304
-     * on a primary index
5305
-     *
5306
-     * @return EE_Model_Field_Base[] indexed by the field's name
5307
-     * @throws \EE_Error
5308
-     */
5309
-    public function get_combined_primary_key_fields()
5310
-    {
5311
-        foreach ($this->indexes() as $index) {
5312
-            if ($index instanceof EE_Primary_Key_Index) {
5313
-                return $index->fields();
5314
-            }
5315
-        }
5316
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5317
-    }
5318
-
5319
-
5320
-
5321
-    /**
5322
-     * Used to build a primary key string (when the model has no primary key),
5323
-     * which can be used a unique string to identify this model object.
5324
-     *
5325
-     * @param array $cols_n_values keys are field names, values are their values
5326
-     * @return string
5327
-     * @throws \EE_Error
5328
-     */
5329
-    public function get_index_primary_key_string($cols_n_values)
5330
-    {
5331
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5332
-            $this->get_combined_primary_key_fields());
5333
-        return http_build_query($cols_n_values_for_primary_key_index);
5334
-    }
5335
-
5336
-
5337
-
5338
-    /**
5339
-     * Gets the field values from the primary key string
5340
-     *
5341
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5342
-     * @param string $index_primary_key_string
5343
-     * @return null|array
5344
-     * @throws \EE_Error
5345
-     */
5346
-    public function parse_index_primary_key_string($index_primary_key_string)
5347
-    {
5348
-        $key_fields = $this->get_combined_primary_key_fields();
5349
-        //check all of them are in the $id
5350
-        $key_vals_in_combined_pk = array();
5351
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5352
-        foreach ($key_fields as $key_field_name => $field_obj) {
5353
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5354
-                return null;
5355
-            }
5356
-        }
5357
-        return $key_vals_in_combined_pk;
5358
-    }
5359
-
5360
-
5361
-
5362
-    /**
5363
-     * verifies that an array of key-value pairs for model fields has a key
5364
-     * for each field comprising the primary key index
5365
-     *
5366
-     * @param array $key_vals
5367
-     * @return boolean
5368
-     * @throws \EE_Error
5369
-     */
5370
-    public function has_all_combined_primary_key_fields($key_vals)
5371
-    {
5372
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5373
-        foreach ($keys_it_should_have as $key) {
5374
-            if (! isset($key_vals[$key])) {
5375
-                return false;
5376
-            }
5377
-        }
5378
-        return true;
5379
-    }
5380
-
5381
-
5382
-
5383
-    /**
5384
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5385
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5386
-     *
5387
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5388
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5389
-     * @throws EE_Error
5390
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5391
-     *                                                              indexed)
5392
-     */
5393
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5394
-    {
5395
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5396
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5397
-        } elseif (is_array($model_object_or_attributes_array)) {
5398
-            $attributes_array = $model_object_or_attributes_array;
5399
-        } else {
5400
-            throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5401
-                "event_espresso"), $model_object_or_attributes_array));
5402
-        }
5403
-        //even copies obviously won't have the same ID, so remove the primary key
5404
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5405
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5406
-            unset($attributes_array[$this->primary_key_name()]);
5407
-        }
5408
-        if (isset($query_params[0])) {
5409
-            $query_params[0] = array_merge($attributes_array, $query_params);
5410
-        } else {
5411
-            $query_params[0] = $attributes_array;
5412
-        }
5413
-        return $this->get_all($query_params);
5414
-    }
5415
-
5416
-
5417
-
5418
-    /**
5419
-     * Gets the first copy we find. See get_all_copies for more details
5420
-     *
5421
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5422
-     * @param array $query_params
5423
-     * @return EE_Base_Class
5424
-     * @throws \EE_Error
5425
-     */
5426
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5427
-    {
5428
-        if (! is_array($query_params)) {
5429
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5430
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5431
-                    gettype($query_params)), '4.6.0');
5432
-            $query_params = array();
5433
-        }
5434
-        $query_params['limit'] = 1;
5435
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5436
-        if (is_array($copies)) {
5437
-            return array_shift($copies);
5438
-        } else {
5439
-            return null;
5440
-        }
5441
-    }
5442
-
5443
-
5444
-
5445
-    /**
5446
-     * Updates the item with the specified id. Ignores default query parameters because
5447
-     * we have specified the ID, and its assumed we KNOW what we're doing
5448
-     *
5449
-     * @param array      $fields_n_values keys are field names, values are their new values
5450
-     * @param int|string $id              the value of the primary key to update
5451
-     * @return int number of rows updated
5452
-     * @throws \EE_Error
5453
-     */
5454
-    public function update_by_ID($fields_n_values, $id)
5455
-    {
5456
-        $query_params = array(
5457
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5458
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5459
-        );
5460
-        return $this->update($fields_n_values, $query_params);
5461
-    }
5462
-
5463
-
5464
-
5465
-    /**
5466
-     * Changes an operator which was supplied to the models into one usable in SQL
5467
-     *
5468
-     * @param string $operator_supplied
5469
-     * @return string an operator which can be used in SQL
5470
-     * @throws EE_Error
5471
-     */
5472
-    private function _prepare_operator_for_sql($operator_supplied)
5473
-    {
5474
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5475
-            : null;
5476
-        if ($sql_operator) {
5477
-            return $sql_operator;
5478
-        } else {
5479
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5480
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5481
-        }
5482
-    }
5483
-
5484
-
5485
-
5486
-    /**
5487
-     * Gets an array where keys are the primary keys and values are their 'names'
5488
-     * (as determined by the model object's name() function, which is often overridden)
5489
-     *
5490
-     * @param array $query_params like get_all's
5491
-     * @return string[]
5492
-     * @throws \EE_Error
5493
-     */
5494
-    public function get_all_names($query_params = array())
5495
-    {
5496
-        $objs = $this->get_all($query_params);
5497
-        $names = array();
5498
-        foreach ($objs as $obj) {
5499
-            $names[$obj->ID()] = $obj->name();
5500
-        }
5501
-        return $names;
5502
-    }
5503
-
5504
-
5505
-
5506
-    /**
5507
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5508
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5509
-     * this is duplicated effort and reduces efficiency) you would be better to use
5510
-     * array_keys() on $model_objects.
5511
-     *
5512
-     * @param \EE_Base_Class[] $model_objects
5513
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5514
-     *                                               in the returned array
5515
-     * @return array
5516
-     * @throws \EE_Error
5517
-     */
5518
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5519
-    {
5520
-        if (! $this->has_primary_key_field()) {
5521
-            if (WP_DEBUG) {
5522
-                EE_Error::add_error(
5523
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5524
-                    __FILE__,
5525
-                    __FUNCTION__,
5526
-                    __LINE__
5527
-                );
5528
-            }
5529
-        }
5530
-        $IDs = array();
5531
-        foreach ($model_objects as $model_object) {
5532
-            $id = $model_object->ID();
5533
-            if (! $id) {
5534
-                if ($filter_out_empty_ids) {
5535
-                    continue;
5536
-                }
5537
-                if (WP_DEBUG) {
5538
-                    EE_Error::add_error(
5539
-                        __(
5540
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5541
-                            'event_espresso'
5542
-                        ),
5543
-                        __FILE__,
5544
-                        __FUNCTION__,
5545
-                        __LINE__
5546
-                    );
5547
-                }
5548
-            }
5549
-            $IDs[] = $id;
5550
-        }
5551
-        return $IDs;
5552
-    }
5553
-
5554
-
5555
-
5556
-    /**
5557
-     * Returns the string used in capabilities relating to this model. If there
5558
-     * are no capabilities that relate to this model returns false
5559
-     *
5560
-     * @return string|false
5561
-     */
5562
-    public function cap_slug()
5563
-    {
5564
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5565
-    }
5566
-
5567
-
5568
-
5569
-    /**
5570
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5571
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5572
-     * only returns the cap restrictions array in that context (ie, the array
5573
-     * at that key)
5574
-     *
5575
-     * @param string $context
5576
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5577
-     * @throws \EE_Error
5578
-     */
5579
-    public function cap_restrictions($context = EEM_Base::caps_read)
5580
-    {
5581
-        EEM_Base::verify_is_valid_cap_context($context);
5582
-        //check if we ought to run the restriction generator first
5583
-        if (
5584
-            isset($this->_cap_restriction_generators[$context])
5585
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5586
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5587
-        ) {
5588
-            $this->_cap_restrictions[$context] = array_merge(
5589
-                $this->_cap_restrictions[$context],
5590
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5591
-            );
5592
-        }
5593
-        //and make sure we've finalized the construction of each restriction
5594
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5595
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5596
-                $where_conditions_obj->_finalize_construct($this);
5597
-            }
5598
-        }
5599
-        return $this->_cap_restrictions[$context];
5600
-    }
5601
-
5602
-
5603
-
5604
-    /**
5605
-     * Indicating whether or not this model thinks its a wp core model
5606
-     *
5607
-     * @return boolean
5608
-     */
5609
-    public function is_wp_core_model()
5610
-    {
5611
-        return $this->_wp_core_model;
5612
-    }
5613
-
5614
-
5615
-
5616
-    /**
5617
-     * Gets all the caps that are missing which impose a restriction on
5618
-     * queries made in this context
5619
-     *
5620
-     * @param string $context one of EEM_Base::caps_ constants
5621
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5622
-     * @throws \EE_Error
5623
-     */
5624
-    public function caps_missing($context = EEM_Base::caps_read)
5625
-    {
5626
-        $missing_caps = array();
5627
-        $cap_restrictions = $this->cap_restrictions($context);
5628
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5629
-            if (! EE_Capabilities::instance()
5630
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5631
-            ) {
5632
-                $missing_caps[$cap] = $restriction_if_no_cap;
5633
-            }
5634
-        }
5635
-        return $missing_caps;
5636
-    }
5637
-
5638
-
5639
-
5640
-    /**
5641
-     * Gets the mapping from capability contexts to action strings used in capability names
5642
-     *
5643
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5644
-     * one of 'read', 'edit', or 'delete'
5645
-     */
5646
-    public function cap_contexts_to_cap_action_map()
5647
-    {
5648
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5649
-            $this);
5650
-    }
5651
-
5652
-
5653
-
5654
-    /**
5655
-     * Gets the action string for the specified capability context
5656
-     *
5657
-     * @param string $context
5658
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5659
-     * @throws \EE_Error
5660
-     */
5661
-    public function cap_action_for_context($context)
5662
-    {
5663
-        $mapping = $this->cap_contexts_to_cap_action_map();
5664
-        if (isset($mapping[$context])) {
5665
-            return $mapping[$context];
5666
-        }
5667
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5668
-            return $action;
5669
-        }
5670
-        throw new EE_Error(
5671
-            sprintf(
5672
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5673
-                $context,
5674
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5675
-            )
5676
-        );
5677
-    }
5678
-
5679
-
5680
-
5681
-    /**
5682
-     * Returns all the capability contexts which are valid when querying models
5683
-     *
5684
-     * @return array
5685
-     */
5686
-    public static function valid_cap_contexts()
5687
-    {
5688
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5689
-            self::caps_read,
5690
-            self::caps_read_admin,
5691
-            self::caps_edit,
5692
-            self::caps_delete,
5693
-        ));
5694
-    }
5695
-
5696
-
5697
-
5698
-    /**
5699
-     * Returns all valid options for 'default_where_conditions'
5700
-     *
5701
-     * @return array
5702
-     */
5703
-    public static function valid_default_where_conditions()
5704
-    {
5705
-        return array(
5706
-            EEM_Base::default_where_conditions_all,
5707
-            EEM_Base::default_where_conditions_this_only,
5708
-            EEM_Base::default_where_conditions_others_only,
5709
-            EEM_Base::default_where_conditions_minimum_all,
5710
-            EEM_Base::default_where_conditions_minimum_others,
5711
-            EEM_Base::default_where_conditions_none
5712
-        );
5713
-    }
5714
-
5715
-    // public static function default_where_conditions_full
5716
-    /**
5717
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5718
-     *
5719
-     * @param string $context
5720
-     * @return bool
5721
-     * @throws \EE_Error
5722
-     */
5723
-    static public function verify_is_valid_cap_context($context)
5724
-    {
5725
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5726
-        if (in_array($context, $valid_cap_contexts)) {
5727
-            return true;
5728
-        } else {
5729
-            throw new EE_Error(
5730
-                sprintf(
5731
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5732
-                        'event_espresso'),
5733
-                    $context,
5734
-                    'EEM_Base',
5735
-                    implode(',', $valid_cap_contexts)
5736
-                )
5737
-            );
5738
-        }
5739
-    }
5740
-
5741
-
5742
-
5743
-    /**
5744
-     * Clears all the models field caches. This is only useful when a sub-class
5745
-     * might have added a field or something and these caches might be invalidated
5746
-     */
5747
-    protected function _invalidate_field_caches()
5748
-    {
5749
-        $this->_cache_foreign_key_to_fields = array();
5750
-        $this->_cached_fields = null;
5751
-        $this->_cached_fields_non_db_only = null;
5752
-    }
3610
+		}
3611
+		return $null_friendly_where_conditions;
3612
+	}
3613
+
3614
+
3615
+
3616
+	/**
3617
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3618
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3619
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3620
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3621
+	 *
3622
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3623
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3624
+	 */
3625
+	private function _get_default_where_conditions($model_relation_path = null)
3626
+	{
3627
+		if ($this->_ignore_where_strategy) {
3628
+			return array();
3629
+		}
3630
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3631
+	}
3632
+
3633
+
3634
+
3635
+	/**
3636
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3637
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3638
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3639
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3640
+	 * Similar to _get_default_where_conditions
3641
+	 *
3642
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3643
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3644
+	 */
3645
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3646
+	{
3647
+		if ($this->_ignore_where_strategy) {
3648
+			return array();
3649
+		}
3650
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3651
+	}
3652
+
3653
+
3654
+
3655
+	/**
3656
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3657
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3658
+	 *
3659
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3660
+	 * @return string
3661
+	 * @throws \EE_Error
3662
+	 */
3663
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3664
+	{
3665
+		$selects = $this->_get_columns_to_select_for_this_model();
3666
+		foreach (
3667
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3668
+			$name_of_other_model_included
3669
+		) {
3670
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3671
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3672
+			foreach ($other_model_selects as $key => $value) {
3673
+				$selects[] = $value;
3674
+			}
3675
+		}
3676
+		return implode(", ", $selects);
3677
+	}
3678
+
3679
+
3680
+
3681
+	/**
3682
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3683
+	 * So that's going to be the columns for all the fields on the model
3684
+	 *
3685
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3686
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3687
+	 */
3688
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3689
+	{
3690
+		$fields = $this->field_settings();
3691
+		$selects = array();
3692
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3693
+			$this->get_this_model_name());
3694
+		foreach ($fields as $field_obj) {
3695
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3696
+						 . $field_obj->get_table_alias()
3697
+						 . "."
3698
+						 . $field_obj->get_table_column()
3699
+						 . " AS '"
3700
+						 . $table_alias_with_model_relation_chain_prefix
3701
+						 . $field_obj->get_table_alias()
3702
+						 . "."
3703
+						 . $field_obj->get_table_column()
3704
+						 . "'";
3705
+		}
3706
+		//make sure we are also getting the PKs of each table
3707
+		$tables = $this->get_tables();
3708
+		if (count($tables) > 1) {
3709
+			foreach ($tables as $table_obj) {
3710
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3711
+									   . $table_obj->get_fully_qualified_pk_column();
3712
+				if (! in_array($qualified_pk_column, $selects)) {
3713
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3714
+				}
3715
+			}
3716
+		}
3717
+		return $selects;
3718
+	}
3719
+
3720
+
3721
+
3722
+	/**
3723
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3724
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3725
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3726
+	 * SQL for joining, and the data types
3727
+	 *
3728
+	 * @param null|string                 $original_query_param
3729
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3730
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3731
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3732
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3733
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3734
+	 *                                                          or 'Registration's
3735
+	 * @param string                      $original_query_param what it originally was (eg
3736
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3737
+	 *                                                          matches $query_param
3738
+	 * @throws EE_Error
3739
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3740
+	 */
3741
+	private function _extract_related_model_info_from_query_param(
3742
+		$query_param,
3743
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3744
+		$query_param_type,
3745
+		$original_query_param = null
3746
+	) {
3747
+		if ($original_query_param === null) {
3748
+			$original_query_param = $query_param;
3749
+		}
3750
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3751
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3752
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3753
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3754
+		//check to see if we have a field on this model
3755
+		$this_model_fields = $this->field_settings(true);
3756
+		if (array_key_exists($query_param, $this_model_fields)) {
3757
+			if ($allow_fields) {
3758
+				return;
3759
+			} else {
3760
+				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3761
+					"event_espresso"),
3762
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3763
+			}
3764
+		} //check if this is a special logic query param
3765
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3766
+			if ($allow_logic_query_params) {
3767
+				return;
3768
+			} else {
3769
+				throw new EE_Error(
3770
+					sprintf(
3771
+						__('Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3772
+							'event_espresso'),
3773
+						implode('", "', $this->_logic_query_param_keys),
3774
+						$query_param,
3775
+						get_class($this),
3776
+						'<br />',
3777
+						"\t"
3778
+						. ' $passed_in_query_info = <pre>'
3779
+						. print_r($passed_in_query_info, true)
3780
+						. '</pre>'
3781
+						. "\n\t"
3782
+						. ' $query_param_type = '
3783
+						. $query_param_type
3784
+						. "\n\t"
3785
+						. ' $original_query_param = '
3786
+						. $original_query_param
3787
+					)
3788
+				);
3789
+			}
3790
+		} //check if it's a custom selection
3791
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3792
+			return;
3793
+		}
3794
+		//check if has a model name at the beginning
3795
+		//and
3796
+		//check if it's a field on a related model
3797
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3798
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3799
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3800
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3801
+				if ($query_param === '') {
3802
+					//nothing left to $query_param
3803
+					//we should actually end in a field name, not a model like this!
3804
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3805
+						"event_espresso"),
3806
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3807
+				} else {
3808
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3809
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3810
+						$passed_in_query_info, $query_param_type, $original_query_param);
3811
+					return;
3812
+				}
3813
+			} elseif ($query_param === $valid_related_model_name) {
3814
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3815
+				return;
3816
+			}
3817
+		}
3818
+		//ok so $query_param didn't start with a model name
3819
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3820
+		//it's wack, that's what it is
3821
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3822
+			"event_espresso"),
3823
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3824
+	}
3825
+
3826
+
3827
+
3828
+	/**
3829
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3830
+	 * and store it on $passed_in_query_info
3831
+	 *
3832
+	 * @param string                      $model_name
3833
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3834
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3835
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3836
+	 *                                                          and are adding a join to 'Payment' with the original
3837
+	 *                                                          query param key
3838
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3839
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3840
+	 *                                                          Payment wants to add default query params so that it
3841
+	 *                                                          will know what models to prepend onto its default query
3842
+	 *                                                          params or in case it wants to rename tables (in case
3843
+	 *                                                          there are multiple joins to the same table)
3844
+	 * @return void
3845
+	 * @throws \EE_Error
3846
+	 */
3847
+	private function _add_join_to_model(
3848
+		$model_name,
3849
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3850
+		$original_query_param
3851
+	) {
3852
+		$relation_obj = $this->related_settings_for($model_name);
3853
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3854
+		//check if the relation is HABTM, because then we're essentially doing two joins
3855
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3856
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3857
+			$join_model_obj = $relation_obj->get_join_model();
3858
+			//replace the model specified with the join model for this relation chain, whi
3859
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3860
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3861
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3862
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3863
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3864
+			$passed_in_query_info->merge($new_query_info);
3865
+		}
3866
+		//now just join to the other table pointed to by the relation object, and add its data types
3867
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3868
+			array($model_relation_chain => $model_name),
3869
+			$relation_obj->get_join_statement($model_relation_chain));
3870
+		$passed_in_query_info->merge($new_query_info);
3871
+	}
3872
+
3873
+
3874
+
3875
+	/**
3876
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3877
+	 *
3878
+	 * @param array $where_params like EEM_Base::get_all
3879
+	 * @return string of SQL
3880
+	 * @throws \EE_Error
3881
+	 */
3882
+	private function _construct_where_clause($where_params)
3883
+	{
3884
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3885
+		if ($SQL) {
3886
+			return " WHERE " . $SQL;
3887
+		} else {
3888
+			return '';
3889
+		}
3890
+	}
3891
+
3892
+
3893
+
3894
+	/**
3895
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3896
+	 * and should be passed HAVING parameters, not WHERE parameters
3897
+	 *
3898
+	 * @param array $having_params
3899
+	 * @return string
3900
+	 * @throws \EE_Error
3901
+	 */
3902
+	private function _construct_having_clause($having_params)
3903
+	{
3904
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3905
+		if ($SQL) {
3906
+			return " HAVING " . $SQL;
3907
+		} else {
3908
+			return '';
3909
+		}
3910
+	}
3911
+
3912
+
3913
+
3914
+	/**
3915
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3916
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3917
+	 * EEM_Attendee.
3918
+	 *
3919
+	 * @param string $field_name
3920
+	 * @param string $model_name
3921
+	 * @return EE_Model_Field_Base
3922
+	 * @throws EE_Error
3923
+	 */
3924
+	protected function _get_field_on_model($field_name, $model_name)
3925
+	{
3926
+		$model_class = 'EEM_' . $model_name;
3927
+		$model_filepath = $model_class . ".model.php";
3928
+		if (is_readable($model_filepath)) {
3929
+			require_once($model_filepath);
3930
+			$model_instance = call_user_func($model_name . "::instance");
3931
+			/* @var $model_instance EEM_Base */
3932
+			return $model_instance->field_settings_for($field_name);
3933
+		} else {
3934
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3935
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3936
+		}
3937
+	}
3938
+
3939
+
3940
+
3941
+	/**
3942
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3943
+	 * Event_Meta.meta_value = 'foo'))"
3944
+	 *
3945
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3946
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3947
+	 * @throws EE_Error
3948
+	 * @return string of SQL
3949
+	 */
3950
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3951
+	{
3952
+		$where_clauses = array();
3953
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3954
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3955
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3956
+				switch ($query_param) {
3957
+					case 'not':
3958
+					case 'NOT':
3959
+						$where_clauses[] = "! ("
3960
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3961
+								$glue)
3962
+										   . ")";
3963
+						break;
3964
+					case 'and':
3965
+					case 'AND':
3966
+						$where_clauses[] = " ("
3967
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3968
+								' AND ')
3969
+										   . ")";
3970
+						break;
3971
+					case 'or':
3972
+					case 'OR':
3973
+						$where_clauses[] = " ("
3974
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3975
+								' OR ')
3976
+										   . ")";
3977
+						break;
3978
+				}
3979
+			} else {
3980
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3981
+				//if it's not a normal field, maybe it's a custom selection?
3982
+				if (! $field_obj) {
3983
+					if (isset($this->_custom_selections[$query_param][1])) {
3984
+						$field_obj = $this->_custom_selections[$query_param][1];
3985
+					} else {
3986
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3987
+							"event_espresso"), $query_param));
3988
+					}
3989
+				}
3990
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3991
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3992
+			}
3993
+		}
3994
+		return $where_clauses ? implode($glue, $where_clauses) : '';
3995
+	}
3996
+
3997
+
3998
+
3999
+	/**
4000
+	 * Takes the input parameter and extract the table name (alias) and column name
4001
+	 *
4002
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4003
+	 * @throws EE_Error
4004
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4005
+	 */
4006
+	private function _deduce_column_name_from_query_param($query_param)
4007
+	{
4008
+		$field = $this->_deduce_field_from_query_param($query_param);
4009
+		if ($field) {
4010
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4011
+				$query_param);
4012
+			return $table_alias_prefix . $field->get_qualified_column();
4013
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4014
+			//maybe it's custom selection item?
4015
+			//if so, just use it as the "column name"
4016
+			return $query_param;
4017
+		} else {
4018
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4019
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4020
+		}
4021
+	}
4022
+
4023
+
4024
+
4025
+	/**
4026
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4027
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4028
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4029
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4030
+	 *
4031
+	 * @param string $condition_query_param_key
4032
+	 * @return string
4033
+	 */
4034
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4035
+	{
4036
+		$pos_of_star = strpos($condition_query_param_key, '*');
4037
+		if ($pos_of_star === false) {
4038
+			return $condition_query_param_key;
4039
+		} else {
4040
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4041
+			return $condition_query_param_sans_star;
4042
+		}
4043
+	}
4044
+
4045
+
4046
+
4047
+	/**
4048
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4049
+	 *
4050
+	 * @param                            mixed      array | string    $op_and_value
4051
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4052
+	 * @throws EE_Error
4053
+	 * @return string
4054
+	 */
4055
+	private function _construct_op_and_value($op_and_value, $field_obj)
4056
+	{
4057
+		if (is_array($op_and_value)) {
4058
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4059
+			if (! $operator) {
4060
+				$php_array_like_string = array();
4061
+				foreach ($op_and_value as $key => $value) {
4062
+					$php_array_like_string[] = "$key=>$value";
4063
+				}
4064
+				throw new EE_Error(
4065
+					sprintf(
4066
+						__(
4067
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4068
+							"event_espresso"
4069
+						),
4070
+						implode(",", $php_array_like_string)
4071
+					)
4072
+				);
4073
+			}
4074
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4075
+		} else {
4076
+			$operator = '=';
4077
+			$value = $op_and_value;
4078
+		}
4079
+		//check to see if the value is actually another field
4080
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4081
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4082
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4083
+			//in this case, the value should be an array, or at least a comma-separated list
4084
+			//it will need to handle a little differently
4085
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4086
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4087
+			return $operator . SP . $cleaned_value;
4088
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4089
+			//the value should be an array with count of two.
4090
+			if (count($value) !== 2) {
4091
+				throw new EE_Error(
4092
+					sprintf(
4093
+						__(
4094
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4095
+							'event_espresso'
4096
+						),
4097
+						"BETWEEN"
4098
+					)
4099
+				);
4100
+			}
4101
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4102
+			return $operator . SP . $cleaned_value;
4103
+		} elseif (in_array($operator, $this->_null_style_operators)) {
4104
+			if ($value !== null) {
4105
+				throw new EE_Error(
4106
+					sprintf(
4107
+						__(
4108
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4109
+							"event_espresso"
4110
+						),
4111
+						$value,
4112
+						$operator
4113
+					)
4114
+				);
4115
+			}
4116
+			return $operator;
4117
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
4118
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4119
+			//remove other junk. So just treat it as a string.
4120
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4121
+		} elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4122
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4123
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4124
+			throw new EE_Error(
4125
+				sprintf(
4126
+					__(
4127
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4128
+						'event_espresso'
4129
+					),
4130
+					$operator,
4131
+					$operator
4132
+				)
4133
+			);
4134
+		} elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4135
+			throw new EE_Error(
4136
+				sprintf(
4137
+					__(
4138
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4139
+						'event_espresso'
4140
+					),
4141
+					$operator,
4142
+					$operator
4143
+				)
4144
+			);
4145
+		} else {
4146
+			throw new EE_Error(
4147
+				sprintf(
4148
+					__(
4149
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4150
+						"event_espresso"
4151
+					),
4152
+					http_build_query($op_and_value)
4153
+				)
4154
+			);
4155
+		}
4156
+	}
4157
+
4158
+
4159
+
4160
+	/**
4161
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4162
+	 *
4163
+	 * @param array                      $values
4164
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4165
+	 *                                              '%s'
4166
+	 * @return string
4167
+	 * @throws \EE_Error
4168
+	 */
4169
+	public function _construct_between_value($values, $field_obj)
4170
+	{
4171
+		$cleaned_values = array();
4172
+		foreach ($values as $value) {
4173
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4174
+		}
4175
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4176
+	}
4177
+
4178
+
4179
+
4180
+	/**
4181
+	 * Takes an array or a comma-separated list of $values and cleans them
4182
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4183
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4184
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4185
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4186
+	 *
4187
+	 * @param mixed                      $values    array or comma-separated string
4188
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4189
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4190
+	 * @throws \EE_Error
4191
+	 */
4192
+	public function _construct_in_value($values, $field_obj)
4193
+	{
4194
+		//check if the value is a CSV list
4195
+		if (is_string($values)) {
4196
+			//in which case, turn it into an array
4197
+			$values = explode(",", $values);
4198
+		}
4199
+		$cleaned_values = array();
4200
+		foreach ($values as $value) {
4201
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4202
+		}
4203
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4204
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4205
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4206
+		if (empty($cleaned_values)) {
4207
+			$all_fields = $this->field_settings();
4208
+			$a_field = array_shift($all_fields);
4209
+			$main_table = $this->_get_main_table();
4210
+			$cleaned_values[] = "SELECT "
4211
+								. $a_field->get_table_column()
4212
+								. " FROM "
4213
+								. $main_table->get_table_name()
4214
+								. " WHERE FALSE";
4215
+		}
4216
+		return "(" . implode(",", $cleaned_values) . ")";
4217
+	}
4218
+
4219
+
4220
+
4221
+	/**
4222
+	 * @param mixed                      $value
4223
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4224
+	 * @throws EE_Error
4225
+	 * @return false|null|string
4226
+	 */
4227
+	private function _wpdb_prepare_using_field($value, $field_obj)
4228
+	{
4229
+		/** @type WPDB $wpdb */
4230
+		global $wpdb;
4231
+		if ($field_obj instanceof EE_Model_Field_Base) {
4232
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4233
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4234
+		} else {//$field_obj should really just be a data type
4235
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4236
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4237
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4238
+			}
4239
+			return $wpdb->prepare($field_obj, $value);
4240
+		}
4241
+	}
4242
+
4243
+
4244
+
4245
+	/**
4246
+	 * Takes the input parameter and finds the model field that it indicates.
4247
+	 *
4248
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4249
+	 * @throws EE_Error
4250
+	 * @return EE_Model_Field_Base
4251
+	 */
4252
+	protected function _deduce_field_from_query_param($query_param_name)
4253
+	{
4254
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4255
+		//which will help us find the database table and column
4256
+		$query_param_parts = explode(".", $query_param_name);
4257
+		if (empty($query_param_parts)) {
4258
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4259
+				'event_espresso'), $query_param_name));
4260
+		}
4261
+		$number_of_parts = count($query_param_parts);
4262
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4263
+		if ($number_of_parts === 1) {
4264
+			$field_name = $last_query_param_part;
4265
+			$model_obj = $this;
4266
+		} else {// $number_of_parts >= 2
4267
+			//the last part is the column name, and there are only 2parts. therefore...
4268
+			$field_name = $last_query_param_part;
4269
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4270
+		}
4271
+		try {
4272
+			return $model_obj->field_settings_for($field_name);
4273
+		} catch (EE_Error $e) {
4274
+			return null;
4275
+		}
4276
+	}
4277
+
4278
+
4279
+
4280
+	/**
4281
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4282
+	 * alias and column which corresponds to it
4283
+	 *
4284
+	 * @param string $field_name
4285
+	 * @throws EE_Error
4286
+	 * @return string
4287
+	 */
4288
+	public function _get_qualified_column_for_field($field_name)
4289
+	{
4290
+		$all_fields = $this->field_settings();
4291
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4292
+		if ($field) {
4293
+			return $field->get_qualified_column();
4294
+		} else {
4295
+			throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4296
+				'event_espresso'), $field_name, get_class($this)));
4297
+		}
4298
+	}
4299
+
4300
+
4301
+
4302
+	/**
4303
+	 * constructs the select use on special limit joins
4304
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4305
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4306
+	 * (as that is typically where the limits would be set).
4307
+	 *
4308
+	 * @param  string       $table_alias The table the select is being built for
4309
+	 * @param  mixed|string $limit       The limit for this select
4310
+	 * @return string                The final select join element for the query.
4311
+	 */
4312
+	public function _construct_limit_join_select($table_alias, $limit)
4313
+	{
4314
+		$SQL = '';
4315
+		foreach ($this->_tables as $table_obj) {
4316
+			if ($table_obj instanceof EE_Primary_Table) {
4317
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4318
+					? $table_obj->get_select_join_limit($limit)
4319
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4320
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4321
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4322
+					? $table_obj->get_select_join_limit_join($limit)
4323
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4324
+			}
4325
+		}
4326
+		return $SQL;
4327
+	}
4328
+
4329
+
4330
+
4331
+	/**
4332
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4333
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4334
+	 *
4335
+	 * @return string SQL
4336
+	 * @throws \EE_Error
4337
+	 */
4338
+	public function _construct_internal_join()
4339
+	{
4340
+		$SQL = $this->_get_main_table()->get_table_sql();
4341
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4342
+		return $SQL;
4343
+	}
4344
+
4345
+
4346
+
4347
+	/**
4348
+	 * Constructs the SQL for joining all the tables on this model.
4349
+	 * Normally $alias should be the primary table's alias, but in cases where
4350
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4351
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4352
+	 * alias, this will construct SQL like:
4353
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4354
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4355
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4356
+	 *
4357
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4358
+	 * @return string
4359
+	 */
4360
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4361
+	{
4362
+		$SQL = '';
4363
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4364
+		foreach ($this->_tables as $table_obj) {
4365
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4366
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4367
+					//so we're joining to this table, meaning the table is already in
4368
+					//the FROM statement, BUT the primary table isn't. So we want
4369
+					//to add the inverse join sql
4370
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4371
+				} else {
4372
+					//just add a regular JOIN to this table from the primary table
4373
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4374
+				}
4375
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4376
+		}
4377
+		return $SQL;
4378
+	}
4379
+
4380
+
4381
+
4382
+	/**
4383
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4384
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4385
+	 * their data type (eg, '%s', '%d', etc)
4386
+	 *
4387
+	 * @return array
4388
+	 */
4389
+	public function _get_data_types()
4390
+	{
4391
+		$data_types = array();
4392
+		foreach ($this->field_settings() as $field_obj) {
4393
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4394
+			/** @var $field_obj EE_Model_Field_Base */
4395
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4396
+		}
4397
+		return $data_types;
4398
+	}
4399
+
4400
+
4401
+
4402
+	/**
4403
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4404
+	 *
4405
+	 * @param string $model_name
4406
+	 * @throws EE_Error
4407
+	 * @return EEM_Base
4408
+	 */
4409
+	public function get_related_model_obj($model_name)
4410
+	{
4411
+		$model_classname = "EEM_" . $model_name;
4412
+		if (! class_exists($model_classname)) {
4413
+			throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4414
+				'event_espresso'), $model_name, $model_classname));
4415
+		}
4416
+		return call_user_func($model_classname . "::instance");
4417
+	}
4418
+
4419
+
4420
+
4421
+	/**
4422
+	 * Returns the array of EE_ModelRelations for this model.
4423
+	 *
4424
+	 * @return EE_Model_Relation_Base[]
4425
+	 */
4426
+	public function relation_settings()
4427
+	{
4428
+		return $this->_model_relations;
4429
+	}
4430
+
4431
+
4432
+
4433
+	/**
4434
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4435
+	 * because without THOSE models, this model probably doesn't have much purpose.
4436
+	 * (Eg, without an event, datetimes have little purpose.)
4437
+	 *
4438
+	 * @return EE_Belongs_To_Relation[]
4439
+	 */
4440
+	public function belongs_to_relations()
4441
+	{
4442
+		$belongs_to_relations = array();
4443
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4444
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4445
+				$belongs_to_relations[$model_name] = $relation_obj;
4446
+			}
4447
+		}
4448
+		return $belongs_to_relations;
4449
+	}
4450
+
4451
+
4452
+
4453
+	/**
4454
+	 * Returns the specified EE_Model_Relation, or throws an exception
4455
+	 *
4456
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4457
+	 * @throws EE_Error
4458
+	 * @return EE_Model_Relation_Base
4459
+	 */
4460
+	public function related_settings_for($relation_name)
4461
+	{
4462
+		$relatedModels = $this->relation_settings();
4463
+		if (! array_key_exists($relation_name, $relatedModels)) {
4464
+			throw new EE_Error(
4465
+				sprintf(
4466
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4467
+						'event_espresso'),
4468
+					$relation_name,
4469
+					$this->_get_class_name(),
4470
+					implode(', ', array_keys($relatedModels))
4471
+				)
4472
+			);
4473
+		}
4474
+		return $relatedModels[$relation_name];
4475
+	}
4476
+
4477
+
4478
+
4479
+	/**
4480
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4481
+	 * fields
4482
+	 *
4483
+	 * @param string $fieldName
4484
+	 * @throws EE_Error
4485
+	 * @return EE_Model_Field_Base
4486
+	 */
4487
+	public function field_settings_for($fieldName)
4488
+	{
4489
+		$fieldSettings = $this->field_settings(true);
4490
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4491
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4492
+				get_class($this)));
4493
+		}
4494
+		return $fieldSettings[$fieldName];
4495
+	}
4496
+
4497
+
4498
+
4499
+	/**
4500
+	 * Checks if this field exists on this model
4501
+	 *
4502
+	 * @param string $fieldName a key in the model's _field_settings array
4503
+	 * @return boolean
4504
+	 */
4505
+	public function has_field($fieldName)
4506
+	{
4507
+		$fieldSettings = $this->field_settings(true);
4508
+		if (isset($fieldSettings[$fieldName])) {
4509
+			return true;
4510
+		} else {
4511
+			return false;
4512
+		}
4513
+	}
4514
+
4515
+
4516
+
4517
+	/**
4518
+	 * Returns whether or not this model has a relation to the specified model
4519
+	 *
4520
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4521
+	 * @return boolean
4522
+	 */
4523
+	public function has_relation($relation_name)
4524
+	{
4525
+		$relations = $this->relation_settings();
4526
+		if (isset($relations[$relation_name])) {
4527
+			return true;
4528
+		} else {
4529
+			return false;
4530
+		}
4531
+	}
4532
+
4533
+
4534
+
4535
+	/**
4536
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4537
+	 * Eg, on EE_Answer that would be ANS_ID field object
4538
+	 *
4539
+	 * @param $field_obj
4540
+	 * @return boolean
4541
+	 */
4542
+	public function is_primary_key_field($field_obj)
4543
+	{
4544
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4545
+	}
4546
+
4547
+
4548
+
4549
+	/**
4550
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4551
+	 * Eg, on EE_Answer that would be ANS_ID field object
4552
+	 *
4553
+	 * @return EE_Model_Field_Base
4554
+	 * @throws EE_Error
4555
+	 */
4556
+	public function get_primary_key_field()
4557
+	{
4558
+		if ($this->_primary_key_field === null) {
4559
+			foreach ($this->field_settings(true) as $field_obj) {
4560
+				if ($this->is_primary_key_field($field_obj)) {
4561
+					$this->_primary_key_field = $field_obj;
4562
+					break;
4563
+				}
4564
+			}
4565
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4566
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4567
+					get_class($this)));
4568
+			}
4569
+		}
4570
+		return $this->_primary_key_field;
4571
+	}
4572
+
4573
+
4574
+
4575
+	/**
4576
+	 * Returns whether or not not there is a primary key on this model.
4577
+	 * Internally does some caching.
4578
+	 *
4579
+	 * @return boolean
4580
+	 */
4581
+	public function has_primary_key_field()
4582
+	{
4583
+		if ($this->_has_primary_key_field === null) {
4584
+			try {
4585
+				$this->get_primary_key_field();
4586
+				$this->_has_primary_key_field = true;
4587
+			} catch (EE_Error $e) {
4588
+				$this->_has_primary_key_field = false;
4589
+			}
4590
+		}
4591
+		return $this->_has_primary_key_field;
4592
+	}
4593
+
4594
+
4595
+
4596
+	/**
4597
+	 * Finds the first field of type $field_class_name.
4598
+	 *
4599
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4600
+	 *                                 EE_Foreign_Key_Field, etc
4601
+	 * @return EE_Model_Field_Base or null if none is found
4602
+	 */
4603
+	public function get_a_field_of_type($field_class_name)
4604
+	{
4605
+		foreach ($this->field_settings() as $field) {
4606
+			if ($field instanceof $field_class_name) {
4607
+				return $field;
4608
+			}
4609
+		}
4610
+		return null;
4611
+	}
4612
+
4613
+
4614
+
4615
+	/**
4616
+	 * Gets a foreign key field pointing to model.
4617
+	 *
4618
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4619
+	 * @return EE_Foreign_Key_Field_Base
4620
+	 * @throws EE_Error
4621
+	 */
4622
+	public function get_foreign_key_to($model_name)
4623
+	{
4624
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4625
+			foreach ($this->field_settings() as $field) {
4626
+				if (
4627
+					$field instanceof EE_Foreign_Key_Field_Base
4628
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4629
+				) {
4630
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4631
+					break;
4632
+				}
4633
+			}
4634
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4635
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4636
+					'event_espresso'), $model_name, get_class($this)));
4637
+			}
4638
+		}
4639
+		return $this->_cache_foreign_key_to_fields[$model_name];
4640
+	}
4641
+
4642
+
4643
+
4644
+	/**
4645
+	 * Gets the actual table for the table alias
4646
+	 *
4647
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4648
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4649
+	 *                            Either one works
4650
+	 * @return EE_Table_Base
4651
+	 */
4652
+	public function get_table_for_alias($table_alias)
4653
+	{
4654
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4655
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4656
+	}
4657
+
4658
+
4659
+
4660
+	/**
4661
+	 * Returns a flat array of all field son this model, instead of organizing them
4662
+	 * by table_alias as they are in the constructor.
4663
+	 *
4664
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4665
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4666
+	 */
4667
+	public function field_settings($include_db_only_fields = false)
4668
+	{
4669
+		if ($include_db_only_fields) {
4670
+			if ($this->_cached_fields === null) {
4671
+				$this->_cached_fields = array();
4672
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4673
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4674
+						$this->_cached_fields[$field_name] = $field_obj;
4675
+					}
4676
+				}
4677
+			}
4678
+			return $this->_cached_fields;
4679
+		} else {
4680
+			if ($this->_cached_fields_non_db_only === null) {
4681
+				$this->_cached_fields_non_db_only = array();
4682
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4683
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4684
+						/** @var $field_obj EE_Model_Field_Base */
4685
+						if (! $field_obj->is_db_only_field()) {
4686
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4687
+						}
4688
+					}
4689
+				}
4690
+			}
4691
+			return $this->_cached_fields_non_db_only;
4692
+		}
4693
+	}
4694
+
4695
+
4696
+
4697
+	/**
4698
+	 *        cycle though array of attendees and create objects out of each item
4699
+	 *
4700
+	 * @access        private
4701
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4702
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4703
+	 *                           numerically indexed)
4704
+	 * @throws \EE_Error
4705
+	 */
4706
+	protected function _create_objects($rows = array())
4707
+	{
4708
+		$array_of_objects = array();
4709
+		if (empty($rows)) {
4710
+			return array();
4711
+		}
4712
+		$count_if_model_has_no_primary_key = 0;
4713
+		$has_primary_key = $this->has_primary_key_field();
4714
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4715
+		foreach ((array)$rows as $row) {
4716
+			if (empty($row)) {
4717
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4718
+				return array();
4719
+			}
4720
+			//check if we've already set this object in the results array,
4721
+			//in which case there's no need to process it further (again)
4722
+			if ($has_primary_key) {
4723
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4724
+					$row,
4725
+					$primary_key_field->get_qualified_column(),
4726
+					$primary_key_field->get_table_column()
4727
+				);
4728
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4729
+					continue;
4730
+				}
4731
+			}
4732
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4733
+			if (! $classInstance) {
4734
+				throw new EE_Error(
4735
+					sprintf(
4736
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4737
+						$this->get_this_model_name(),
4738
+						http_build_query($row)
4739
+					)
4740
+				);
4741
+			}
4742
+			//set the timezone on the instantiated objects
4743
+			$classInstance->set_timezone($this->_timezone);
4744
+			//make sure if there is any timezone setting present that we set the timezone for the object
4745
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4746
+			$array_of_objects[$key] = $classInstance;
4747
+			//also, for all the relations of type BelongsTo, see if we can cache
4748
+			//those related models
4749
+			//(we could do this for other relations too, but if there are conditions
4750
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4751
+			//so it requires a little more thought than just caching them immediately...)
4752
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4753
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4754
+					//check if this model's INFO is present. If so, cache it on the model
4755
+					$other_model = $relation_obj->get_other_model();
4756
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4757
+					//if we managed to make a model object from the results, cache it on the main model object
4758
+					if ($other_model_obj_maybe) {
4759
+						//set timezone on these other model objects if they are present
4760
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4761
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4762
+					}
4763
+				}
4764
+			}
4765
+		}
4766
+		return $array_of_objects;
4767
+	}
4768
+
4769
+
4770
+
4771
+	/**
4772
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4773
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4774
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4775
+	 * object (as set in the model_field!).
4776
+	 *
4777
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4778
+	 */
4779
+	public function create_default_object()
4780
+	{
4781
+		$this_model_fields_and_values = array();
4782
+		//setup the row using default values;
4783
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4784
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4785
+		}
4786
+		$className = $this->_get_class_name();
4787
+		$classInstance = EE_Registry::instance()
4788
+									->load_class($className, array($this_model_fields_and_values), false, false);
4789
+		return $classInstance;
4790
+	}
4791
+
4792
+
4793
+
4794
+	/**
4795
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4796
+	 *                             or an stdClass where each property is the name of a column,
4797
+	 * @return EE_Base_Class
4798
+	 * @throws \EE_Error
4799
+	 */
4800
+	public function instantiate_class_from_array_or_object($cols_n_values)
4801
+	{
4802
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4803
+			$cols_n_values = get_object_vars($cols_n_values);
4804
+		}
4805
+		$primary_key = null;
4806
+		//make sure the array only has keys that are fields/columns on this model
4807
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4808
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4809
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4810
+		}
4811
+		$className = $this->_get_class_name();
4812
+		//check we actually found results that we can use to build our model object
4813
+		//if not, return null
4814
+		if ($this->has_primary_key_field()) {
4815
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4816
+				return null;
4817
+			}
4818
+		} else if ($this->unique_indexes()) {
4819
+			$first_column = reset($this_model_fields_n_values);
4820
+			if (empty($first_column)) {
4821
+				return null;
4822
+			}
4823
+		}
4824
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4825
+		if ($primary_key) {
4826
+			$classInstance = $this->get_from_entity_map($primary_key);
4827
+			if (! $classInstance) {
4828
+				$classInstance = EE_Registry::instance()
4829
+											->load_class($className,
4830
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4831
+				// add this new object to the entity map
4832
+				$classInstance = $this->add_to_entity_map($classInstance);
4833
+			}
4834
+		} else {
4835
+			$classInstance = EE_Registry::instance()
4836
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4837
+											true, false);
4838
+		}
4839
+		//it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4840
+		$this->set_timezone($classInstance->get_timezone());
4841
+		return $classInstance;
4842
+	}
4843
+
4844
+
4845
+
4846
+	/**
4847
+	 * Gets the model object from the  entity map if it exists
4848
+	 *
4849
+	 * @param int|string $id the ID of the model object
4850
+	 * @return EE_Base_Class
4851
+	 */
4852
+	public function get_from_entity_map($id)
4853
+	{
4854
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4855
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4856
+	}
4857
+
4858
+
4859
+
4860
+	/**
4861
+	 * add_to_entity_map
4862
+	 * Adds the object to the model's entity mappings
4863
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4864
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4865
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4866
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4867
+	 *        then this method should be called immediately after the update query
4868
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4869
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4870
+	 *
4871
+	 * @param    EE_Base_Class $object
4872
+	 * @throws EE_Error
4873
+	 * @return \EE_Base_Class
4874
+	 */
4875
+	public function add_to_entity_map(EE_Base_Class $object)
4876
+	{
4877
+		$className = $this->_get_class_name();
4878
+		if (! $object instanceof $className) {
4879
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4880
+				is_object($object) ? get_class($object) : $object, $className));
4881
+		}
4882
+		/** @var $object EE_Base_Class */
4883
+		if (! $object->ID()) {
4884
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4885
+				"event_espresso"), get_class($this)));
4886
+		}
4887
+		// double check it's not already there
4888
+		$classInstance = $this->get_from_entity_map($object->ID());
4889
+		if ($classInstance) {
4890
+			return $classInstance;
4891
+		} else {
4892
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4893
+			return $object;
4894
+		}
4895
+	}
4896
+
4897
+
4898
+
4899
+	/**
4900
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4901
+	 * if no identifier is provided, then the entire entity map is emptied
4902
+	 *
4903
+	 * @param int|string $id the ID of the model object
4904
+	 * @return boolean
4905
+	 */
4906
+	public function clear_entity_map($id = null)
4907
+	{
4908
+		if (empty($id)) {
4909
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4910
+			return true;
4911
+		}
4912
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4913
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4914
+			return true;
4915
+		}
4916
+		return false;
4917
+	}
4918
+
4919
+
4920
+
4921
+	/**
4922
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4923
+	 * Given an array where keys are column (or column alias) names and values,
4924
+	 * returns an array of their corresponding field names and database values
4925
+	 *
4926
+	 * @param array $cols_n_values
4927
+	 * @return array
4928
+	 */
4929
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4930
+	{
4931
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4932
+	}
4933
+
4934
+
4935
+
4936
+	/**
4937
+	 * _deduce_fields_n_values_from_cols_n_values
4938
+	 * Given an array where keys are column (or column alias) names and values,
4939
+	 * returns an array of their corresponding field names and database values
4940
+	 *
4941
+	 * @param string $cols_n_values
4942
+	 * @return array
4943
+	 */
4944
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4945
+	{
4946
+		$this_model_fields_n_values = array();
4947
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
4948
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4949
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4950
+			//there is a primary key on this table and its not set. Use defaults for all its columns
4951
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
4952
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4953
+					if (! $field_obj->is_db_only_field()) {
4954
+						//prepare field as if its coming from db
4955
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4956
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4957
+					}
4958
+				}
4959
+			} else {
4960
+				//the table's rows existed. Use their values
4961
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4962
+					if (! $field_obj->is_db_only_field()) {
4963
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4964
+							$cols_n_values, $field_obj->get_qualified_column(),
4965
+							$field_obj->get_table_column()
4966
+						);
4967
+					}
4968
+				}
4969
+			}
4970
+		}
4971
+		return $this_model_fields_n_values;
4972
+	}
4973
+
4974
+
4975
+
4976
+	/**
4977
+	 * @param $cols_n_values
4978
+	 * @param $qualified_column
4979
+	 * @param $regular_column
4980
+	 * @return null
4981
+	 */
4982
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4983
+	{
4984
+		$value = null;
4985
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4986
+		//does the field on the model relate to this column retrieved from the db?
4987
+		//or is it a db-only field? (not relating to the model)
4988
+		if (isset($cols_n_values[$qualified_column])) {
4989
+			$value = $cols_n_values[$qualified_column];
4990
+		} elseif (isset($cols_n_values[$regular_column])) {
4991
+			$value = $cols_n_values[$regular_column];
4992
+		}
4993
+		return $value;
4994
+	}
4995
+
4996
+
4997
+
4998
+	/**
4999
+	 * refresh_entity_map_from_db
5000
+	 * Makes sure the model object in the entity map at $id assumes the values
5001
+	 * of the database (opposite of EE_base_Class::save())
5002
+	 *
5003
+	 * @param int|string $id
5004
+	 * @return EE_Base_Class
5005
+	 * @throws \EE_Error
5006
+	 */
5007
+	public function refresh_entity_map_from_db($id)
5008
+	{
5009
+		$obj_in_map = $this->get_from_entity_map($id);
5010
+		if ($obj_in_map) {
5011
+			$wpdb_results = $this->_get_all_wpdb_results(
5012
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5013
+			);
5014
+			if ($wpdb_results && is_array($wpdb_results)) {
5015
+				$one_row = reset($wpdb_results);
5016
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5017
+					$obj_in_map->set_from_db($field_name, $db_value);
5018
+				}
5019
+				//clear the cache of related model objects
5020
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5021
+					$obj_in_map->clear_cache($relation_name, null, true);
5022
+				}
5023
+			}
5024
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5025
+			return $obj_in_map;
5026
+		} else {
5027
+			return $this->get_one_by_ID($id);
5028
+		}
5029
+	}
5030
+
5031
+
5032
+
5033
+	/**
5034
+	 * refresh_entity_map_with
5035
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5036
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5037
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5038
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5039
+	 *
5040
+	 * @param int|string    $id
5041
+	 * @param EE_Base_Class $replacing_model_obj
5042
+	 * @return \EE_Base_Class
5043
+	 * @throws \EE_Error
5044
+	 */
5045
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5046
+	{
5047
+		$obj_in_map = $this->get_from_entity_map($id);
5048
+		if ($obj_in_map) {
5049
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5050
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5051
+					$obj_in_map->set($field_name, $value);
5052
+				}
5053
+				//make the model object in the entity map's cache match the $replacing_model_obj
5054
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5055
+					$obj_in_map->clear_cache($relation_name, null, true);
5056
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5057
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5058
+					}
5059
+				}
5060
+			}
5061
+			return $obj_in_map;
5062
+		} else {
5063
+			$this->add_to_entity_map($replacing_model_obj);
5064
+			return $replacing_model_obj;
5065
+		}
5066
+	}
5067
+
5068
+
5069
+
5070
+	/**
5071
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5072
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5073
+	 * require_once($this->_getClassName().".class.php");
5074
+	 *
5075
+	 * @return string
5076
+	 */
5077
+	private function _get_class_name()
5078
+	{
5079
+		return "EE_" . $this->get_this_model_name();
5080
+	}
5081
+
5082
+
5083
+
5084
+	/**
5085
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5086
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5087
+	 * it would be 'Events'.
5088
+	 *
5089
+	 * @param int $quantity
5090
+	 * @return string
5091
+	 */
5092
+	public function item_name($quantity = 1)
5093
+	{
5094
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5095
+	}
5096
+
5097
+
5098
+
5099
+	/**
5100
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5101
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5102
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5103
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5104
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5105
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5106
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5107
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5108
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5109
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5110
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5111
+	 *        return $previousReturnValue.$returnString;
5112
+	 * }
5113
+	 * require('EEM_Answer.model.php');
5114
+	 * $answer=EEM_Answer::instance();
5115
+	 * echo $answer->my_callback('monkeys',100);
5116
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5117
+	 *
5118
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5119
+	 * @param array  $args       array of original arguments passed to the function
5120
+	 * @throws EE_Error
5121
+	 * @return mixed whatever the plugin which calls add_filter decides
5122
+	 */
5123
+	public function __call($methodName, $args)
5124
+	{
5125
+		$className = get_class($this);
5126
+		$tagName = "FHEE__{$className}__{$methodName}";
5127
+		if (! has_filter($tagName)) {
5128
+			throw new EE_Error(
5129
+				sprintf(
5130
+					__('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5131
+						'event_espresso'),
5132
+					$methodName,
5133
+					$className,
5134
+					$tagName,
5135
+					'<br />'
5136
+				)
5137
+			);
5138
+		}
5139
+		return apply_filters($tagName, null, $this, $args);
5140
+	}
5141
+
5142
+
5143
+
5144
+	/**
5145
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5146
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5147
+	 *
5148
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5149
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5150
+	 *                                                       the object's class name
5151
+	 *                                                       or object's ID
5152
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5153
+	 *                                                       exists in the database. If it does not, we add it
5154
+	 * @throws EE_Error
5155
+	 * @return EE_Base_Class
5156
+	 */
5157
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5158
+	{
5159
+		$className = $this->_get_class_name();
5160
+		if ($base_class_obj_or_id instanceof $className) {
5161
+			$model_object = $base_class_obj_or_id;
5162
+		} else {
5163
+			$primary_key_field = $this->get_primary_key_field();
5164
+			if (
5165
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5166
+				&& (
5167
+					is_int($base_class_obj_or_id)
5168
+					|| is_string($base_class_obj_or_id)
5169
+				)
5170
+			) {
5171
+				// assume it's an ID.
5172
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5173
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5174
+			} else if (
5175
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5176
+				&& is_string($base_class_obj_or_id)
5177
+			) {
5178
+				// assume its a string representation of the object
5179
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5180
+			} else {
5181
+				throw new EE_Error(
5182
+					sprintf(
5183
+						__(
5184
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5185
+							'event_espresso'
5186
+						),
5187
+						$base_class_obj_or_id,
5188
+						$this->_get_class_name(),
5189
+						print_r($base_class_obj_or_id, true)
5190
+					)
5191
+				);
5192
+			}
5193
+		}
5194
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5195
+			$model_object->save();
5196
+		}
5197
+		return $model_object;
5198
+	}
5199
+
5200
+
5201
+
5202
+	/**
5203
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5204
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5205
+	 * returns it ID.
5206
+	 *
5207
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5208
+	 * @return int|string depending on the type of this model object's ID
5209
+	 * @throws EE_Error
5210
+	 */
5211
+	public function ensure_is_ID($base_class_obj_or_id)
5212
+	{
5213
+		$className = $this->_get_class_name();
5214
+		if ($base_class_obj_or_id instanceof $className) {
5215
+			/** @var $base_class_obj_or_id EE_Base_Class */
5216
+			$id = $base_class_obj_or_id->ID();
5217
+		} elseif (is_int($base_class_obj_or_id)) {
5218
+			//assume it's an ID
5219
+			$id = $base_class_obj_or_id;
5220
+		} elseif (is_string($base_class_obj_or_id)) {
5221
+			//assume its a string representation of the object
5222
+			$id = $base_class_obj_or_id;
5223
+		} else {
5224
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5225
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5226
+				print_r($base_class_obj_or_id, true)));
5227
+		}
5228
+		return $id;
5229
+	}
5230
+
5231
+
5232
+
5233
+	/**
5234
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5235
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5236
+	 * been sanitized and converted into the appropriate domain.
5237
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5238
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5239
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5240
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5241
+	 * $EVT = EEM_Event::instance(); $old_setting =
5242
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5243
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5244
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5245
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5246
+	 *
5247
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5248
+	 * @return void
5249
+	 */
5250
+	public function assume_values_already_prepared_by_model_object(
5251
+		$values_already_prepared = self::not_prepared_by_model_object
5252
+	) {
5253
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5254
+	}
5255
+
5256
+
5257
+
5258
+	/**
5259
+	 * Read comments for assume_values_already_prepared_by_model_object()
5260
+	 *
5261
+	 * @return int
5262
+	 */
5263
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5264
+	{
5265
+		return $this->_values_already_prepared_by_model_object;
5266
+	}
5267
+
5268
+
5269
+
5270
+	/**
5271
+	 * Gets all the indexes on this model
5272
+	 *
5273
+	 * @return EE_Index[]
5274
+	 */
5275
+	public function indexes()
5276
+	{
5277
+		return $this->_indexes;
5278
+	}
5279
+
5280
+
5281
+
5282
+	/**
5283
+	 * Gets all the Unique Indexes on this model
5284
+	 *
5285
+	 * @return EE_Unique_Index[]
5286
+	 */
5287
+	public function unique_indexes()
5288
+	{
5289
+		$unique_indexes = array();
5290
+		foreach ($this->_indexes as $name => $index) {
5291
+			if ($index instanceof EE_Unique_Index) {
5292
+				$unique_indexes [$name] = $index;
5293
+			}
5294
+		}
5295
+		return $unique_indexes;
5296
+	}
5297
+
5298
+
5299
+
5300
+	/**
5301
+	 * Gets all the fields which, when combined, make the primary key.
5302
+	 * This is usually just an array with 1 element (the primary key), but in cases
5303
+	 * where there is no primary key, it's a combination of fields as defined
5304
+	 * on a primary index
5305
+	 *
5306
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5307
+	 * @throws \EE_Error
5308
+	 */
5309
+	public function get_combined_primary_key_fields()
5310
+	{
5311
+		foreach ($this->indexes() as $index) {
5312
+			if ($index instanceof EE_Primary_Key_Index) {
5313
+				return $index->fields();
5314
+			}
5315
+		}
5316
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5317
+	}
5318
+
5319
+
5320
+
5321
+	/**
5322
+	 * Used to build a primary key string (when the model has no primary key),
5323
+	 * which can be used a unique string to identify this model object.
5324
+	 *
5325
+	 * @param array $cols_n_values keys are field names, values are their values
5326
+	 * @return string
5327
+	 * @throws \EE_Error
5328
+	 */
5329
+	public function get_index_primary_key_string($cols_n_values)
5330
+	{
5331
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5332
+			$this->get_combined_primary_key_fields());
5333
+		return http_build_query($cols_n_values_for_primary_key_index);
5334
+	}
5335
+
5336
+
5337
+
5338
+	/**
5339
+	 * Gets the field values from the primary key string
5340
+	 *
5341
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5342
+	 * @param string $index_primary_key_string
5343
+	 * @return null|array
5344
+	 * @throws \EE_Error
5345
+	 */
5346
+	public function parse_index_primary_key_string($index_primary_key_string)
5347
+	{
5348
+		$key_fields = $this->get_combined_primary_key_fields();
5349
+		//check all of them are in the $id
5350
+		$key_vals_in_combined_pk = array();
5351
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5352
+		foreach ($key_fields as $key_field_name => $field_obj) {
5353
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5354
+				return null;
5355
+			}
5356
+		}
5357
+		return $key_vals_in_combined_pk;
5358
+	}
5359
+
5360
+
5361
+
5362
+	/**
5363
+	 * verifies that an array of key-value pairs for model fields has a key
5364
+	 * for each field comprising the primary key index
5365
+	 *
5366
+	 * @param array $key_vals
5367
+	 * @return boolean
5368
+	 * @throws \EE_Error
5369
+	 */
5370
+	public function has_all_combined_primary_key_fields($key_vals)
5371
+	{
5372
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5373
+		foreach ($keys_it_should_have as $key) {
5374
+			if (! isset($key_vals[$key])) {
5375
+				return false;
5376
+			}
5377
+		}
5378
+		return true;
5379
+	}
5380
+
5381
+
5382
+
5383
+	/**
5384
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5385
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5386
+	 *
5387
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5388
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5389
+	 * @throws EE_Error
5390
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5391
+	 *                                                              indexed)
5392
+	 */
5393
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5394
+	{
5395
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5396
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5397
+		} elseif (is_array($model_object_or_attributes_array)) {
5398
+			$attributes_array = $model_object_or_attributes_array;
5399
+		} else {
5400
+			throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5401
+				"event_espresso"), $model_object_or_attributes_array));
5402
+		}
5403
+		//even copies obviously won't have the same ID, so remove the primary key
5404
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5405
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5406
+			unset($attributes_array[$this->primary_key_name()]);
5407
+		}
5408
+		if (isset($query_params[0])) {
5409
+			$query_params[0] = array_merge($attributes_array, $query_params);
5410
+		} else {
5411
+			$query_params[0] = $attributes_array;
5412
+		}
5413
+		return $this->get_all($query_params);
5414
+	}
5415
+
5416
+
5417
+
5418
+	/**
5419
+	 * Gets the first copy we find. See get_all_copies for more details
5420
+	 *
5421
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5422
+	 * @param array $query_params
5423
+	 * @return EE_Base_Class
5424
+	 * @throws \EE_Error
5425
+	 */
5426
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5427
+	{
5428
+		if (! is_array($query_params)) {
5429
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5430
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5431
+					gettype($query_params)), '4.6.0');
5432
+			$query_params = array();
5433
+		}
5434
+		$query_params['limit'] = 1;
5435
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5436
+		if (is_array($copies)) {
5437
+			return array_shift($copies);
5438
+		} else {
5439
+			return null;
5440
+		}
5441
+	}
5442
+
5443
+
5444
+
5445
+	/**
5446
+	 * Updates the item with the specified id. Ignores default query parameters because
5447
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5448
+	 *
5449
+	 * @param array      $fields_n_values keys are field names, values are their new values
5450
+	 * @param int|string $id              the value of the primary key to update
5451
+	 * @return int number of rows updated
5452
+	 * @throws \EE_Error
5453
+	 */
5454
+	public function update_by_ID($fields_n_values, $id)
5455
+	{
5456
+		$query_params = array(
5457
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5458
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5459
+		);
5460
+		return $this->update($fields_n_values, $query_params);
5461
+	}
5462
+
5463
+
5464
+
5465
+	/**
5466
+	 * Changes an operator which was supplied to the models into one usable in SQL
5467
+	 *
5468
+	 * @param string $operator_supplied
5469
+	 * @return string an operator which can be used in SQL
5470
+	 * @throws EE_Error
5471
+	 */
5472
+	private function _prepare_operator_for_sql($operator_supplied)
5473
+	{
5474
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5475
+			: null;
5476
+		if ($sql_operator) {
5477
+			return $sql_operator;
5478
+		} else {
5479
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5480
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5481
+		}
5482
+	}
5483
+
5484
+
5485
+
5486
+	/**
5487
+	 * Gets an array where keys are the primary keys and values are their 'names'
5488
+	 * (as determined by the model object's name() function, which is often overridden)
5489
+	 *
5490
+	 * @param array $query_params like get_all's
5491
+	 * @return string[]
5492
+	 * @throws \EE_Error
5493
+	 */
5494
+	public function get_all_names($query_params = array())
5495
+	{
5496
+		$objs = $this->get_all($query_params);
5497
+		$names = array();
5498
+		foreach ($objs as $obj) {
5499
+			$names[$obj->ID()] = $obj->name();
5500
+		}
5501
+		return $names;
5502
+	}
5503
+
5504
+
5505
+
5506
+	/**
5507
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5508
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5509
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5510
+	 * array_keys() on $model_objects.
5511
+	 *
5512
+	 * @param \EE_Base_Class[] $model_objects
5513
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5514
+	 *                                               in the returned array
5515
+	 * @return array
5516
+	 * @throws \EE_Error
5517
+	 */
5518
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5519
+	{
5520
+		if (! $this->has_primary_key_field()) {
5521
+			if (WP_DEBUG) {
5522
+				EE_Error::add_error(
5523
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5524
+					__FILE__,
5525
+					__FUNCTION__,
5526
+					__LINE__
5527
+				);
5528
+			}
5529
+		}
5530
+		$IDs = array();
5531
+		foreach ($model_objects as $model_object) {
5532
+			$id = $model_object->ID();
5533
+			if (! $id) {
5534
+				if ($filter_out_empty_ids) {
5535
+					continue;
5536
+				}
5537
+				if (WP_DEBUG) {
5538
+					EE_Error::add_error(
5539
+						__(
5540
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5541
+							'event_espresso'
5542
+						),
5543
+						__FILE__,
5544
+						__FUNCTION__,
5545
+						__LINE__
5546
+					);
5547
+				}
5548
+			}
5549
+			$IDs[] = $id;
5550
+		}
5551
+		return $IDs;
5552
+	}
5553
+
5554
+
5555
+
5556
+	/**
5557
+	 * Returns the string used in capabilities relating to this model. If there
5558
+	 * are no capabilities that relate to this model returns false
5559
+	 *
5560
+	 * @return string|false
5561
+	 */
5562
+	public function cap_slug()
5563
+	{
5564
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5565
+	}
5566
+
5567
+
5568
+
5569
+	/**
5570
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5571
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5572
+	 * only returns the cap restrictions array in that context (ie, the array
5573
+	 * at that key)
5574
+	 *
5575
+	 * @param string $context
5576
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5577
+	 * @throws \EE_Error
5578
+	 */
5579
+	public function cap_restrictions($context = EEM_Base::caps_read)
5580
+	{
5581
+		EEM_Base::verify_is_valid_cap_context($context);
5582
+		//check if we ought to run the restriction generator first
5583
+		if (
5584
+			isset($this->_cap_restriction_generators[$context])
5585
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5586
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5587
+		) {
5588
+			$this->_cap_restrictions[$context] = array_merge(
5589
+				$this->_cap_restrictions[$context],
5590
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5591
+			);
5592
+		}
5593
+		//and make sure we've finalized the construction of each restriction
5594
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5595
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5596
+				$where_conditions_obj->_finalize_construct($this);
5597
+			}
5598
+		}
5599
+		return $this->_cap_restrictions[$context];
5600
+	}
5601
+
5602
+
5603
+
5604
+	/**
5605
+	 * Indicating whether or not this model thinks its a wp core model
5606
+	 *
5607
+	 * @return boolean
5608
+	 */
5609
+	public function is_wp_core_model()
5610
+	{
5611
+		return $this->_wp_core_model;
5612
+	}
5613
+
5614
+
5615
+
5616
+	/**
5617
+	 * Gets all the caps that are missing which impose a restriction on
5618
+	 * queries made in this context
5619
+	 *
5620
+	 * @param string $context one of EEM_Base::caps_ constants
5621
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5622
+	 * @throws \EE_Error
5623
+	 */
5624
+	public function caps_missing($context = EEM_Base::caps_read)
5625
+	{
5626
+		$missing_caps = array();
5627
+		$cap_restrictions = $this->cap_restrictions($context);
5628
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5629
+			if (! EE_Capabilities::instance()
5630
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5631
+			) {
5632
+				$missing_caps[$cap] = $restriction_if_no_cap;
5633
+			}
5634
+		}
5635
+		return $missing_caps;
5636
+	}
5637
+
5638
+
5639
+
5640
+	/**
5641
+	 * Gets the mapping from capability contexts to action strings used in capability names
5642
+	 *
5643
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5644
+	 * one of 'read', 'edit', or 'delete'
5645
+	 */
5646
+	public function cap_contexts_to_cap_action_map()
5647
+	{
5648
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5649
+			$this);
5650
+	}
5651
+
5652
+
5653
+
5654
+	/**
5655
+	 * Gets the action string for the specified capability context
5656
+	 *
5657
+	 * @param string $context
5658
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5659
+	 * @throws \EE_Error
5660
+	 */
5661
+	public function cap_action_for_context($context)
5662
+	{
5663
+		$mapping = $this->cap_contexts_to_cap_action_map();
5664
+		if (isset($mapping[$context])) {
5665
+			return $mapping[$context];
5666
+		}
5667
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5668
+			return $action;
5669
+		}
5670
+		throw new EE_Error(
5671
+			sprintf(
5672
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5673
+				$context,
5674
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5675
+			)
5676
+		);
5677
+	}
5678
+
5679
+
5680
+
5681
+	/**
5682
+	 * Returns all the capability contexts which are valid when querying models
5683
+	 *
5684
+	 * @return array
5685
+	 */
5686
+	public static function valid_cap_contexts()
5687
+	{
5688
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5689
+			self::caps_read,
5690
+			self::caps_read_admin,
5691
+			self::caps_edit,
5692
+			self::caps_delete,
5693
+		));
5694
+	}
5695
+
5696
+
5697
+
5698
+	/**
5699
+	 * Returns all valid options for 'default_where_conditions'
5700
+	 *
5701
+	 * @return array
5702
+	 */
5703
+	public static function valid_default_where_conditions()
5704
+	{
5705
+		return array(
5706
+			EEM_Base::default_where_conditions_all,
5707
+			EEM_Base::default_where_conditions_this_only,
5708
+			EEM_Base::default_where_conditions_others_only,
5709
+			EEM_Base::default_where_conditions_minimum_all,
5710
+			EEM_Base::default_where_conditions_minimum_others,
5711
+			EEM_Base::default_where_conditions_none
5712
+		);
5713
+	}
5714
+
5715
+	// public static function default_where_conditions_full
5716
+	/**
5717
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5718
+	 *
5719
+	 * @param string $context
5720
+	 * @return bool
5721
+	 * @throws \EE_Error
5722
+	 */
5723
+	static public function verify_is_valid_cap_context($context)
5724
+	{
5725
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5726
+		if (in_array($context, $valid_cap_contexts)) {
5727
+			return true;
5728
+		} else {
5729
+			throw new EE_Error(
5730
+				sprintf(
5731
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5732
+						'event_espresso'),
5733
+					$context,
5734
+					'EEM_Base',
5735
+					implode(',', $valid_cap_contexts)
5736
+				)
5737
+			);
5738
+		}
5739
+	}
5740
+
5741
+
5742
+
5743
+	/**
5744
+	 * Clears all the models field caches. This is only useful when a sub-class
5745
+	 * might have added a field or something and these caches might be invalidated
5746
+	 */
5747
+	protected function _invalidate_field_caches()
5748
+	{
5749
+		$this->_cache_foreign_key_to_fields = array();
5750
+		$this->_cached_fields = null;
5751
+		$this->_cached_fields_non_db_only = null;
5752
+	}
5753 5753
 
5754 5754
 
5755 5755
 
Please login to merge, or discard this patch.
Spacing   +152 added lines, -152 removed lines patch added patch discarded remove patch
@@ -516,8 +516,8 @@  discard block
 block discarded – undo
516 516
     protected function __construct($timezone = null)
517 517
     {
518 518
         // check that the model has not been loaded too soon
519
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
520
-            throw new EE_Error (
519
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
520
+            throw new EE_Error(
521 521
                 sprintf(
522 522
                     __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
523 523
                         'event_espresso'),
@@ -537,7 +537,7 @@  discard block
 block discarded – undo
537 537
          *
538 538
          * @var EE_Table_Base[] $_tables
539 539
          */
540
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
541 541
         foreach ($this->_tables as $table_alias => $table_obj) {
542 542
             /** @var $table_obj EE_Table_Base */
543 543
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -552,10 +552,10 @@  discard block
 block discarded – undo
552 552
          *
553 553
          * @param EE_Model_Field_Base[] $_fields
554 554
          */
555
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
556 556
         $this->_invalidate_field_caches();
557 557
         foreach ($this->_fields as $table_alias => $fields_for_table) {
558
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
559 559
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
560 560
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
561 561
             }
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
          *
584 584
          * @param EE_Model_Relation_Base[] $_model_relations
585 585
          */
586
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
587 587
             $this->_model_relations);
588 588
         foreach ($this->_model_relations as $model_name => $relation_obj) {
589 589
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -595,12 +595,12 @@  discard block
 block discarded – undo
595 595
         }
596 596
         $this->set_timezone($timezone);
597 597
         //finalize default where condition strategy, or set default
598
-        if (! $this->_default_where_conditions_strategy) {
598
+        if ( ! $this->_default_where_conditions_strategy) {
599 599
             //nothing was set during child constructor, so set default
600 600
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
601 601
         }
602 602
         $this->_default_where_conditions_strategy->_finalize_construct($this);
603
-        if (! $this->_minimum_where_conditions_strategy) {
603
+        if ( ! $this->_minimum_where_conditions_strategy) {
604 604
             //nothing was set during child constructor, so set default
605 605
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
606 606
         }
@@ -613,7 +613,7 @@  discard block
 block discarded – undo
613 613
         //initialize the standard cap restriction generators if none were specified by the child constructor
614 614
         if ($this->_cap_restriction_generators !== false) {
615 615
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
616
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
617 617
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
618 618
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
619 619
                         new EE_Restriction_Generator_Protected(),
@@ -626,10 +626,10 @@  discard block
 block discarded – undo
626 626
         //if there are cap restriction generators, use them to make the default cap restrictions
627 627
         if ($this->_cap_restriction_generators !== false) {
628 628
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
629
-                if (! $generator_object) {
629
+                if ( ! $generator_object) {
630 630
                     continue;
631 631
                 }
632
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
633 633
                     throw new EE_Error(
634 634
                         sprintf(
635 635
                             __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
@@ -640,12 +640,12 @@  discard block
 block discarded – undo
640 640
                     );
641 641
                 }
642 642
                 $action = $this->cap_action_for_context($context);
643
-                if (! $generator_object->construction_finalized()) {
643
+                if ( ! $generator_object->construction_finalized()) {
644 644
                     $generator_object->_construct_finalize($this, $action);
645 645
                 }
646 646
             }
647 647
         }
648
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
+        do_action('AHEE__'.get_class($this).'__construct__end');
649 649
     }
650 650
 
651 651
 
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
      */
681 681
     public static function set_model_query_blog_id($blog_id = 0)
682 682
     {
683
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
684 684
     }
685 685
 
686 686
 
@@ -710,7 +710,7 @@  discard block
 block discarded – undo
710 710
     public static function instance($timezone = null)
711 711
     {
712 712
         // check if instance of Espresso_model already exists
713
-        if (! static::$_instance instanceof static) {
713
+        if ( ! static::$_instance instanceof static) {
714 714
             // instantiate Espresso_model
715 715
             static::$_instance = new static($timezone);
716 716
         }
@@ -741,7 +741,7 @@  discard block
 block discarded – undo
741 741
             foreach ($r->getDefaultProperties() as $property => $value) {
742 742
                 //don't set instance to null like it was originally,
743 743
                 //but it's static anyways, and we're ignoring static properties (for now at least)
744
-                if (! isset($static_properties[$property])) {
744
+                if ( ! isset($static_properties[$property])) {
745 745
                     static::$_instance->{$property} = $value;
746 746
                 }
747 747
             }
@@ -764,7 +764,7 @@  discard block
 block discarded – undo
764 764
      */
765 765
     public function status_array($translated = false)
766 766
     {
767
-        if (! array_key_exists('Status', $this->_model_relations)) {
767
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
768 768
             return array();
769 769
         }
770 770
         $model_name = $this->get_this_model_name();
@@ -967,17 +967,17 @@  discard block
 block discarded – undo
967 967
     public function wp_user_field_name()
968 968
     {
969 969
         try {
970
-            if (! empty($this->_model_chain_to_wp_user)) {
970
+            if ( ! empty($this->_model_chain_to_wp_user)) {
971 971
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
972 972
                 $last_model_name = end($models_to_follow_to_wp_users);
973 973
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
974
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
975 975
             } else {
976 976
                 $model_with_fk_to_wp_users = $this;
977 977
                 $model_chain_to_wp_user = '';
978 978
             }
979 979
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
980
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
980
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
981 981
         } catch (EE_Error $e) {
982 982
             return false;
983 983
         }
@@ -1049,12 +1049,12 @@  discard block
 block discarded – undo
1049 1049
         // remember the custom selections, if any, and type cast as array
1050 1050
         // (unless $columns_to_select is an object, then just set as an empty array)
1051 1051
         // Note: (array) 'some string' === array( 'some string' )
1052
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1053 1053
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1054 1054
         $select_expressions = $columns_to_select !== null
1055 1055
             ? $this->_construct_select_from_input($columns_to_select)
1056 1056
             : $this->_construct_default_select_sql($model_query_info);
1057
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1058 1058
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1059 1059
     }
1060 1060
 
@@ -1099,7 +1099,7 @@  discard block
 block discarded – undo
1099 1099
         if (is_array($columns_to_select)) {
1100 1100
             $select_sql_array = array();
1101 1101
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1102
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1103 1103
                     throw new EE_Error(
1104 1104
                         sprintf(
1105 1105
                             __(
@@ -1111,7 +1111,7 @@  discard block
 block discarded – undo
1111 1111
                         )
1112 1112
                     );
1113 1113
                 }
1114
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1115 1115
                     throw new EE_Error(
1116 1116
                         sprintf(
1117 1117
                             __(
@@ -1183,7 +1183,7 @@  discard block
 block discarded – undo
1183 1183
      */
1184 1184
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1185 1185
     {
1186
-        if (! isset($query_params[0])) {
1186
+        if ( ! isset($query_params[0])) {
1187 1187
             $query_params[0] = array();
1188 1188
         }
1189 1189
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1208,7 +1208,7 @@  discard block
 block discarded – undo
1208 1208
      */
1209 1209
     public function get_one($query_params = array())
1210 1210
     {
1211
-        if (! is_array($query_params)) {
1211
+        if ( ! is_array($query_params)) {
1212 1212
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1213 1213
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1214 1214
                     gettype($query_params)), '4.6.0');
@@ -1376,7 +1376,7 @@  discard block
 block discarded – undo
1376 1376
                 return array();
1377 1377
             }
1378 1378
         }
1379
-        if (! is_array($query_params)) {
1379
+        if ( ! is_array($query_params)) {
1380 1380
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1381 1381
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1382 1382
                     gettype($query_params)), '4.6.0');
@@ -1386,7 +1386,7 @@  discard block
 block discarded – undo
1386 1386
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1387 1387
         $query_params['limit'] = $limit;
1388 1388
         //set direction
1389
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1390 1390
         $query_params['order_by'] = $operand === '>'
1391 1391
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1392 1392
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1465,7 +1465,7 @@  discard block
 block discarded – undo
1465 1465
     {
1466 1466
         $field_settings = $this->field_settings_for($field_name);
1467 1467
         //if not a valid EE_Datetime_Field then throw error
1468
-        if (! $field_settings instanceof EE_Datetime_Field) {
1468
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1469 1469
             throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1470 1470
                 'event_espresso'), $field_name));
1471 1471
         }
@@ -1610,7 +1610,7 @@  discard block
 block discarded – undo
1610 1610
      */
1611 1611
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1612 1612
     {
1613
-        if (! is_array($query_params)) {
1613
+        if ( ! is_array($query_params)) {
1614 1614
             EE_Error::doing_it_wrong('EEM_Base::update',
1615 1615
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1616 1616
                     gettype($query_params)), '4.6.0');
@@ -1632,7 +1632,7 @@  discard block
 block discarded – undo
1632 1632
          * @param EEM_Base $model           the model being queried
1633 1633
          * @param array    $query_params    see EEM_Base::get_all()
1634 1634
          */
1635
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1635
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1636 1636
             $query_params);
1637 1637
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1638 1638
         //to do that, for each table, verify that it's PK isn't null.
@@ -1646,7 +1646,7 @@  discard block
 block discarded – undo
1646 1646
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1647 1647
         foreach ($wpdb_select_results as $wpdb_result) {
1648 1648
             // type cast stdClass as array
1649
-            $wpdb_result = (array)$wpdb_result;
1649
+            $wpdb_result = (array) $wpdb_result;
1650 1650
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1651 1651
             if ($this->has_primary_key_field()) {
1652 1652
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1663,13 +1663,13 @@  discard block
 block discarded – undo
1663 1663
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1664 1664
                     //if there is no private key for this table on the results, it means there's no entry
1665 1665
                     //in this table, right? so insert a row in the current table, using any fields available
1666
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1666
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1667 1667
                            && $wpdb_result[$this_table_pk_column])
1668 1668
                     ) {
1669 1669
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1670 1670
                             $main_table_pk_value);
1671 1671
                         //if we died here, report the error
1672
-                        if (! $success) {
1672
+                        if ( ! $success) {
1673 1673
                             return false;
1674 1674
                         }
1675 1675
                     }
@@ -1700,7 +1700,7 @@  discard block
 block discarded – undo
1700 1700
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1701 1701
                 }
1702 1702
             }
1703
-            if (! $model_objs_affected_ids) {
1703
+            if ( ! $model_objs_affected_ids) {
1704 1704
                 //wait wait wait- if nothing was affected let's stop here
1705 1705
                 return 0;
1706 1706
             }
@@ -1727,7 +1727,7 @@  discard block
 block discarded – undo
1727 1727
                . $model_query_info->get_full_join_sql()
1728 1728
                . " SET "
1729 1729
                . $this->_construct_update_sql($fields_n_values)
1730
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1730
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1731 1731
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1732 1732
         /**
1733 1733
          * Action called after a model update call has been made.
@@ -1738,7 +1738,7 @@  discard block
 block discarded – undo
1738 1738
          * @param int      $rows_affected
1739 1739
          */
1740 1740
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1741
-        return $rows_affected;//how many supposedly got updated
1741
+        return $rows_affected; //how many supposedly got updated
1742 1742
     }
1743 1743
 
1744 1744
 
@@ -1766,7 +1766,7 @@  discard block
 block discarded – undo
1766 1766
         }
1767 1767
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1768 1768
         $select_expressions = $field->get_qualified_column();
1769
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1769
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1770 1770
         return $this->_do_wpdb_query('get_col', array($SQL));
1771 1771
     }
1772 1772
 
@@ -1784,7 +1784,7 @@  discard block
 block discarded – undo
1784 1784
     {
1785 1785
         $query_params['limit'] = 1;
1786 1786
         $col = $this->get_col($query_params, $field_to_select);
1787
-        if (! empty($col)) {
1787
+        if ( ! empty($col)) {
1788 1788
             return reset($col);
1789 1789
         } else {
1790 1790
             return null;
@@ -1816,7 +1816,7 @@  discard block
 block discarded – undo
1816 1816
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1817 1817
             $value_sql = $prepared_value === null ? 'NULL'
1818 1818
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1819
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1819
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1820 1820
         }
1821 1821
         return implode(",", $cols_n_values);
1822 1822
     }
@@ -1948,7 +1948,7 @@  discard block
 block discarded – undo
1948 1948
          * @param int      $rows_deleted
1949 1949
          */
1950 1950
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1951
-        return $rows_deleted;//how many supposedly got deleted
1951
+        return $rows_deleted; //how many supposedly got deleted
1952 1952
     }
1953 1953
 
1954 1954
 
@@ -2041,7 +2041,7 @@  discard block
 block discarded – undo
2041 2041
                     $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2042 2042
                 }
2043 2043
                 //other tables
2044
-                if (! empty($other_tables)) {
2044
+                if ( ! empty($other_tables)) {
2045 2045
                     foreach ($other_tables as $ot) {
2046 2046
                         //first check if we've got the foreign key column here.
2047 2047
                         if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
@@ -2064,7 +2064,7 @@  discard block
 block discarded – undo
2064 2064
             foreach ($deletes as $column => $values) {
2065 2065
                 //make sure we have unique $values;
2066 2066
                 $values = array_unique($values);
2067
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2067
+                $query[] = $column.' IN('.implode(",", $values).')';
2068 2068
             }
2069 2069
             return ! empty($query) ? implode(' AND ', $query) : '';
2070 2070
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2080,7 +2080,7 @@  discard block
 block discarded – undo
2080 2080
                                                            . $delete_object[$cpk_field->get_qualified_column()];
2081 2081
                     }
2082 2082
                 }
2083
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2083
+                $ways_to_identify_a_row[] = "(".implode(" AND ", $values_for_each_cpk_for_a_row).")";
2084 2084
             }
2085 2085
             return implode(" OR ", $ways_to_identify_a_row);
2086 2086
         } else {
@@ -2129,9 +2129,9 @@  discard block
 block discarded – undo
2129 2129
                 $column_to_count = '*';
2130 2130
             }
2131 2131
         }
2132
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2133
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2134
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2132
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2133
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2134
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2135 2135
     }
2136 2136
 
2137 2137
 
@@ -2153,13 +2153,13 @@  discard block
 block discarded – undo
2153 2153
             $field_obj = $this->get_primary_key_field();
2154 2154
         }
2155 2155
         $column_to_count = $field_obj->get_qualified_column();
2156
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2156
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2157 2157
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2158 2158
         $data_type = $field_obj->get_wpdb_data_type();
2159 2159
         if ($data_type === '%d' || $data_type === '%s') {
2160
-            return (float)$return_value;
2160
+            return (float) $return_value;
2161 2161
         } else {//must be %f
2162
-            return (float)$return_value;
2162
+            return (float) $return_value;
2163 2163
         }
2164 2164
     }
2165 2165
 
@@ -2180,13 +2180,13 @@  discard block
 block discarded – undo
2180 2180
         //if we're in maintenance mode level 2, DON'T run any queries
2181 2181
         //because level 2 indicates the database needs updating and
2182 2182
         //is probably out of sync with the code
2183
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2183
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2184 2184
             throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2185 2185
                 "event_espresso")));
2186 2186
         }
2187 2187
         /** @type WPDB $wpdb */
2188 2188
         global $wpdb;
2189
-        if (! method_exists($wpdb, $wpdb_method)) {
2189
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2190 2190
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2191 2191
                 'event_espresso'), $wpdb_method));
2192 2192
         }
@@ -2198,7 +2198,7 @@  discard block
 block discarded – undo
2198 2198
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2199 2199
         if (WP_DEBUG) {
2200 2200
             $wpdb->show_errors($old_show_errors_value);
2201
-            if (! empty($wpdb->last_error)) {
2201
+            if ( ! empty($wpdb->last_error)) {
2202 2202
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2203 2203
             } elseif ($result === false) {
2204 2204
                 throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
@@ -2258,7 +2258,7 @@  discard block
 block discarded – undo
2258 2258
                     return $result;
2259 2259
                     break;
2260 2260
             }
2261
-            if (! empty($error_message)) {
2261
+            if ( ! empty($error_message)) {
2262 2262
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2263 2263
                 trigger_error($error_message);
2264 2264
             }
@@ -2334,11 +2334,11 @@  discard block
 block discarded – undo
2334 2334
      */
2335 2335
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2336 2336
     {
2337
-        return " FROM " . $model_query_info->get_full_join_sql() .
2338
-               $model_query_info->get_where_sql() .
2339
-               $model_query_info->get_group_by_sql() .
2340
-               $model_query_info->get_having_sql() .
2341
-               $model_query_info->get_order_by_sql() .
2337
+        return " FROM ".$model_query_info->get_full_join_sql().
2338
+               $model_query_info->get_where_sql().
2339
+               $model_query_info->get_group_by_sql().
2340
+               $model_query_info->get_having_sql().
2341
+               $model_query_info->get_order_by_sql().
2342 2342
                $model_query_info->get_limit_sql();
2343 2343
     }
2344 2344
 
@@ -2534,12 +2534,12 @@  discard block
 block discarded – undo
2534 2534
         $related_model = $this->get_related_model_obj($model_name);
2535 2535
         //we're just going to use the query params on the related model's normal get_all query,
2536 2536
         //except add a condition to say to match the current mod
2537
-        if (! isset($query_params['default_where_conditions'])) {
2537
+        if ( ! isset($query_params['default_where_conditions'])) {
2538 2538
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2539 2539
         }
2540 2540
         $this_model_name = $this->get_this_model_name();
2541 2541
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2542
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2542
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2543 2543
         return $related_model->count($query_params, $field_to_count, $distinct);
2544 2544
     }
2545 2545
 
@@ -2559,7 +2559,7 @@  discard block
 block discarded – undo
2559 2559
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2560 2560
     {
2561 2561
         $related_model = $this->get_related_model_obj($model_name);
2562
-        if (! is_array($query_params)) {
2562
+        if ( ! is_array($query_params)) {
2563 2563
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2564 2564
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2565 2565
                     gettype($query_params)), '4.6.0');
@@ -2567,12 +2567,12 @@  discard block
 block discarded – undo
2567 2567
         }
2568 2568
         //we're just going to use the query params on the related model's normal get_all query,
2569 2569
         //except add a condition to say to match the current mod
2570
-        if (! isset($query_params['default_where_conditions'])) {
2570
+        if ( ! isset($query_params['default_where_conditions'])) {
2571 2571
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2572 2572
         }
2573 2573
         $this_model_name = $this->get_this_model_name();
2574 2574
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2575
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2575
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2576 2576
         return $related_model->sum($query_params, $field_to_sum);
2577 2577
     }
2578 2578
 
@@ -2626,7 +2626,7 @@  discard block
 block discarded – undo
2626 2626
                 $field_with_model_name = $field;
2627 2627
             }
2628 2628
         }
2629
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2629
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2630 2630
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2631 2631
                 $this->get_this_model_name()));
2632 2632
         }
@@ -2659,7 +2659,7 @@  discard block
 block discarded – undo
2659 2659
          * @param array    $fields_n_values keys are the fields and values are their new values
2660 2660
          * @param EEM_Base $model           the model used
2661 2661
          */
2662
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2662
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2663 2663
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2664 2664
             $main_table = $this->_get_main_table();
2665 2665
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2767,7 +2767,7 @@  discard block
 block discarded – undo
2767 2767
         }
2768 2768
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2769 2769
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2770
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2770
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2771 2771
         }
2772 2772
         //if there is nothing to base this search on, then we shouldn't find anything
2773 2773
         if (empty($query_params)) {
@@ -2854,7 +2854,7 @@  discard block
 block discarded – undo
2854 2854
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2855 2855
             //so add the fk to the main table as a column
2856 2856
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2857
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2857
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2858 2858
         }
2859 2859
         //insert the new entry
2860 2860
         $result = $this->_do_wpdb_query('insert',
@@ -2893,7 +2893,7 @@  discard block
 block discarded – undo
2893 2893
     protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2894 2894
     {
2895 2895
         //if this field doesn't allow nullable, don't allow it
2896
-        if (! $field_obj->is_nullable()
2896
+        if ( ! $field_obj->is_nullable()
2897 2897
             && (
2898 2898
                 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2899 2899
         ) {
@@ -3056,7 +3056,7 @@  discard block
 block discarded – undo
3056 3056
                     $query_info_carrier,
3057 3057
                     'group_by'
3058 3058
                 );
3059
-            } elseif (! empty ($query_params['group_by'])) {
3059
+            } elseif ( ! empty ($query_params['group_by'])) {
3060 3060
                 $this->_extract_related_model_info_from_query_param(
3061 3061
                     $query_params['group_by'],
3062 3062
                     $query_info_carrier,
@@ -3078,7 +3078,7 @@  discard block
 block discarded – undo
3078 3078
                     $query_info_carrier,
3079 3079
                     'order_by'
3080 3080
                 );
3081
-            } elseif (! empty($query_params['order_by'])) {
3081
+            } elseif ( ! empty($query_params['order_by'])) {
3082 3082
                 $this->_extract_related_model_info_from_query_param(
3083 3083
                     $query_params['order_by'],
3084 3084
                     $query_info_carrier,
@@ -3113,8 +3113,8 @@  discard block
 block discarded – undo
3113 3113
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3114 3114
         $query_param_type
3115 3115
     ) {
3116
-        if (! empty($sub_query_params)) {
3117
-            $sub_query_params = (array)$sub_query_params;
3116
+        if ( ! empty($sub_query_params)) {
3117
+            $sub_query_params = (array) $sub_query_params;
3118 3118
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3119 3119
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3120 3120
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3125,7 +3125,7 @@  discard block
 block discarded – undo
3125 3125
                 //of array('Registration.TXN_ID'=>23)
3126 3126
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3127 3127
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3128
-                    if (! is_array($possibly_array_of_params)) {
3128
+                    if ( ! is_array($possibly_array_of_params)) {
3129 3129
                         throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3130 3130
                             "event_espresso"),
3131 3131
                             $param, $possibly_array_of_params));
@@ -3141,7 +3141,7 @@  discard block
 block discarded – undo
3141 3141
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3142 3142
                     //indicating that $possible_array_of_params[1] is actually a field name,
3143 3143
                     //from which we should extract query parameters!
3144
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3144
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3145 3145
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3146 3146
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3147 3147
                     }
@@ -3171,8 +3171,8 @@  discard block
 block discarded – undo
3171 3171
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3172 3172
         $query_param_type
3173 3173
     ) {
3174
-        if (! empty($sub_query_params)) {
3175
-            if (! is_array($sub_query_params)) {
3174
+        if ( ! empty($sub_query_params)) {
3175
+            if ( ! is_array($sub_query_params)) {
3176 3176
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3177 3177
                     $sub_query_params));
3178 3178
             }
@@ -3201,7 +3201,7 @@  discard block
 block discarded – undo
3201 3201
      */
3202 3202
     public function _create_model_query_info_carrier($query_params)
3203 3203
     {
3204
-        if (! is_array($query_params)) {
3204
+        if ( ! is_array($query_params)) {
3205 3205
             EE_Error::doing_it_wrong(
3206 3206
                 'EEM_Base::_create_model_query_info_carrier',
3207 3207
                 sprintf(
@@ -3277,7 +3277,7 @@  discard block
 block discarded – undo
3277 3277
         //set limit
3278 3278
         if (array_key_exists('limit', $query_params)) {
3279 3279
             if (is_array($query_params['limit'])) {
3280
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3280
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3281 3281
                     $e = sprintf(
3282 3282
                         __(
3283 3283
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3285,12 +3285,12 @@  discard block
 block discarded – undo
3285 3285
                         ),
3286 3286
                         http_build_query($query_params['limit'])
3287 3287
                     );
3288
-                    throw new EE_Error($e . "|" . $e);
3288
+                    throw new EE_Error($e."|".$e);
3289 3289
                 }
3290 3290
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3291
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3292
-            } elseif (! empty ($query_params['limit'])) {
3293
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3291
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3292
+            } elseif ( ! empty ($query_params['limit'])) {
3293
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3294 3294
             }
3295 3295
         }
3296 3296
         //set order by
@@ -3322,10 +3322,10 @@  discard block
 block discarded – undo
3322 3322
                 $order_array = array();
3323 3323
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3324 3324
                     $order = $this->_extract_order($order);
3325
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3325
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3326 3326
                 }
3327
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3328
-            } elseif (! empty ($query_params['order_by'])) {
3327
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3328
+            } elseif ( ! empty ($query_params['order_by'])) {
3329 3329
                 $this->_extract_related_model_info_from_query_param(
3330 3330
                     $query_params['order_by'],
3331 3331
                     $query_object,
@@ -3336,18 +3336,18 @@  discard block
 block discarded – undo
3336 3336
                     ? $this->_extract_order($query_params['order'])
3337 3337
                     : 'DESC';
3338 3338
                 $query_object->set_order_by_sql(
3339
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3339
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3340 3340
                 );
3341 3341
             }
3342 3342
         }
3343 3343
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3344
-        if (! array_key_exists('order_by', $query_params)
3344
+        if ( ! array_key_exists('order_by', $query_params)
3345 3345
             && array_key_exists('order', $query_params)
3346 3346
             && ! empty($query_params['order'])
3347 3347
         ) {
3348 3348
             $pk_field = $this->get_primary_key_field();
3349 3349
             $order = $this->_extract_order($query_params['order']);
3350
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3350
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3351 3351
         }
3352 3352
         //set group by
3353 3353
         if (array_key_exists('group_by', $query_params)) {
@@ -3357,10 +3357,10 @@  discard block
 block discarded – undo
3357 3357
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3358 3358
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3359 3359
                 }
3360
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3361
-            } elseif (! empty ($query_params['group_by'])) {
3360
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3361
+            } elseif ( ! empty ($query_params['group_by'])) {
3362 3362
                 $query_object->set_group_by_sql(
3363
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3363
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3364 3364
                 );
3365 3365
             }
3366 3366
         }
@@ -3370,7 +3370,7 @@  discard block
 block discarded – undo
3370 3370
         }
3371 3371
         //now, just verify they didn't pass anything wack
3372 3372
         foreach ($query_params as $query_key => $query_value) {
3373
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3373
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3374 3374
                 throw new EE_Error(
3375 3375
                     sprintf(
3376 3376
                         __(
@@ -3464,22 +3464,22 @@  discard block
 block discarded – undo
3464 3464
         $where_query_params = array()
3465 3465
     ) {
3466 3466
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3467
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3467
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3468 3468
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3469 3469
                 "event_espresso"), $use_default_where_conditions,
3470 3470
                 implode(", ", $allowed_used_default_where_conditions_values)));
3471 3471
         }
3472 3472
         $universal_query_params = array();
3473
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3473
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3474 3474
             $universal_query_params = $this->_get_default_where_conditions();
3475
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3475
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3476 3476
             $universal_query_params = $this->_get_minimum_where_conditions();
3477 3477
         }
3478 3478
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3479 3479
             $related_model = $this->get_related_model_obj($model_name);
3480
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3480
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3481 3481
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3482
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3482
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3483 3483
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3484 3484
             } else {
3485 3485
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3512,7 +3512,7 @@  discard block
 block discarded – undo
3512 3512
      * @param bool $for_this_model false means this is for OTHER related models
3513 3513
      * @return bool
3514 3514
      */
3515
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3515
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3516 3516
     {
3517 3517
         return (
3518 3518
                    $for_this_model
@@ -3591,7 +3591,7 @@  discard block
 block discarded – undo
3591 3591
     ) {
3592 3592
         $null_friendly_where_conditions = array();
3593 3593
         $none_overridden = true;
3594
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3594
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3595 3595
         foreach ($default_where_conditions as $key => $val) {
3596 3596
             if (isset($provided_where_conditions[$key])) {
3597 3597
                 $none_overridden = false;
@@ -3709,7 +3709,7 @@  discard block
 block discarded – undo
3709 3709
             foreach ($tables as $table_obj) {
3710 3710
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3711 3711
                                        . $table_obj->get_fully_qualified_pk_column();
3712
-                if (! in_array($qualified_pk_column, $selects)) {
3712
+                if ( ! in_array($qualified_pk_column, $selects)) {
3713 3713
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3714 3714
                 }
3715 3715
             }
@@ -3795,9 +3795,9 @@  discard block
 block discarded – undo
3795 3795
         //and
3796 3796
         //check if it's a field on a related model
3797 3797
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3798
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3798
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3799 3799
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3800
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3800
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3801 3801
                 if ($query_param === '') {
3802 3802
                     //nothing left to $query_param
3803 3803
                     //we should actually end in a field name, not a model like this!
@@ -3883,7 +3883,7 @@  discard block
 block discarded – undo
3883 3883
     {
3884 3884
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3885 3885
         if ($SQL) {
3886
-            return " WHERE " . $SQL;
3886
+            return " WHERE ".$SQL;
3887 3887
         } else {
3888 3888
             return '';
3889 3889
         }
@@ -3903,7 +3903,7 @@  discard block
 block discarded – undo
3903 3903
     {
3904 3904
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3905 3905
         if ($SQL) {
3906
-            return " HAVING " . $SQL;
3906
+            return " HAVING ".$SQL;
3907 3907
         } else {
3908 3908
             return '';
3909 3909
         }
@@ -3923,11 +3923,11 @@  discard block
 block discarded – undo
3923 3923
      */
3924 3924
     protected function _get_field_on_model($field_name, $model_name)
3925 3925
     {
3926
-        $model_class = 'EEM_' . $model_name;
3927
-        $model_filepath = $model_class . ".model.php";
3926
+        $model_class = 'EEM_'.$model_name;
3927
+        $model_filepath = $model_class.".model.php";
3928 3928
         if (is_readable($model_filepath)) {
3929 3929
             require_once($model_filepath);
3930
-            $model_instance = call_user_func($model_name . "::instance");
3930
+            $model_instance = call_user_func($model_name."::instance");
3931 3931
             /* @var $model_instance EEM_Base */
3932 3932
             return $model_instance->field_settings_for($field_name);
3933 3933
         } else {
@@ -3951,7 +3951,7 @@  discard block
 block discarded – undo
3951 3951
     {
3952 3952
         $where_clauses = array();
3953 3953
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3954
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3954
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
3955 3955
             if (in_array($query_param, $this->_logic_query_param_keys)) {
3956 3956
                 switch ($query_param) {
3957 3957
                     case 'not':
@@ -3979,7 +3979,7 @@  discard block
 block discarded – undo
3979 3979
             } else {
3980 3980
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
3981 3981
                 //if it's not a normal field, maybe it's a custom selection?
3982
-                if (! $field_obj) {
3982
+                if ( ! $field_obj) {
3983 3983
                     if (isset($this->_custom_selections[$query_param][1])) {
3984 3984
                         $field_obj = $this->_custom_selections[$query_param][1];
3985 3985
                     } else {
@@ -3988,7 +3988,7 @@  discard block
 block discarded – undo
3988 3988
                     }
3989 3989
                 }
3990 3990
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3991
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3991
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
3992 3992
             }
3993 3993
         }
3994 3994
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4009,7 +4009,7 @@  discard block
 block discarded – undo
4009 4009
         if ($field) {
4010 4010
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4011 4011
                 $query_param);
4012
-            return $table_alias_prefix . $field->get_qualified_column();
4012
+            return $table_alias_prefix.$field->get_qualified_column();
4013 4013
         } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4014 4014
             //maybe it's custom selection item?
4015 4015
             //if so, just use it as the "column name"
@@ -4056,7 +4056,7 @@  discard block
 block discarded – undo
4056 4056
     {
4057 4057
         if (is_array($op_and_value)) {
4058 4058
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4059
-            if (! $operator) {
4059
+            if ( ! $operator) {
4060 4060
                 $php_array_like_string = array();
4061 4061
                 foreach ($op_and_value as $key => $value) {
4062 4062
                     $php_array_like_string[] = "$key=>$value";
@@ -4078,13 +4078,13 @@  discard block
 block discarded – undo
4078 4078
         }
4079 4079
         //check to see if the value is actually another field
4080 4080
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4081
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4081
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4082 4082
         } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4083 4083
             //in this case, the value should be an array, or at least a comma-separated list
4084 4084
             //it will need to handle a little differently
4085 4085
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4086 4086
             //note: $cleaned_value has already been run through $wpdb->prepare()
4087
-            return $operator . SP . $cleaned_value;
4087
+            return $operator.SP.$cleaned_value;
4088 4088
         } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4089 4089
             //the value should be an array with count of two.
4090 4090
             if (count($value) !== 2) {
@@ -4099,7 +4099,7 @@  discard block
 block discarded – undo
4099 4099
                 );
4100 4100
             }
4101 4101
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4102
-            return $operator . SP . $cleaned_value;
4102
+            return $operator.SP.$cleaned_value;
4103 4103
         } elseif (in_array($operator, $this->_null_style_operators)) {
4104 4104
             if ($value !== null) {
4105 4105
                 throw new EE_Error(
@@ -4117,9 +4117,9 @@  discard block
 block discarded – undo
4117 4117
         } elseif ($operator === 'LIKE' && ! is_array($value)) {
4118 4118
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4119 4119
             //remove other junk. So just treat it as a string.
4120
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4121
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4122
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4120
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4121
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4122
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4123 4123
         } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4124 4124
             throw new EE_Error(
4125 4125
                 sprintf(
@@ -4131,7 +4131,7 @@  discard block
 block discarded – undo
4131 4131
                     $operator
4132 4132
                 )
4133 4133
             );
4134
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4134
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4135 4135
             throw new EE_Error(
4136 4136
                 sprintf(
4137 4137
                     __(
@@ -4172,7 +4172,7 @@  discard block
 block discarded – undo
4172 4172
         foreach ($values as $value) {
4173 4173
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4174 4174
         }
4175
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4175
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4176 4176
     }
4177 4177
 
4178 4178
 
@@ -4213,7 +4213,7 @@  discard block
 block discarded – undo
4213 4213
                                 . $main_table->get_table_name()
4214 4214
                                 . " WHERE FALSE";
4215 4215
         }
4216
-        return "(" . implode(",", $cleaned_values) . ")";
4216
+        return "(".implode(",", $cleaned_values).")";
4217 4217
     }
4218 4218
 
4219 4219
 
@@ -4232,7 +4232,7 @@  discard block
 block discarded – undo
4232 4232
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4233 4233
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4234 4234
         } else {//$field_obj should really just be a data type
4235
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4235
+            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4236 4236
                 throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4237 4237
                     $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4238 4238
             }
@@ -4316,11 +4316,11 @@  discard block
 block discarded – undo
4316 4316
             if ($table_obj instanceof EE_Primary_Table) {
4317 4317
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4318 4318
                     ? $table_obj->get_select_join_limit($limit)
4319
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4319
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4320 4320
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4321 4321
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4322 4322
                     ? $table_obj->get_select_join_limit_join($limit)
4323
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4323
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4324 4324
             }
4325 4325
         }
4326 4326
         return $SQL;
@@ -4408,12 +4408,12 @@  discard block
 block discarded – undo
4408 4408
      */
4409 4409
     public function get_related_model_obj($model_name)
4410 4410
     {
4411
-        $model_classname = "EEM_" . $model_name;
4412
-        if (! class_exists($model_classname)) {
4411
+        $model_classname = "EEM_".$model_name;
4412
+        if ( ! class_exists($model_classname)) {
4413 4413
             throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4414 4414
                 'event_espresso'), $model_name, $model_classname));
4415 4415
         }
4416
-        return call_user_func($model_classname . "::instance");
4416
+        return call_user_func($model_classname."::instance");
4417 4417
     }
4418 4418
 
4419 4419
 
@@ -4460,7 +4460,7 @@  discard block
 block discarded – undo
4460 4460
     public function related_settings_for($relation_name)
4461 4461
     {
4462 4462
         $relatedModels = $this->relation_settings();
4463
-        if (! array_key_exists($relation_name, $relatedModels)) {
4463
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4464 4464
             throw new EE_Error(
4465 4465
                 sprintf(
4466 4466
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4487,7 +4487,7 @@  discard block
 block discarded – undo
4487 4487
     public function field_settings_for($fieldName)
4488 4488
     {
4489 4489
         $fieldSettings = $this->field_settings(true);
4490
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4490
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4491 4491
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4492 4492
                 get_class($this)));
4493 4493
         }
@@ -4562,7 +4562,7 @@  discard block
 block discarded – undo
4562 4562
                     break;
4563 4563
                 }
4564 4564
             }
4565
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4565
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4566 4566
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4567 4567
                     get_class($this)));
4568 4568
             }
@@ -4621,7 +4621,7 @@  discard block
 block discarded – undo
4621 4621
      */
4622 4622
     public function get_foreign_key_to($model_name)
4623 4623
     {
4624
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4624
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4625 4625
             foreach ($this->field_settings() as $field) {
4626 4626
                 if (
4627 4627
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4631,7 +4631,7 @@  discard block
 block discarded – undo
4631 4631
                     break;
4632 4632
                 }
4633 4633
             }
4634
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4634
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4635 4635
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4636 4636
                     'event_espresso'), $model_name, get_class($this)));
4637 4637
             }
@@ -4682,7 +4682,7 @@  discard block
 block discarded – undo
4682 4682
                 foreach ($this->_fields as $fields_corresponding_to_table) {
4683 4683
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4684 4684
                         /** @var $field_obj EE_Model_Field_Base */
4685
-                        if (! $field_obj->is_db_only_field()) {
4685
+                        if ( ! $field_obj->is_db_only_field()) {
4686 4686
                             $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4687 4687
                         }
4688 4688
                     }
@@ -4712,7 +4712,7 @@  discard block
 block discarded – undo
4712 4712
         $count_if_model_has_no_primary_key = 0;
4713 4713
         $has_primary_key = $this->has_primary_key_field();
4714 4714
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4715
-        foreach ((array)$rows as $row) {
4715
+        foreach ((array) $rows as $row) {
4716 4716
             if (empty($row)) {
4717 4717
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4718 4718
                 return array();
@@ -4730,7 +4730,7 @@  discard block
 block discarded – undo
4730 4730
                 }
4731 4731
             }
4732 4732
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4733
-            if (! $classInstance) {
4733
+            if ( ! $classInstance) {
4734 4734
                 throw new EE_Error(
4735 4735
                     sprintf(
4736 4736
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -4799,7 +4799,7 @@  discard block
 block discarded – undo
4799 4799
      */
4800 4800
     public function instantiate_class_from_array_or_object($cols_n_values)
4801 4801
     {
4802
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4802
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4803 4803
             $cols_n_values = get_object_vars($cols_n_values);
4804 4804
         }
4805 4805
         $primary_key = null;
@@ -4824,7 +4824,7 @@  discard block
 block discarded – undo
4824 4824
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4825 4825
         if ($primary_key) {
4826 4826
             $classInstance = $this->get_from_entity_map($primary_key);
4827
-            if (! $classInstance) {
4827
+            if ( ! $classInstance) {
4828 4828
                 $classInstance = EE_Registry::instance()
4829 4829
                                             ->load_class($className,
4830 4830
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -4875,12 +4875,12 @@  discard block
 block discarded – undo
4875 4875
     public function add_to_entity_map(EE_Base_Class $object)
4876 4876
     {
4877 4877
         $className = $this->_get_class_name();
4878
-        if (! $object instanceof $className) {
4878
+        if ( ! $object instanceof $className) {
4879 4879
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4880 4880
                 is_object($object) ? get_class($object) : $object, $className));
4881 4881
         }
4882 4882
         /** @var $object EE_Base_Class */
4883
-        if (! $object->ID()) {
4883
+        if ( ! $object->ID()) {
4884 4884
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4885 4885
                 "event_espresso"), get_class($this)));
4886 4886
         }
@@ -4950,7 +4950,7 @@  discard block
 block discarded – undo
4950 4950
             //there is a primary key on this table and its not set. Use defaults for all its columns
4951 4951
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
4952 4952
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4953
-                    if (! $field_obj->is_db_only_field()) {
4953
+                    if ( ! $field_obj->is_db_only_field()) {
4954 4954
                         //prepare field as if its coming from db
4955 4955
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4956 4956
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -4959,7 +4959,7 @@  discard block
 block discarded – undo
4959 4959
             } else {
4960 4960
                 //the table's rows existed. Use their values
4961 4961
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4962
-                    if (! $field_obj->is_db_only_field()) {
4962
+                    if ( ! $field_obj->is_db_only_field()) {
4963 4963
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4964 4964
                             $cols_n_values, $field_obj->get_qualified_column(),
4965 4965
                             $field_obj->get_table_column()
@@ -5076,7 +5076,7 @@  discard block
 block discarded – undo
5076 5076
      */
5077 5077
     private function _get_class_name()
5078 5078
     {
5079
-        return "EE_" . $this->get_this_model_name();
5079
+        return "EE_".$this->get_this_model_name();
5080 5080
     }
5081 5081
 
5082 5082
 
@@ -5091,7 +5091,7 @@  discard block
 block discarded – undo
5091 5091
      */
5092 5092
     public function item_name($quantity = 1)
5093 5093
     {
5094
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5094
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5095 5095
     }
5096 5096
 
5097 5097
 
@@ -5124,7 +5124,7 @@  discard block
 block discarded – undo
5124 5124
     {
5125 5125
         $className = get_class($this);
5126 5126
         $tagName = "FHEE__{$className}__{$methodName}";
5127
-        if (! has_filter($tagName)) {
5127
+        if ( ! has_filter($tagName)) {
5128 5128
             throw new EE_Error(
5129 5129
                 sprintf(
5130 5130
                     __('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
@@ -5350,7 +5350,7 @@  discard block
 block discarded – undo
5350 5350
         $key_vals_in_combined_pk = array();
5351 5351
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5352 5352
         foreach ($key_fields as $key_field_name => $field_obj) {
5353
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5353
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5354 5354
                 return null;
5355 5355
             }
5356 5356
         }
@@ -5371,7 +5371,7 @@  discard block
 block discarded – undo
5371 5371
     {
5372 5372
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5373 5373
         foreach ($keys_it_should_have as $key) {
5374
-            if (! isset($key_vals[$key])) {
5374
+            if ( ! isset($key_vals[$key])) {
5375 5375
                 return false;
5376 5376
             }
5377 5377
         }
@@ -5425,7 +5425,7 @@  discard block
 block discarded – undo
5425 5425
      */
5426 5426
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5427 5427
     {
5428
-        if (! is_array($query_params)) {
5428
+        if ( ! is_array($query_params)) {
5429 5429
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5430 5430
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5431 5431
                     gettype($query_params)), '4.6.0');
@@ -5517,7 +5517,7 @@  discard block
 block discarded – undo
5517 5517
      */
5518 5518
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5519 5519
     {
5520
-        if (! $this->has_primary_key_field()) {
5520
+        if ( ! $this->has_primary_key_field()) {
5521 5521
             if (WP_DEBUG) {
5522 5522
                 EE_Error::add_error(
5523 5523
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5530,7 +5530,7 @@  discard block
 block discarded – undo
5530 5530
         $IDs = array();
5531 5531
         foreach ($model_objects as $model_object) {
5532 5532
             $id = $model_object->ID();
5533
-            if (! $id) {
5533
+            if ( ! $id) {
5534 5534
                 if ($filter_out_empty_ids) {
5535 5535
                     continue;
5536 5536
                 }
@@ -5626,8 +5626,8 @@  discard block
 block discarded – undo
5626 5626
         $missing_caps = array();
5627 5627
         $cap_restrictions = $this->cap_restrictions($context);
5628 5628
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5629
-            if (! EE_Capabilities::instance()
5630
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5629
+            if ( ! EE_Capabilities::instance()
5630
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5631 5631
             ) {
5632 5632
                 $missing_caps[$cap] = $restriction_if_no_cap;
5633 5633
             }
Please login to merge, or discard this patch.
admin/extend/registration_form/Extend_Registration_Form_Admin_Page.core.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -504,7 +504,7 @@
 block discarded – undo
504 504
      *
505 505
      * @param int                  $id
506 506
      * @param EEM_Soft_Delete_Base $model
507
-     * @return boolean
507
+     * @return integer
508 508
      */
509 509
     protected function _delete_item($id, $model)
510 510
     {
Please login to merge, or discard this patch.
Indentation   +1085 added lines, -1085 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
 /**
@@ -25,1090 +25,1090 @@  discard block
 block discarded – undo
25 25
 {
26 26
 
27 27
 
28
-    /**
29
-     * @Constructor
30
-     * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
31
-     * @access public
32
-     */
33
-    public function __construct($routing = true)
34
-    {
35
-        define('REGISTRATION_FORM_CAF_ADMIN', EE_CORE_CAF_ADMIN_EXTEND . 'registration_form' . DS);
36
-        define('REGISTRATION_FORM_CAF_ASSETS_PATH', REGISTRATION_FORM_CAF_ADMIN . 'assets' . DS);
37
-        define('REGISTRATION_FORM_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/assets/');
38
-        define('REGISTRATION_FORM_CAF_TEMPLATE_PATH', REGISTRATION_FORM_CAF_ADMIN . 'templates' . DS);
39
-        define('REGISTRATION_FORM_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/templates/');
40
-        parent::__construct($routing);
41
-    }
42
-
43
-
44
-    protected function _extend_page_config()
45
-    {
46
-        $this->_admin_base_path = REGISTRATION_FORM_CAF_ADMIN;
47
-        $qst_id                 = ! empty($this->_req_data['QST_ID']) && ! is_array($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0;
48
-        $qsg_id                 = ! empty($this->_req_data['QSG_ID']) && ! is_array($this->_req_data['QSG_ID']) ? $this->_req_data['QSG_ID'] : 0;
49
-
50
-        $new_page_routes    = array(
51
-            'question_groups'    => array(
52
-                'func'       => '_question_groups_overview_list_table',
53
-                'capability' => 'ee_read_question_groups',
54
-            ),
55
-            'add_question'       => array(
56
-                'func'       => '_edit_question',
57
-                'capability' => 'ee_edit_questions',
58
-            ),
59
-            'insert_question'    => array(
60
-                'func'       => '_insert_or_update_question',
61
-                'args'       => array('new_question' => true),
62
-                'capability' => 'ee_edit_questions',
63
-                'noheader'   => true,
64
-            ),
65
-            'duplicate_question' => array(
66
-                'func'       => '_duplicate_question',
67
-                'capability' => 'ee_edit_questions',
68
-                'noheader'   => true,
69
-            ),
70
-            'trash_question'     => array(
71
-                'func'       => '_trash_question',
72
-                'capability' => 'ee_delete_question',
73
-                'obj_id'     => $qst_id,
74
-                'noheader'   => true,
75
-            ),
76
-
77
-            'restore_question' => array(
78
-                'func'       => '_trash_or_restore_questions',
79
-                'capability' => 'ee_delete_question',
80
-                'obj_id'     => $qst_id,
81
-                'args'       => array('trash' => false),
82
-                'noheader'   => true,
83
-            ),
84
-
85
-            'delete_question' => array(
86
-                'func'       => '_delete_question',
87
-                'capability' => 'ee_delete_question',
88
-                'obj_id'     => $qst_id,
89
-                'noheader'   => true,
90
-            ),
91
-
92
-            'trash_questions' => array(
93
-                'func'       => '_trash_or_restore_questions',
94
-                'capability' => 'ee_delete_questions',
95
-                'args'       => array('trash' => true),
96
-                'noheader'   => true,
97
-            ),
98
-
99
-            'restore_questions' => array(
100
-                'func'       => '_trash_or_restore_questions',
101
-                'capability' => 'ee_delete_questions',
102
-                'args'       => array('trash' => false),
103
-                'noheader'   => true,
104
-            ),
105
-
106
-            'delete_questions' => array(
107
-                'func'       => '_delete_questions',
108
-                'args'       => array(),
109
-                'capability' => 'ee_delete_questions',
110
-                'noheader'   => true,
111
-            ),
112
-
113
-            'add_question_group' => array(
114
-                'func'       => '_edit_question_group',
115
-                'capability' => 'ee_edit_question_groups',
116
-            ),
117
-
118
-            'edit_question_group' => array(
119
-                'func'       => '_edit_question_group',
120
-                'capability' => 'ee_edit_question_group',
121
-                'obj_id'     => $qsg_id,
122
-                'args'       => array('edit'),
123
-            ),
124
-
125
-            'delete_question_groups' => array(
126
-                'func'       => '_delete_question_groups',
127
-                'capability' => 'ee_delete_question_groups',
128
-                'noheader'   => true,
129
-            ),
130
-
131
-            'delete_question_group' => array(
132
-                'func'       => '_delete_question_groups',
133
-                'capability' => 'ee_delete_question_group',
134
-                'obj_id'     => $qsg_id,
135
-                'noheader'   => true,
136
-            ),
137
-
138
-            'trash_question_group' => array(
139
-                'func'       => '_trash_or_restore_question_groups',
140
-                'args'       => array('trash' => true),
141
-                'capability' => 'ee_delete_question_group',
142
-                'obj_id'     => $qsg_id,
143
-                'noheader'   => true,
144
-            ),
145
-
146
-            'restore_question_group' => array(
147
-                'func'       => '_trash_or_restore_question_groups',
148
-                'args'       => array('trash' => false),
149
-                'capability' => 'ee_delete_question_group',
150
-                'obj_id'     => $qsg_id,
151
-                'noheader'   => true,
152
-            ),
153
-
154
-            'insert_question_group' => array(
155
-                'func'       => '_insert_or_update_question_group',
156
-                'args'       => array('new_question_group' => true),
157
-                'capability' => 'ee_edit_question_groups',
158
-                'noheader'   => true,
159
-            ),
160
-
161
-            'update_question_group' => array(
162
-                'func'       => '_insert_or_update_question_group',
163
-                'args'       => array('new_question_group' => false),
164
-                'capability' => 'ee_edit_question_group',
165
-                'obj_id'     => $qsg_id,
166
-                'noheader'   => true,
167
-            ),
168
-
169
-            'trash_question_groups' => array(
170
-                'func'       => '_trash_or_restore_question_groups',
171
-                'args'       => array('trash' => true),
172
-                'capability' => 'ee_delete_question_groups',
173
-                'noheader'   => array('trash' => false),
174
-            ),
175
-
176
-            'restore_question_groups' => array(
177
-                'func'       => '_trash_or_restore_question_groups',
178
-                'args'       => array('trash' => false),
179
-                'capability' => 'ee_delete_question_groups',
180
-                'noheader'   => true,
181
-            ),
182
-
183
-
184
-            'espresso_update_question_group_order' => array(
185
-                'func'       => 'update_question_group_order',
186
-                'capability' => 'ee_edit_question_groups',
187
-                'noheader'   => true,
188
-            ),
189
-
190
-            'view_reg_form_settings' => array(
191
-                'func'       => '_reg_form_settings',
192
-                'capability' => 'manage_options',
193
-            ),
194
-
195
-            'update_reg_form_settings' => array(
196
-                'func'       => '_update_reg_form_settings',
197
-                'capability' => 'manage_options',
198
-                'noheader'   => true,
199
-            ),
200
-        );
201
-        $this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
202
-
203
-        $new_page_config    = array(
204
-
205
-            'question_groups' => array(
206
-                'nav'           => array(
207
-                    'label' => esc_html__('Question Groups', 'event_espresso'),
208
-                    'order' => 20,
209
-                ),
210
-                'list_table'    => 'Registration_Form_Question_Groups_Admin_List_Table',
211
-                'help_tabs'     => array(
212
-                    'registration_form_question_groups_help_tab'                           => array(
213
-                        'title'    => esc_html__('Question Groups', 'event_espresso'),
214
-                        'filename' => 'registration_form_question_groups',
215
-                    ),
216
-                    'registration_form_question_groups_table_column_headings_help_tab'     => array(
217
-                        'title'    => esc_html__('Question Groups Table Column Headings', 'event_espresso'),
218
-                        'filename' => 'registration_form_question_groups_table_column_headings',
219
-                    ),
220
-                    'registration_form_question_groups_views_bulk_actions_search_help_tab' => array(
221
-                        'title'    => esc_html__('Question Groups Views & Bulk Actions & Search', 'event_espresso'),
222
-                        'filename' => 'registration_form_question_groups_views_bulk_actions_search',
223
-                    ),
224
-                ),
225
-                'help_tour'     => array('Registration_Form_Question_Groups_Help_Tour'),
226
-                'metaboxes'     => $this->_default_espresso_metaboxes,
227
-                'require_nonce' => false,
228
-                'qtips'         => array(
229
-                    'EE_Registration_Form_Tips',
230
-                ),
231
-            ),
232
-
233
-            'add_question' => array(
234
-                'nav'           => array(
235
-                    'label'      => esc_html__('Add Question', 'event_espresso'),
236
-                    'order'      => 5,
237
-                    'persistent' => false,
238
-                ),
239
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
240
-                'help_tabs'     => array(
241
-                    'registration_form_add_question_help_tab' => array(
242
-                        'title'    => esc_html__('Add Question', 'event_espresso'),
243
-                        'filename' => 'registration_form_add_question',
244
-                    ),
245
-                ),
246
-                'help_tour'     => array('Registration_Form_Add_Question_Help_Tour'),
247
-                'require_nonce' => false,
248
-            ),
249
-
250
-            'add_question_group' => array(
251
-                'nav'           => array(
252
-                    'label'      => esc_html__('Add Question Group', 'event_espresso'),
253
-                    'order'      => 5,
254
-                    'persistent' => false,
255
-                ),
256
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
257
-                'help_tabs'     => array(
258
-                    'registration_form_add_question_group_help_tab' => array(
259
-                        'title'    => esc_html__('Add Question Group', 'event_espresso'),
260
-                        'filename' => 'registration_form_add_question_group',
261
-                    ),
262
-                ),
263
-                'help_tour'     => array('Registration_Form_Add_Question_Group_Help_Tour'),
264
-                'require_nonce' => false,
265
-            ),
266
-
267
-            'edit_question_group' => array(
268
-                'nav'           => array(
269
-                    'label'      => esc_html__('Edit Question Group', 'event_espresso'),
270
-                    'order'      => 5,
271
-                    'persistent' => false,
272
-                    'url'        => isset($this->_req_data['question_group_id']) ? add_query_arg(array('question_group_id' => $this->_req_data['question_group_id']),
273
-                        $this->_current_page_view_url) : $this->_admin_base_url,
274
-                ),
275
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
276
-                'help_tabs'     => array(
277
-                    'registration_form_edit_question_group_help_tab' => array(
278
-                        'title'    => esc_html__('Edit Question Group', 'event_espresso'),
279
-                        'filename' => 'registration_form_edit_question_group',
280
-                    ),
281
-                ),
282
-                'help_tour'     => array('Registration_Form_Edit_Question_Group_Help_Tour'),
283
-                'require_nonce' => false,
284
-            ),
285
-
286
-            'view_reg_form_settings' => array(
287
-                'nav'           => array(
288
-                    'label' => esc_html__('Reg Form Settings', 'event_espresso'),
289
-                    'order' => 40,
290
-                ),
291
-                'labels'        => array(
292
-                    'publishbox' => esc_html__('Update Settings', 'event_espresso'),
293
-                ),
294
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
295
-                'help_tabs'     => array(
296
-                    'registration_form_reg_form_settings_help_tab' => array(
297
-                        'title'    => esc_html__('Registration Form Settings', 'event_espresso'),
298
-                        'filename' => 'registration_form_reg_form_settings',
299
-                    ),
300
-                ),
301
-                'help_tour'     => array('Registration_Form_Settings_Help_Tour'),
302
-                'require_nonce' => false,
303
-            ),
304
-
305
-        );
306
-        $this->_page_config = array_merge($this->_page_config, $new_page_config);
307
-
308
-        //change the list table we're going to use so it's the NEW list table!
309
-        $this->_page_config['default']['list_table'] = 'Extend_Registration_Form_Questions_Admin_List_Table';
310
-
311
-
312
-        //additional labels
313
-        $new_labels               = array(
314
-            'add_question'          => esc_html__('Add New Question', 'event_espresso'),
315
-            'delete_question'       => esc_html__('Delete Question', 'event_espresso'),
316
-            'add_question_group'    => esc_html__('Add New Question Group', 'event_espresso'),
317
-            'edit_question_group'   => esc_html__('Edit Question Group', 'event_espresso'),
318
-            'delete_question_group' => esc_html__('Delete Question Group', 'event_espresso'),
319
-        );
320
-        $this->_labels['buttons'] = array_merge($this->_labels['buttons'], $new_labels);
321
-
322
-    }
323
-
324
-
325
-    protected function _ajax_hooks()
326
-    {
327
-        add_action('wp_ajax_espresso_update_question_group_order', array($this, 'update_question_group_order'));
328
-    }
329
-
330
-
331
-    public function load_scripts_styles_question_groups()
332
-    {
333
-        wp_enqueue_script('espresso_ajax_table_sorting');
334
-    }
335
-
336
-
337
-    public function load_scripts_styles_add_question_group()
338
-    {
339
-        $this->load_scripts_styles_forms();
340
-        $this->load_sortable_question_script();
341
-    }
342
-
343
-    public function load_scripts_styles_edit_question_group()
344
-    {
345
-        $this->load_scripts_styles_forms();
346
-        $this->load_sortable_question_script();
347
-    }
348
-
349
-
350
-    /**
351
-     * registers and enqueues script for questions
352
-     *
353
-     * @return void
354
-     */
355
-    public function load_sortable_question_script()
356
-    {
357
-        wp_register_script('ee-question-sortable', REGISTRATION_FORM_CAF_ASSETS_URL . 'ee_question_order.js',
358
-            array('jquery-ui-sortable'), EVENT_ESPRESSO_VERSION, true);
359
-        wp_enqueue_script('ee-question-sortable');
360
-    }
361
-
362
-
363
-    protected function _set_list_table_views_default()
364
-    {
365
-        $this->_views = array(
366
-            'all' => array(
367
-                'slug'        => 'all',
368
-                'label'       => esc_html__('View All Questions', 'event_espresso'),
369
-                'count'       => 0,
370
-                'bulk_action' => array(
371
-                    'trash_questions' => esc_html__('Trash', 'event_espresso'),
372
-                ),
373
-            ),
374
-        );
375
-
376
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_questions',
377
-            'espresso_registration_form_trash_questions')
378
-        ) {
379
-            $this->_views['trash'] = array(
380
-                'slug'        => 'trash',
381
-                'label'       => esc_html__('Trash', 'event_espresso'),
382
-                'count'       => 0,
383
-                'bulk_action' => array(
384
-                    'delete_questions'  => esc_html__('Delete Permanently', 'event_espresso'),
385
-                    'restore_questions' => esc_html__('Restore', 'event_espresso'),
386
-                ),
387
-            );
388
-        }
389
-    }
390
-
391
-
392
-    protected function _set_list_table_views_question_groups()
393
-    {
394
-        $this->_views = array(
395
-            'all' => array(
396
-                'slug'        => 'all',
397
-                'label'       => esc_html__('All', 'event_espresso'),
398
-                'count'       => 0,
399
-                'bulk_action' => array(
400
-                    'trash_question_groups' => esc_html__('Trash', 'event_espresso'),
401
-                ),
402
-            ),
403
-        );
404
-
405
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_question_groups',
406
-            'espresso_registration_form_trash_question_groups')
407
-        ) {
408
-            $this->_views['trash'] = array(
409
-                'slug'        => 'trash',
410
-                'label'       => esc_html__('Trash', 'event_espresso'),
411
-                'count'       => 0,
412
-                'bulk_action' => array(
413
-                    'delete_question_groups'  => esc_html__('Delete Permanently', 'event_espresso'),
414
-                    'restore_question_groups' => esc_html__('Restore', 'event_espresso'),
415
-                ),
416
-            );
417
-        }
418
-    }
419
-
420
-
421
-    protected function _questions_overview_list_table()
422
-    {
423
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
424
-                'add_question',
425
-                'add_question',
426
-                array(),
427
-                'add-new-h2'
428
-            );
429
-        parent::_questions_overview_list_table();
430
-    }
431
-
432
-
433
-    protected function _question_groups_overview_list_table()
434
-    {
435
-        $this->_search_btn_label = esc_html__('Question Groups', 'event_espresso');
436
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
437
-                'add_question_group',
438
-                'add_question_group',
439
-                array(),
440
-                'add-new-h2'
441
-            );
442
-        $this->display_admin_list_table_page_with_sidebar();
443
-    }
444
-
445
-
446
-    protected function _delete_question()
447
-    {
448
-        $success = $this->_delete_items($this->_question_model);
449
-        $this->_redirect_after_action(
450
-            $success,
451
-            $this->_question_model->item_name($success),
452
-            'deleted',
453
-            array('action' => 'default', 'status' => 'all')
454
-        );
455
-    }
456
-
457
-
458
-    protected function _delete_questions()
459
-    {
460
-        $success = $this->_delete_items($this->_question_model);
461
-        $this->_redirect_after_action(
462
-            $success,
463
-            $this->_question_model->item_name($success),
464
-            'deleted permanently',
465
-            array('action' => 'default', 'status' => 'trash')
466
-        );
467
-    }
468
-
469
-
470
-    /**
471
-     * Performs the deletion of a single or multiple questions or question groups.
472
-     *
473
-     * @param EEM_Soft_Delete_Base $model
474
-     * @return int number of items deleted permanently
475
-     */
476
-    private function _delete_items(EEM_Soft_Delete_Base $model)
477
-    {
478
-        $success = 0;
479
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
480
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
481
-            // if array has more than one element than success message should be plural
482
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
483
-            // cycle thru bulk action checkboxes
484
-            while (list($ID, $value) = each($this->_req_data['checkbox'])) {
485
-                if (! $this->_delete_item($ID, $model)) {
486
-                    $success = 0;
487
-                }
488
-            }
489
-
490
-        } elseif (! empty($this->_req_data['QSG_ID'])) {
491
-            $success = $this->_delete_item($this->_req_data['QSG_ID'], $model);
492
-
493
-        } elseif (! empty($this->_req_data['QST_ID'])) {
494
-            $success = $this->_delete_item($this->_req_data['QST_ID'], $model);
495
-        } else {
496
-            EE_Error::add_error(sprintf(esc_html__("No Questions or Question Groups were selected for deleting. This error usually shows when you've attempted to delete via bulk action but there were no selections.",
497
-                "event_espresso")), __FILE__, __FUNCTION__, __LINE__);
498
-        }
499
-        return $success;
500
-    }
501
-
502
-    /**
503
-     * Deletes the specified question (and its associated question options) or question group
504
-     *
505
-     * @param int                  $id
506
-     * @param EEM_Soft_Delete_Base $model
507
-     * @return boolean
508
-     */
509
-    protected function _delete_item($id, $model)
510
-    {
511
-        if ($model instanceof EEM_Question) {
512
-            EEM_Question_Option::instance()->delete_permanently(array(array('QST_ID' => absint($id))));
513
-        }
514
-        return $model->delete_permanently_by_ID(absint($id));
515
-    }
516
-
517
-
518
-    /******************************    QUESTION GROUPS    ******************************/
519
-
520
-
521
-    protected function _edit_question_group($type = 'add')
522
-    {
523
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
524
-        $ID = isset($this->_req_data['QSG_ID']) && ! empty($this->_req_data['QSG_ID']) ? absint($this->_req_data['QSG_ID']) : false;
525
-
526
-        switch ($this->_req_action) {
527
-            case 'add_question_group' :
528
-                $this->_admin_page_title = esc_html__('Add Question Group', 'event_espresso');
529
-                break;
530
-            case 'edit_question_group' :
531
-                $this->_admin_page_title = esc_html__('Edit Question Group', 'event_espresso');
532
-                break;
533
-            default :
534
-                $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
535
-        }
536
-        // add ID to title if editing
537
-        $this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
538
-        if ($ID) {
539
-            /** @var EE_Question_Group $questionGroup */
540
-            $questionGroup            = $this->_question_group_model->get_one_by_ID($ID);
541
-            $additional_hidden_fields = array('QSG_ID' => array('type' => 'hidden', 'value' => $ID));
542
-            $this->_set_add_edit_form_tags('update_question_group', $additional_hidden_fields);
543
-        } else {
544
-            /** @var EE_Question_Group $questionGroup */
545
-            $questionGroup = EEM_Question_Group::instance()->create_default_object();
546
-            $questionGroup->set_order_to_latest();
547
-            $this->_set_add_edit_form_tags('insert_question_group');
548
-        }
549
-        $this->_template_args['values']         = $this->_yes_no_values;
550
-        $this->_template_args['all_questions']  = $questionGroup->questions_in_and_not_in_group();
551
-        $this->_template_args['QSG_ID']         = $ID ? $ID : true;
552
-        $this->_template_args['question_group'] = $questionGroup;
553
-
554
-        $redirect_URL = add_query_arg(array('action' => 'question_groups'), $this->_admin_base_url);
555
-        $this->_set_publish_post_box_vars('id', $ID, false, $redirect_URL);
556
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'question_groups_main_meta_box.template.php',
557
-            $this->_template_args, true);
558
-
559
-        // the details template wrapper
560
-        $this->display_admin_page_with_sidebar();
561
-    }
562
-
563
-
564
-    protected function _delete_question_groups()
565
-    {
566
-        $success = $this->_delete_items($this->_question_group_model);
567
-        $this->_redirect_after_action($success, $this->_question_group_model->item_name($success),
568
-            'deleted permanently', array('action' => 'question_groups', 'status' => 'trash'));
569
-    }
570
-
571
-
572
-    /**
573
-     * @param bool $new_question_group
574
-     */
575
-    protected function _insert_or_update_question_group($new_question_group = true)
576
-    {
577
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
578
-        $set_column_values = $this->_set_column_values_for($this->_question_group_model);
579
-        if ($new_question_group) {
580
-            $QSG_ID  = $this->_question_group_model->insert($set_column_values);
581
-            $success = $QSG_ID ? 1 : 0;
582
-        } else {
583
-            $QSG_ID = absint($this->_req_data['QSG_ID']);
584
-            unset($set_column_values['QSG_ID']);
585
-            $success = $this->_question_group_model->update($set_column_values, array(array('QSG_ID' => $QSG_ID)));
586
-        }
587
-        $phone_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(EEM_Attendee::system_question_phone);
588
-        // update the existing related questions
589
-        // BUT FIRST...  delete the phone question from the Question_Group_Question if it is being added to this question group (therefore removed from the existing group)
590
-        if (isset($this->_req_data['questions'], $this->_req_data['questions'][$phone_question_id])) {
591
-            // delete where QST ID = system phone question ID and Question Group ID is NOT this group
592
-            EEM_Question_Group_Question::instance()->delete(array(
593
-                array(
594
-                    'QST_ID' => $phone_question_id,
595
-                    'QSG_ID' => array('!=', $QSG_ID),
596
-                ),
597
-            ));
598
-        }
599
-        /** @type EE_Question_Group $question_group */
600
-        $question_group = $this->_question_group_model->get_one_by_ID($QSG_ID);
601
-        $questions      = $question_group->questions();
602
-        // make sure system phone question is added to list of questions for this group
603
-        if (! isset($questions[$phone_question_id])) {
604
-            $questions[$phone_question_id] = EEM_Question::instance()->get_one_by_ID($phone_question_id);
605
-        }
606
-
607
-        foreach ($questions as $question_ID => $question) {
608
-            // first we always check for order.
609
-            if (! empty($this->_req_data['question_orders'][$question_ID])) {
610
-                //update question order
611
-                $question_group->update_question_order($question_ID, $this->_req_data['question_orders'][$question_ID]);
612
-            }
613
-
614
-            // then we always check if adding or removing.
615
-            if (isset($this->_req_data['questions'], $this->_req_data['questions'][$question_ID])) {
616
-                $question_group->add_question($question_ID);
617
-            } else {
618
-                // not found, remove it (but only if not a system question for the personal group with the exception of lname system question - we allow removal of it)
619
-                if (
620
-                in_array(
621
-                    $question->system_ID(),
622
-                    EEM_Question::instance()->required_system_questions_in_system_question_group($question_group->system_group())
623
-                )
624
-                ) {
625
-                    continue;
626
-                } else {
627
-                    $question_group->remove_question($question_ID);
628
-                }
629
-            }
630
-        }
631
-        // save new related questions
632
-        if (isset($this->_req_data['questions'])) {
633
-            foreach ($this->_req_data['questions'] as $QST_ID) {
634
-                $question_group->add_question($QST_ID);
635
-                if (isset($this->_req_data['question_orders'][$QST_ID])) {
636
-                    $question_group->update_question_order($QST_ID, $this->_req_data['question_orders'][$QST_ID]);
637
-                }
638
-            }
639
-        }
640
-
641
-        if ($success !== false) {
642
-            $msg = $new_question_group ? sprintf(esc_html__('The %s has been created', 'event_espresso'),
643
-                $this->_question_group_model->item_name()) : sprintf(esc_html__('The %s has been updated',
644
-                'event_espresso'), $this->_question_group_model->item_name());
645
-            EE_Error::add_success($msg);
646
-        }
647
-        $this->_redirect_after_action(false, '', '', array('action' => 'edit_question_group', 'QSG_ID' => $QSG_ID),
648
-            true);
649
-
650
-    }
651
-
652
-    /**
653
-     * duplicates a question and all its question options and redirects to the new question.
654
-     */
655
-    public function _duplicate_question()
656
-    {
657
-        $question_ID = (int)$this->_req_data['QST_ID'];
658
-        $question    = EEM_Question::instance()->get_one_by_ID($question_ID);
659
-        if ($question instanceof EE_Question) {
660
-            $new_question = $question->duplicate();
661
-            if ($new_question instanceof EE_Question) {
662
-                $this->_redirect_after_action(true, esc_html__('Question', 'event_espresso'),
663
-                    esc_html__('Duplicated', 'event_espresso'),
664
-                    array('action' => 'edit_question', 'QST_ID' => $new_question->ID()), true);
665
-            } else {
666
-                global $wpdb;
667
-                EE_Error::add_error(sprintf(esc_html__('Could not duplicate question with ID %1$d because: %2$s',
668
-                    'event_espresso'), $question_ID, $wpdb->last_error), __FILE__, __FUNCTION__, __LINE__);
669
-                $this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
670
-            }
671
-        } else {
672
-            EE_Error::add_error(sprintf(esc_html__('Could not duplicate question with ID %d because it didn\'t exist!',
673
-                'event_espresso'), $question_ID), __FILE__, __FUNCTION__, __LINE__);
674
-            $this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
675
-        }
676
-    }
677
-
678
-
679
-    /**
680
-     * @param bool $trash
681
-     */
682
-    protected function _trash_or_restore_question_groups($trash = true)
683
-    {
684
-        $this->_trash_or_restore_items($this->_question_group_model, $trash);
685
-    }
686
-
687
-
688
-    /**
689
-     *_trash_question
690
-     */
691
-    protected function _trash_question()
692
-    {
693
-        $success    = $this->_question_model->delete_by_ID((int)$this->_req_data['QST_ID']);
694
-        $query_args = array('action' => 'default', 'status' => 'all');
695
-        $this->_redirect_after_action($success, $this->_question_model->item_name($success), 'trashed', $query_args);
696
-    }
697
-
698
-
699
-    /**
700
-     * @param bool $trash
701
-     */
702
-    protected function _trash_or_restore_questions($trash = true)
703
-    {
704
-        $this->_trash_or_restore_items($this->_question_model, $trash);
705
-    }
706
-
707
-
708
-    /**
709
-     * Internally used to delete or restore items, using the request data. Meant to be
710
-     * flexible between question or question groups
711
-     *
712
-     * @param EEM_Soft_Delete_Base $model
713
-     * @param boolean              $trash whether to trash or restore
714
-     */
715
-    private function _trash_or_restore_items(EEM_Soft_Delete_Base $model, $trash = true)
716
-    {
717
-
718
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
719
-
720
-        $success = 1;
721
-        //Checkboxes
722
-        //echo "trash $trash";
723
-        //var_dump($this->_req_data['checkbox']);die;
724
-        if (isset($this->_req_data['checkbox'])) {
725
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
726
-                // if array has more than one element than success message should be plural
727
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
728
-                // cycle thru bulk action checkboxes
729
-                while (list($ID, $value) = each($this->_req_data['checkbox'])) {
730
-                    if (! $model->delete_or_restore_by_ID($trash, absint($ID))) {
731
-                        $success = 0;
732
-                    }
733
-                }
734
-
735
-            } else {
736
-                // grab single id and delete
737
-                $ID = absint($this->_req_data['checkbox']);
738
-                if (! $model->delete_or_restore_by_ID($trash, $ID)) {
739
-                    $success = 0;
740
-                }
741
-            }
742
-
743
-        } else {
744
-            // delete via trash link
745
-            // grab single id and delete
746
-            $ID = absint($this->_req_data[$model->primary_key_name()]);
747
-            if (! $model->delete_or_restore_by_ID($trash, $ID)) {
748
-                $success = 0;
749
-            }
750
-
751
-        }
752
-
753
-
754
-        $action = $model instanceof EEM_Question ? 'default' : 'question_groups';//strtolower( $model->item_name(2) );
755
-        //echo "action :$action";
756
-        //$action = 'questions' ? 'default' : $action;
757
-        if ($trash) {
758
-            $action_desc = 'trashed';
759
-            $status      = 'trash';
760
-        } else {
761
-            $action_desc = 'restored';
762
-            $status      = 'all';
763
-        }
764
-        $this->_redirect_after_action($success, $model->item_name($success), $action_desc,
765
-            array('action' => $action, 'status' => $status));
766
-    }
767
-
768
-
769
-    /**
770
-     * @param            $per_page
771
-     * @param int        $current_page
772
-     * @param bool|false $count
773
-     * @return \EE_Soft_Delete_Base_Class[]|int
774
-     */
775
-    public function get_trashed_questions($per_page, $current_page = 1, $count = false)
776
-    {
777
-        $query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
778
-
779
-        if ($count) {
780
-            //note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
781
-            $where   = isset($query_params[0]) ? array($query_params[0]) : array();
782
-            $results = $this->_question_model->count_deleted($where);
783
-        } else {
784
-            //note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
785
-            $results = $this->_question_model->get_all_deleted($query_params);
786
-        }
787
-        return $results;
788
-    }
789
-
790
-
791
-    /**
792
-     * @param            $per_page
793
-     * @param int        $current_page
794
-     * @param bool|false $count
795
-     * @return \EE_Soft_Delete_Base_Class[]
796
-     */
797
-    public function get_question_groups($per_page, $current_page = 1, $count = false)
798
-    {
799
-        $questionGroupModel = EEM_Question_Group::instance();
800
-        $query_params       = $this->get_query_params($questionGroupModel, $per_page, $current_page);
801
-        if ($count) {
802
-            $where   = isset($query_params[0]) ? array($query_params[0]) : array();
803
-            $results = $questionGroupModel->count($where);
804
-        } else {
805
-            $results = $questionGroupModel->get_all($query_params);
806
-        }
807
-        return $results;
808
-    }
809
-
810
-
811
-    /**
812
-     * @param      $per_page
813
-     * @param int  $current_page
814
-     * @param bool $count
815
-     * @return \EE_Soft_Delete_Base_Class[]|int
816
-     */
817
-    public function get_trashed_question_groups($per_page, $current_page = 1, $count = false)
818
-    {
819
-        $questionGroupModel = EEM_Question_Group::instance();
820
-        $query_params       = $this->get_query_params($questionGroupModel, $per_page, $current_page);
821
-        if ($count) {
822
-            $where                 = isset($query_params[0]) ? array($query_params[0]) : array();
823
-            $query_params['limit'] = null;
824
-            $results               = $questionGroupModel->count_deleted($where);
825
-        } else {
826
-            $results = $questionGroupModel->get_all_deleted($query_params);
827
-        }
828
-        return $results;
829
-    }
830
-
831
-
832
-    /**
833
-     * method for performing updates to question order
834
-     *
835
-     * @return array results array
836
-     */
837
-    public function update_question_group_order()
838
-    {
839
-
840
-        $success = esc_html__('Question group order was updated successfully.', 'event_espresso');
841
-
842
-        // grab our row IDs
843
-        $row_ids = isset($this->_req_data['row_ids']) && ! empty($this->_req_data['row_ids'])
844
-            ? explode(',', rtrim($this->_req_data['row_ids'], ','))
845
-            : array();
846
-
847
-        $perpage = ! empty($this->_req_data['perpage'])
848
-            ? (int)$this->_req_data['perpage']
849
-            : null;
850
-        $curpage = ! empty($this->_req_data['curpage'])
851
-            ? (int)$this->_req_data['curpage']
852
-            : null;
853
-
854
-        if (! empty($row_ids)) {
855
-            //figure out where we start the row_id count at for the current page.
856
-            $qsgcount = empty($curpage) ? 0 : ($curpage - 1) * $perpage;
857
-
858
-            $row_count = count($row_ids);
859
-            for ($i = 0; $i < $row_count; $i++) {
860
-                //Update the questions when re-ordering
861
-                $updated = EEM_Question_Group::instance()->update(
862
-                    array('QSG_order' => $qsgcount),
863
-                    array(array('QSG_ID' => $row_ids[$i]))
864
-                );
865
-                if ($updated === false) {
866
-                    $success = false;
867
-                }
868
-                $qsgcount++;
869
-            }
870
-        } else {
871
-            $success = false;
872
-        }
873
-
874
-        $errors = ! $success
875
-            ? esc_html__('An error occurred. The question group order was not updated.', 'event_espresso')
876
-            : false;
877
-
878
-        echo wp_json_encode(array('return_data' => false, 'success' => $success, 'errors' => $errors));
879
-        die();
880
-
881
-    }
882
-
883
-
884
-
885
-    /***************************************        REGISTRATION SETTINGS        ***************************************/
886
-
887
-
888
-    /**
889
-     * _reg_form_settings
890
-     *
891
-     * @throws \EE_Error
892
-     */
893
-    protected function _reg_form_settings()
894
-    {
895
-        $this->_template_args['values'] = $this->_yes_no_values;
896
-        add_action(
897
-            'AHEE__Extend_Registration_Form_Admin_Page___reg_form_settings_template',
898
-            array($this, 'email_validation_settings_form'),
899
-            2
900
-        );
901
-        $this->_template_args = (array)apply_filters(
902
-            'FHEE__Extend_Registration_Form_Admin_Page___reg_form_settings___template_args',
903
-            $this->_template_args
904
-        );
905
-        $this->_set_add_edit_form_tags('update_reg_form_settings');
906
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
907
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
908
-            REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'reg_form_settings.template.php',
909
-            $this->_template_args,
910
-            true
911
-        );
912
-        $this->display_admin_page_with_sidebar();
913
-    }
914
-
915
-
916
-    /**
917
-     * _update_reg_form_settings
918
-     */
919
-    protected function _update_reg_form_settings()
920
-    {
921
-        EE_Registry::instance()->CFG->registration = $this->update_email_validation_settings_form(
922
-            EE_Registry::instance()->CFG->registration
923
-        );
924
-        EE_Registry::instance()->CFG->registration = apply_filters(
925
-            'FHEE__Extend_Registration_Form_Admin_Page___update_reg_form_settings__CFG_registration',
926
-            EE_Registry::instance()->CFG->registration
927
-        );
928
-        $success                                   = $this->_update_espresso_configuration(
929
-            esc_html__('Registration Form Options', 'event_espresso'),
930
-            EE_Registry::instance()->CFG,
931
-            __FILE__, __FUNCTION__, __LINE__
932
-        );
933
-        $this->_redirect_after_action($success, esc_html__('Registration Form Options', 'event_espresso'), 'updated',
934
-            array('action' => 'view_reg_form_settings'));
935
-    }
936
-
937
-
938
-    /**
939
-     * email_validation_settings_form
940
-     *
941
-     * @access    public
942
-     * @return    void
943
-     * @throws \EE_Error
944
-     */
945
-    public function email_validation_settings_form()
946
-    {
947
-        echo $this->_email_validation_settings_form()->get_html();
948
-    }
949
-
950
-
951
-    /**
952
-     * _email_validation_settings_form
953
-     *
954
-     * @access protected
955
-     * @return EE_Form_Section_Proper
956
-     * @throws \EE_Error
957
-     */
958
-    protected function _email_validation_settings_form()
959
-    {
960
-        return new EE_Form_Section_Proper(
961
-            array(
962
-                'name'            => 'email_validation_settings',
963
-                'html_id'         => 'email_validation_settings',
964
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
965
-                'subsections'     => array(
966
-                    'email_validation_hdr'   => new EE_Form_Section_HTML(
967
-                        EEH_HTML::h2(esc_html__('Email Validation Settings', 'event_espresso'))
968
-                    ),
969
-                    'email_validation_level' => new EE_Select_Input(
970
-                        array(
971
-                            'basic'      => esc_html__('Basic', 'event_espresso'),
972
-                            'wp_default' => esc_html__('WordPress Default', 'event_espresso'),
973
-                            'i18n'       => esc_html__('International', 'event_espresso'),
974
-                            'i18n_dns'   => esc_html__('International + DNS Check', 'event_espresso'),
975
-                        ),
976
-                        array(
977
-                            'html_label_text' => esc_html__('Email Validation Level', 'event_espresso')
978
-                                                 . EEH_Template::get_help_tab_link('email_validation_info'),
979
-                            'html_help_text'  => esc_html__('These levels range from basic validation ( ie: [email protected] ) to more advanced checks against international email addresses (ie: üñîçøðé@example.com ) with additional MX and A record checks to confirm the domain actually exists. More information on on each level can be found within the help section.',
980
-                                'event_espresso'),
981
-                            'default'         => isset(EE_Registry::instance()->CFG->registration->email_validation_level)
982
-                                ? EE_Registry::instance()->CFG->registration->email_validation_level
983
-                                : 'wp_default',
984
-                            'required'        => false,
985
-                        )
986
-                    ),
987
-                ),
988
-            )
989
-        );
990
-    }
991
-
992
-
993
-    /**
994
-     * update_email_validation_settings_form
995
-     *
996
-     * @access    public
997
-     * @param \EE_Registration_Config $EE_Registration_Config
998
-     * @return \EE_Registration_Config
999
-     */
1000
-    public function update_email_validation_settings_form(EE_Registration_Config $EE_Registration_Config)
1001
-    {
1002
-        $prev_email_validation_level = $EE_Registration_Config->email_validation_level;
1003
-        try {
1004
-            $email_validation_settings_form = $this->_email_validation_settings_form();
1005
-            // if not displaying a form, then check for form submission
1006
-            if ($email_validation_settings_form->was_submitted()) {
1007
-                // capture form data
1008
-                $email_validation_settings_form->receive_form_submission();
1009
-                // validate form data
1010
-                if ($email_validation_settings_form->is_valid()) {
1011
-                    // grab validated data from form
1012
-                    $valid_data = $email_validation_settings_form->valid_data();
1013
-                    if (isset($valid_data['email_validation_level'])) {
1014
-                        $email_validation_level = $valid_data['email_validation_level'];
1015
-                        // now if they want to use international email addresses
1016
-                        if ($email_validation_level === 'i18n' || $email_validation_level === 'i18n_dns') {
1017
-                            // in case we need to reset their email validation level,
1018
-                            // make sure that the previous value wasn't already set to one of the i18n options.
1019
-                            if ($prev_email_validation_level === 'i18n' || $prev_email_validation_level === 'i18n_dns') {
1020
-                                // if so, then reset it back to "basic" since that is the only other option that,
1021
-                                // despite offering poor validation, supports i18n email addresses
1022
-                                $prev_email_validation_level = 'basic';
1023
-                            }
1024
-                            // confirm our i18n email validation will work on the server
1025
-                            if (! $this->_verify_pcre_support($EE_Registration_Config, $email_validation_level)) {
1026
-                                // or reset email validation level to previous value
1027
-                                $email_validation_level = $prev_email_validation_level;
1028
-                            }
1029
-                        }
1030
-                        $EE_Registration_Config->email_validation_level = $email_validation_level;
1031
-                    } else {
1032
-                        EE_Error::add_error(
1033
-                            esc_html__(
1034
-                                'Invalid or missing Email Validation settings. Please refresh the form and try again.',
1035
-                                'event_espresso'
1036
-                            ),
1037
-                            __FILE__, __FUNCTION__, __LINE__
1038
-                        );
1039
-                    }
1040
-                } else {
1041
-                    if ($email_validation_settings_form->submission_error_message() !== '') {
1042
-                        EE_Error::add_error(
1043
-                            $email_validation_settings_form->submission_error_message(),
1044
-                            __FILE__, __FUNCTION__, __LINE__
1045
-                        );
1046
-                    }
1047
-                }
1048
-            }
1049
-        } catch (EE_Error $e) {
1050
-            $e->get_error();
1051
-        }
1052
-        return $EE_Registration_Config;
1053
-    }
1054
-
1055
-
1056
-    /**
1057
-     * confirms that the server's PHP version has the PCRE module enabled,
1058
-     * and that the PCRE version works with our i18n email validation
1059
-     *
1060
-     * @param \EE_Registration_Config $EE_Registration_Config
1061
-     * @param string                  $email_validation_level
1062
-     * @return bool
1063
-     */
1064
-    private function _verify_pcre_support(EE_Registration_Config $EE_Registration_Config, $email_validation_level)
1065
-    {
1066
-        // first check that PCRE is enabled
1067
-        if (! defined('PREG_BAD_UTF8_ERROR')) {
1068
-            EE_Error::add_error(
1069
-                sprintf(
1070
-                    esc_html__(
1071
-                        'We\'re sorry, but it appears that your server\'s version of PHP was not compiled with PCRE unicode support.%1$sPlease contact your hosting company and ask them whether the PCRE compiled with your version of PHP on your server can be been built with the "--enable-unicode-properties" and "--enable-utf8" configuration switches to enable more complex regex expressions.%1$sIf they are unable, or unwilling to do so, then your server will not support international email addresses using UTF-8 unicode characters. This means you will either have to lower your email validation level to "Basic" or "WordPress Default", or switch to a hosting company that has/can enable PCRE unicode support on the server.',
1072
-                        'event_espresso'
1073
-                    ),
1074
-                    '<br />'
1075
-                ),
1076
-                __FILE__,
1077
-                __FUNCTION__,
1078
-                __LINE__
1079
-            );
1080
-            return false;
1081
-        } else {
1082
-            // PCRE support is enabled, but let's still
1083
-            // perform a test to see if the server will support it.
1084
-            // but first, save the updated validation level to the config,
1085
-            // so that the validation strategy picks it up.
1086
-            // this will get bumped back down if it doesn't work
1087
-            $EE_Registration_Config->email_validation_level = $email_validation_level;
1088
-            try {
1089
-                $email_validator    = new EE_Email_Validation_Strategy();
1090
-                $i18n_email_address = apply_filters(
1091
-                    'FHEE__Extend_Registration_Form_Admin_Page__update_email_validation_settings_form__i18n_email_address',
1092
-                    'jägerjü[email protected]'
1093
-                );
1094
-                $email_validator->validate($i18n_email_address);
1095
-            } catch (Exception $e) {
1096
-                EE_Error::add_error(
1097
-                    sprintf(
1098
-                        esc_html__(
1099
-                            'We\'re sorry, but it appears that your server\'s configuration will not support the "International" or "International + DNS Check" email validation levels.%1$sTo correct this issue, please consult with your hosting company regarding your server\'s PCRE settings.%1$sIt is recommended that your PHP version be configured to use PCRE 8.10 or newer.%1$sMore information regarding PCRE versions and installation can be found here: %2$s',
1100
-                            'event_espresso'
1101
-                        ),
1102
-                        '<br />',
1103
-                        '<a href="http://php.net/manual/en/pcre.installation.php" target="_blank">http://php.net/manual/en/pcre.installation.php</a>'
1104
-                    ),
1105
-                    __FILE__, __FUNCTION__, __LINE__
1106
-                );
1107
-                return false;
1108
-            }
1109
-        }
1110
-        return true;
1111
-    }
28
+	/**
29
+	 * @Constructor
30
+	 * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
31
+	 * @access public
32
+	 */
33
+	public function __construct($routing = true)
34
+	{
35
+		define('REGISTRATION_FORM_CAF_ADMIN', EE_CORE_CAF_ADMIN_EXTEND . 'registration_form' . DS);
36
+		define('REGISTRATION_FORM_CAF_ASSETS_PATH', REGISTRATION_FORM_CAF_ADMIN . 'assets' . DS);
37
+		define('REGISTRATION_FORM_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/assets/');
38
+		define('REGISTRATION_FORM_CAF_TEMPLATE_PATH', REGISTRATION_FORM_CAF_ADMIN . 'templates' . DS);
39
+		define('REGISTRATION_FORM_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/templates/');
40
+		parent::__construct($routing);
41
+	}
42
+
43
+
44
+	protected function _extend_page_config()
45
+	{
46
+		$this->_admin_base_path = REGISTRATION_FORM_CAF_ADMIN;
47
+		$qst_id                 = ! empty($this->_req_data['QST_ID']) && ! is_array($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0;
48
+		$qsg_id                 = ! empty($this->_req_data['QSG_ID']) && ! is_array($this->_req_data['QSG_ID']) ? $this->_req_data['QSG_ID'] : 0;
49
+
50
+		$new_page_routes    = array(
51
+			'question_groups'    => array(
52
+				'func'       => '_question_groups_overview_list_table',
53
+				'capability' => 'ee_read_question_groups',
54
+			),
55
+			'add_question'       => array(
56
+				'func'       => '_edit_question',
57
+				'capability' => 'ee_edit_questions',
58
+			),
59
+			'insert_question'    => array(
60
+				'func'       => '_insert_or_update_question',
61
+				'args'       => array('new_question' => true),
62
+				'capability' => 'ee_edit_questions',
63
+				'noheader'   => true,
64
+			),
65
+			'duplicate_question' => array(
66
+				'func'       => '_duplicate_question',
67
+				'capability' => 'ee_edit_questions',
68
+				'noheader'   => true,
69
+			),
70
+			'trash_question'     => array(
71
+				'func'       => '_trash_question',
72
+				'capability' => 'ee_delete_question',
73
+				'obj_id'     => $qst_id,
74
+				'noheader'   => true,
75
+			),
76
+
77
+			'restore_question' => array(
78
+				'func'       => '_trash_or_restore_questions',
79
+				'capability' => 'ee_delete_question',
80
+				'obj_id'     => $qst_id,
81
+				'args'       => array('trash' => false),
82
+				'noheader'   => true,
83
+			),
84
+
85
+			'delete_question' => array(
86
+				'func'       => '_delete_question',
87
+				'capability' => 'ee_delete_question',
88
+				'obj_id'     => $qst_id,
89
+				'noheader'   => true,
90
+			),
91
+
92
+			'trash_questions' => array(
93
+				'func'       => '_trash_or_restore_questions',
94
+				'capability' => 'ee_delete_questions',
95
+				'args'       => array('trash' => true),
96
+				'noheader'   => true,
97
+			),
98
+
99
+			'restore_questions' => array(
100
+				'func'       => '_trash_or_restore_questions',
101
+				'capability' => 'ee_delete_questions',
102
+				'args'       => array('trash' => false),
103
+				'noheader'   => true,
104
+			),
105
+
106
+			'delete_questions' => array(
107
+				'func'       => '_delete_questions',
108
+				'args'       => array(),
109
+				'capability' => 'ee_delete_questions',
110
+				'noheader'   => true,
111
+			),
112
+
113
+			'add_question_group' => array(
114
+				'func'       => '_edit_question_group',
115
+				'capability' => 'ee_edit_question_groups',
116
+			),
117
+
118
+			'edit_question_group' => array(
119
+				'func'       => '_edit_question_group',
120
+				'capability' => 'ee_edit_question_group',
121
+				'obj_id'     => $qsg_id,
122
+				'args'       => array('edit'),
123
+			),
124
+
125
+			'delete_question_groups' => array(
126
+				'func'       => '_delete_question_groups',
127
+				'capability' => 'ee_delete_question_groups',
128
+				'noheader'   => true,
129
+			),
130
+
131
+			'delete_question_group' => array(
132
+				'func'       => '_delete_question_groups',
133
+				'capability' => 'ee_delete_question_group',
134
+				'obj_id'     => $qsg_id,
135
+				'noheader'   => true,
136
+			),
137
+
138
+			'trash_question_group' => array(
139
+				'func'       => '_trash_or_restore_question_groups',
140
+				'args'       => array('trash' => true),
141
+				'capability' => 'ee_delete_question_group',
142
+				'obj_id'     => $qsg_id,
143
+				'noheader'   => true,
144
+			),
145
+
146
+			'restore_question_group' => array(
147
+				'func'       => '_trash_or_restore_question_groups',
148
+				'args'       => array('trash' => false),
149
+				'capability' => 'ee_delete_question_group',
150
+				'obj_id'     => $qsg_id,
151
+				'noheader'   => true,
152
+			),
153
+
154
+			'insert_question_group' => array(
155
+				'func'       => '_insert_or_update_question_group',
156
+				'args'       => array('new_question_group' => true),
157
+				'capability' => 'ee_edit_question_groups',
158
+				'noheader'   => true,
159
+			),
160
+
161
+			'update_question_group' => array(
162
+				'func'       => '_insert_or_update_question_group',
163
+				'args'       => array('new_question_group' => false),
164
+				'capability' => 'ee_edit_question_group',
165
+				'obj_id'     => $qsg_id,
166
+				'noheader'   => true,
167
+			),
168
+
169
+			'trash_question_groups' => array(
170
+				'func'       => '_trash_or_restore_question_groups',
171
+				'args'       => array('trash' => true),
172
+				'capability' => 'ee_delete_question_groups',
173
+				'noheader'   => array('trash' => false),
174
+			),
175
+
176
+			'restore_question_groups' => array(
177
+				'func'       => '_trash_or_restore_question_groups',
178
+				'args'       => array('trash' => false),
179
+				'capability' => 'ee_delete_question_groups',
180
+				'noheader'   => true,
181
+			),
182
+
183
+
184
+			'espresso_update_question_group_order' => array(
185
+				'func'       => 'update_question_group_order',
186
+				'capability' => 'ee_edit_question_groups',
187
+				'noheader'   => true,
188
+			),
189
+
190
+			'view_reg_form_settings' => array(
191
+				'func'       => '_reg_form_settings',
192
+				'capability' => 'manage_options',
193
+			),
194
+
195
+			'update_reg_form_settings' => array(
196
+				'func'       => '_update_reg_form_settings',
197
+				'capability' => 'manage_options',
198
+				'noheader'   => true,
199
+			),
200
+		);
201
+		$this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
202
+
203
+		$new_page_config    = array(
204
+
205
+			'question_groups' => array(
206
+				'nav'           => array(
207
+					'label' => esc_html__('Question Groups', 'event_espresso'),
208
+					'order' => 20,
209
+				),
210
+				'list_table'    => 'Registration_Form_Question_Groups_Admin_List_Table',
211
+				'help_tabs'     => array(
212
+					'registration_form_question_groups_help_tab'                           => array(
213
+						'title'    => esc_html__('Question Groups', 'event_espresso'),
214
+						'filename' => 'registration_form_question_groups',
215
+					),
216
+					'registration_form_question_groups_table_column_headings_help_tab'     => array(
217
+						'title'    => esc_html__('Question Groups Table Column Headings', 'event_espresso'),
218
+						'filename' => 'registration_form_question_groups_table_column_headings',
219
+					),
220
+					'registration_form_question_groups_views_bulk_actions_search_help_tab' => array(
221
+						'title'    => esc_html__('Question Groups Views & Bulk Actions & Search', 'event_espresso'),
222
+						'filename' => 'registration_form_question_groups_views_bulk_actions_search',
223
+					),
224
+				),
225
+				'help_tour'     => array('Registration_Form_Question_Groups_Help_Tour'),
226
+				'metaboxes'     => $this->_default_espresso_metaboxes,
227
+				'require_nonce' => false,
228
+				'qtips'         => array(
229
+					'EE_Registration_Form_Tips',
230
+				),
231
+			),
232
+
233
+			'add_question' => array(
234
+				'nav'           => array(
235
+					'label'      => esc_html__('Add Question', 'event_espresso'),
236
+					'order'      => 5,
237
+					'persistent' => false,
238
+				),
239
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
240
+				'help_tabs'     => array(
241
+					'registration_form_add_question_help_tab' => array(
242
+						'title'    => esc_html__('Add Question', 'event_espresso'),
243
+						'filename' => 'registration_form_add_question',
244
+					),
245
+				),
246
+				'help_tour'     => array('Registration_Form_Add_Question_Help_Tour'),
247
+				'require_nonce' => false,
248
+			),
249
+
250
+			'add_question_group' => array(
251
+				'nav'           => array(
252
+					'label'      => esc_html__('Add Question Group', 'event_espresso'),
253
+					'order'      => 5,
254
+					'persistent' => false,
255
+				),
256
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
257
+				'help_tabs'     => array(
258
+					'registration_form_add_question_group_help_tab' => array(
259
+						'title'    => esc_html__('Add Question Group', 'event_espresso'),
260
+						'filename' => 'registration_form_add_question_group',
261
+					),
262
+				),
263
+				'help_tour'     => array('Registration_Form_Add_Question_Group_Help_Tour'),
264
+				'require_nonce' => false,
265
+			),
266
+
267
+			'edit_question_group' => array(
268
+				'nav'           => array(
269
+					'label'      => esc_html__('Edit Question Group', 'event_espresso'),
270
+					'order'      => 5,
271
+					'persistent' => false,
272
+					'url'        => isset($this->_req_data['question_group_id']) ? add_query_arg(array('question_group_id' => $this->_req_data['question_group_id']),
273
+						$this->_current_page_view_url) : $this->_admin_base_url,
274
+				),
275
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
276
+				'help_tabs'     => array(
277
+					'registration_form_edit_question_group_help_tab' => array(
278
+						'title'    => esc_html__('Edit Question Group', 'event_espresso'),
279
+						'filename' => 'registration_form_edit_question_group',
280
+					),
281
+				),
282
+				'help_tour'     => array('Registration_Form_Edit_Question_Group_Help_Tour'),
283
+				'require_nonce' => false,
284
+			),
285
+
286
+			'view_reg_form_settings' => array(
287
+				'nav'           => array(
288
+					'label' => esc_html__('Reg Form Settings', 'event_espresso'),
289
+					'order' => 40,
290
+				),
291
+				'labels'        => array(
292
+					'publishbox' => esc_html__('Update Settings', 'event_espresso'),
293
+				),
294
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
295
+				'help_tabs'     => array(
296
+					'registration_form_reg_form_settings_help_tab' => array(
297
+						'title'    => esc_html__('Registration Form Settings', 'event_espresso'),
298
+						'filename' => 'registration_form_reg_form_settings',
299
+					),
300
+				),
301
+				'help_tour'     => array('Registration_Form_Settings_Help_Tour'),
302
+				'require_nonce' => false,
303
+			),
304
+
305
+		);
306
+		$this->_page_config = array_merge($this->_page_config, $new_page_config);
307
+
308
+		//change the list table we're going to use so it's the NEW list table!
309
+		$this->_page_config['default']['list_table'] = 'Extend_Registration_Form_Questions_Admin_List_Table';
310
+
311
+
312
+		//additional labels
313
+		$new_labels               = array(
314
+			'add_question'          => esc_html__('Add New Question', 'event_espresso'),
315
+			'delete_question'       => esc_html__('Delete Question', 'event_espresso'),
316
+			'add_question_group'    => esc_html__('Add New Question Group', 'event_espresso'),
317
+			'edit_question_group'   => esc_html__('Edit Question Group', 'event_espresso'),
318
+			'delete_question_group' => esc_html__('Delete Question Group', 'event_espresso'),
319
+		);
320
+		$this->_labels['buttons'] = array_merge($this->_labels['buttons'], $new_labels);
321
+
322
+	}
323
+
324
+
325
+	protected function _ajax_hooks()
326
+	{
327
+		add_action('wp_ajax_espresso_update_question_group_order', array($this, 'update_question_group_order'));
328
+	}
329
+
330
+
331
+	public function load_scripts_styles_question_groups()
332
+	{
333
+		wp_enqueue_script('espresso_ajax_table_sorting');
334
+	}
335
+
336
+
337
+	public function load_scripts_styles_add_question_group()
338
+	{
339
+		$this->load_scripts_styles_forms();
340
+		$this->load_sortable_question_script();
341
+	}
342
+
343
+	public function load_scripts_styles_edit_question_group()
344
+	{
345
+		$this->load_scripts_styles_forms();
346
+		$this->load_sortable_question_script();
347
+	}
348
+
349
+
350
+	/**
351
+	 * registers and enqueues script for questions
352
+	 *
353
+	 * @return void
354
+	 */
355
+	public function load_sortable_question_script()
356
+	{
357
+		wp_register_script('ee-question-sortable', REGISTRATION_FORM_CAF_ASSETS_URL . 'ee_question_order.js',
358
+			array('jquery-ui-sortable'), EVENT_ESPRESSO_VERSION, true);
359
+		wp_enqueue_script('ee-question-sortable');
360
+	}
361
+
362
+
363
+	protected function _set_list_table_views_default()
364
+	{
365
+		$this->_views = array(
366
+			'all' => array(
367
+				'slug'        => 'all',
368
+				'label'       => esc_html__('View All Questions', 'event_espresso'),
369
+				'count'       => 0,
370
+				'bulk_action' => array(
371
+					'trash_questions' => esc_html__('Trash', 'event_espresso'),
372
+				),
373
+			),
374
+		);
375
+
376
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_questions',
377
+			'espresso_registration_form_trash_questions')
378
+		) {
379
+			$this->_views['trash'] = array(
380
+				'slug'        => 'trash',
381
+				'label'       => esc_html__('Trash', 'event_espresso'),
382
+				'count'       => 0,
383
+				'bulk_action' => array(
384
+					'delete_questions'  => esc_html__('Delete Permanently', 'event_espresso'),
385
+					'restore_questions' => esc_html__('Restore', 'event_espresso'),
386
+				),
387
+			);
388
+		}
389
+	}
390
+
391
+
392
+	protected function _set_list_table_views_question_groups()
393
+	{
394
+		$this->_views = array(
395
+			'all' => array(
396
+				'slug'        => 'all',
397
+				'label'       => esc_html__('All', 'event_espresso'),
398
+				'count'       => 0,
399
+				'bulk_action' => array(
400
+					'trash_question_groups' => esc_html__('Trash', 'event_espresso'),
401
+				),
402
+			),
403
+		);
404
+
405
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_question_groups',
406
+			'espresso_registration_form_trash_question_groups')
407
+		) {
408
+			$this->_views['trash'] = array(
409
+				'slug'        => 'trash',
410
+				'label'       => esc_html__('Trash', 'event_espresso'),
411
+				'count'       => 0,
412
+				'bulk_action' => array(
413
+					'delete_question_groups'  => esc_html__('Delete Permanently', 'event_espresso'),
414
+					'restore_question_groups' => esc_html__('Restore', 'event_espresso'),
415
+				),
416
+			);
417
+		}
418
+	}
419
+
420
+
421
+	protected function _questions_overview_list_table()
422
+	{
423
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
424
+				'add_question',
425
+				'add_question',
426
+				array(),
427
+				'add-new-h2'
428
+			);
429
+		parent::_questions_overview_list_table();
430
+	}
431
+
432
+
433
+	protected function _question_groups_overview_list_table()
434
+	{
435
+		$this->_search_btn_label = esc_html__('Question Groups', 'event_espresso');
436
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
437
+				'add_question_group',
438
+				'add_question_group',
439
+				array(),
440
+				'add-new-h2'
441
+			);
442
+		$this->display_admin_list_table_page_with_sidebar();
443
+	}
444
+
445
+
446
+	protected function _delete_question()
447
+	{
448
+		$success = $this->_delete_items($this->_question_model);
449
+		$this->_redirect_after_action(
450
+			$success,
451
+			$this->_question_model->item_name($success),
452
+			'deleted',
453
+			array('action' => 'default', 'status' => 'all')
454
+		);
455
+	}
456
+
457
+
458
+	protected function _delete_questions()
459
+	{
460
+		$success = $this->_delete_items($this->_question_model);
461
+		$this->_redirect_after_action(
462
+			$success,
463
+			$this->_question_model->item_name($success),
464
+			'deleted permanently',
465
+			array('action' => 'default', 'status' => 'trash')
466
+		);
467
+	}
468
+
469
+
470
+	/**
471
+	 * Performs the deletion of a single or multiple questions or question groups.
472
+	 *
473
+	 * @param EEM_Soft_Delete_Base $model
474
+	 * @return int number of items deleted permanently
475
+	 */
476
+	private function _delete_items(EEM_Soft_Delete_Base $model)
477
+	{
478
+		$success = 0;
479
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
480
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
481
+			// if array has more than one element than success message should be plural
482
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
483
+			// cycle thru bulk action checkboxes
484
+			while (list($ID, $value) = each($this->_req_data['checkbox'])) {
485
+				if (! $this->_delete_item($ID, $model)) {
486
+					$success = 0;
487
+				}
488
+			}
489
+
490
+		} elseif (! empty($this->_req_data['QSG_ID'])) {
491
+			$success = $this->_delete_item($this->_req_data['QSG_ID'], $model);
492
+
493
+		} elseif (! empty($this->_req_data['QST_ID'])) {
494
+			$success = $this->_delete_item($this->_req_data['QST_ID'], $model);
495
+		} else {
496
+			EE_Error::add_error(sprintf(esc_html__("No Questions or Question Groups were selected for deleting. This error usually shows when you've attempted to delete via bulk action but there were no selections.",
497
+				"event_espresso")), __FILE__, __FUNCTION__, __LINE__);
498
+		}
499
+		return $success;
500
+	}
501
+
502
+	/**
503
+	 * Deletes the specified question (and its associated question options) or question group
504
+	 *
505
+	 * @param int                  $id
506
+	 * @param EEM_Soft_Delete_Base $model
507
+	 * @return boolean
508
+	 */
509
+	protected function _delete_item($id, $model)
510
+	{
511
+		if ($model instanceof EEM_Question) {
512
+			EEM_Question_Option::instance()->delete_permanently(array(array('QST_ID' => absint($id))));
513
+		}
514
+		return $model->delete_permanently_by_ID(absint($id));
515
+	}
516
+
517
+
518
+	/******************************    QUESTION GROUPS    ******************************/
519
+
520
+
521
+	protected function _edit_question_group($type = 'add')
522
+	{
523
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
524
+		$ID = isset($this->_req_data['QSG_ID']) && ! empty($this->_req_data['QSG_ID']) ? absint($this->_req_data['QSG_ID']) : false;
525
+
526
+		switch ($this->_req_action) {
527
+			case 'add_question_group' :
528
+				$this->_admin_page_title = esc_html__('Add Question Group', 'event_espresso');
529
+				break;
530
+			case 'edit_question_group' :
531
+				$this->_admin_page_title = esc_html__('Edit Question Group', 'event_espresso');
532
+				break;
533
+			default :
534
+				$this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
535
+		}
536
+		// add ID to title if editing
537
+		$this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
538
+		if ($ID) {
539
+			/** @var EE_Question_Group $questionGroup */
540
+			$questionGroup            = $this->_question_group_model->get_one_by_ID($ID);
541
+			$additional_hidden_fields = array('QSG_ID' => array('type' => 'hidden', 'value' => $ID));
542
+			$this->_set_add_edit_form_tags('update_question_group', $additional_hidden_fields);
543
+		} else {
544
+			/** @var EE_Question_Group $questionGroup */
545
+			$questionGroup = EEM_Question_Group::instance()->create_default_object();
546
+			$questionGroup->set_order_to_latest();
547
+			$this->_set_add_edit_form_tags('insert_question_group');
548
+		}
549
+		$this->_template_args['values']         = $this->_yes_no_values;
550
+		$this->_template_args['all_questions']  = $questionGroup->questions_in_and_not_in_group();
551
+		$this->_template_args['QSG_ID']         = $ID ? $ID : true;
552
+		$this->_template_args['question_group'] = $questionGroup;
553
+
554
+		$redirect_URL = add_query_arg(array('action' => 'question_groups'), $this->_admin_base_url);
555
+		$this->_set_publish_post_box_vars('id', $ID, false, $redirect_URL);
556
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'question_groups_main_meta_box.template.php',
557
+			$this->_template_args, true);
558
+
559
+		// the details template wrapper
560
+		$this->display_admin_page_with_sidebar();
561
+	}
562
+
563
+
564
+	protected function _delete_question_groups()
565
+	{
566
+		$success = $this->_delete_items($this->_question_group_model);
567
+		$this->_redirect_after_action($success, $this->_question_group_model->item_name($success),
568
+			'deleted permanently', array('action' => 'question_groups', 'status' => 'trash'));
569
+	}
570
+
571
+
572
+	/**
573
+	 * @param bool $new_question_group
574
+	 */
575
+	protected function _insert_or_update_question_group($new_question_group = true)
576
+	{
577
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
578
+		$set_column_values = $this->_set_column_values_for($this->_question_group_model);
579
+		if ($new_question_group) {
580
+			$QSG_ID  = $this->_question_group_model->insert($set_column_values);
581
+			$success = $QSG_ID ? 1 : 0;
582
+		} else {
583
+			$QSG_ID = absint($this->_req_data['QSG_ID']);
584
+			unset($set_column_values['QSG_ID']);
585
+			$success = $this->_question_group_model->update($set_column_values, array(array('QSG_ID' => $QSG_ID)));
586
+		}
587
+		$phone_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(EEM_Attendee::system_question_phone);
588
+		// update the existing related questions
589
+		// BUT FIRST...  delete the phone question from the Question_Group_Question if it is being added to this question group (therefore removed from the existing group)
590
+		if (isset($this->_req_data['questions'], $this->_req_data['questions'][$phone_question_id])) {
591
+			// delete where QST ID = system phone question ID and Question Group ID is NOT this group
592
+			EEM_Question_Group_Question::instance()->delete(array(
593
+				array(
594
+					'QST_ID' => $phone_question_id,
595
+					'QSG_ID' => array('!=', $QSG_ID),
596
+				),
597
+			));
598
+		}
599
+		/** @type EE_Question_Group $question_group */
600
+		$question_group = $this->_question_group_model->get_one_by_ID($QSG_ID);
601
+		$questions      = $question_group->questions();
602
+		// make sure system phone question is added to list of questions for this group
603
+		if (! isset($questions[$phone_question_id])) {
604
+			$questions[$phone_question_id] = EEM_Question::instance()->get_one_by_ID($phone_question_id);
605
+		}
606
+
607
+		foreach ($questions as $question_ID => $question) {
608
+			// first we always check for order.
609
+			if (! empty($this->_req_data['question_orders'][$question_ID])) {
610
+				//update question order
611
+				$question_group->update_question_order($question_ID, $this->_req_data['question_orders'][$question_ID]);
612
+			}
613
+
614
+			// then we always check if adding or removing.
615
+			if (isset($this->_req_data['questions'], $this->_req_data['questions'][$question_ID])) {
616
+				$question_group->add_question($question_ID);
617
+			} else {
618
+				// not found, remove it (but only if not a system question for the personal group with the exception of lname system question - we allow removal of it)
619
+				if (
620
+				in_array(
621
+					$question->system_ID(),
622
+					EEM_Question::instance()->required_system_questions_in_system_question_group($question_group->system_group())
623
+				)
624
+				) {
625
+					continue;
626
+				} else {
627
+					$question_group->remove_question($question_ID);
628
+				}
629
+			}
630
+		}
631
+		// save new related questions
632
+		if (isset($this->_req_data['questions'])) {
633
+			foreach ($this->_req_data['questions'] as $QST_ID) {
634
+				$question_group->add_question($QST_ID);
635
+				if (isset($this->_req_data['question_orders'][$QST_ID])) {
636
+					$question_group->update_question_order($QST_ID, $this->_req_data['question_orders'][$QST_ID]);
637
+				}
638
+			}
639
+		}
640
+
641
+		if ($success !== false) {
642
+			$msg = $new_question_group ? sprintf(esc_html__('The %s has been created', 'event_espresso'),
643
+				$this->_question_group_model->item_name()) : sprintf(esc_html__('The %s has been updated',
644
+				'event_espresso'), $this->_question_group_model->item_name());
645
+			EE_Error::add_success($msg);
646
+		}
647
+		$this->_redirect_after_action(false, '', '', array('action' => 'edit_question_group', 'QSG_ID' => $QSG_ID),
648
+			true);
649
+
650
+	}
651
+
652
+	/**
653
+	 * duplicates a question and all its question options and redirects to the new question.
654
+	 */
655
+	public function _duplicate_question()
656
+	{
657
+		$question_ID = (int)$this->_req_data['QST_ID'];
658
+		$question    = EEM_Question::instance()->get_one_by_ID($question_ID);
659
+		if ($question instanceof EE_Question) {
660
+			$new_question = $question->duplicate();
661
+			if ($new_question instanceof EE_Question) {
662
+				$this->_redirect_after_action(true, esc_html__('Question', 'event_espresso'),
663
+					esc_html__('Duplicated', 'event_espresso'),
664
+					array('action' => 'edit_question', 'QST_ID' => $new_question->ID()), true);
665
+			} else {
666
+				global $wpdb;
667
+				EE_Error::add_error(sprintf(esc_html__('Could not duplicate question with ID %1$d because: %2$s',
668
+					'event_espresso'), $question_ID, $wpdb->last_error), __FILE__, __FUNCTION__, __LINE__);
669
+				$this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
670
+			}
671
+		} else {
672
+			EE_Error::add_error(sprintf(esc_html__('Could not duplicate question with ID %d because it didn\'t exist!',
673
+				'event_espresso'), $question_ID), __FILE__, __FUNCTION__, __LINE__);
674
+			$this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
675
+		}
676
+	}
677
+
678
+
679
+	/**
680
+	 * @param bool $trash
681
+	 */
682
+	protected function _trash_or_restore_question_groups($trash = true)
683
+	{
684
+		$this->_trash_or_restore_items($this->_question_group_model, $trash);
685
+	}
686
+
687
+
688
+	/**
689
+	 *_trash_question
690
+	 */
691
+	protected function _trash_question()
692
+	{
693
+		$success    = $this->_question_model->delete_by_ID((int)$this->_req_data['QST_ID']);
694
+		$query_args = array('action' => 'default', 'status' => 'all');
695
+		$this->_redirect_after_action($success, $this->_question_model->item_name($success), 'trashed', $query_args);
696
+	}
697
+
698
+
699
+	/**
700
+	 * @param bool $trash
701
+	 */
702
+	protected function _trash_or_restore_questions($trash = true)
703
+	{
704
+		$this->_trash_or_restore_items($this->_question_model, $trash);
705
+	}
706
+
707
+
708
+	/**
709
+	 * Internally used to delete or restore items, using the request data. Meant to be
710
+	 * flexible between question or question groups
711
+	 *
712
+	 * @param EEM_Soft_Delete_Base $model
713
+	 * @param boolean              $trash whether to trash or restore
714
+	 */
715
+	private function _trash_or_restore_items(EEM_Soft_Delete_Base $model, $trash = true)
716
+	{
717
+
718
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
719
+
720
+		$success = 1;
721
+		//Checkboxes
722
+		//echo "trash $trash";
723
+		//var_dump($this->_req_data['checkbox']);die;
724
+		if (isset($this->_req_data['checkbox'])) {
725
+			if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
726
+				// if array has more than one element than success message should be plural
727
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
728
+				// cycle thru bulk action checkboxes
729
+				while (list($ID, $value) = each($this->_req_data['checkbox'])) {
730
+					if (! $model->delete_or_restore_by_ID($trash, absint($ID))) {
731
+						$success = 0;
732
+					}
733
+				}
734
+
735
+			} else {
736
+				// grab single id and delete
737
+				$ID = absint($this->_req_data['checkbox']);
738
+				if (! $model->delete_or_restore_by_ID($trash, $ID)) {
739
+					$success = 0;
740
+				}
741
+			}
742
+
743
+		} else {
744
+			// delete via trash link
745
+			// grab single id and delete
746
+			$ID = absint($this->_req_data[$model->primary_key_name()]);
747
+			if (! $model->delete_or_restore_by_ID($trash, $ID)) {
748
+				$success = 0;
749
+			}
750
+
751
+		}
752
+
753
+
754
+		$action = $model instanceof EEM_Question ? 'default' : 'question_groups';//strtolower( $model->item_name(2) );
755
+		//echo "action :$action";
756
+		//$action = 'questions' ? 'default' : $action;
757
+		if ($trash) {
758
+			$action_desc = 'trashed';
759
+			$status      = 'trash';
760
+		} else {
761
+			$action_desc = 'restored';
762
+			$status      = 'all';
763
+		}
764
+		$this->_redirect_after_action($success, $model->item_name($success), $action_desc,
765
+			array('action' => $action, 'status' => $status));
766
+	}
767
+
768
+
769
+	/**
770
+	 * @param            $per_page
771
+	 * @param int        $current_page
772
+	 * @param bool|false $count
773
+	 * @return \EE_Soft_Delete_Base_Class[]|int
774
+	 */
775
+	public function get_trashed_questions($per_page, $current_page = 1, $count = false)
776
+	{
777
+		$query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
778
+
779
+		if ($count) {
780
+			//note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
781
+			$where   = isset($query_params[0]) ? array($query_params[0]) : array();
782
+			$results = $this->_question_model->count_deleted($where);
783
+		} else {
784
+			//note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
785
+			$results = $this->_question_model->get_all_deleted($query_params);
786
+		}
787
+		return $results;
788
+	}
789
+
790
+
791
+	/**
792
+	 * @param            $per_page
793
+	 * @param int        $current_page
794
+	 * @param bool|false $count
795
+	 * @return \EE_Soft_Delete_Base_Class[]
796
+	 */
797
+	public function get_question_groups($per_page, $current_page = 1, $count = false)
798
+	{
799
+		$questionGroupModel = EEM_Question_Group::instance();
800
+		$query_params       = $this->get_query_params($questionGroupModel, $per_page, $current_page);
801
+		if ($count) {
802
+			$where   = isset($query_params[0]) ? array($query_params[0]) : array();
803
+			$results = $questionGroupModel->count($where);
804
+		} else {
805
+			$results = $questionGroupModel->get_all($query_params);
806
+		}
807
+		return $results;
808
+	}
809
+
810
+
811
+	/**
812
+	 * @param      $per_page
813
+	 * @param int  $current_page
814
+	 * @param bool $count
815
+	 * @return \EE_Soft_Delete_Base_Class[]|int
816
+	 */
817
+	public function get_trashed_question_groups($per_page, $current_page = 1, $count = false)
818
+	{
819
+		$questionGroupModel = EEM_Question_Group::instance();
820
+		$query_params       = $this->get_query_params($questionGroupModel, $per_page, $current_page);
821
+		if ($count) {
822
+			$where                 = isset($query_params[0]) ? array($query_params[0]) : array();
823
+			$query_params['limit'] = null;
824
+			$results               = $questionGroupModel->count_deleted($where);
825
+		} else {
826
+			$results = $questionGroupModel->get_all_deleted($query_params);
827
+		}
828
+		return $results;
829
+	}
830
+
831
+
832
+	/**
833
+	 * method for performing updates to question order
834
+	 *
835
+	 * @return array results array
836
+	 */
837
+	public function update_question_group_order()
838
+	{
839
+
840
+		$success = esc_html__('Question group order was updated successfully.', 'event_espresso');
841
+
842
+		// grab our row IDs
843
+		$row_ids = isset($this->_req_data['row_ids']) && ! empty($this->_req_data['row_ids'])
844
+			? explode(',', rtrim($this->_req_data['row_ids'], ','))
845
+			: array();
846
+
847
+		$perpage = ! empty($this->_req_data['perpage'])
848
+			? (int)$this->_req_data['perpage']
849
+			: null;
850
+		$curpage = ! empty($this->_req_data['curpage'])
851
+			? (int)$this->_req_data['curpage']
852
+			: null;
853
+
854
+		if (! empty($row_ids)) {
855
+			//figure out where we start the row_id count at for the current page.
856
+			$qsgcount = empty($curpage) ? 0 : ($curpage - 1) * $perpage;
857
+
858
+			$row_count = count($row_ids);
859
+			for ($i = 0; $i < $row_count; $i++) {
860
+				//Update the questions when re-ordering
861
+				$updated = EEM_Question_Group::instance()->update(
862
+					array('QSG_order' => $qsgcount),
863
+					array(array('QSG_ID' => $row_ids[$i]))
864
+				);
865
+				if ($updated === false) {
866
+					$success = false;
867
+				}
868
+				$qsgcount++;
869
+			}
870
+		} else {
871
+			$success = false;
872
+		}
873
+
874
+		$errors = ! $success
875
+			? esc_html__('An error occurred. The question group order was not updated.', 'event_espresso')
876
+			: false;
877
+
878
+		echo wp_json_encode(array('return_data' => false, 'success' => $success, 'errors' => $errors));
879
+		die();
880
+
881
+	}
882
+
883
+
884
+
885
+	/***************************************        REGISTRATION SETTINGS        ***************************************/
886
+
887
+
888
+	/**
889
+	 * _reg_form_settings
890
+	 *
891
+	 * @throws \EE_Error
892
+	 */
893
+	protected function _reg_form_settings()
894
+	{
895
+		$this->_template_args['values'] = $this->_yes_no_values;
896
+		add_action(
897
+			'AHEE__Extend_Registration_Form_Admin_Page___reg_form_settings_template',
898
+			array($this, 'email_validation_settings_form'),
899
+			2
900
+		);
901
+		$this->_template_args = (array)apply_filters(
902
+			'FHEE__Extend_Registration_Form_Admin_Page___reg_form_settings___template_args',
903
+			$this->_template_args
904
+		);
905
+		$this->_set_add_edit_form_tags('update_reg_form_settings');
906
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
907
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
908
+			REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'reg_form_settings.template.php',
909
+			$this->_template_args,
910
+			true
911
+		);
912
+		$this->display_admin_page_with_sidebar();
913
+	}
914
+
915
+
916
+	/**
917
+	 * _update_reg_form_settings
918
+	 */
919
+	protected function _update_reg_form_settings()
920
+	{
921
+		EE_Registry::instance()->CFG->registration = $this->update_email_validation_settings_form(
922
+			EE_Registry::instance()->CFG->registration
923
+		);
924
+		EE_Registry::instance()->CFG->registration = apply_filters(
925
+			'FHEE__Extend_Registration_Form_Admin_Page___update_reg_form_settings__CFG_registration',
926
+			EE_Registry::instance()->CFG->registration
927
+		);
928
+		$success                                   = $this->_update_espresso_configuration(
929
+			esc_html__('Registration Form Options', 'event_espresso'),
930
+			EE_Registry::instance()->CFG,
931
+			__FILE__, __FUNCTION__, __LINE__
932
+		);
933
+		$this->_redirect_after_action($success, esc_html__('Registration Form Options', 'event_espresso'), 'updated',
934
+			array('action' => 'view_reg_form_settings'));
935
+	}
936
+
937
+
938
+	/**
939
+	 * email_validation_settings_form
940
+	 *
941
+	 * @access    public
942
+	 * @return    void
943
+	 * @throws \EE_Error
944
+	 */
945
+	public function email_validation_settings_form()
946
+	{
947
+		echo $this->_email_validation_settings_form()->get_html();
948
+	}
949
+
950
+
951
+	/**
952
+	 * _email_validation_settings_form
953
+	 *
954
+	 * @access protected
955
+	 * @return EE_Form_Section_Proper
956
+	 * @throws \EE_Error
957
+	 */
958
+	protected function _email_validation_settings_form()
959
+	{
960
+		return new EE_Form_Section_Proper(
961
+			array(
962
+				'name'            => 'email_validation_settings',
963
+				'html_id'         => 'email_validation_settings',
964
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
965
+				'subsections'     => array(
966
+					'email_validation_hdr'   => new EE_Form_Section_HTML(
967
+						EEH_HTML::h2(esc_html__('Email Validation Settings', 'event_espresso'))
968
+					),
969
+					'email_validation_level' => new EE_Select_Input(
970
+						array(
971
+							'basic'      => esc_html__('Basic', 'event_espresso'),
972
+							'wp_default' => esc_html__('WordPress Default', 'event_espresso'),
973
+							'i18n'       => esc_html__('International', 'event_espresso'),
974
+							'i18n_dns'   => esc_html__('International + DNS Check', 'event_espresso'),
975
+						),
976
+						array(
977
+							'html_label_text' => esc_html__('Email Validation Level', 'event_espresso')
978
+												 . EEH_Template::get_help_tab_link('email_validation_info'),
979
+							'html_help_text'  => esc_html__('These levels range from basic validation ( ie: [email protected] ) to more advanced checks against international email addresses (ie: üñîçøðé@example.com ) with additional MX and A record checks to confirm the domain actually exists. More information on on each level can be found within the help section.',
980
+								'event_espresso'),
981
+							'default'         => isset(EE_Registry::instance()->CFG->registration->email_validation_level)
982
+								? EE_Registry::instance()->CFG->registration->email_validation_level
983
+								: 'wp_default',
984
+							'required'        => false,
985
+						)
986
+					),
987
+				),
988
+			)
989
+		);
990
+	}
991
+
992
+
993
+	/**
994
+	 * update_email_validation_settings_form
995
+	 *
996
+	 * @access    public
997
+	 * @param \EE_Registration_Config $EE_Registration_Config
998
+	 * @return \EE_Registration_Config
999
+	 */
1000
+	public function update_email_validation_settings_form(EE_Registration_Config $EE_Registration_Config)
1001
+	{
1002
+		$prev_email_validation_level = $EE_Registration_Config->email_validation_level;
1003
+		try {
1004
+			$email_validation_settings_form = $this->_email_validation_settings_form();
1005
+			// if not displaying a form, then check for form submission
1006
+			if ($email_validation_settings_form->was_submitted()) {
1007
+				// capture form data
1008
+				$email_validation_settings_form->receive_form_submission();
1009
+				// validate form data
1010
+				if ($email_validation_settings_form->is_valid()) {
1011
+					// grab validated data from form
1012
+					$valid_data = $email_validation_settings_form->valid_data();
1013
+					if (isset($valid_data['email_validation_level'])) {
1014
+						$email_validation_level = $valid_data['email_validation_level'];
1015
+						// now if they want to use international email addresses
1016
+						if ($email_validation_level === 'i18n' || $email_validation_level === 'i18n_dns') {
1017
+							// in case we need to reset their email validation level,
1018
+							// make sure that the previous value wasn't already set to one of the i18n options.
1019
+							if ($prev_email_validation_level === 'i18n' || $prev_email_validation_level === 'i18n_dns') {
1020
+								// if so, then reset it back to "basic" since that is the only other option that,
1021
+								// despite offering poor validation, supports i18n email addresses
1022
+								$prev_email_validation_level = 'basic';
1023
+							}
1024
+							// confirm our i18n email validation will work on the server
1025
+							if (! $this->_verify_pcre_support($EE_Registration_Config, $email_validation_level)) {
1026
+								// or reset email validation level to previous value
1027
+								$email_validation_level = $prev_email_validation_level;
1028
+							}
1029
+						}
1030
+						$EE_Registration_Config->email_validation_level = $email_validation_level;
1031
+					} else {
1032
+						EE_Error::add_error(
1033
+							esc_html__(
1034
+								'Invalid or missing Email Validation settings. Please refresh the form and try again.',
1035
+								'event_espresso'
1036
+							),
1037
+							__FILE__, __FUNCTION__, __LINE__
1038
+						);
1039
+					}
1040
+				} else {
1041
+					if ($email_validation_settings_form->submission_error_message() !== '') {
1042
+						EE_Error::add_error(
1043
+							$email_validation_settings_form->submission_error_message(),
1044
+							__FILE__, __FUNCTION__, __LINE__
1045
+						);
1046
+					}
1047
+				}
1048
+			}
1049
+		} catch (EE_Error $e) {
1050
+			$e->get_error();
1051
+		}
1052
+		return $EE_Registration_Config;
1053
+	}
1054
+
1055
+
1056
+	/**
1057
+	 * confirms that the server's PHP version has the PCRE module enabled,
1058
+	 * and that the PCRE version works with our i18n email validation
1059
+	 *
1060
+	 * @param \EE_Registration_Config $EE_Registration_Config
1061
+	 * @param string                  $email_validation_level
1062
+	 * @return bool
1063
+	 */
1064
+	private function _verify_pcre_support(EE_Registration_Config $EE_Registration_Config, $email_validation_level)
1065
+	{
1066
+		// first check that PCRE is enabled
1067
+		if (! defined('PREG_BAD_UTF8_ERROR')) {
1068
+			EE_Error::add_error(
1069
+				sprintf(
1070
+					esc_html__(
1071
+						'We\'re sorry, but it appears that your server\'s version of PHP was not compiled with PCRE unicode support.%1$sPlease contact your hosting company and ask them whether the PCRE compiled with your version of PHP on your server can be been built with the "--enable-unicode-properties" and "--enable-utf8" configuration switches to enable more complex regex expressions.%1$sIf they are unable, or unwilling to do so, then your server will not support international email addresses using UTF-8 unicode characters. This means you will either have to lower your email validation level to "Basic" or "WordPress Default", or switch to a hosting company that has/can enable PCRE unicode support on the server.',
1072
+						'event_espresso'
1073
+					),
1074
+					'<br />'
1075
+				),
1076
+				__FILE__,
1077
+				__FUNCTION__,
1078
+				__LINE__
1079
+			);
1080
+			return false;
1081
+		} else {
1082
+			// PCRE support is enabled, but let's still
1083
+			// perform a test to see if the server will support it.
1084
+			// but first, save the updated validation level to the config,
1085
+			// so that the validation strategy picks it up.
1086
+			// this will get bumped back down if it doesn't work
1087
+			$EE_Registration_Config->email_validation_level = $email_validation_level;
1088
+			try {
1089
+				$email_validator    = new EE_Email_Validation_Strategy();
1090
+				$i18n_email_address = apply_filters(
1091
+					'FHEE__Extend_Registration_Form_Admin_Page__update_email_validation_settings_form__i18n_email_address',
1092
+					'jägerjü[email protected]'
1093
+				);
1094
+				$email_validator->validate($i18n_email_address);
1095
+			} catch (Exception $e) {
1096
+				EE_Error::add_error(
1097
+					sprintf(
1098
+						esc_html__(
1099
+							'We\'re sorry, but it appears that your server\'s configuration will not support the "International" or "International + DNS Check" email validation levels.%1$sTo correct this issue, please consult with your hosting company regarding your server\'s PCRE settings.%1$sIt is recommended that your PHP version be configured to use PCRE 8.10 or newer.%1$sMore information regarding PCRE versions and installation can be found here: %2$s',
1100
+							'event_espresso'
1101
+						),
1102
+						'<br />',
1103
+						'<a href="http://php.net/manual/en/pcre.installation.php" target="_blank">http://php.net/manual/en/pcre.installation.php</a>'
1104
+					),
1105
+					__FILE__, __FUNCTION__, __LINE__
1106
+				);
1107
+				return false;
1108
+			}
1109
+		}
1110
+		return true;
1111
+	}
1112 1112
 
1113 1113
 
1114 1114
 }
Please login to merge, or discard this patch.
Spacing   +34 added lines, -34 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
 
@@ -32,11 +32,11 @@  discard block
 block discarded – undo
32 32
      */
33 33
     public function __construct($routing = true)
34 34
     {
35
-        define('REGISTRATION_FORM_CAF_ADMIN', EE_CORE_CAF_ADMIN_EXTEND . 'registration_form' . DS);
36
-        define('REGISTRATION_FORM_CAF_ASSETS_PATH', REGISTRATION_FORM_CAF_ADMIN . 'assets' . DS);
37
-        define('REGISTRATION_FORM_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/assets/');
38
-        define('REGISTRATION_FORM_CAF_TEMPLATE_PATH', REGISTRATION_FORM_CAF_ADMIN . 'templates' . DS);
39
-        define('REGISTRATION_FORM_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/templates/');
35
+        define('REGISTRATION_FORM_CAF_ADMIN', EE_CORE_CAF_ADMIN_EXTEND.'registration_form'.DS);
36
+        define('REGISTRATION_FORM_CAF_ASSETS_PATH', REGISTRATION_FORM_CAF_ADMIN.'assets'.DS);
37
+        define('REGISTRATION_FORM_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL.'registration_form/assets/');
38
+        define('REGISTRATION_FORM_CAF_TEMPLATE_PATH', REGISTRATION_FORM_CAF_ADMIN.'templates'.DS);
39
+        define('REGISTRATION_FORM_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL.'registration_form/templates/');
40 40
         parent::__construct($routing);
41 41
     }
42 42
 
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
         $qst_id                 = ! empty($this->_req_data['QST_ID']) && ! is_array($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0;
48 48
         $qsg_id                 = ! empty($this->_req_data['QSG_ID']) && ! is_array($this->_req_data['QSG_ID']) ? $this->_req_data['QSG_ID'] : 0;
49 49
 
50
-        $new_page_routes    = array(
50
+        $new_page_routes = array(
51 51
             'question_groups'    => array(
52 52
                 'func'       => '_question_groups_overview_list_table',
53 53
                 'capability' => 'ee_read_question_groups',
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 
311 311
 
312 312
         //additional labels
313
-        $new_labels               = array(
313
+        $new_labels = array(
314 314
             'add_question'          => esc_html__('Add New Question', 'event_espresso'),
315 315
             'delete_question'       => esc_html__('Delete Question', 'event_espresso'),
316 316
             'add_question_group'    => esc_html__('Add New Question Group', 'event_espresso'),
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
      */
355 355
     public function load_sortable_question_script()
356 356
     {
357
-        wp_register_script('ee-question-sortable', REGISTRATION_FORM_CAF_ASSETS_URL . 'ee_question_order.js',
357
+        wp_register_script('ee-question-sortable', REGISTRATION_FORM_CAF_ASSETS_URL.'ee_question_order.js',
358 358
             array('jquery-ui-sortable'), EVENT_ESPRESSO_VERSION, true);
359 359
         wp_enqueue_script('ee-question-sortable');
360 360
     }
@@ -420,7 +420,7 @@  discard block
 block discarded – undo
420 420
 
421 421
     protected function _questions_overview_list_table()
422 422
     {
423
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
423
+        $this->_admin_page_title .= ' '.$this->get_action_link_or_button(
424 424
                 'add_question',
425 425
                 'add_question',
426 426
                 array(),
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
     protected function _question_groups_overview_list_table()
434 434
     {
435 435
         $this->_search_btn_label = esc_html__('Question Groups', 'event_espresso');
436
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
436
+        $this->_admin_page_title .= ' '.$this->get_action_link_or_button(
437 437
                 'add_question_group',
438 438
                 'add_question_group',
439 439
                 array(),
@@ -477,20 +477,20 @@  discard block
 block discarded – undo
477 477
     {
478 478
         $success = 0;
479 479
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
480
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
480
+        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
481 481
             // if array has more than one element than success message should be plural
482 482
             $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
483 483
             // cycle thru bulk action checkboxes
484 484
             while (list($ID, $value) = each($this->_req_data['checkbox'])) {
485
-                if (! $this->_delete_item($ID, $model)) {
485
+                if ( ! $this->_delete_item($ID, $model)) {
486 486
                     $success = 0;
487 487
                 }
488 488
             }
489 489
 
490
-        } elseif (! empty($this->_req_data['QSG_ID'])) {
490
+        } elseif ( ! empty($this->_req_data['QSG_ID'])) {
491 491
             $success = $this->_delete_item($this->_req_data['QSG_ID'], $model);
492 492
 
493
-        } elseif (! empty($this->_req_data['QST_ID'])) {
493
+        } elseif ( ! empty($this->_req_data['QST_ID'])) {
494 494
             $success = $this->_delete_item($this->_req_data['QST_ID'], $model);
495 495
         } else {
496 496
             EE_Error::add_error(sprintf(esc_html__("No Questions or Question Groups were selected for deleting. This error usually shows when you've attempted to delete via bulk action but there were no selections.",
@@ -534,7 +534,7 @@  discard block
 block discarded – undo
534 534
                 $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
535 535
         }
536 536
         // add ID to title if editing
537
-        $this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
537
+        $this->_admin_page_title = $ID ? $this->_admin_page_title.' # '.$ID : $this->_admin_page_title;
538 538
         if ($ID) {
539 539
             /** @var EE_Question_Group $questionGroup */
540 540
             $questionGroup            = $this->_question_group_model->get_one_by_ID($ID);
@@ -553,7 +553,7 @@  discard block
 block discarded – undo
553 553
 
554 554
         $redirect_URL = add_query_arg(array('action' => 'question_groups'), $this->_admin_base_url);
555 555
         $this->_set_publish_post_box_vars('id', $ID, false, $redirect_URL);
556
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'question_groups_main_meta_box.template.php',
556
+        $this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_CAF_TEMPLATE_PATH.'question_groups_main_meta_box.template.php',
557 557
             $this->_template_args, true);
558 558
 
559 559
         // the details template wrapper
@@ -600,13 +600,13 @@  discard block
 block discarded – undo
600 600
         $question_group = $this->_question_group_model->get_one_by_ID($QSG_ID);
601 601
         $questions      = $question_group->questions();
602 602
         // make sure system phone question is added to list of questions for this group
603
-        if (! isset($questions[$phone_question_id])) {
603
+        if ( ! isset($questions[$phone_question_id])) {
604 604
             $questions[$phone_question_id] = EEM_Question::instance()->get_one_by_ID($phone_question_id);
605 605
         }
606 606
 
607 607
         foreach ($questions as $question_ID => $question) {
608 608
             // first we always check for order.
609
-            if (! empty($this->_req_data['question_orders'][$question_ID])) {
609
+            if ( ! empty($this->_req_data['question_orders'][$question_ID])) {
610 610
                 //update question order
611 611
                 $question_group->update_question_order($question_ID, $this->_req_data['question_orders'][$question_ID]);
612 612
             }
@@ -654,7 +654,7 @@  discard block
 block discarded – undo
654 654
      */
655 655
     public function _duplicate_question()
656 656
     {
657
-        $question_ID = (int)$this->_req_data['QST_ID'];
657
+        $question_ID = (int) $this->_req_data['QST_ID'];
658 658
         $question    = EEM_Question::instance()->get_one_by_ID($question_ID);
659 659
         if ($question instanceof EE_Question) {
660 660
             $new_question = $question->duplicate();
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
      */
691 691
     protected function _trash_question()
692 692
     {
693
-        $success    = $this->_question_model->delete_by_ID((int)$this->_req_data['QST_ID']);
693
+        $success    = $this->_question_model->delete_by_ID((int) $this->_req_data['QST_ID']);
694 694
         $query_args = array('action' => 'default', 'status' => 'all');
695 695
         $this->_redirect_after_action($success, $this->_question_model->item_name($success), 'trashed', $query_args);
696 696
     }
@@ -722,12 +722,12 @@  discard block
 block discarded – undo
722 722
         //echo "trash $trash";
723 723
         //var_dump($this->_req_data['checkbox']);die;
724 724
         if (isset($this->_req_data['checkbox'])) {
725
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
725
+            if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
726 726
                 // if array has more than one element than success message should be plural
727 727
                 $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
728 728
                 // cycle thru bulk action checkboxes
729 729
                 while (list($ID, $value) = each($this->_req_data['checkbox'])) {
730
-                    if (! $model->delete_or_restore_by_ID($trash, absint($ID))) {
730
+                    if ( ! $model->delete_or_restore_by_ID($trash, absint($ID))) {
731 731
                         $success = 0;
732 732
                     }
733 733
                 }
@@ -735,7 +735,7 @@  discard block
 block discarded – undo
735 735
             } else {
736 736
                 // grab single id and delete
737 737
                 $ID = absint($this->_req_data['checkbox']);
738
-                if (! $model->delete_or_restore_by_ID($trash, $ID)) {
738
+                if ( ! $model->delete_or_restore_by_ID($trash, $ID)) {
739 739
                     $success = 0;
740 740
                 }
741 741
             }
@@ -744,14 +744,14 @@  discard block
 block discarded – undo
744 744
             // delete via trash link
745 745
             // grab single id and delete
746 746
             $ID = absint($this->_req_data[$model->primary_key_name()]);
747
-            if (! $model->delete_or_restore_by_ID($trash, $ID)) {
747
+            if ( ! $model->delete_or_restore_by_ID($trash, $ID)) {
748 748
                 $success = 0;
749 749
             }
750 750
 
751 751
         }
752 752
 
753 753
 
754
-        $action = $model instanceof EEM_Question ? 'default' : 'question_groups';//strtolower( $model->item_name(2) );
754
+        $action = $model instanceof EEM_Question ? 'default' : 'question_groups'; //strtolower( $model->item_name(2) );
755 755
         //echo "action :$action";
756 756
         //$action = 'questions' ? 'default' : $action;
757 757
         if ($trash) {
@@ -845,13 +845,13 @@  discard block
 block discarded – undo
845 845
             : array();
846 846
 
847 847
         $perpage = ! empty($this->_req_data['perpage'])
848
-            ? (int)$this->_req_data['perpage']
848
+            ? (int) $this->_req_data['perpage']
849 849
             : null;
850 850
         $curpage = ! empty($this->_req_data['curpage'])
851
-            ? (int)$this->_req_data['curpage']
851
+            ? (int) $this->_req_data['curpage']
852 852
             : null;
853 853
 
854
-        if (! empty($row_ids)) {
854
+        if ( ! empty($row_ids)) {
855 855
             //figure out where we start the row_id count at for the current page.
856 856
             $qsgcount = empty($curpage) ? 0 : ($curpage - 1) * $perpage;
857 857
 
@@ -898,14 +898,14 @@  discard block
 block discarded – undo
898 898
             array($this, 'email_validation_settings_form'),
899 899
             2
900 900
         );
901
-        $this->_template_args = (array)apply_filters(
901
+        $this->_template_args = (array) apply_filters(
902 902
             'FHEE__Extend_Registration_Form_Admin_Page___reg_form_settings___template_args',
903 903
             $this->_template_args
904 904
         );
905 905
         $this->_set_add_edit_form_tags('update_reg_form_settings');
906 906
         $this->_set_publish_post_box_vars(null, false, false, null, false);
907 907
         $this->_template_args['admin_page_content'] = EEH_Template::display_template(
908
-            REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'reg_form_settings.template.php',
908
+            REGISTRATION_FORM_CAF_TEMPLATE_PATH.'reg_form_settings.template.php',
909 909
             $this->_template_args,
910 910
             true
911 911
         );
@@ -925,7 +925,7 @@  discard block
 block discarded – undo
925 925
             'FHEE__Extend_Registration_Form_Admin_Page___update_reg_form_settings__CFG_registration',
926 926
             EE_Registry::instance()->CFG->registration
927 927
         );
928
-        $success                                   = $this->_update_espresso_configuration(
928
+        $success = $this->_update_espresso_configuration(
929 929
             esc_html__('Registration Form Options', 'event_espresso'),
930 930
             EE_Registry::instance()->CFG,
931 931
             __FILE__, __FUNCTION__, __LINE__
@@ -1022,7 +1022,7 @@  discard block
 block discarded – undo
1022 1022
                                 $prev_email_validation_level = 'basic';
1023 1023
                             }
1024 1024
                             // confirm our i18n email validation will work on the server
1025
-                            if (! $this->_verify_pcre_support($EE_Registration_Config, $email_validation_level)) {
1025
+                            if ( ! $this->_verify_pcre_support($EE_Registration_Config, $email_validation_level)) {
1026 1026
                                 // or reset email validation level to previous value
1027 1027
                                 $email_validation_level = $prev_email_validation_level;
1028 1028
                             }
@@ -1064,7 +1064,7 @@  discard block
 block discarded – undo
1064 1064
     private function _verify_pcre_support(EE_Registration_Config $EE_Registration_Config, $email_validation_level)
1065 1065
     {
1066 1066
         // first check that PCRE is enabled
1067
-        if (! defined('PREG_BAD_UTF8_ERROR')) {
1067
+        if ( ! defined('PREG_BAD_UTF8_ERROR')) {
1068 1068
             EE_Error::add_error(
1069 1069
                 sprintf(
1070 1070
                     esc_html__(
Please login to merge, or discard this patch.
admin_pages/registration_form/Registration_Form_Admin_Page.core.php 2 patches
Indentation   +624 added lines, -624 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,580 +28,580 @@  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 Caffeinated version of Event Espresso.  With the Question Groups feature you are able to: create new question groups, edit existing question groups, and also 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 Caffeinated version of Event Espresso.  With the Question Groups feature you are able to: create new question groups, edit existing question groups, and also 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
-        $question_types                                     = $question->has_answers() ? $this->_question_model->question_types_in_same_category($question->type()) : $this->_question_model->allowed_question_types();
434
-        $this->_template_args['QST_ID']                     = $ID;
435
-        $this->_template_args['question']                   = $question;
436
-        $this->_template_args['question_types']             = $question_types;
437
-        $this->_template_args['max_max']                    = EEM_Question::instance()->absolute_max_for_system_question($question->system_ID());
438
-        $this->_template_args['question_type_descriptions'] = $this->_get_question_type_descriptions();
439
-        $this->_set_publish_post_box_vars('id', $ID);
440
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_TEMPLATE_PATH . 'questions_main_meta_box.template.php',
441
-            $this->_template_args, true);
442
-
443
-        // the details template wrapper
444
-        $this->display_admin_page_with_sidebar();
445
-    }
446
-
447
-
448
-    /**
449
-     * @return string
450
-     */
451
-    protected function _get_question_type_descriptions()
452
-    {
453
-        EE_Registry::instance()->load_helper('HTML');
454
-        $descriptions               = '';
455
-        $question_type_descriptions = EEM_Question::instance()->question_descriptions();
456
-        foreach ($question_type_descriptions as $type => $question_type_description) {
457
-            if ($type == 'HTML_TEXTAREA') {
458
-                $html = new EE_Simple_HTML_Validation_Strategy();
459
-                $question_type_description .= sprintf(
460
-                    esc_html__('%1$s(allowed tags: %2$s)', 'event_espresso'),
461
-                    '<br/>',
462
-                    $html->get_list_of_allowed_tags()
463
-                );
464
-            }
465
-            $descriptions .= EEH_HTML::p(
466
-                $question_type_description,
467
-                'question_type_description-' . $type,
468
-                'question_type_description description',
469
-                'display:none;'
470
-            );
471
-        }
472
-        return $descriptions;
473
-    }
474
-
475
-
476
-    /**
477
-     * @param bool|true $new_question
478
-     * @throws \EE_Error
479
-     */
480
-    protected function _insert_or_update_question($new_question = true)
481
-    {
482
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
483
-        $set_column_values = $this->_set_column_values_for($this->_question_model);
484
-        if ($new_question) {
485
-            $ID          = $this->_question_model->insert($set_column_values);
486
-            $success     = $ID ? true : false;
487
-            $action_desc = 'added';
488
-        } else {
489
-            $ID     = absint($this->_req_data['QST_ID']);
490
-            $pk     = $this->_question_model->primary_key_name();
491
-            $wheres = array($pk => $ID);
492
-            unset($set_column_values[$pk]);
493
-            $success     = $this->_question_model->update($set_column_values, array($wheres));
494
-            $action_desc = 'updated';
495
-        }
496
-
497
-        if ($ID) {
498
-            //save the related options
499
-            //trash removed options, save old ones
500
-            //get list of all options
501
-            /** @type EE_Question $question */
502
-            $question = $this->_question_model->get_one_by_ID($ID);
503
-            $options  = $question->options();
504
-            if (! empty($options)) {
505
-                foreach ($options as $option_ID => $option) {
506
-                    $option_req_index = $this->_get_option_req_data_index($option_ID);
507
-                    if ($option_req_index !== false) {
508
-                        $option->save($this->_req_data['question_options'][$option_req_index]);
509
-                    } else {
510
-                        //not found, remove it
511
-                        $option->delete();
512
-                    }
513
-                }
514
-            }
515
-            //save new related options
516
-            foreach ($this->_req_data['question_options'] as $index => $option_req_data) {
517
-                if (empty($option_req_data['QSO_ID']) && ((isset($option_req_data['QSO_value']) && $option_req_data['QSO_value'] !== '') || ! empty($option_req_data['QSO_desc']))) {//no ID! save it!
518
-                    if (! isset($option_req_data['QSO_value']) || $option_req_data['QSO_value'] === '') {
519
-                        $option_req_data['QSO_value'] = $option_req_data['QSO_desc'];
520
-                    }
521
-                    $new_option = EE_Question_Option::new_instance(array(
522
-                        'QSO_value' => $option_req_data['QSO_value'],
523
-                        'QSO_desc'  => $option_req_data['QSO_desc'],
524
-                        'QSO_order' => $option_req_data['QSO_order'],
525
-                        'QST_ID'    => $question->ID(),
526
-                    ));
527
-                    $new_option->save();
528
-                }
529
-            }
530
-        }
531
-        $query_args = array('action' => 'edit_question', 'QST_ID' => $ID);
532
-        if ($success !== false) {
533
-            $msg = $new_question ? sprintf(esc_html__('The %s has been created', 'event_espresso'),
534
-                $this->_question_model->item_name()) : sprintf(esc_html__('The %s has been updated', 'event_espresso'),
535
-                $this->_question_model->item_name());
536
-            EE_Error::add_success($msg);
537
-        }
538
-
539
-        $this->_redirect_after_action(false, '', $action_desc, $query_args, true);
540
-    }
541
-
542
-
543
-    /**
544
-     * Upon saving a question, there should be an array of 'question_options'. This array is index numerically, but not
545
-     * by ID
546
-     * (this is done because new question options don't have an ID, but we may want to add multiple simultaneously).
547
-     * So, this function gets the index in that request data array called question_options. Returns FALSE if not found.
548
-     *
549
-     * @param int $ID of the question option to find
550
-     * @return int index in question_options array if successful, FALSE if unsuccessful
551
-     */
552
-    protected function _get_option_req_data_index($ID)
553
-    {
554
-        $req_data_for_question_options = $this->_req_data['question_options'];
555
-        foreach ($req_data_for_question_options as $num => $option_data) {
556
-            if (array_key_exists('QSO_ID', $option_data) && (int)$option_data['QSO_ID'] === $ID) {
557
-                return $num;
558
-            }
559
-        }
560
-        return false;
561
-    }
562
-
563
-
564
-
565
-
566
-    /***********/
567
-    /* QUERIES */
568
-    /**
569
-     * For internal use in getting all the query parameters
570
-     * (because it's pretty well the same between question, question groups,
571
-     * and for both when searching for trashed and untrashed ones)
572
-     *
573
-     * @param EEM_Base $model either EEM_Question or EEM_Question_Group
574
-     * @param int      $per_page
575
-     * @param int      $current_page
576
-     * @return array lik EEM_Base::get_all's $query_params parameter
577
-     */
578
-    protected function get_query_params($model, $per_page = 10, $current_page = 10)
579
-    {
580
-        $query_params             = array();
581
-        $offset                   = ($current_page - 1) * $per_page;
582
-        $query_params['limit']    = array($offset, $per_page);
583
-        $order                    = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'ASC';
584
-        $orderby_field            = $model instanceof EEM_Question ? 'QST_ID' : 'QSG_order';
585
-        $field_to_order_by        = empty($this->_req_data['orderby']) ? $orderby_field : $this->_req_data['orderby'];
586
-        $query_params['order_by'] = array($field_to_order_by => $order);
587
-        $search_string            = array_key_exists('s', $this->_req_data) ? $this->_req_data['s'] : null;
588
-        if (! empty($search_string)) {
589
-            if ($model instanceof EEM_Question_Group) {
590
-                $query_params[0] = array(
591
-                    'OR' => array(
592
-                        'QSG_name' => array('LIKE', "%$search_string%"),
593
-                        'QSG_desc' => array('LIKE', "%$search_string%"),
594
-                    ),
595
-                );
596
-            } else {
597
-                $query_params[0] = array(
598
-                    'QST_display_text' => array('LIKE', "%$search_string%"),
599
-                );
600
-            }
601
-        }
602
-
603
-        //capability checks (just leaving this commented out for reference because it illustrates some complicated query params that could be useful when fully implemented)
604
-        /*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
+		$question_types                                     = $question->has_answers() ? $this->_question_model->question_types_in_same_category($question->type()) : $this->_question_model->allowed_question_types();
434
+		$this->_template_args['QST_ID']                     = $ID;
435
+		$this->_template_args['question']                   = $question;
436
+		$this->_template_args['question_types']             = $question_types;
437
+		$this->_template_args['max_max']                    = EEM_Question::instance()->absolute_max_for_system_question($question->system_ID());
438
+		$this->_template_args['question_type_descriptions'] = $this->_get_question_type_descriptions();
439
+		$this->_set_publish_post_box_vars('id', $ID);
440
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_TEMPLATE_PATH . 'questions_main_meta_box.template.php',
441
+			$this->_template_args, true);
442
+
443
+		// the details template wrapper
444
+		$this->display_admin_page_with_sidebar();
445
+	}
446
+
447
+
448
+	/**
449
+	 * @return string
450
+	 */
451
+	protected function _get_question_type_descriptions()
452
+	{
453
+		EE_Registry::instance()->load_helper('HTML');
454
+		$descriptions               = '';
455
+		$question_type_descriptions = EEM_Question::instance()->question_descriptions();
456
+		foreach ($question_type_descriptions as $type => $question_type_description) {
457
+			if ($type == 'HTML_TEXTAREA') {
458
+				$html = new EE_Simple_HTML_Validation_Strategy();
459
+				$question_type_description .= sprintf(
460
+					esc_html__('%1$s(allowed tags: %2$s)', 'event_espresso'),
461
+					'<br/>',
462
+					$html->get_list_of_allowed_tags()
463
+				);
464
+			}
465
+			$descriptions .= EEH_HTML::p(
466
+				$question_type_description,
467
+				'question_type_description-' . $type,
468
+				'question_type_description description',
469
+				'display:none;'
470
+			);
471
+		}
472
+		return $descriptions;
473
+	}
474
+
475
+
476
+	/**
477
+	 * @param bool|true $new_question
478
+	 * @throws \EE_Error
479
+	 */
480
+	protected function _insert_or_update_question($new_question = true)
481
+	{
482
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
483
+		$set_column_values = $this->_set_column_values_for($this->_question_model);
484
+		if ($new_question) {
485
+			$ID          = $this->_question_model->insert($set_column_values);
486
+			$success     = $ID ? true : false;
487
+			$action_desc = 'added';
488
+		} else {
489
+			$ID     = absint($this->_req_data['QST_ID']);
490
+			$pk     = $this->_question_model->primary_key_name();
491
+			$wheres = array($pk => $ID);
492
+			unset($set_column_values[$pk]);
493
+			$success     = $this->_question_model->update($set_column_values, array($wheres));
494
+			$action_desc = 'updated';
495
+		}
496
+
497
+		if ($ID) {
498
+			//save the related options
499
+			//trash removed options, save old ones
500
+			//get list of all options
501
+			/** @type EE_Question $question */
502
+			$question = $this->_question_model->get_one_by_ID($ID);
503
+			$options  = $question->options();
504
+			if (! empty($options)) {
505
+				foreach ($options as $option_ID => $option) {
506
+					$option_req_index = $this->_get_option_req_data_index($option_ID);
507
+					if ($option_req_index !== false) {
508
+						$option->save($this->_req_data['question_options'][$option_req_index]);
509
+					} else {
510
+						//not found, remove it
511
+						$option->delete();
512
+					}
513
+				}
514
+			}
515
+			//save new related options
516
+			foreach ($this->_req_data['question_options'] as $index => $option_req_data) {
517
+				if (empty($option_req_data['QSO_ID']) && ((isset($option_req_data['QSO_value']) && $option_req_data['QSO_value'] !== '') || ! empty($option_req_data['QSO_desc']))) {//no ID! save it!
518
+					if (! isset($option_req_data['QSO_value']) || $option_req_data['QSO_value'] === '') {
519
+						$option_req_data['QSO_value'] = $option_req_data['QSO_desc'];
520
+					}
521
+					$new_option = EE_Question_Option::new_instance(array(
522
+						'QSO_value' => $option_req_data['QSO_value'],
523
+						'QSO_desc'  => $option_req_data['QSO_desc'],
524
+						'QSO_order' => $option_req_data['QSO_order'],
525
+						'QST_ID'    => $question->ID(),
526
+					));
527
+					$new_option->save();
528
+				}
529
+			}
530
+		}
531
+		$query_args = array('action' => 'edit_question', 'QST_ID' => $ID);
532
+		if ($success !== false) {
533
+			$msg = $new_question ? sprintf(esc_html__('The %s has been created', 'event_espresso'),
534
+				$this->_question_model->item_name()) : sprintf(esc_html__('The %s has been updated', 'event_espresso'),
535
+				$this->_question_model->item_name());
536
+			EE_Error::add_success($msg);
537
+		}
538
+
539
+		$this->_redirect_after_action(false, '', $action_desc, $query_args, true);
540
+	}
541
+
542
+
543
+	/**
544
+	 * Upon saving a question, there should be an array of 'question_options'. This array is index numerically, but not
545
+	 * by ID
546
+	 * (this is done because new question options don't have an ID, but we may want to add multiple simultaneously).
547
+	 * So, this function gets the index in that request data array called question_options. Returns FALSE if not found.
548
+	 *
549
+	 * @param int $ID of the question option to find
550
+	 * @return int index in question_options array if successful, FALSE if unsuccessful
551
+	 */
552
+	protected function _get_option_req_data_index($ID)
553
+	{
554
+		$req_data_for_question_options = $this->_req_data['question_options'];
555
+		foreach ($req_data_for_question_options as $num => $option_data) {
556
+			if (array_key_exists('QSO_ID', $option_data) && (int)$option_data['QSO_ID'] === $ID) {
557
+				return $num;
558
+			}
559
+		}
560
+		return false;
561
+	}
562
+
563
+
564
+
565
+
566
+	/***********/
567
+	/* QUERIES */
568
+	/**
569
+	 * For internal use in getting all the query parameters
570
+	 * (because it's pretty well the same between question, question groups,
571
+	 * and for both when searching for trashed and untrashed ones)
572
+	 *
573
+	 * @param EEM_Base $model either EEM_Question or EEM_Question_Group
574
+	 * @param int      $per_page
575
+	 * @param int      $current_page
576
+	 * @return array lik EEM_Base::get_all's $query_params parameter
577
+	 */
578
+	protected function get_query_params($model, $per_page = 10, $current_page = 10)
579
+	{
580
+		$query_params             = array();
581
+		$offset                   = ($current_page - 1) * $per_page;
582
+		$query_params['limit']    = array($offset, $per_page);
583
+		$order                    = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'ASC';
584
+		$orderby_field            = $model instanceof EEM_Question ? 'QST_ID' : 'QSG_order';
585
+		$field_to_order_by        = empty($this->_req_data['orderby']) ? $orderby_field : $this->_req_data['orderby'];
586
+		$query_params['order_by'] = array($field_to_order_by => $order);
587
+		$search_string            = array_key_exists('s', $this->_req_data) ? $this->_req_data['s'] : null;
588
+		if (! empty($search_string)) {
589
+			if ($model instanceof EEM_Question_Group) {
590
+				$query_params[0] = array(
591
+					'OR' => array(
592
+						'QSG_name' => array('LIKE', "%$search_string%"),
593
+						'QSG_desc' => array('LIKE', "%$search_string%"),
594
+					),
595
+				);
596
+			} else {
597
+				$query_params[0] = array(
598
+					'QST_display_text' => array('LIKE', "%$search_string%"),
599
+				);
600
+			}
601
+		}
602
+
603
+		//capability checks (just leaving this commented out for reference because it illustrates some complicated query params that could be useful when fully implemented)
604
+		/*if ( $model instanceof EEM_Question_Group ) {
605 605
             if ( ! EE_Registry::instance()->CAP->current_user_can( 'edit_others_question_groups', 'espresso_registration_form_edit_question_group' ) ) {
606 606
                 $query_params[0] = array(
607 607
                     'AND' => array(
@@ -631,62 +631,62 @@  discard block
 block discarded – undo
631 631
             }
632 632
         }/**/
633 633
 
634
-        return $query_params;
635
-
636
-    }
637
-
638
-
639
-    /**
640
-     * @param int        $per_page
641
-     * @param int        $current_page
642
-     * @param bool|false $count
643
-     * @return \EE_Soft_Delete_Base_Class[]|int
644
-     */
645
-    public function get_questions($per_page = 10, $current_page = 1, $count = false)
646
-    {
647
-        $QST          = EEM_Question::instance();
648
-        $query_params = $this->get_query_params($QST, $per_page, $current_page);
649
-        if ($count) {
650
-            $where   = isset($query_params[0]) ? array($query_params[0]) : array();
651
-            $results = $QST->count($where);
652
-        } else {
653
-            $results = $QST->get_all($query_params);
654
-        }
655
-        return $results;
656
-
657
-    }
658
-
659
-
660
-    /**
661
-     * @param            $per_page
662
-     * @param int        $current_page
663
-     * @param bool|false $count
664
-     * @return \EE_Soft_Delete_Base_Class[]|int
665
-     */
666
-    public function get_trashed_questions($per_page, $current_page = 1, $count = false)
667
-    {
668
-        $query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
669
-        $where        = isset($query_params[0]) ? array($query_params[0]) : array();
670
-        $questions    = $count ? EEM_Question::instance()->count_deleted($where) : EEM_Question::instance()->get_all_deleted($query_params);
671
-        return $questions;
672
-    }
673
-
674
-
675
-    /**
676
-     * @param            $per_page
677
-     * @param int        $current_page
678
-     * @param bool|false $count
679
-     * @return \EE_Soft_Delete_Base_Class[]
680
-     */
681
-    public function get_question_groups($per_page, $current_page = 1, $count = false)
682
-    {
683
-        /** @type EEM_Question_Group $questionGroupModel */
684
-        $questionGroupModel = EEM_Question_Group::instance();
685
-        //note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
686
-        return $questionGroupModel->get_all(
687
-            $this->get_query_params($questionGroupModel, $per_page, $current_page)
688
-        );
689
-    }
634
+		return $query_params;
635
+
636
+	}
637
+
638
+
639
+	/**
640
+	 * @param int        $per_page
641
+	 * @param int        $current_page
642
+	 * @param bool|false $count
643
+	 * @return \EE_Soft_Delete_Base_Class[]|int
644
+	 */
645
+	public function get_questions($per_page = 10, $current_page = 1, $count = false)
646
+	{
647
+		$QST          = EEM_Question::instance();
648
+		$query_params = $this->get_query_params($QST, $per_page, $current_page);
649
+		if ($count) {
650
+			$where   = isset($query_params[0]) ? array($query_params[0]) : array();
651
+			$results = $QST->count($where);
652
+		} else {
653
+			$results = $QST->get_all($query_params);
654
+		}
655
+		return $results;
656
+
657
+	}
658
+
659
+
660
+	/**
661
+	 * @param            $per_page
662
+	 * @param int        $current_page
663
+	 * @param bool|false $count
664
+	 * @return \EE_Soft_Delete_Base_Class[]|int
665
+	 */
666
+	public function get_trashed_questions($per_page, $current_page = 1, $count = false)
667
+	{
668
+		$query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
669
+		$where        = isset($query_params[0]) ? array($query_params[0]) : array();
670
+		$questions    = $count ? EEM_Question::instance()->count_deleted($where) : EEM_Question::instance()->get_all_deleted($query_params);
671
+		return $questions;
672
+	}
673
+
674
+
675
+	/**
676
+	 * @param            $per_page
677
+	 * @param int        $current_page
678
+	 * @param bool|false $count
679
+	 * @return \EE_Soft_Delete_Base_Class[]
680
+	 */
681
+	public function get_question_groups($per_page, $current_page = 1, $count = false)
682
+	{
683
+		/** @type EEM_Question_Group $questionGroupModel */
684
+		$questionGroupModel = EEM_Question_Group::instance();
685
+		//note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
686
+		return $questionGroupModel->get_all(
687
+			$this->get_query_params($questionGroupModel, $per_page, $current_page)
688
+		);
689
+	}
690 690
 
691 691
 
692 692
 } //ends Registration_Form_Admin_Page class
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 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 Caffeinated version of Event Espresso.  With the Question Groups feature you are able to: create new question groups, edit existing question groups, and also 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 Caffeinated version of Event Espresso.  With the Question Groups feature you are able to: create new question groups, edit existing question groups, and also 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));
@@ -437,7 +437,7 @@  discard block
 block discarded – undo
437 437
         $this->_template_args['max_max']                    = EEM_Question::instance()->absolute_max_for_system_question($question->system_ID());
438 438
         $this->_template_args['question_type_descriptions'] = $this->_get_question_type_descriptions();
439 439
         $this->_set_publish_post_box_vars('id', $ID);
440
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_TEMPLATE_PATH . 'questions_main_meta_box.template.php',
440
+        $this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_TEMPLATE_PATH.'questions_main_meta_box.template.php',
441 441
             $this->_template_args, true);
442 442
 
443 443
         // the details template wrapper
@@ -464,7 +464,7 @@  discard block
 block discarded – undo
464 464
             }
465 465
             $descriptions .= EEH_HTML::p(
466 466
                 $question_type_description,
467
-                'question_type_description-' . $type,
467
+                'question_type_description-'.$type,
468 468
                 'question_type_description description',
469 469
                 'display:none;'
470 470
             );
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
             /** @type EE_Question $question */
502 502
             $question = $this->_question_model->get_one_by_ID($ID);
503 503
             $options  = $question->options();
504
-            if (! empty($options)) {
504
+            if ( ! empty($options)) {
505 505
                 foreach ($options as $option_ID => $option) {
506 506
                     $option_req_index = $this->_get_option_req_data_index($option_ID);
507 507
                     if ($option_req_index !== false) {
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
             //save new related options
516 516
             foreach ($this->_req_data['question_options'] as $index => $option_req_data) {
517 517
                 if (empty($option_req_data['QSO_ID']) && ((isset($option_req_data['QSO_value']) && $option_req_data['QSO_value'] !== '') || ! empty($option_req_data['QSO_desc']))) {//no ID! save it!
518
-                    if (! isset($option_req_data['QSO_value']) || $option_req_data['QSO_value'] === '') {
518
+                    if ( ! isset($option_req_data['QSO_value']) || $option_req_data['QSO_value'] === '') {
519 519
                         $option_req_data['QSO_value'] = $option_req_data['QSO_desc'];
520 520
                     }
521 521
                     $new_option = EE_Question_Option::new_instance(array(
@@ -553,7 +553,7 @@  discard block
 block discarded – undo
553 553
     {
554 554
         $req_data_for_question_options = $this->_req_data['question_options'];
555 555
         foreach ($req_data_for_question_options as $num => $option_data) {
556
-            if (array_key_exists('QSO_ID', $option_data) && (int)$option_data['QSO_ID'] === $ID) {
556
+            if (array_key_exists('QSO_ID', $option_data) && (int) $option_data['QSO_ID'] === $ID) {
557 557
                 return $num;
558 558
             }
559 559
         }
@@ -585,7 +585,7 @@  discard block
 block discarded – undo
585 585
         $field_to_order_by        = empty($this->_req_data['orderby']) ? $orderby_field : $this->_req_data['orderby'];
586 586
         $query_params['order_by'] = array($field_to_order_by => $order);
587 587
         $search_string            = array_key_exists('s', $this->_req_data) ? $this->_req_data['s'] : null;
588
-        if (! empty($search_string)) {
588
+        if ( ! empty($search_string)) {
589 589
             if ($model instanceof EEM_Question_Group) {
590 590
                 $query_params[0] = array(
591 591
                     'OR' => array(
Please login to merge, or discard this patch.
core/admin/EE_Admin_Page.core.php 1 patch
Indentation   +3285 added lines, -3285 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -28,2119 +28,2119 @@  discard block
 block discarded – undo
28 28
 {
29 29
 
30 30
 
31
-    //set in _init_page_props()
32
-    public $page_slug;
31
+	//set in _init_page_props()
32
+	public $page_slug;
33 33
 
34
-    public $page_label;
34
+	public $page_label;
35 35
 
36
-    public $page_folder;
36
+	public $page_folder;
37 37
 
38
-    //set in define_page_props()
39
-    protected $_admin_base_url;
38
+	//set in define_page_props()
39
+	protected $_admin_base_url;
40 40
 
41
-    protected $_admin_base_path;
41
+	protected $_admin_base_path;
42 42
 
43
-    protected $_admin_page_title;
43
+	protected $_admin_page_title;
44 44
 
45
-    protected $_labels;
45
+	protected $_labels;
46 46
 
47 47
 
48
-    //set early within EE_Admin_Init
49
-    protected $_wp_page_slug;
48
+	//set early within EE_Admin_Init
49
+	protected $_wp_page_slug;
50 50
 
51
-    //navtabs
52
-    protected $_nav_tabs;
51
+	//navtabs
52
+	protected $_nav_tabs;
53 53
 
54
-    protected $_default_nav_tab_name;
54
+	protected $_default_nav_tab_name;
55 55
 
56
-    //helptourstops
57
-    protected $_help_tour = array();
56
+	//helptourstops
57
+	protected $_help_tour = array();
58 58
 
59 59
 
60
-    //template variables (used by templates)
61
-    protected $_template_path;
60
+	//template variables (used by templates)
61
+	protected $_template_path;
62 62
 
63
-    protected $_column_template_path;
63
+	protected $_column_template_path;
64 64
 
65
-    /**
66
-     * @var array $_template_args
67
-     */
68
-    protected $_template_args = array();
65
+	/**
66
+	 * @var array $_template_args
67
+	 */
68
+	protected $_template_args = array();
69 69
 
70
-    /**
71
-     * this will hold the list table object for a given view.
72
-     *
73
-     * @var EE_Admin_List_Table $_list_table_object
74
-     */
75
-    protected $_list_table_object;
70
+	/**
71
+	 * this will hold the list table object for a given view.
72
+	 *
73
+	 * @var EE_Admin_List_Table $_list_table_object
74
+	 */
75
+	protected $_list_table_object;
76 76
 
77
-    //bools
78
-    protected $_is_UI_request = null; //this starts at null so we can have no header routes progress through two states.
77
+	//bools
78
+	protected $_is_UI_request = null; //this starts at null so we can have no header routes progress through two states.
79 79
 
80
-    protected $_routing;
80
+	protected $_routing;
81 81
 
82
-    //list table args
83
-    protected $_view;
82
+	//list table args
83
+	protected $_view;
84 84
 
85
-    protected $_views;
85
+	protected $_views;
86 86
 
87 87
 
88
-    //action => method pairs used for routing incoming requests
89
-    protected $_page_routes;
88
+	//action => method pairs used for routing incoming requests
89
+	protected $_page_routes;
90 90
 
91
-    protected $_page_config;
91
+	protected $_page_config;
92 92
 
93
-    //the current page route and route config
94
-    protected $_route;
93
+	//the current page route and route config
94
+	protected $_route;
95 95
 
96
-    protected $_route_config;
96
+	protected $_route_config;
97 97
 
98
-    /**
99
-     * Used to hold default query args for list table routes to help preserve stickiness of filters for carried out
100
-     * actions.
101
-     *
102
-     * @since 4.6.x
103
-     * @var array.
104
-     */
105
-    protected $_default_route_query_args;
98
+	/**
99
+	 * Used to hold default query args for list table routes to help preserve stickiness of filters for carried out
100
+	 * actions.
101
+	 *
102
+	 * @since 4.6.x
103
+	 * @var array.
104
+	 */
105
+	protected $_default_route_query_args;
106 106
 
107
-    //set via request page and action args.
108
-    protected $_current_page;
107
+	//set via request page and action args.
108
+	protected $_current_page;
109 109
 
110
-    protected $_current_view;
110
+	protected $_current_view;
111 111
 
112
-    protected $_current_page_view_url;
112
+	protected $_current_page_view_url;
113 113
 
114
-    //sanitized request action (and nonce)
115
-    /**
116
-     * @var string $_req_action
117
-     */
118
-    protected $_req_action;
114
+	//sanitized request action (and nonce)
115
+	/**
116
+	 * @var string $_req_action
117
+	 */
118
+	protected $_req_action;
119 119
 
120
-    /**
121
-     * @var string $_req_nonce
122
-     */
123
-    protected $_req_nonce;
120
+	/**
121
+	 * @var string $_req_nonce
122
+	 */
123
+	protected $_req_nonce;
124 124
 
125
-    //search related
126
-    protected $_search_btn_label;
125
+	//search related
126
+	protected $_search_btn_label;
127 127
 
128
-    protected $_search_box_callback;
128
+	protected $_search_box_callback;
129 129
 
130
-    /**
131
-     * WP Current Screen object
132
-     *
133
-     * @var WP_Screen
134
-     */
135
-    protected $_current_screen;
130
+	/**
131
+	 * WP Current Screen object
132
+	 *
133
+	 * @var WP_Screen
134
+	 */
135
+	protected $_current_screen;
136 136
 
137
-    //for holding EE_Admin_Hooks object when needed (set via set_hook_object())
138
-    protected $_hook_obj;
137
+	//for holding EE_Admin_Hooks object when needed (set via set_hook_object())
138
+	protected $_hook_obj;
139 139
 
140
-    //for holding incoming request data
141
-    protected $_req_data;
140
+	//for holding incoming request data
141
+	protected $_req_data;
142 142
 
143
-    // yes / no array for admin form fields
144
-    protected $_yes_no_values = array();
145
-
146
-    //some default things shared by all child classes
147
-    protected $_default_espresso_metaboxes;
148
-
149
-    /**
150
-     *    EE_Registry Object
151
-     *
152
-     * @var    EE_Registry
153
-     * @access    protected
154
-     */
155
-    protected $EE = null;
156
-
157
-
158
-
159
-    /**
160
-     * This is just a property that flags whether the given route is a caffeinated route or not.
161
-     *
162
-     * @var boolean
163
-     */
164
-    protected $_is_caf = false;
165
-
166
-
167
-
168
-    /**
169
-     * @Constructor
170
-     * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
171
-     * @access public
172
-     */
173
-    public function __construct($routing = true)
174
-    {
175
-        if (strpos($this->_get_dir(), 'caffeinated') !== false) {
176
-            $this->_is_caf = true;
177
-        }
178
-        $this->_yes_no_values = array(
179
-                array('id' => true, 'text' => __('Yes', 'event_espresso')),
180
-                array('id' => false, 'text' => __('No', 'event_espresso')),
181
-        );
182
-        //set the _req_data property.
183
-        $this->_req_data = array_merge($_GET, $_POST);
184
-        //routing enabled?
185
-        $this->_routing = $routing;
186
-        //set initial page props (child method)
187
-        $this->_init_page_props();
188
-        //set global defaults
189
-        $this->_set_defaults();
190
-        //set early because incoming requests could be ajax related and we need to register those hooks.
191
-        $this->_global_ajax_hooks();
192
-        $this->_ajax_hooks();
193
-        //other_page_hooks have to be early too.
194
-        $this->_do_other_page_hooks();
195
-        //This just allows us to have extending clases do something specific before the parent constructor runs _page_setup.
196
-        if (method_exists($this, '_before_page_setup')) {
197
-            $this->_before_page_setup();
198
-        }
199
-        //set up page dependencies
200
-        $this->_page_setup();
201
-    }
202
-
203
-
204
-
205
-    /**
206
-     * _init_page_props
207
-     * Child classes use to set at least the following properties:
208
-     * $page_slug.
209
-     * $page_label.
210
-     *
211
-     * @abstract
212
-     * @access protected
213
-     * @return void
214
-     */
215
-    abstract protected function _init_page_props();
216
-
217
-
218
-
219
-    /**
220
-     * _ajax_hooks
221
-     * child classes put all their add_action('wp_ajax_{name_of_hook}') hooks in here.
222
-     * Note: within the ajax callback methods.
223
-     *
224
-     * @abstract
225
-     * @access protected
226
-     * @return void
227
-     */
228
-    abstract protected function _ajax_hooks();
229
-
230
-
231
-
232
-    /**
233
-     * _define_page_props
234
-     * child classes define page properties in here.  Must include at least:
235
-     * $_admin_base_url = base_url for all admin pages
236
-     * $_admin_page_title = default admin_page_title for admin pages
237
-     * $_labels = array of default labels for various automatically generated elements:
238
-     *    array(
239
-     *        'buttons' => array(
240
-     *            'add' => __('label for add new button'),
241
-     *            'edit' => __('label for edit button'),
242
-     *            'delete' => __('label for delete button')
243
-     *            )
244
-     *        )
245
-     *
246
-     * @abstract
247
-     * @access protected
248
-     * @return void
249
-     */
250
-    abstract protected function _define_page_props();
251
-
252
-
253
-
254
-    /**
255
-     * _set_page_routes
256
-     * child classes use this to define the page routes for all subpages handled by the class.  Page routes are assigned to a action => method pairs in an array and to the $_page_routes property.  Each page route must also have a 'default'
257
-     * route. Here's the format
258
-     * $this->_page_routes = array(
259
-     *        'default' => array(
260
-     *            'func' => '_default_method_handling_route',
261
-     *            'args' => array('array','of','args'),
262
-     *            'noheader' => true, //add this in if this page route is processed before any headers are loaded (i.e. ajax request, backend processing)
263
-     *            'headers_sent_route'=>'headers_route_reference', //add this if noheader=>true, and you want to load a headers route after.  The string you enter here should match the defined route reference for a headers sent route.
264
-     *            'capability' => 'route_capability', //indicate a string for minimum capability required to access this route.
265
-     *            'obj_id' => 10 // if this route has an object id, then this can include it (used for capability checks).
266
-     *        ),
267
-     *        'insert_item' => '_method_for_handling_insert_item' //this can be used if all we need to have is a handling method.
268
-     *        )
269
-     * )
270
-     *
271
-     * @abstract
272
-     * @access protected
273
-     * @return void
274
-     */
275
-    abstract protected function _set_page_routes();
276
-
277
-
278
-
279
-    /**
280
-     * _set_page_config
281
-     * child classes use this to define the _page_config array for all subpages handled by the class. Each key in the array corresponds to the page_route for the loaded page.
282
-     * Format:
283
-     * $this->_page_config = array(
284
-     *        'default' => array(
285
-     *            'labels' => array(
286
-     *                'buttons' => array(
287
-     *                    'add' => __('label for adding item'),
288
-     *                    'edit' => __('label for editing item'),
289
-     *                    'delete' => __('label for deleting item')
290
-     *                ),
291
-     *                'publishbox' => __('Localized Title for Publish metabox', 'event_espresso')
292
-     *            ), //optional an array of custom labels for various automatically generated elements to use on the page. If this isn't present then the defaults will be used as set for the $this->_labels in _define_page_props() method
293
-     *            'nav' => array(
294
-     *                'label' => __('Label for Tab', 'event_espresso').
295
-     *                'url' => 'http://someurl', //automatically generated UNLESS you define
296
-     *                'css_class' => 'css-class', //automatically generated UNLESS you define
297
-     *                'order' => 10, //required to indicate tab position.
298
-     *                'persistent' => false //if you want the nav tab to ONLY display when the specific route is displayed then add this parameter.
299
-     *            'list_table' => 'name_of_list_table' //string for list table class to be loaded for this admin_page.
300
-     *            'metaboxes' => array('metabox1', 'metabox2'), //if present this key indicates we want to load metaboxes set for eventespresso admin pages.
301
-     *            'has_metaboxes' => true, //this boolean flag can simply be used to indicate if the route will have metaboxes.  Typically this is used if the 'metaboxes' index is not used because metaboxes are added later.  We just use
302
-     *            this flag to make sure the necessary js gets enqueued on page load.
303
-     *            'has_help_popups' => false //defaults(true) //this boolean flag can simply be used to indicate if the given route has help popups setup and if it does then we need to make sure thickbox is enqueued.
304
-     *            'columns' => array(4, 2), //this key triggers the setup of a page that uses columns (metaboxes).  The array indicates the max number of columns (4) and the default number of columns on page load (2).  There is an option
305
-     *            in the "screen_options" dropdown that is setup so users can pick what columns they want to display.
306
-     *            'help_tabs' => array( //this is used for adding help tabs to a page
307
-     *                'tab_id' => array(
308
-     *                    'title' => 'tab_title',
309
-     *                    'filename' => 'name_of_file_containing_content', //this is the primary method for setting help tab content.  The fallback if it isn't present is to try a the callback.  Filename should match a file in the admin
310
-     *                    folder's "help_tabs" dir (ie.. events/help_tabs/name_of_file_containing_content.help_tab.php)
311
-     *                    'callback' => 'callback_method_for_content', //if 'filename' isn't present then system will attempt to use the callback which should match the name of a method in the class
312
-     *                    ),
313
-     *                'tab2_id' => array(
314
-     *                    'title' => 'tab2 title',
315
-     *                    'filename' => 'file_name_2'
316
-     *                    'callback' => 'callback_method_for_content',
317
-     *                 ),
318
-     *            'help_sidebar' => 'callback_for_sidebar_content', //this is used for setting up the sidebar in the help tab area on an admin page. @link http://make.wordpress.org/core/2011/12/06/help-and-screen-api-changes-in-3-3/
319
-     *            'help_tour' => array(
320
-     *                'name_of_help_tour_class', //all help tours shoudl be a child class of EE_Help_Tour and located in a folder for this admin page named "help_tours", a file name matching the key given here
321
-     *                (name_of_help_tour_class.class.php), and class matching key given here (name_of_help_tour_class)
322
-     *            ),
323
-     *            'require_nonce' => TRUE //this is used if you want to set a route to NOT require a nonce (default is true if it isn't present).  To remove the requirement for a nonce check when this route is visited just set
324
-     *            'require_nonce' to FALSE
325
-     *            )
326
-     * )
327
-     *
328
-     * @abstract
329
-     * @access protected
330
-     * @return void
331
-     */
332
-    abstract protected function _set_page_config();
333
-
334
-
335
-
336
-
337
-
338
-    /** end sample help_tour methods **/
339
-    /**
340
-     * _add_screen_options
341
-     * Child classes can add any extra wp_screen_options within this method using built-in WP functions/methods for doing so.
342
-     * Note child classes can also define _add_screen_options_($this->_current_view) to limit screen options to a particular view.
343
-     *
344
-     * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
345
-     *         see also WP_Screen object documents...
346
-     * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
347
-     * @abstract
348
-     * @access protected
349
-     * @return void
350
-     */
351
-    abstract protected function _add_screen_options();
352
-
353
-
354
-
355
-    /**
356
-     * _add_feature_pointers
357
-     * Child classes should use this method for implementing any "feature pointers" (using built-in WP styling js).
358
-     * Note child classes can also define _add_feature_pointers_($this->_current_view) to limit screen options to a particular view.
359
-     * Note: this is just a placeholder for now.  Implementation will come down the road
360
-     * See: WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be extended) also see:
361
-     *
362
-     * @link   http://eamann.com/tech/wordpress-portland/
363
-     * @abstract
364
-     * @access protected
365
-     * @return void
366
-     */
367
-    abstract protected function _add_feature_pointers();
368
-
369
-
370
-
371
-    /**
372
-     * load_scripts_styles
373
-     * child classes put their wp_enqueue_script and wp_enqueue_style hooks in here for anything they need loaded for their pages/subpages.  Note this is for all pages/subpages of the system.  You can also load only specific scripts/styles
374
-     * per view by putting them in a dynamic function in this format (load_scripts_styles_{$this->_current_view}) which matches your page route (action request arg)
375
-     *
376
-     * @abstract
377
-     * @access public
378
-     * @return void
379
-     */
380
-    abstract public function load_scripts_styles();
381
-
382
-
383
-
384
-    /**
385
-     * admin_init
386
-     * Anything that should be set/executed at 'admin_init' WP hook runtime should be put in here.  This will apply to all pages/views loaded by child class.
387
-     *
388
-     * @abstract
389
-     * @access public
390
-     * @return void
391
-     */
392
-    abstract public function admin_init();
393
-
394
-
395
-
396
-    /**
397
-     * admin_notices
398
-     * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply to all pages/views loaded by child class.
399
-     *
400
-     * @abstract
401
-     * @access public
402
-     * @return void
403
-     */
404
-    abstract public function admin_notices();
405
-
406
-
407
-
408
-    /**
409
-     * admin_footer_scripts
410
-     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method will apply to all pages/views loaded by child class.
411
-     *
412
-     * @access public
413
-     * @return void
414
-     */
415
-    abstract public function admin_footer_scripts();
416
-
417
-
418
-
419
-    /**
420
-     * admin_footer
421
-     * anything triggered by the 'admin_footer' WP action hook should be added to here. This particular method will apply to all pages/views loaded by child class.
422
-     *
423
-     * @access  public
424
-     * @return void
425
-     */
426
-    public function admin_footer()
427
-    {
428
-    }
429
-
430
-
431
-
432
-    /**
433
-     * _global_ajax_hooks
434
-     * all global add_action('wp_ajax_{name_of_hook}') hooks in here.
435
-     * Note: within the ajax callback methods.
436
-     *
437
-     * @abstract
438
-     * @access protected
439
-     * @return void
440
-     */
441
-    protected function _global_ajax_hooks()
442
-    {
443
-        //for lazy loading of metabox content
444
-        add_action('wp_ajax_espresso-ajax-content', array($this, 'ajax_metabox_content'), 10);
445
-    }
446
-
447
-
448
-
449
-    public function ajax_metabox_content()
450
-    {
451
-        $contentid = isset($this->_req_data['contentid']) ? $this->_req_data['contentid'] : '';
452
-        $url = isset($this->_req_data['contenturl']) ? $this->_req_data['contenturl'] : '';
453
-        self::cached_rss_display($contentid, $url);
454
-        wp_die();
455
-    }
456
-
457
-
458
-
459
-    /**
460
-     * _page_setup
461
-     * Makes sure any things that need to be loaded early get handled.  We also escape early here if the page requested doesn't match the object.
462
-     *
463
-     * @final
464
-     * @access protected
465
-     * @return void
466
-     */
467
-    final protected function _page_setup()
468
-    {
469
-        //requires?
470
-        //admin_init stuff - global - we're setting this REALLY early so if EE_Admin pages have to hook into other WP pages they can.  But keep in mind, not everything is available from the EE_Admin Page object at this point.
471
-        add_action('admin_init', array($this, 'admin_init_global'), 5);
472
-        //next verify if we need to load anything...
473
-        $this->_current_page = ! empty($_GET['page']) ? sanitize_key($_GET['page']) : '';
474
-        $this->page_folder = strtolower(str_replace('_Admin_Page', '', str_replace('Extend_', '', get_class($this))));
475
-        global $ee_menu_slugs;
476
-        $ee_menu_slugs = (array)$ee_menu_slugs;
477
-        if (( ! $this->_current_page || ! isset($ee_menu_slugs[$this->_current_page])) && ! defined('DOING_AJAX')) {
478
-            return false;
479
-        }
480
-        // becuz WP List tables have two duplicate select inputs for choosing bulk actions, we need to copy the action from the second to the first
481
-        if (isset($this->_req_data['action2']) && $this->_req_data['action'] == -1) {
482
-            $this->_req_data['action'] = ! empty($this->_req_data['action2']) && $this->_req_data['action2'] != -1 ? $this->_req_data['action2'] : $this->_req_data['action'];
483
-        }
484
-        // then set blank or -1 action values to 'default'
485
-        $this->_req_action = isset($this->_req_data['action']) && ! empty($this->_req_data['action']) && $this->_req_data['action'] != -1 ? sanitize_key($this->_req_data['action']) : 'default';
486
-        //if action is 'default' after the above BUT we have  'route' var set, then let's use the route as the action.  This covers cases where we're coming in from a list table that isn't on the default route.
487
-        $this->_req_action = $this->_req_action == 'default' && isset($this->_req_data['route']) ? $this->_req_data['route'] : $this->_req_action;
488
-        //however if we are doing_ajax and we've got a 'route' set then that's what the req_action will be
489
-        $this->_req_action = defined('DOING_AJAX') && isset($this->_req_data['route']) ? $this->_req_data['route'] : $this->_req_action;
490
-        $this->_current_view = $this->_req_action;
491
-        $this->_req_nonce = $this->_req_action . '_nonce';
492
-        $this->_define_page_props();
493
-        $this->_current_page_view_url = add_query_arg(array('page' => $this->_current_page, 'action' => $this->_current_view), $this->_admin_base_url);
494
-        //default things
495
-        $this->_default_espresso_metaboxes = array('_espresso_news_post_box', '_espresso_links_post_box', '_espresso_ratings_request', '_espresso_sponsors_post_box');
496
-        //set page configs
497
-        $this->_set_page_routes();
498
-        $this->_set_page_config();
499
-        //let's include any referrer data in our default_query_args for this route for "stickiness".
500
-        if (isset($this->_req_data['wp_referer'])) {
501
-            $this->_default_route_query_args['wp_referer'] = $this->_req_data['wp_referer'];
502
-        }
503
-        //for caffeinated and other extended functionality.  If there is a _extend_page_config method then let's run that to modify the all the various page configuration arrays
504
-        if (method_exists($this, '_extend_page_config')) {
505
-            $this->_extend_page_config();
506
-        }
507
-        //for CPT and other extended functionality. If there is an _extend_page_config_for_cpt then let's run that to modify all the various page configuration arrays.
508
-        if (method_exists($this, '_extend_page_config_for_cpt')) {
509
-            $this->_extend_page_config_for_cpt();
510
-        }
511
-        //filter routes and page_config so addons can add their stuff. Filtering done per class
512
-        $this->_page_routes = apply_filters('FHEE__' . get_class($this) . '__page_setup__page_routes', $this->_page_routes, $this);
513
-        $this->_page_config = apply_filters('FHEE__' . get_class($this) . '__page_setup__page_config', $this->_page_config, $this);
514
-        //if AHEE__EE_Admin_Page__route_admin_request_$this->_current_view method is present then we call it hooked into the AHEE__EE_Admin_Page__route_admin_request action
515
-        if (method_exists($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view)) {
516
-            add_action('AHEE__EE_Admin_Page__route_admin_request', array($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view), 10, 2);
517
-        }
518
-        //next route only if routing enabled
519
-        if ($this->_routing && ! defined('DOING_AJAX')) {
520
-            $this->_verify_routes();
521
-            //next let's just check user_access and kill if no access
522
-            $this->check_user_access();
523
-            if ($this->_is_UI_request) {
524
-                //admin_init stuff - global, all views for this page class, specific view
525
-                add_action('admin_init', array($this, 'admin_init'), 10);
526
-                if (method_exists($this, 'admin_init_' . $this->_current_view)) {
527
-                    add_action('admin_init', array($this, 'admin_init_' . $this->_current_view), 15);
528
-                }
529
-            } else {
530
-                //hijack regular WP loading and route admin request immediately
531
-                @ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT));
532
-                $this->route_admin_request();
533
-            }
534
-        }
535
-    }
536
-
537
-
538
-
539
-    /**
540
-     * Provides a way for related child admin pages to load stuff on the loaded admin page.
541
-     *
542
-     * @access private
543
-     * @return void
544
-     */
545
-    private function _do_other_page_hooks()
546
-    {
547
-        $registered_pages = apply_filters('FHEE_do_other_page_hooks_' . $this->page_slug, array());
548
-        foreach ($registered_pages as $page) {
549
-            //now let's setup the file name and class that should be present
550
-            $classname = str_replace('.class.php', '', $page);
551
-            //autoloaders should take care of loading file
552
-            if ( ! class_exists($classname)) {
553
-                $error_msg[] = sprintf(__('Something went wrong with loading the %s admin hooks page.', 'event_espresso'), $page);
554
-                $error_msg[] = $error_msg[0]
555
-                               . "\r\n"
556
-                               . sprintf(__('There is no class in place for the %s admin hooks page.%sMake sure you have <strong>%s</strong> defined. If this is a non-EE-core admin page then you also must have an autoloader in place for your class',
557
-                                'event_espresso'), $page, '<br />', $classname);
558
-                throw new EE_Error(implode('||', $error_msg));
559
-            }
560
-            $a = new ReflectionClass($classname);
561
-            //notice we are passing the instance of this class to the hook object.
562
-            $hookobj[] = $a->newInstance($this);
563
-        }
564
-    }
565
-
566
-
567
-
568
-    public function load_page_dependencies()
569
-    {
570
-        try {
571
-            $this->_load_page_dependencies();
572
-        } catch (EE_Error $e) {
573
-            $e->get_error();
574
-        }
575
-    }
576
-
577
-
578
-
579
-    /**
580
-     * load_page_dependencies
581
-     * loads things specific to this page class when its loaded.  Really helps with efficiency.
582
-     *
583
-     * @access public
584
-     * @return void
585
-     */
586
-    protected function _load_page_dependencies()
587
-    {
588
-        //let's set the current_screen and screen options to override what WP set
589
-        $this->_current_screen = get_current_screen();
590
-        //load admin_notices - global, page class, and view specific
591
-        add_action('admin_notices', array($this, 'admin_notices_global'), 5);
592
-        add_action('admin_notices', array($this, 'admin_notices'), 10);
593
-        if (method_exists($this, 'admin_notices_' . $this->_current_view)) {
594
-            add_action('admin_notices', array($this, 'admin_notices_' . $this->_current_view), 15);
595
-        }
596
-        //load network admin_notices - global, page class, and view specific
597
-        add_action('network_admin_notices', array($this, 'network_admin_notices_global'), 5);
598
-        if (method_exists($this, 'network_admin_notices_' . $this->_current_view)) {
599
-            add_action('network_admin_notices', array($this, 'network_admin_notices_' . $this->_current_view));
600
-        }
601
-        //this will save any per_page screen options if they are present
602
-        $this->_set_per_page_screen_options();
603
-        //setup list table properties
604
-        $this->_set_list_table();
605
-        // child classes can "register" a metabox to be automatically handled via the _page_config array property.  However in some cases the metaboxes will need to be added within a route handling callback.
606
-        $this->_add_registered_meta_boxes();
607
-        $this->_add_screen_columns();
608
-        //add screen options - global, page child class, and view specific
609
-        $this->_add_global_screen_options();
610
-        $this->_add_screen_options();
611
-        if (method_exists($this, '_add_screen_options_' . $this->_current_view)) {
612
-            call_user_func(array($this, '_add_screen_options_' . $this->_current_view));
613
-        }
614
-        //add help tab(s) and tours- set via page_config and qtips.
615
-        $this->_add_help_tour();
616
-        $this->_add_help_tabs();
617
-        $this->_add_qtips();
618
-        //add feature_pointers - global, page child class, and view specific
619
-        $this->_add_feature_pointers();
620
-        $this->_add_global_feature_pointers();
621
-        if (method_exists($this, '_add_feature_pointer_' . $this->_current_view)) {
622
-            call_user_func(array($this, '_add_feature_pointer_' . $this->_current_view));
623
-        }
624
-        //enqueue scripts/styles - global, page class, and view specific
625
-        add_action('admin_enqueue_scripts', array($this, 'load_global_scripts_styles'), 5);
626
-        add_action('admin_enqueue_scripts', array($this, 'load_scripts_styles'), 10);
627
-        if (method_exists($this, 'load_scripts_styles_' . $this->_current_view)) {
628
-            add_action('admin_enqueue_scripts', array($this, 'load_scripts_styles_' . $this->_current_view), 15);
629
-        }
630
-        add_action('admin_enqueue_scripts', array($this, 'admin_footer_scripts_eei18n_js_strings'), 100);
631
-        //admin_print_footer_scripts - global, page child class, and view specific.  NOTE, despite the name, whenever possible, scripts should NOT be loaded using this.  In most cases that's doing_it_wrong().  But adding hidden container elements etc. is a good use case. Notice the late priority we're giving these
632
-        add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts_global'), 99);
633
-        add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts'), 100);
634
-        if (method_exists($this, 'admin_footer_scripts_' . $this->_current_view)) {
635
-            add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts_' . $this->_current_view), 101);
636
-        }
637
-        //admin footer scripts
638
-        add_action('admin_footer', array($this, 'admin_footer_global'), 99);
639
-        add_action('admin_footer', array($this, 'admin_footer'), 100);
640
-        if (method_exists($this, 'admin_footer_' . $this->_current_view)) {
641
-            add_action('admin_footer', array($this, 'admin_footer_' . $this->_current_view), 101);
642
-        }
643
-        do_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', $this->page_slug);
644
-        //targeted hook
645
-        do_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load__' . $this->page_slug . '__' . $this->_req_action);
646
-    }
647
-
648
-
649
-
650
-    /**
651
-     * _set_defaults
652
-     * This sets some global defaults for class properties.
653
-     */
654
-    private function _set_defaults()
655
-    {
656
-        $this->_current_screen = $this->_admin_page_title = $this->_req_action = $this->_req_nonce = $this->_event = $this->_template_path = $this->_column_template_path = null;
657
-        $this->_nav_tabs = $this_views = $this->_page_routes = $this->_page_config = $this->_default_route_query_args = array();
658
-        $this->default_nav_tab_name = 'overview';
659
-        //init template args
660
-        $this->_template_args = array(
661
-                'admin_page_header'  => '',
662
-                'admin_page_content' => '',
663
-                'post_body_content'  => '',
664
-                'before_list_table'  => '',
665
-                'after_list_table'   => '',
666
-        );
667
-    }
668
-
669
-
670
-
671
-    /**
672
-     * route_admin_request
673
-     *
674
-     * @see    _route_admin_request()
675
-     * @access public
676
-     * @return void|exception error
677
-     */
678
-    public function route_admin_request()
679
-    {
680
-        try {
681
-            $this->_route_admin_request();
682
-        } catch (EE_Error $e) {
683
-            $e->get_error();
684
-        }
685
-    }
686
-
687
-
688
-
689
-    public function set_wp_page_slug($wp_page_slug)
690
-    {
691
-        $this->_wp_page_slug = $wp_page_slug;
692
-        //if in network admin then we need to append "-network" to the page slug. Why? Because that's how WP rolls...
693
-        if (is_network_admin()) {
694
-            $this->_wp_page_slug .= '-network';
695
-        }
696
-    }
697
-
698
-
699
-
700
-    /**
701
-     * _verify_routes
702
-     * All this method does is verify the incoming request and make sure that routes exist for it.  We do this early so we know if we need to drop out.
703
-     *
704
-     * @access protected
705
-     * @return void
706
-     */
707
-    protected function _verify_routes()
708
-    {
709
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
710
-        if ( ! $this->_current_page && ! defined('DOING_AJAX')) {
711
-            return false;
712
-        }
713
-        $this->_route = false;
714
-        $func = false;
715
-        $args = array();
716
-        // check that the page_routes array is not empty
717
-        if (empty($this->_page_routes)) {
718
-            // user error msg
719
-            $error_msg = sprintf(__('No page routes have been set for the %s admin page.', 'event_espresso'), $this->_admin_page_title);
720
-            // developer error msg
721
-            $error_msg .= '||' . $error_msg . __(' Make sure the "set_page_routes()" method exists, and is setting the "_page_routes" array properly.', 'event_espresso');
722
-            throw new EE_Error($error_msg);
723
-        }
724
-        // and that the requested page route exists
725
-        if (array_key_exists($this->_req_action, $this->_page_routes)) {
726
-            $this->_route = $this->_page_routes[$this->_req_action];
727
-            $this->_route_config = isset($this->_page_config[$this->_req_action]) ? $this->_page_config[$this->_req_action] : array();
728
-        } else {
729
-            // user error msg
730
-            $error_msg = sprintf(__('The requested page route does not exist for the %s admin page.', 'event_espresso'), $this->_admin_page_title);
731
-            // developer error msg
732
-            $error_msg .= '||' . $error_msg . sprintf(__(' Create a key in the "_page_routes" array named "%s" and set its value to the appropriate method.', 'event_espresso'), $this->_req_action);
733
-            throw new EE_Error($error_msg);
734
-        }
735
-        // and that a default route exists
736
-        if ( ! array_key_exists('default', $this->_page_routes)) {
737
-            // user error msg
738
-            $error_msg = sprintf(__('A default page route has not been set for the % admin page.', 'event_espresso'), $this->_admin_page_title);
739
-            // developer error msg
740
-            $error_msg .= '||' . $error_msg . __(' Create a key in the "_page_routes" array named "default" and set its value to your default page method.', 'event_espresso');
741
-            throw new EE_Error($error_msg);
742
-        }
743
-        //first lets' catch if the UI request has EVER been set.
744
-        if ($this->_is_UI_request === null) {
745
-            //lets set if this is a UI request or not.
746
-            $this->_is_UI_request = ( ! isset($this->_req_data['noheader']) || $this->_req_data['noheader'] !== true) ? true : false;
747
-            //wait a minute... we might have a noheader in the route array
748
-            $this->_is_UI_request = is_array($this->_route) && isset($this->_route['noheader']) && $this->_route['noheader'] ? false : $this->_is_UI_request;
749
-        }
750
-        $this->_set_current_labels();
751
-    }
752
-
753
-
754
-
755
-    /**
756
-     * this method simply verifies a given route and makes sure its an actual route available for the loaded page
757
-     *
758
-     * @param  string $route the route name we're verifying
759
-     * @return mixed  (bool|Exception)      we'll throw an exception if this isn't a valid route.
760
-     */
761
-    protected function _verify_route($route)
762
-    {
763
-        if (array_key_exists($this->_req_action, $this->_page_routes)) {
764
-            return true;
765
-        } else {
766
-            // user error msg
767
-            $error_msg = sprintf(__('The given page route does not exist for the %s admin page.', 'event_espresso'), $this->_admin_page_title);
768
-            // developer error msg
769
-            $error_msg .= '||' . $error_msg . sprintf(__(' Check the route you are using in your method (%s) and make sure it matches a route set in your "_page_routes" array property', 'event_espresso'), $route);
770
-            throw new EE_Error($error_msg);
771
-        }
772
-    }
773
-
774
-
775
-
776
-    /**
777
-     * perform nonce verification
778
-     * This method has be encapsulated here so that any ajax requests that bypass normal routes can verify their nonces using this method (and save retyping!)
779
-     *
780
-     * @param  string $nonce     The nonce sent
781
-     * @param  string $nonce_ref The nonce reference string (name0)
782
-     * @return mixed (bool|die)
783
-     */
784
-    protected function _verify_nonce($nonce, $nonce_ref)
785
-    {
786
-        // verify nonce against expected value
787
-        if ( ! wp_verify_nonce($nonce, $nonce_ref)) {
788
-            // these are not the droids you are looking for !!!
789
-            $msg = sprintf(__('%sNonce Fail.%s', 'event_espresso'), '<a href="http://www.youtube.com/watch?v=56_S0WeTkzs">', '</a>');
790
-            if (WP_DEBUG) {
791
-                $msg .= "\n  " . sprintf(__('In order to dynamically generate nonces for your actions, use the %s::add_query_args_and_nonce() method. May the Nonce be with you!', 'event_espresso'), __CLASS__);
792
-            }
793
-            if ( ! defined('DOING_AJAX')) {
794
-                wp_die($msg);
795
-            } else {
796
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
797
-                $this->_return_json();
798
-            }
799
-        }
800
-    }
801
-
802
-
803
-
804
-    /**
805
-     * _route_admin_request()
806
-     * Meat and potatoes of the class.  Basically, this dude checks out what's being requested and sees if theres are
807
-     * some doodads to work the magic and handle the flingjangy. Translation:  Checks if the requested action is listed
808
-     * in the page routes and then will try to load the corresponding method.
809
-     *
810
-     * @access protected
811
-     * @return void
812
-     * @throws \EE_Error
813
-     */
814
-    protected function _route_admin_request()
815
-    {
816
-        if ( ! $this->_is_UI_request) {
817
-            $this->_verify_routes();
818
-        }
819
-        $nonce_check = isset($this->_route_config['require_nonce'])
820
-            ? $this->_route_config['require_nonce']
821
-            : true;
822
-        if ($this->_req_action !== 'default' && $nonce_check) {
823
-            // set nonce from post data
824
-            $nonce = isset($this->_req_data[$this->_req_nonce])
825
-                ? sanitize_text_field($this->_req_data[$this->_req_nonce])
826
-                : '';
827
-            $this->_verify_nonce($nonce, $this->_req_nonce);
828
-        }
829
-        //set the nav_tabs array but ONLY if this is  UI_request
830
-        if ($this->_is_UI_request) {
831
-            $this->_set_nav_tabs();
832
-        }
833
-        // grab callback function
834
-        $func = is_array($this->_route) ? $this->_route['func'] : $this->_route;
835
-        // check if callback has args
836
-        $args = is_array($this->_route) && isset($this->_route['args']) ? $this->_route['args'] : array();
837
-        $error_msg = '';
838
-        // action right before calling route
839
-        // (hook is something like 'AHEE__Registrations_Admin_Page__route_admin_request')
840
-        if ( ! did_action('AHEE__EE_Admin_Page__route_admin_request')) {
841
-            do_action('AHEE__EE_Admin_Page__route_admin_request', $this->_current_view, $this);
842
-        }
843
-        // right before calling the route, let's remove _wp_http_referer from the
844
-        // $_SERVER[REQUEST_URI] global (its now in _req_data for route processing).
845
-        $_SERVER['REQUEST_URI'] = remove_query_arg('_wp_http_referer', wp_unslash($_SERVER['REQUEST_URI']));
846
-        if ( ! empty($func)) {
847
-            if (is_array($func)) {
848
-                list($class, $method) = $func;
849
-            } else if (strpos($func, '::') !== false) {
850
-                list($class, $method) = explode('::', $func);
851
-            } else {
852
-                $class = $this;
853
-                $method = $func;
854
-            }
855
-            if ( ! (is_object($class) && $class === $this)) {
856
-                // send along this admin page object for access by addons.
857
-                $args['admin_page_object'] = $this;
858
-            }
859
-
860
-            if (
861
-                //is it a method on a class that doesn't work?
862
-                (
863
-                    (
864
-                        method_exists($class, $method)
865
-                        && call_user_func_array(array($class, $method), $args) === false
866
-                    )
867
-                    && (
868
-                        //is it a standalone function that doesn't work?
869
-                        function_exists($method)
870
-                        && call_user_func_array($func, array_merge(array('admin_page_object' => $this), $args)) === false
871
-                    )
872
-                )
873
-                || (
874
-                    //is it neither a class method NOR a standalone function?
875
-                    ! method_exists($class, $method)
876
-                    && ! function_exists($method)
877
-                )
878
-            ) {
879
-                // user error msg
880
-                $error_msg = __('An error occurred. The  requested page route could not be found.', 'event_espresso');
881
-                // developer error msg
882
-                $error_msg .= '||';
883
-                $error_msg .= sprintf(
884
-                    __(
885
-                        'Page route "%s" could not be called. Check that the spelling for method names and actions in the "_page_routes" array are all correct.',
886
-                        'event_espresso'
887
-                    ),
888
-                    $method
889
-                );
890
-            }
891
-            if ( ! empty($error_msg)) {
892
-                throw new EE_Error($error_msg);
893
-            }
894
-        }
895
-        //if we've routed and this route has a no headers route AND a sent_headers_route, then we need to reset the routing properties to the new route.
896
-        //now if UI request is FALSE and noheader is true AND we have a headers_sent_route in the route array then let's set UI_request to true because the no header route has a second func after headers have been sent.
897
-        if ($this->_is_UI_request === false
898
-            && is_array($this->_route)
899
-            && ! empty($this->_route['headers_sent_route'])
900
-        ) {
901
-            $this->_reset_routing_properties($this->_route['headers_sent_route']);
902
-        }
903
-    }
904
-
905
-
906
-
907
-    /**
908
-     * This method just allows the resetting of page properties in the case where a no headers
909
-     * route redirects to a headers route in its route config.
910
-     *
911
-     * @since   4.3.0
912
-     * @param  string $new_route New (non header) route to redirect to.
913
-     * @return   void
914
-     */
915
-    protected function _reset_routing_properties($new_route)
916
-    {
917
-        $this->_is_UI_request = true;
918
-        //now we set the current route to whatever the headers_sent_route is set at
919
-        $this->_req_data['action'] = $new_route;
920
-        //rerun page setup
921
-        $this->_page_setup();
922
-    }
923
-
924
-
925
-
926
-    /**
927
-     * _add_query_arg
928
-     * adds nonce to array of arguments then calls WP add_query_arg function
929
-     *(internally just uses EEH_URL's function with the same name)
930
-     *
931
-     * @access public
932
-     * @param array  $args
933
-     * @param string $url
934
-     * @param bool   $sticky                  if true, then the existing Request params will be appended to the generated
935
-     *                                        url in an associative array indexed by the key 'wp_referer';
936
-     *                                        Example usage:
937
-     *                                        If the current page is:
938
-     *                                        http://mydomain.com/wp-admin/admin.php?page=espresso_registrations
939
-     *                                        &action=default&event_id=20&month_range=March%202015
940
-     *                                        &_wpnonce=5467821
941
-     *                                        and you call:
942
-     *                                        EE_Admin_Page::add_query_args_and_nonce(
943
-     *                                        array(
944
-     *                                        'action' => 'resend_something',
945
-     *                                        'page=>espresso_registrations'
946
-     *                                        ),
947
-     *                                        $some_url,
948
-     *                                        true
949
-     *                                        );
950
-     *                                        It will produce a url in this structure:
951
-     *                                        http://{$some_url}/?page=espresso_registrations&action=resend_something
952
-     *                                        &wp_referer[action]=default&wp_referer[event_id]=20&wpreferer[
953
-     *                                        month_range]=March%202015
954
-     * @param   bool $exclude_nonce           If true, the the nonce will be excluded from the generated nonce.
955
-     * @return string
956
-     */
957
-    public static function add_query_args_and_nonce($args = array(), $url = false, $sticky = false, $exclude_nonce = false)
958
-    {
959
-        //if there is a _wp_http_referer include the values from the request but only if sticky = true
960
-        if ($sticky) {
961
-            $request = $_REQUEST;
962
-            unset($request['_wp_http_referer']);
963
-            unset($request['wp_referer']);
964
-            foreach ($request as $key => $value) {
965
-                //do not add nonces
966
-                if (strpos($key, 'nonce') !== false) {
967
-                    continue;
968
-                }
969
-                $args['wp_referer[' . $key . ']'] = $value;
970
-            }
971
-        }
972
-        return EEH_URL::add_query_args_and_nonce($args, $url, $exclude_nonce);
973
-    }
974
-
975
-
976
-
977
-    /**
978
-     * This returns a generated link that will load the related help tab.
979
-     *
980
-     * @param  string $help_tab_id the id for the connected help tab
981
-     * @param  string $icon_style  (optional) include css class for the style you want to use for the help icon.
982
-     * @param  string $help_text   (optional) send help text you want to use for the link if default not to be used
983
-     * @uses EEH_Template::get_help_tab_link()
984
-     * @return string              generated link
985
-     */
986
-    protected function _get_help_tab_link($help_tab_id, $icon_style = false, $help_text = false)
987
-    {
988
-        return EEH_Template::get_help_tab_link($help_tab_id, $this->page_slug, $this->_req_action, $icon_style, $help_text);
989
-    }
990
-
991
-
992
-
993
-    /**
994
-     * _add_help_tabs
995
-     * Note child classes define their help tabs within the page_config array.
996
-     *
997
-     * @link   http://codex.wordpress.org/Function_Reference/add_help_tab
998
-     * @access protected
999
-     * @return void
1000
-     */
1001
-    protected function _add_help_tabs()
1002
-    {
1003
-        $tour_buttons = '';
1004
-        if (isset($this->_page_config[$this->_req_action])) {
1005
-            $config = $this->_page_config[$this->_req_action];
1006
-            //is there a help tour for the current route?  if there is let's setup the tour buttons
1007
-            if (isset($this->_help_tour[$this->_req_action])) {
1008
-                $tb = array();
1009
-                $tour_buttons = '<div class="ee-abs-container"><div class="ee-help-tour-restart-buttons">';
1010
-                foreach ($this->_help_tour['tours'] as $tour) {
1011
-                    //if this is the end tour then we don't need to setup a button
1012
-                    if ($tour instanceof EE_Help_Tour_final_stop) {
1013
-                        continue;
1014
-                    }
1015
-                    $tb[] = '<button id="trigger-tour-' . $tour->get_slug() . '" class="button-primary trigger-ee-help-tour">' . $tour->get_label() . '</button>';
1016
-                }
1017
-                $tour_buttons .= implode('<br />', $tb);
1018
-                $tour_buttons .= '</div></div>';
1019
-            }
1020
-            // let's see if there is a help_sidebar set for the current route and we'll set that up for usage as well.
1021
-            if (is_array($config) && isset($config['help_sidebar'])) {
1022
-                //check that the callback given is valid
1023
-                if ( ! method_exists($this, $config['help_sidebar'])) {
1024
-                    throw new EE_Error(sprintf(__('The _page_config array has a callback set for the "help_sidebar" option.  However the callback given (%s) is not a valid callback.  Doublecheck the spelling and make sure this method exists for the class %s',
1025
-                            'event_espresso'), $config['help_sidebar'], get_class($this)));
1026
-                }
1027
-                $content = apply_filters('FHEE__' . get_class($this) . '__add_help_tabs__help_sidebar', call_user_func(array($this, $config['help_sidebar'])));
1028
-                $content .= $tour_buttons; //add help tour buttons.
1029
-                //do we have any help tours setup?  Cause if we do we want to add the buttons
1030
-                $this->_current_screen->set_help_sidebar($content);
1031
-            }
1032
-            //if we DON'T have config help sidebar and there ARE toure buttons then we'll just add the tour buttons to the sidebar.
1033
-            if ( ! isset($config['help_sidebar']) && ! empty($tour_buttons)) {
1034
-                $this->_current_screen->set_help_sidebar($tour_buttons);
1035
-            }
1036
-            //handle if no help_tabs are set so the sidebar will still show for the help tour buttons
1037
-            if ( ! isset($config['help_tabs']) && ! empty($tour_buttons)) {
1038
-                $_ht['id'] = $this->page_slug;
1039
-                $_ht['title'] = __('Help Tours', 'event_espresso');
1040
-                $_ht['content'] = '<p>' . __('The buttons to the right allow you to start/restart any help tours available for this page', 'event_espresso') . '</p>';
1041
-                $this->_current_screen->add_help_tab($_ht);
1042
-            }/**/
1043
-            if ( ! isset($config['help_tabs'])) {
1044
-                return;
1045
-            } //no help tabs for this route
1046
-            foreach ((array)$config['help_tabs'] as $tab_id => $cfg) {
1047
-                //we're here so there ARE help tabs!
1048
-                //make sure we've got what we need
1049
-                if ( ! isset($cfg['title'])) {
1050
-                    throw new EE_Error(__('The _page_config array is not set up properly for help tabs.  It is missing a title', 'event_espresso'));
1051
-                }
1052
-                if ( ! isset($cfg['filename']) && ! isset($cfg['callback']) && ! isset($cfg['content'])) {
1053
-                    throw new EE_Error(__('The _page_config array is not setup properly for help tabs. It is missing a either a filename reference, or a callback reference or a content reference so there is no way to know the content for the help tab',
1054
-                            'event_espresso'));
1055
-                }
1056
-                //first priority goes to content.
1057
-                if ( ! empty($cfg['content'])) {
1058
-                    $content = ! empty($cfg['content']) ? $cfg['content'] : null;
1059
-                    //second priority goes to filename
1060
-                } else if ( ! empty($cfg['filename'])) {
1061
-                    $file_path = $this->_get_dir() . '/help_tabs/' . $cfg['filename'] . '.help_tab.php';
1062
-                    //it's possible that the file is located on decaf route (and above sets up for caf route, if this is the case then lets check decaf route too)
1063
-                    $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES . basename($this->_get_dir()) . '/help_tabs/' . $cfg['filename'] . '.help_tab.php' : $file_path;
1064
-                    //if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1065
-                    if ( ! is_readable($file_path) && ! isset($cfg['callback'])) {
1066
-                        EE_Error::add_error(sprintf(__('The filename given for the help tab %s is not a valid file and there is no other configuration for the tab content.  Please check that the string you set for the help tab on this route (%s) is the correct spelling.  The file should be in %s',
1067
-                                'event_espresso'), $tab_id, key($config), $file_path), __FILE__, __FUNCTION__, __LINE__);
1068
-                        return;
1069
-                    }
1070
-                    $template_args['admin_page_obj'] = $this;
1071
-                    $content = EEH_Template::display_template($file_path, $template_args, true);
1072
-                } else {
1073
-                    $content = '';
1074
-                }
1075
-                //check if callback is valid
1076
-                if (empty($content) && ( ! isset($cfg['callback']) || ! method_exists($this, $cfg['callback']))) {
1077
-                    EE_Error::add_error(sprintf(__('The callback given for a %s help tab on this page does not content OR a corresponding method for generating the content.  Check the spelling or make sure the method is present.',
1078
-                            'event_espresso'), $cfg['title']), __FILE__, __FUNCTION__, __LINE__);
1079
-                    return;
1080
-                }
1081
-                //setup config array for help tab method
1082
-                $id = $this->page_slug . '-' . $this->_req_action . '-' . $tab_id;
1083
-                $_ht = array(
1084
-                        'id'       => $id,
1085
-                        'title'    => $cfg['title'],
1086
-                        'callback' => isset($cfg['callback']) && empty($content) ? array($this, $cfg['callback']) : null,
1087
-                        'content'  => $content,
1088
-                );
1089
-                $this->_current_screen->add_help_tab($_ht);
1090
-            }
1091
-        }
1092
-    }
1093
-
1094
-
1095
-
1096
-    /**
1097
-     * This basically checks loaded $_page_config property to see if there are any help_tours defined.  "help_tours" is an array with properties for setting up usage of the joyride plugin
1098
-     *
1099
-     * @link   http://zurb.com/playground/jquery-joyride-feature-tour-plugin
1100
-     * @see    instructions regarding the format and construction of the "help_tour" array element is found in the _set_page_config() comments
1101
-     * @access protected
1102
-     * @return void
1103
-     */
1104
-    protected function _add_help_tour()
1105
-    {
1106
-        $tours = array();
1107
-        $this->_help_tour = array();
1108
-        //exit early if help tours are turned off globally
1109
-        if ( ! EE_Registry::instance()->CFG->admin->help_tour_activation || (defined('EE_DISABLE_HELP_TOURS') && EE_DISABLE_HELP_TOURS)) {
1110
-            return;
1111
-        }
1112
-        //loop through _page_config to find any help_tour defined
1113
-        foreach ($this->_page_config as $route => $config) {
1114
-            //we're only going to set things up for this route
1115
-            if ($route !== $this->_req_action) {
1116
-                continue;
1117
-            }
1118
-            if (isset($config['help_tour'])) {
1119
-                foreach ($config['help_tour'] as $tour) {
1120
-                    $file_path = $this->_get_dir() . '/help_tours/' . $tour . '.class.php';
1121
-                    //let's see if we can get that file... if not its possible this is a decaf route not set in caffienated so lets try and get the caffeinated equivalent
1122
-                    $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES . basename($this->_get_dir()) . '/help_tours/' . $tour . '.class.php' : $file_path;
1123
-                    //if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1124
-                    if ( ! is_readable($file_path)) {
1125
-                        EE_Error::add_error(sprintf(__('The file path given for the help tour (%s) is not a valid path.  Please check that the string you set for the help tour on this route (%s) is the correct spelling', 'event_espresso'),
1126
-                                $file_path, $tour), __FILE__, __FUNCTION__, __LINE__);
1127
-                        return;
1128
-                    }
1129
-                    require_once $file_path;
1130
-                    if ( ! class_exists($tour)) {
1131
-                        $error_msg[] = sprintf(__('Something went wrong with loading the %s Help Tour Class.', 'event_espresso'), $tour);
1132
-                        $error_msg[] = $error_msg[0] . "\r\n" . sprintf(__('There is no class in place for the %s help tour.%s Make sure you have <strong>%s</strong> defined in the "help_tour" array for the %s route of the % admin page.',
1133
-                                        'event_espresso'), $tour, '<br />', $tour, $this->_req_action, get_class($this));
1134
-                        throw new EE_Error(implode('||', $error_msg));
1135
-                    }
1136
-                    $a = new ReflectionClass($tour);
1137
-                    $tour_obj = $a->newInstance($this->_is_caf);
1138
-                    $tours[] = $tour_obj;
1139
-                    $this->_help_tour[$route][] = EEH_Template::help_tour_stops_generator($tour_obj);
1140
-                }
1141
-                //let's inject the end tour stop element common to all pages... this will only get seen once per machine.
1142
-                $end_stop_tour = new EE_Help_Tour_final_stop($this->_is_caf);
1143
-                $tours[] = $end_stop_tour;
1144
-                $this->_help_tour[$route][] = EEH_Template::help_tour_stops_generator($end_stop_tour);
1145
-            }
1146
-        }
1147
-        if ( ! empty($tours)) {
1148
-            $this->_help_tour['tours'] = $tours;
1149
-        }
1150
-        //thats it!  Now that the $_help_tours property is set (or not) the scripts and html should be taken care of automatically.
1151
-    }
1152
-
1153
-
1154
-
1155
-    /**
1156
-     * This simply sets up any qtips that have been defined in the page config
1157
-     *
1158
-     * @access protected
1159
-     * @return void
1160
-     */
1161
-    protected function _add_qtips()
1162
-    {
1163
-        if (isset($this->_route_config['qtips'])) {
1164
-            $qtips = (array)$this->_route_config['qtips'];
1165
-            //load qtip loader
1166
-            $path = array(
1167
-                    $this->_get_dir() . '/qtips/',
1168
-                    EE_ADMIN_PAGES . basename($this->_get_dir()) . '/qtips/',
1169
-            );
1170
-            EEH_Qtip_Loader::instance()->register($qtips, $path);
1171
-        }
1172
-    }
1173
-
1174
-
1175
-
1176
-    /**
1177
-     * _set_nav_tabs
1178
-     * This sets up the nav tabs from the page_routes array.  This method can be overwritten by child classes if you wish to add additional tabs or modify accordingly.
1179
-     *
1180
-     * @access protected
1181
-     * @return void
1182
-     */
1183
-    protected function _set_nav_tabs()
1184
-    {
1185
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1186
-        $i = 0;
1187
-        foreach ($this->_page_config as $slug => $config) {
1188
-            if ( ! is_array($config) || (is_array($config) && (isset($config['nav']) && ! $config['nav']) || ! isset($config['nav']))) {
1189
-                continue;
1190
-            } //no nav tab for this config
1191
-            //check for persistent flag
1192
-            if (isset($config['nav']['persistent']) && ! $config['nav']['persistent'] && $slug !== $this->_req_action) {
1193
-                continue;
1194
-            } //nav tab is only to appear when route requested.
1195
-            if ( ! $this->check_user_access($slug, true)) {
1196
-                continue;
1197
-            } //no nav tab becasue current user does not have access.
1198
-            $css_class = isset($config['css_class']) ? $config['css_class'] . ' ' : '';
1199
-            $this->_nav_tabs[$slug] = array(
1200
-                    'url'       => isset($config['nav']['url']) ? $config['nav']['url'] : self::add_query_args_and_nonce(array('action' => $slug), $this->_admin_base_url),
1201
-                    'link_text' => isset($config['nav']['label']) ? $config['nav']['label'] : ucwords(str_replace('_', ' ', $slug)),
1202
-                    'css_class' => $this->_req_action == $slug ? $css_class . 'nav-tab-active' : $css_class,
1203
-                    'order'     => isset($config['nav']['order']) ? $config['nav']['order'] : $i,
1204
-            );
1205
-            $i++;
1206
-        }
1207
-        //if $this->_nav_tabs is empty then lets set the default
1208
-        if (empty($this->_nav_tabs)) {
1209
-            $this->_nav_tabs[$this->default_nav_tab_name] = array(
1210
-                    'url'       => $this->admin_base_url,
1211
-                    'link_text' => ucwords(str_replace('_', ' ', $this->default_nav_tab_name)),
1212
-                    'css_class' => 'nav-tab-active',
1213
-                    'order'     => 10,
1214
-            );
1215
-        }
1216
-        //now let's sort the tabs according to order
1217
-        usort($this->_nav_tabs, array($this, '_sort_nav_tabs'));
1218
-    }
1219
-
1220
-
1221
-
1222
-    /**
1223
-     * _set_current_labels
1224
-     * This method modifies the _labels property with any optional specific labels indicated in the _page_routes property array
1225
-     *
1226
-     * @access private
1227
-     * @return void
1228
-     */
1229
-    private function _set_current_labels()
1230
-    {
1231
-        if (is_array($this->_route_config) && isset($this->_route_config['labels'])) {
1232
-            foreach ($this->_route_config['labels'] as $label => $text) {
1233
-                if (is_array($text)) {
1234
-                    foreach ($text as $sublabel => $subtext) {
1235
-                        $this->_labels[$label][$sublabel] = $subtext;
1236
-                    }
1237
-                } else {
1238
-                    $this->_labels[$label] = $text;
1239
-                }
1240
-            }
1241
-        }
1242
-    }
1243
-
1244
-
1245
-
1246
-    /**
1247
-     *        verifies user access for this admin page
1248
-     *
1249
-     * @param string $route_to_check if present then the capability for the route matching this string is checked.
1250
-     * @param bool   $verify_only    Default is FALSE which means if user check fails then wp_die().  Otherwise just return false if verify fail.
1251
-     * @return        BOOL|wp_die()
1252
-     */
1253
-    public function check_user_access($route_to_check = '', $verify_only = false)
1254
-    {
1255
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1256
-        $route_to_check = empty($route_to_check) ? $this->_req_action : $route_to_check;
1257
-        $capability = ! empty($route_to_check) && isset($this->_page_routes[$route_to_check]) && is_array($this->_page_routes[$route_to_check]) && ! empty($this->_page_routes[$route_to_check]['capability'])
1258
-                ? $this->_page_routes[$route_to_check]['capability'] : null;
1259
-        if (empty($capability) && empty($route_to_check)) {
1260
-            $capability = is_array($this->_route) && empty($this->_route['capability']) ? 'manage_options' : $this->_route['capability'];
1261
-        } else {
1262
-            $capability = empty($capability) ? 'manage_options' : $capability;
1263
-        }
1264
-        $id = is_array($this->_route) && ! empty($this->_route['obj_id']) ? $this->_route['obj_id'] : 0;
1265
-        if (( ! function_exists('is_admin') || ! EE_Registry::instance()->CAP->current_user_can($capability, $this->page_slug . '_' . $route_to_check, $id)) && ! defined('DOING_AJAX')) {
1266
-            if ($verify_only) {
1267
-                return false;
1268
-            } else {
1269
-                if ( is_user_logged_in() ) {
1270
-                    wp_die(__('You do not have access to this route.', 'event_espresso'));
1271
-                } else {
1272
-                    return false;
1273
-                }
1274
-            }
1275
-        }
1276
-        return true;
1277
-    }
1278
-
1279
-
1280
-
1281
-    /**
1282
-     * admin_init_global
1283
-     * This runs all the code that we want executed within the WP admin_init hook.
1284
-     * This method executes for ALL EE Admin pages.
1285
-     *
1286
-     * @access public
1287
-     * @return void
1288
-     */
1289
-    public function admin_init_global()
1290
-    {
1291
-    }
1292
-
1293
-
1294
-
1295
-    /**
1296
-     * wp_loaded_global
1297
-     * This runs all the code that we want executed within the WP wp_loaded hook.  This method is optional for an EE_Admin page and will execute on every EE Admin Page load
1298
-     *
1299
-     * @access public
1300
-     * @return void
1301
-     */
1302
-    public function wp_loaded()
1303
-    {
1304
-    }
1305
-
1306
-
1307
-
1308
-    /**
1309
-     * admin_notices
1310
-     * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply on ALL EE_Admin pages.
1311
-     *
1312
-     * @access public
1313
-     * @return void
1314
-     */
1315
-    public function admin_notices_global()
1316
-    {
1317
-        $this->_display_no_javascript_warning();
1318
-        $this->_display_espresso_notices();
1319
-    }
1320
-
1321
-
1322
-
1323
-    public function network_admin_notices_global()
1324
-    {
1325
-        $this->_display_no_javascript_warning();
1326
-        $this->_display_espresso_notices();
1327
-    }
1328
-
1329
-
1330
-
1331
-    /**
1332
-     * admin_footer_scripts_global
1333
-     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method will apply on ALL EE_Admin pages.
1334
-     *
1335
-     * @access public
1336
-     * @return void
1337
-     */
1338
-    public function admin_footer_scripts_global()
1339
-    {
1340
-        $this->_add_admin_page_ajax_loading_img();
1341
-        $this->_add_admin_page_overlay();
1342
-        //if metaboxes are present we need to add the nonce field
1343
-        if ((isset($this->_route_config['metaboxes']) || (isset($this->_route_config['has_metaboxes']) && $this->_route_config['has_metaboxes']) || isset($this->_route_config['list_table']))) {
1344
-            wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
1345
-            wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
1346
-        }
1347
-    }
1348
-
1349
-
1350
-
1351
-    /**
1352
-     * admin_footer_global
1353
-     * Anything triggered by the wp 'admin_footer' wp hook should be put in here. This particluar method will apply on ALL EE_Admin Pages.
1354
-     *
1355
-     * @access  public
1356
-     * @return  void
1357
-     */
1358
-    public function admin_footer_global()
1359
-    {
1360
-        //dialog container for dialog helper
1361
-        $d_cont = '<div class="ee-admin-dialog-container auto-hide hidden">' . "\n";
1362
-        $d_cont .= '<div class="ee-notices"></div>';
1363
-        $d_cont .= '<div class="ee-admin-dialog-container-inner-content"></div>';
1364
-        $d_cont .= '</div>';
1365
-        echo $d_cont;
1366
-        //help tour stuff?
1367
-        if (isset($this->_help_tour[$this->_req_action])) {
1368
-            echo implode('<br />', $this->_help_tour[$this->_req_action]);
1369
-        }
1370
-        //current set timezone for timezone js
1371
-        echo '<span id="current_timezone" class="hidden">' . EEH_DTT_Helper::get_timezone() . '</span>';
1372
-    }
1373
-
1374
-
1375
-
1376
-    /**
1377
-     * This function sees if there is a method for help popup content existing for the given route.  If there is then we'll use the retrieved array to output the content using the template.
1378
-     * For child classes:
1379
-     * If you want to have help popups then in your templates or your content you set "triggers" for the content using the "_set_help_trigger('help_trigger_id')" where "help_trigger_id" is what you will use later in your custom method for
1380
-     * the help popup content on that page. Then in your Child_Admin_Page class you need to define a help popup method for the content in the format "_help_popup_content_{route_name}()"  So if you are setting help content for the
1381
-     * 'edit_event' route you should have a method named "_help_popup_content_edit_route". In your defined "help_popup_content_..." method.  You must prepare and return an array in the following format array(
1382
-     *    'help_trigger_id' => array(
1383
-     *        'title' => __('localized title for popup', 'event_espresso'),
1384
-     *        'content' => __('localized content for popup', 'event_espresso')
1385
-     *    )
1386
-     * );
1387
-     * Then the EE_Admin_Parent will take care of making sure that is setup properly on the correct route.
1388
-     *
1389
-     * @access protected
1390
-     * @return string content
1391
-     */
1392
-    protected function _set_help_popup_content($help_array = array(), $display = false)
1393
-    {
1394
-        $content = '';
1395
-        $help_array = empty($help_array) ? $this->_get_help_content() : $help_array;
1396
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_help_popup.template.php';
1397
-        //loop through the array and setup content
1398
-        foreach ($help_array as $trigger => $help) {
1399
-            //make sure the array is setup properly
1400
-            if ( ! isset($help['title']) || ! isset($help['content'])) {
1401
-                throw new EE_Error(__('Does not look like the popup content array has been setup correctly.  Might want to double check that.  Read the comments for the _get_help_popup_content method found in "EE_Admin_Page" class',
1402
-                        'event_espresso'));
1403
-            }
1404
-            //we're good so let'd setup the template vars and then assign parsed template content to our content.
1405
-            $template_args = array(
1406
-                    'help_popup_id'      => $trigger,
1407
-                    'help_popup_title'   => $help['title'],
1408
-                    'help_popup_content' => $help['content'],
1409
-            );
1410
-            $content .= EEH_Template::display_template($template_path, $template_args, true);
1411
-        }
1412
-        if ($display) {
1413
-            echo $content;
1414
-        } else {
1415
-            return $content;
1416
-        }
1417
-    }
1418
-
1419
-
1420
-
1421
-    /**
1422
-     * All this does is retrive the help content array if set by the EE_Admin_Page child
1423
-     *
1424
-     * @access private
1425
-     * @return array properly formatted array for help popup content
1426
-     */
1427
-    private function _get_help_content()
1428
-    {
1429
-        //what is the method we're looking for?
1430
-        $method_name = '_help_popup_content_' . $this->_req_action;
1431
-        //if method doesn't exist let's get out.
1432
-        if ( ! method_exists($this, $method_name)) {
1433
-            return array();
1434
-        }
1435
-        //k we're good to go let's retrieve the help array
1436
-        $help_array = call_user_func(array($this, $method_name));
1437
-        //make sure we've got an array!
1438
-        if ( ! is_array($help_array)) {
1439
-            throw new EE_Error(__('Something went wrong with help popup content generation. Expecting an array and well, this ain\'t no array bub.', 'event_espresso'));
1440
-        }
1441
-        return $help_array;
1442
-    }
1443
-
1444
-
1445
-
1446
-    /**
1447
-     * EE Admin Pages can use this to set a properly formatted trigger for a help popup.
1448
-     * By default the trigger html is printed.  Otherwise it can be returned if the $display flag is set "false"
1449
-     * See comments made on the _set_help_content method for understanding other parts to the help popup tool.
1450
-     *
1451
-     * @access protected
1452
-     * @param string  $trigger_id reference for retrieving the trigger content for the popup
1453
-     * @param boolean $display    if false then we return the trigger string
1454
-     * @param array   $dimensions an array of dimensions for the box (array(h,w))
1455
-     * @return string
1456
-     */
1457
-    protected function _set_help_trigger($trigger_id, $display = true, $dimensions = array('400', '640'))
1458
-    {
1459
-        if (defined('DOING_AJAX')) {
1460
-            return;
1461
-        }
1462
-        //let's check and see if there is any content set for this popup.  If there isn't then we'll include a default title and content so that developers know something needs to be corrected
1463
-        $help_array = $this->_get_help_content();
1464
-        $help_content = '';
1465
-        if (empty($help_array) || ! isset($help_array[$trigger_id])) {
1466
-            $help_array[$trigger_id] = array(
1467
-                    'title'   => __('Missing Content', 'event_espresso'),
1468
-                    'content' => __('A trigger has been set that doesn\'t have any corresponding content. Make sure you have set the help content. (see the "_set_help_popup_content" method in the EE_Admin_Page for instructions.)',
1469
-                            'event_espresso'),
1470
-            );
1471
-            $help_content = $this->_set_help_popup_content($help_array, false);
1472
-        }
1473
-        //let's setup the trigger
1474
-        $content = '<a class="ee-dialog" href="?height=' . $dimensions[0] . '&width=' . $dimensions[1] . '&inlineId=' . $trigger_id . '" target="_blank"><span class="question ee-help-popup-question"></span></a>';
1475
-        $content = $content . $help_content;
1476
-        if ($display) {
1477
-            echo $content;
1478
-        } else {
1479
-            return $content;
1480
-        }
1481
-    }
1482
-
1483
-
1484
-
1485
-    /**
1486
-     * _add_global_screen_options
1487
-     * Add any extra wp_screen_options within this method using built-in WP functions/methods for doing so.
1488
-     * This particular method will add_screen_options on ALL EE_Admin Pages
1489
-     *
1490
-     * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
1491
-     *         see also WP_Screen object documents...
1492
-     * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
1493
-     * @abstract
1494
-     * @access private
1495
-     * @return void
1496
-     */
1497
-    private function _add_global_screen_options()
1498
-    {
1499
-    }
1500
-
1501
-
1502
-
1503
-    /**
1504
-     * _add_global_feature_pointers
1505
-     * This method is used for implementing any "feature pointers" (using built-in WP styling js).
1506
-     * This particular method will implement feature pointers for ALL EE_Admin pages.
1507
-     * Note: this is just a placeholder for now.  Implementation will come down the road
1508
-     *
1509
-     * @see    WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be extended) also see:
1510
-     * @link   http://eamann.com/tech/wordpress-portland/
1511
-     * @abstract
1512
-     * @access protected
1513
-     * @return void
1514
-     */
1515
-    private function _add_global_feature_pointers()
1516
-    {
1517
-    }
1518
-
1519
-
1520
-
1521
-    /**
1522
-     * load_global_scripts_styles
1523
-     * The scripts and styles enqueued in here will be loaded on every EE Admin page
1524
-     *
1525
-     * @return void
1526
-     */
1527
-    public function load_global_scripts_styles()
1528
-    {
1529
-        /** STYLES **/
1530
-        // add debugging styles
1531
-        if (WP_DEBUG) {
1532
-            add_action('admin_head', array($this, 'add_xdebug_style'));
1533
-        }
1534
-        //register all styles
1535
-        wp_register_style('espresso-ui-theme', EE_GLOBAL_ASSETS_URL . 'css/espresso-ui-theme/jquery-ui-1.10.3.custom.min.css', array(), EVENT_ESPRESSO_VERSION);
1536
-        wp_register_style('ee-admin-css', EE_ADMIN_URL . 'assets/ee-admin-page.css', array(), EVENT_ESPRESSO_VERSION);
1537
-        //helpers styles
1538
-        wp_register_style('ee-text-links', EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.css', array(), EVENT_ESPRESSO_VERSION);
1539
-        //enqueue global styles
1540
-        wp_enqueue_style('ee-admin-css');
1541
-        /** SCRIPTS **/
1542
-        //register all scripts
1543
-        wp_register_script('espresso_core', EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js', array('jquery'), EVENT_ESPRESSO_VERSION, true);
1544
-        wp_register_script('ee-dialog', EE_ADMIN_URL . 'assets/ee-dialog-helper.js', array('jquery', 'jquery-ui-draggable'), EVENT_ESPRESSO_VERSION, true);
1545
-        wp_register_script('ee_admin_js', EE_ADMIN_URL . 'assets/ee-admin-page.js', array('espresso_core', 'ee-parse-uri', 'ee-dialog'), EVENT_ESPRESSO_VERSION, true);
1546
-        wp_register_script('jquery-ui-timepicker-addon', EE_GLOBAL_ASSETS_URL . 'scripts/jquery-ui-timepicker-addon.js', array('jquery-ui-datepicker', 'jquery-ui-slider'), EVENT_ESPRESSO_VERSION, true);
1547
-        // register jQuery Validate - see /includes/functions/wp_hooks.php
1548
-        add_filter('FHEE_load_jquery_validate', '__return_true');
1549
-        add_filter('FHEE_load_joyride', '__return_true');
1550
-        //script for sorting tables
1551
-        wp_register_script('espresso_ajax_table_sorting', EE_ADMIN_URL . "assets/espresso_ajax_table_sorting.js", array('ee_admin_js', 'jquery-ui-sortable'), EVENT_ESPRESSO_VERSION, true);
1552
-        //script for parsing uri's
1553
-        wp_register_script('ee-parse-uri', EE_GLOBAL_ASSETS_URL . 'scripts/parseuri.js', array(), EVENT_ESPRESSO_VERSION, true);
1554
-        //and parsing associative serialized form elements
1555
-        wp_register_script('ee-serialize-full-array', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.serializefullarray.js', array('jquery'), EVENT_ESPRESSO_VERSION, true);
1556
-        //helpers scripts
1557
-        wp_register_script('ee-text-links', EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.js', array('jquery'), EVENT_ESPRESSO_VERSION, true);
1558
-        wp_register_script('ee-moment-core', EE_THIRD_PARTY_URL . 'moment/moment-with-locales.min.js', array(), EVENT_ESPRESSO_VERSION, true);
1559
-        wp_register_script('ee-moment', EE_THIRD_PARTY_URL . 'moment/moment-timezone-with-data.min.js', array('ee-moment-core'), EVENT_ESPRESSO_VERSION, true);
1560
-        wp_register_script('ee-datepicker', EE_ADMIN_URL . 'assets/ee-datepicker.js', array('jquery-ui-timepicker-addon', 'ee-moment'), EVENT_ESPRESSO_VERSION, true);
1561
-        //google charts
1562
-        wp_register_script('google-charts', 'https://www.gstatic.com/charts/loader.js', array(), EVENT_ESPRESSO_VERSION, false);
1563
-        //enqueue global scripts
1564
-        //taking care of metaboxes
1565
-        if ((isset($this->_route_config['metaboxes']) || isset($this->_route_config['has_metaboxes'])) && empty($this->_cpt_route)) {
1566
-            wp_enqueue_script('dashboard');
1567
-        }
1568
-        //enqueue thickbox for ee help popups.  default is to enqueue unless its explicitly set to false since we're assuming all EE pages will have popups
1569
-        if ( ! isset($this->_route_config['has_help_popups']) || (isset($this->_route_config['has_help_popups']) && $this->_route_config['has_help_popups'])) {
1570
-            wp_enqueue_script('ee_admin_js');
1571
-            wp_enqueue_style('ee-admin-css');
1572
-        }
1573
-        //localize script for ajax lazy loading
1574
-        $lazy_loader_container_ids = apply_filters('FHEE__EE_Admin_Page_Core__load_global_scripts_styles__loader_containers', array('espresso_news_post_box_content'));
1575
-        wp_localize_script('ee_admin_js', 'eeLazyLoadingContainers', $lazy_loader_container_ids);
1576
-        /**
1577
-         * help tour stuff
1578
-         */
1579
-        if ( ! empty($this->_help_tour)) {
1580
-            //register the js for kicking things off
1581
-            wp_enqueue_script('ee-help-tour', EE_ADMIN_URL . 'assets/ee-help-tour.js', array('jquery-joyride'), EVENT_ESPRESSO_VERSION, true);
1582
-            //setup tours for the js tour object
1583
-            foreach ($this->_help_tour['tours'] as $tour) {
1584
-                $tours[] = array(
1585
-                        'id'      => $tour->get_slug(),
1586
-                        'options' => $tour->get_options(),
1587
-                );
1588
-            }
1589
-            wp_localize_script('ee-help-tour', 'EE_HELP_TOUR', array('tours' => $tours));
1590
-            //admin_footer_global will take care of making sure our help_tour skeleton gets printed via the info stored in $this->_help_tour
1591
-        }
1592
-    }
1593
-
1594
-
1595
-
1596
-    /**
1597
-     *        admin_footer_scripts_eei18n_js_strings
1598
-     *
1599
-     * @access        public
1600
-     * @return        void
1601
-     */
1602
-    public function admin_footer_scripts_eei18n_js_strings()
1603
-    {
1604
-        EE_Registry::$i18n_js_strings['ajax_url'] = WP_AJAX_URL;
1605
-        EE_Registry::$i18n_js_strings['confirm_delete'] = __('Are you absolutely sure you want to delete this item?\nThis action will delete ALL DATA associated with this item!!!\nThis can NOT be undone!!!', 'event_espresso');
1606
-        EE_Registry::$i18n_js_strings['January'] = __('January', 'event_espresso');
1607
-        EE_Registry::$i18n_js_strings['February'] = __('February', 'event_espresso');
1608
-        EE_Registry::$i18n_js_strings['March'] = __('March', 'event_espresso');
1609
-        EE_Registry::$i18n_js_strings['April'] = __('April', 'event_espresso');
1610
-        EE_Registry::$i18n_js_strings['May'] = __('May', 'event_espresso');
1611
-        EE_Registry::$i18n_js_strings['June'] = __('June', 'event_espresso');
1612
-        EE_Registry::$i18n_js_strings['July'] = __('July', 'event_espresso');
1613
-        EE_Registry::$i18n_js_strings['August'] = __('August', 'event_espresso');
1614
-        EE_Registry::$i18n_js_strings['September'] = __('September', 'event_espresso');
1615
-        EE_Registry::$i18n_js_strings['October'] = __('October', 'event_espresso');
1616
-        EE_Registry::$i18n_js_strings['November'] = __('November', 'event_espresso');
1617
-        EE_Registry::$i18n_js_strings['December'] = __('December', 'event_espresso');
1618
-        EE_Registry::$i18n_js_strings['Jan'] = __('Jan', 'event_espresso');
1619
-        EE_Registry::$i18n_js_strings['Feb'] = __('Feb', 'event_espresso');
1620
-        EE_Registry::$i18n_js_strings['Mar'] = __('Mar', 'event_espresso');
1621
-        EE_Registry::$i18n_js_strings['Apr'] = __('Apr', 'event_espresso');
1622
-        EE_Registry::$i18n_js_strings['May'] = __('May', 'event_espresso');
1623
-        EE_Registry::$i18n_js_strings['Jun'] = __('Jun', 'event_espresso');
1624
-        EE_Registry::$i18n_js_strings['Jul'] = __('Jul', 'event_espresso');
1625
-        EE_Registry::$i18n_js_strings['Aug'] = __('Aug', 'event_espresso');
1626
-        EE_Registry::$i18n_js_strings['Sep'] = __('Sep', 'event_espresso');
1627
-        EE_Registry::$i18n_js_strings['Oct'] = __('Oct', 'event_espresso');
1628
-        EE_Registry::$i18n_js_strings['Nov'] = __('Nov', 'event_espresso');
1629
-        EE_Registry::$i18n_js_strings['Dec'] = __('Dec', 'event_espresso');
1630
-        EE_Registry::$i18n_js_strings['Sunday'] = __('Sunday', 'event_espresso');
1631
-        EE_Registry::$i18n_js_strings['Monday'] = __('Monday', 'event_espresso');
1632
-        EE_Registry::$i18n_js_strings['Tuesday'] = __('Tuesday', 'event_espresso');
1633
-        EE_Registry::$i18n_js_strings['Wednesday'] = __('Wednesday', 'event_espresso');
1634
-        EE_Registry::$i18n_js_strings['Thursday'] = __('Thursday', 'event_espresso');
1635
-        EE_Registry::$i18n_js_strings['Friday'] = __('Friday', 'event_espresso');
1636
-        EE_Registry::$i18n_js_strings['Saturday'] = __('Saturday', 'event_espresso');
1637
-        EE_Registry::$i18n_js_strings['Sun'] = __('Sun', 'event_espresso');
1638
-        EE_Registry::$i18n_js_strings['Mon'] = __('Mon', 'event_espresso');
1639
-        EE_Registry::$i18n_js_strings['Tue'] = __('Tue', 'event_espresso');
1640
-        EE_Registry::$i18n_js_strings['Wed'] = __('Wed', 'event_espresso');
1641
-        EE_Registry::$i18n_js_strings['Thu'] = __('Thu', 'event_espresso');
1642
-        EE_Registry::$i18n_js_strings['Fri'] = __('Fri', 'event_espresso');
1643
-        EE_Registry::$i18n_js_strings['Sat'] = __('Sat', 'event_espresso');
1644
-        //setting on espresso_core instead of ee_admin_js because espresso_core is enqueued by the maintenance
1645
-        //admin page when in maintenance mode and ee_admin_js is not loaded then.  This works everywhere else because
1646
-        //espresso_core is listed as a dependency of ee_admin_js.
1647
-        wp_localize_script('espresso_core', 'eei18n', EE_Registry::$i18n_js_strings);
1648
-    }
1649
-
1650
-
1651
-
1652
-    /**
1653
-     *        load enhanced xdebug styles for ppl with failing eyesight
1654
-     *
1655
-     * @access        public
1656
-     * @return        void
1657
-     */
1658
-    public function add_xdebug_style()
1659
-    {
1660
-        echo '<style>.xdebug-error { font-size:1.5em; }</style>';
1661
-    }
1662
-
1663
-
1664
-    /************************/
1665
-    /** LIST TABLE METHODS **/
1666
-    /************************/
1667
-    /**
1668
-     * this sets up the list table if the current view requires it.
1669
-     *
1670
-     * @access protected
1671
-     * @return void
1672
-     */
1673
-    protected function _set_list_table()
1674
-    {
1675
-        //first is this a list_table view?
1676
-        if ( ! isset($this->_route_config['list_table'])) {
1677
-            return;
1678
-        } //not a list_table view so get out.
1679
-        //list table functions are per view specific (because some admin pages might have more than one listtable!)
1680
-        if (call_user_func(array($this, '_set_list_table_views_' . $this->_req_action)) === false) {
1681
-            //user error msg
1682
-            $error_msg = __('An error occurred. The requested list table views could not be found.', 'event_espresso');
1683
-            //developer error msg
1684
-            $error_msg .= '||' . sprintf(__('List table views for "%s" route could not be setup. Check that you have the corresponding method, "%s" set up for defining list_table_views for this route.', 'event_espresso'),
1685
-                            $this->_req_action, '_set_list_table_views_' . $this->_req_action);
1686
-            throw new EE_Error($error_msg);
1687
-        }
1688
-        //let's provide the ability to filter the views per PAGE AND ROUTE, per PAGE, and globally
1689
-        $this->_views = apply_filters('FHEE_list_table_views_' . $this->page_slug . '_' . $this->_req_action, $this->_views);
1690
-        $this->_views = apply_filters('FHEE_list_table_views_' . $this->page_slug, $this->_views);
1691
-        $this->_views = apply_filters('FHEE_list_table_views', $this->_views);
1692
-        $this->_set_list_table_view();
1693
-        $this->_set_list_table_object();
1694
-    }
1695
-
1696
-
1697
-
1698
-    /**
1699
-     *        set current view for List Table
1700
-     *
1701
-     * @access public
1702
-     * @return array
1703
-     */
1704
-    protected function _set_list_table_view()
1705
-    {
1706
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1707
-        // looking at active items or dumpster diving ?
1708
-        if ( ! isset($this->_req_data['status']) || ! array_key_exists($this->_req_data['status'], $this->_views)) {
1709
-            $this->_view = isset($this->_views['in_use']) ? 'in_use' : 'all';
1710
-        } else {
1711
-            $this->_view = sanitize_key($this->_req_data['status']);
1712
-        }
1713
-    }
1714
-
1715
-
1716
-
1717
-    /**
1718
-     * _set_list_table_object
1719
-     * WP_List_Table objects need to be loaded fairly early so automatic stuff WP does is taken care of.
1720
-     *
1721
-     * @throws \EE_Error
1722
-     */
1723
-    protected function _set_list_table_object()
1724
-    {
1725
-        if (isset($this->_route_config['list_table'])) {
1726
-            if ( ! class_exists($this->_route_config['list_table'])) {
1727
-                throw new EE_Error(
1728
-                        sprintf(
1729
-                                __(
1730
-                                        'The %s class defined for the list table does not exist.  Please check the spelling of the class ref in the $_page_config property on %s.',
1731
-                                        'event_espresso'
1732
-                                ),
1733
-                                $this->_route_config['list_table'],
1734
-                                get_class($this)
1735
-                        )
1736
-                );
1737
-            }
1738
-            $list_table = $this->_route_config['list_table'];
1739
-            $this->_list_table_object = new $list_table($this);
1740
-        }
1741
-    }
1742
-
1743
-
1744
-
1745
-    /**
1746
-     * get_list_table_view_RLs - get it? View RL ?? VU-RL???  URL ??
1747
-     *
1748
-     * @param array $extra_query_args                     Optional. An array of extra query args to add to the generated
1749
-     *                                                    urls.  The array should be indexed by the view it is being
1750
-     *                                                    added to.
1751
-     * @return array
1752
-     */
1753
-    public function get_list_table_view_RLs($extra_query_args = array())
1754
-    {
1755
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1756
-        if (empty($this->_views)) {
1757
-            $this->_views = array();
1758
-        }
1759
-        // cycle thru views
1760
-        foreach ($this->_views as $key => $view) {
1761
-            $query_args = array();
1762
-            // check for current view
1763
-            $this->_views[$key]['class'] = $this->_view == $view['slug'] ? 'current' : '';
1764
-            $query_args['action'] = $this->_req_action;
1765
-            $query_args[$this->_req_action . '_nonce'] = wp_create_nonce($query_args['action'] . '_nonce');
1766
-            $query_args['status'] = $view['slug'];
1767
-            //merge any other arguments sent in.
1768
-            if (isset($extra_query_args[$view['slug']])) {
1769
-                $query_args = array_merge($query_args, $extra_query_args[$view['slug']]);
1770
-            }
1771
-            $this->_views[$key]['url'] = EE_Admin_Page::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1772
-        }
1773
-        return $this->_views;
1774
-    }
1775
-
1776
-
1777
-
1778
-    /**
1779
-     * _entries_per_page_dropdown
1780
-     * generates a drop down box for selecting the number of visiable rows in an admin page list table
1781
-     *
1782
-     * @todo   : Note: ideally this should be added to the screen options dropdown as that would be consistent with how WP does it.
1783
-     * @access protected
1784
-     * @param int $max_entries total number of rows in the table
1785
-     * @return string
1786
-     */
1787
-    protected function _entries_per_page_dropdown($max_entries = false)
1788
-    {
1789
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1790
-        $values = array(10, 25, 50, 100);
1791
-        $per_page = ( ! empty($this->_req_data['per_page'])) ? absint($this->_req_data['per_page']) : 10;
1792
-        if ($max_entries) {
1793
-            $values[] = $max_entries;
1794
-            sort($values);
1795
-        }
1796
-        $entries_per_page_dropdown = '
143
+	// yes / no array for admin form fields
144
+	protected $_yes_no_values = array();
145
+
146
+	//some default things shared by all child classes
147
+	protected $_default_espresso_metaboxes;
148
+
149
+	/**
150
+	 *    EE_Registry Object
151
+	 *
152
+	 * @var    EE_Registry
153
+	 * @access    protected
154
+	 */
155
+	protected $EE = null;
156
+
157
+
158
+
159
+	/**
160
+	 * This is just a property that flags whether the given route is a caffeinated route or not.
161
+	 *
162
+	 * @var boolean
163
+	 */
164
+	protected $_is_caf = false;
165
+
166
+
167
+
168
+	/**
169
+	 * @Constructor
170
+	 * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
171
+	 * @access public
172
+	 */
173
+	public function __construct($routing = true)
174
+	{
175
+		if (strpos($this->_get_dir(), 'caffeinated') !== false) {
176
+			$this->_is_caf = true;
177
+		}
178
+		$this->_yes_no_values = array(
179
+				array('id' => true, 'text' => __('Yes', 'event_espresso')),
180
+				array('id' => false, 'text' => __('No', 'event_espresso')),
181
+		);
182
+		//set the _req_data property.
183
+		$this->_req_data = array_merge($_GET, $_POST);
184
+		//routing enabled?
185
+		$this->_routing = $routing;
186
+		//set initial page props (child method)
187
+		$this->_init_page_props();
188
+		//set global defaults
189
+		$this->_set_defaults();
190
+		//set early because incoming requests could be ajax related and we need to register those hooks.
191
+		$this->_global_ajax_hooks();
192
+		$this->_ajax_hooks();
193
+		//other_page_hooks have to be early too.
194
+		$this->_do_other_page_hooks();
195
+		//This just allows us to have extending clases do something specific before the parent constructor runs _page_setup.
196
+		if (method_exists($this, '_before_page_setup')) {
197
+			$this->_before_page_setup();
198
+		}
199
+		//set up page dependencies
200
+		$this->_page_setup();
201
+	}
202
+
203
+
204
+
205
+	/**
206
+	 * _init_page_props
207
+	 * Child classes use to set at least the following properties:
208
+	 * $page_slug.
209
+	 * $page_label.
210
+	 *
211
+	 * @abstract
212
+	 * @access protected
213
+	 * @return void
214
+	 */
215
+	abstract protected function _init_page_props();
216
+
217
+
218
+
219
+	/**
220
+	 * _ajax_hooks
221
+	 * child classes put all their add_action('wp_ajax_{name_of_hook}') hooks in here.
222
+	 * Note: within the ajax callback methods.
223
+	 *
224
+	 * @abstract
225
+	 * @access protected
226
+	 * @return void
227
+	 */
228
+	abstract protected function _ajax_hooks();
229
+
230
+
231
+
232
+	/**
233
+	 * _define_page_props
234
+	 * child classes define page properties in here.  Must include at least:
235
+	 * $_admin_base_url = base_url for all admin pages
236
+	 * $_admin_page_title = default admin_page_title for admin pages
237
+	 * $_labels = array of default labels for various automatically generated elements:
238
+	 *    array(
239
+	 *        'buttons' => array(
240
+	 *            'add' => __('label for add new button'),
241
+	 *            'edit' => __('label for edit button'),
242
+	 *            'delete' => __('label for delete button')
243
+	 *            )
244
+	 *        )
245
+	 *
246
+	 * @abstract
247
+	 * @access protected
248
+	 * @return void
249
+	 */
250
+	abstract protected function _define_page_props();
251
+
252
+
253
+
254
+	/**
255
+	 * _set_page_routes
256
+	 * child classes use this to define the page routes for all subpages handled by the class.  Page routes are assigned to a action => method pairs in an array and to the $_page_routes property.  Each page route must also have a 'default'
257
+	 * route. Here's the format
258
+	 * $this->_page_routes = array(
259
+	 *        'default' => array(
260
+	 *            'func' => '_default_method_handling_route',
261
+	 *            'args' => array('array','of','args'),
262
+	 *            'noheader' => true, //add this in if this page route is processed before any headers are loaded (i.e. ajax request, backend processing)
263
+	 *            'headers_sent_route'=>'headers_route_reference', //add this if noheader=>true, and you want to load a headers route after.  The string you enter here should match the defined route reference for a headers sent route.
264
+	 *            'capability' => 'route_capability', //indicate a string for minimum capability required to access this route.
265
+	 *            'obj_id' => 10 // if this route has an object id, then this can include it (used for capability checks).
266
+	 *        ),
267
+	 *        'insert_item' => '_method_for_handling_insert_item' //this can be used if all we need to have is a handling method.
268
+	 *        )
269
+	 * )
270
+	 *
271
+	 * @abstract
272
+	 * @access protected
273
+	 * @return void
274
+	 */
275
+	abstract protected function _set_page_routes();
276
+
277
+
278
+
279
+	/**
280
+	 * _set_page_config
281
+	 * child classes use this to define the _page_config array for all subpages handled by the class. Each key in the array corresponds to the page_route for the loaded page.
282
+	 * Format:
283
+	 * $this->_page_config = array(
284
+	 *        'default' => array(
285
+	 *            'labels' => array(
286
+	 *                'buttons' => array(
287
+	 *                    'add' => __('label for adding item'),
288
+	 *                    'edit' => __('label for editing item'),
289
+	 *                    'delete' => __('label for deleting item')
290
+	 *                ),
291
+	 *                'publishbox' => __('Localized Title for Publish metabox', 'event_espresso')
292
+	 *            ), //optional an array of custom labels for various automatically generated elements to use on the page. If this isn't present then the defaults will be used as set for the $this->_labels in _define_page_props() method
293
+	 *            'nav' => array(
294
+	 *                'label' => __('Label for Tab', 'event_espresso').
295
+	 *                'url' => 'http://someurl', //automatically generated UNLESS you define
296
+	 *                'css_class' => 'css-class', //automatically generated UNLESS you define
297
+	 *                'order' => 10, //required to indicate tab position.
298
+	 *                'persistent' => false //if you want the nav tab to ONLY display when the specific route is displayed then add this parameter.
299
+	 *            'list_table' => 'name_of_list_table' //string for list table class to be loaded for this admin_page.
300
+	 *            'metaboxes' => array('metabox1', 'metabox2'), //if present this key indicates we want to load metaboxes set for eventespresso admin pages.
301
+	 *            'has_metaboxes' => true, //this boolean flag can simply be used to indicate if the route will have metaboxes.  Typically this is used if the 'metaboxes' index is not used because metaboxes are added later.  We just use
302
+	 *            this flag to make sure the necessary js gets enqueued on page load.
303
+	 *            'has_help_popups' => false //defaults(true) //this boolean flag can simply be used to indicate if the given route has help popups setup and if it does then we need to make sure thickbox is enqueued.
304
+	 *            'columns' => array(4, 2), //this key triggers the setup of a page that uses columns (metaboxes).  The array indicates the max number of columns (4) and the default number of columns on page load (2).  There is an option
305
+	 *            in the "screen_options" dropdown that is setup so users can pick what columns they want to display.
306
+	 *            'help_tabs' => array( //this is used for adding help tabs to a page
307
+	 *                'tab_id' => array(
308
+	 *                    'title' => 'tab_title',
309
+	 *                    'filename' => 'name_of_file_containing_content', //this is the primary method for setting help tab content.  The fallback if it isn't present is to try a the callback.  Filename should match a file in the admin
310
+	 *                    folder's "help_tabs" dir (ie.. events/help_tabs/name_of_file_containing_content.help_tab.php)
311
+	 *                    'callback' => 'callback_method_for_content', //if 'filename' isn't present then system will attempt to use the callback which should match the name of a method in the class
312
+	 *                    ),
313
+	 *                'tab2_id' => array(
314
+	 *                    'title' => 'tab2 title',
315
+	 *                    'filename' => 'file_name_2'
316
+	 *                    'callback' => 'callback_method_for_content',
317
+	 *                 ),
318
+	 *            'help_sidebar' => 'callback_for_sidebar_content', //this is used for setting up the sidebar in the help tab area on an admin page. @link http://make.wordpress.org/core/2011/12/06/help-and-screen-api-changes-in-3-3/
319
+	 *            'help_tour' => array(
320
+	 *                'name_of_help_tour_class', //all help tours shoudl be a child class of EE_Help_Tour and located in a folder for this admin page named "help_tours", a file name matching the key given here
321
+	 *                (name_of_help_tour_class.class.php), and class matching key given here (name_of_help_tour_class)
322
+	 *            ),
323
+	 *            'require_nonce' => TRUE //this is used if you want to set a route to NOT require a nonce (default is true if it isn't present).  To remove the requirement for a nonce check when this route is visited just set
324
+	 *            'require_nonce' to FALSE
325
+	 *            )
326
+	 * )
327
+	 *
328
+	 * @abstract
329
+	 * @access protected
330
+	 * @return void
331
+	 */
332
+	abstract protected function _set_page_config();
333
+
334
+
335
+
336
+
337
+
338
+	/** end sample help_tour methods **/
339
+	/**
340
+	 * _add_screen_options
341
+	 * Child classes can add any extra wp_screen_options within this method using built-in WP functions/methods for doing so.
342
+	 * Note child classes can also define _add_screen_options_($this->_current_view) to limit screen options to a particular view.
343
+	 *
344
+	 * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
345
+	 *         see also WP_Screen object documents...
346
+	 * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
347
+	 * @abstract
348
+	 * @access protected
349
+	 * @return void
350
+	 */
351
+	abstract protected function _add_screen_options();
352
+
353
+
354
+
355
+	/**
356
+	 * _add_feature_pointers
357
+	 * Child classes should use this method for implementing any "feature pointers" (using built-in WP styling js).
358
+	 * Note child classes can also define _add_feature_pointers_($this->_current_view) to limit screen options to a particular view.
359
+	 * Note: this is just a placeholder for now.  Implementation will come down the road
360
+	 * See: WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be extended) also see:
361
+	 *
362
+	 * @link   http://eamann.com/tech/wordpress-portland/
363
+	 * @abstract
364
+	 * @access protected
365
+	 * @return void
366
+	 */
367
+	abstract protected function _add_feature_pointers();
368
+
369
+
370
+
371
+	/**
372
+	 * load_scripts_styles
373
+	 * child classes put their wp_enqueue_script and wp_enqueue_style hooks in here for anything they need loaded for their pages/subpages.  Note this is for all pages/subpages of the system.  You can also load only specific scripts/styles
374
+	 * per view by putting them in a dynamic function in this format (load_scripts_styles_{$this->_current_view}) which matches your page route (action request arg)
375
+	 *
376
+	 * @abstract
377
+	 * @access public
378
+	 * @return void
379
+	 */
380
+	abstract public function load_scripts_styles();
381
+
382
+
383
+
384
+	/**
385
+	 * admin_init
386
+	 * Anything that should be set/executed at 'admin_init' WP hook runtime should be put in here.  This will apply to all pages/views loaded by child class.
387
+	 *
388
+	 * @abstract
389
+	 * @access public
390
+	 * @return void
391
+	 */
392
+	abstract public function admin_init();
393
+
394
+
395
+
396
+	/**
397
+	 * admin_notices
398
+	 * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply to all pages/views loaded by child class.
399
+	 *
400
+	 * @abstract
401
+	 * @access public
402
+	 * @return void
403
+	 */
404
+	abstract public function admin_notices();
405
+
406
+
407
+
408
+	/**
409
+	 * admin_footer_scripts
410
+	 * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method will apply to all pages/views loaded by child class.
411
+	 *
412
+	 * @access public
413
+	 * @return void
414
+	 */
415
+	abstract public function admin_footer_scripts();
416
+
417
+
418
+
419
+	/**
420
+	 * admin_footer
421
+	 * anything triggered by the 'admin_footer' WP action hook should be added to here. This particular method will apply to all pages/views loaded by child class.
422
+	 *
423
+	 * @access  public
424
+	 * @return void
425
+	 */
426
+	public function admin_footer()
427
+	{
428
+	}
429
+
430
+
431
+
432
+	/**
433
+	 * _global_ajax_hooks
434
+	 * all global add_action('wp_ajax_{name_of_hook}') hooks in here.
435
+	 * Note: within the ajax callback methods.
436
+	 *
437
+	 * @abstract
438
+	 * @access protected
439
+	 * @return void
440
+	 */
441
+	protected function _global_ajax_hooks()
442
+	{
443
+		//for lazy loading of metabox content
444
+		add_action('wp_ajax_espresso-ajax-content', array($this, 'ajax_metabox_content'), 10);
445
+	}
446
+
447
+
448
+
449
+	public function ajax_metabox_content()
450
+	{
451
+		$contentid = isset($this->_req_data['contentid']) ? $this->_req_data['contentid'] : '';
452
+		$url = isset($this->_req_data['contenturl']) ? $this->_req_data['contenturl'] : '';
453
+		self::cached_rss_display($contentid, $url);
454
+		wp_die();
455
+	}
456
+
457
+
458
+
459
+	/**
460
+	 * _page_setup
461
+	 * Makes sure any things that need to be loaded early get handled.  We also escape early here if the page requested doesn't match the object.
462
+	 *
463
+	 * @final
464
+	 * @access protected
465
+	 * @return void
466
+	 */
467
+	final protected function _page_setup()
468
+	{
469
+		//requires?
470
+		//admin_init stuff - global - we're setting this REALLY early so if EE_Admin pages have to hook into other WP pages they can.  But keep in mind, not everything is available from the EE_Admin Page object at this point.
471
+		add_action('admin_init', array($this, 'admin_init_global'), 5);
472
+		//next verify if we need to load anything...
473
+		$this->_current_page = ! empty($_GET['page']) ? sanitize_key($_GET['page']) : '';
474
+		$this->page_folder = strtolower(str_replace('_Admin_Page', '', str_replace('Extend_', '', get_class($this))));
475
+		global $ee_menu_slugs;
476
+		$ee_menu_slugs = (array)$ee_menu_slugs;
477
+		if (( ! $this->_current_page || ! isset($ee_menu_slugs[$this->_current_page])) && ! defined('DOING_AJAX')) {
478
+			return false;
479
+		}
480
+		// becuz WP List tables have two duplicate select inputs for choosing bulk actions, we need to copy the action from the second to the first
481
+		if (isset($this->_req_data['action2']) && $this->_req_data['action'] == -1) {
482
+			$this->_req_data['action'] = ! empty($this->_req_data['action2']) && $this->_req_data['action2'] != -1 ? $this->_req_data['action2'] : $this->_req_data['action'];
483
+		}
484
+		// then set blank or -1 action values to 'default'
485
+		$this->_req_action = isset($this->_req_data['action']) && ! empty($this->_req_data['action']) && $this->_req_data['action'] != -1 ? sanitize_key($this->_req_data['action']) : 'default';
486
+		//if action is 'default' after the above BUT we have  'route' var set, then let's use the route as the action.  This covers cases where we're coming in from a list table that isn't on the default route.
487
+		$this->_req_action = $this->_req_action == 'default' && isset($this->_req_data['route']) ? $this->_req_data['route'] : $this->_req_action;
488
+		//however if we are doing_ajax and we've got a 'route' set then that's what the req_action will be
489
+		$this->_req_action = defined('DOING_AJAX') && isset($this->_req_data['route']) ? $this->_req_data['route'] : $this->_req_action;
490
+		$this->_current_view = $this->_req_action;
491
+		$this->_req_nonce = $this->_req_action . '_nonce';
492
+		$this->_define_page_props();
493
+		$this->_current_page_view_url = add_query_arg(array('page' => $this->_current_page, 'action' => $this->_current_view), $this->_admin_base_url);
494
+		//default things
495
+		$this->_default_espresso_metaboxes = array('_espresso_news_post_box', '_espresso_links_post_box', '_espresso_ratings_request', '_espresso_sponsors_post_box');
496
+		//set page configs
497
+		$this->_set_page_routes();
498
+		$this->_set_page_config();
499
+		//let's include any referrer data in our default_query_args for this route for "stickiness".
500
+		if (isset($this->_req_data['wp_referer'])) {
501
+			$this->_default_route_query_args['wp_referer'] = $this->_req_data['wp_referer'];
502
+		}
503
+		//for caffeinated and other extended functionality.  If there is a _extend_page_config method then let's run that to modify the all the various page configuration arrays
504
+		if (method_exists($this, '_extend_page_config')) {
505
+			$this->_extend_page_config();
506
+		}
507
+		//for CPT and other extended functionality. If there is an _extend_page_config_for_cpt then let's run that to modify all the various page configuration arrays.
508
+		if (method_exists($this, '_extend_page_config_for_cpt')) {
509
+			$this->_extend_page_config_for_cpt();
510
+		}
511
+		//filter routes and page_config so addons can add their stuff. Filtering done per class
512
+		$this->_page_routes = apply_filters('FHEE__' . get_class($this) . '__page_setup__page_routes', $this->_page_routes, $this);
513
+		$this->_page_config = apply_filters('FHEE__' . get_class($this) . '__page_setup__page_config', $this->_page_config, $this);
514
+		//if AHEE__EE_Admin_Page__route_admin_request_$this->_current_view method is present then we call it hooked into the AHEE__EE_Admin_Page__route_admin_request action
515
+		if (method_exists($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view)) {
516
+			add_action('AHEE__EE_Admin_Page__route_admin_request', array($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view), 10, 2);
517
+		}
518
+		//next route only if routing enabled
519
+		if ($this->_routing && ! defined('DOING_AJAX')) {
520
+			$this->_verify_routes();
521
+			//next let's just check user_access and kill if no access
522
+			$this->check_user_access();
523
+			if ($this->_is_UI_request) {
524
+				//admin_init stuff - global, all views for this page class, specific view
525
+				add_action('admin_init', array($this, 'admin_init'), 10);
526
+				if (method_exists($this, 'admin_init_' . $this->_current_view)) {
527
+					add_action('admin_init', array($this, 'admin_init_' . $this->_current_view), 15);
528
+				}
529
+			} else {
530
+				//hijack regular WP loading and route admin request immediately
531
+				@ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT));
532
+				$this->route_admin_request();
533
+			}
534
+		}
535
+	}
536
+
537
+
538
+
539
+	/**
540
+	 * Provides a way for related child admin pages to load stuff on the loaded admin page.
541
+	 *
542
+	 * @access private
543
+	 * @return void
544
+	 */
545
+	private function _do_other_page_hooks()
546
+	{
547
+		$registered_pages = apply_filters('FHEE_do_other_page_hooks_' . $this->page_slug, array());
548
+		foreach ($registered_pages as $page) {
549
+			//now let's setup the file name and class that should be present
550
+			$classname = str_replace('.class.php', '', $page);
551
+			//autoloaders should take care of loading file
552
+			if ( ! class_exists($classname)) {
553
+				$error_msg[] = sprintf(__('Something went wrong with loading the %s admin hooks page.', 'event_espresso'), $page);
554
+				$error_msg[] = $error_msg[0]
555
+							   . "\r\n"
556
+							   . sprintf(__('There is no class in place for the %s admin hooks page.%sMake sure you have <strong>%s</strong> defined. If this is a non-EE-core admin page then you also must have an autoloader in place for your class',
557
+								'event_espresso'), $page, '<br />', $classname);
558
+				throw new EE_Error(implode('||', $error_msg));
559
+			}
560
+			$a = new ReflectionClass($classname);
561
+			//notice we are passing the instance of this class to the hook object.
562
+			$hookobj[] = $a->newInstance($this);
563
+		}
564
+	}
565
+
566
+
567
+
568
+	public function load_page_dependencies()
569
+	{
570
+		try {
571
+			$this->_load_page_dependencies();
572
+		} catch (EE_Error $e) {
573
+			$e->get_error();
574
+		}
575
+	}
576
+
577
+
578
+
579
+	/**
580
+	 * load_page_dependencies
581
+	 * loads things specific to this page class when its loaded.  Really helps with efficiency.
582
+	 *
583
+	 * @access public
584
+	 * @return void
585
+	 */
586
+	protected function _load_page_dependencies()
587
+	{
588
+		//let's set the current_screen and screen options to override what WP set
589
+		$this->_current_screen = get_current_screen();
590
+		//load admin_notices - global, page class, and view specific
591
+		add_action('admin_notices', array($this, 'admin_notices_global'), 5);
592
+		add_action('admin_notices', array($this, 'admin_notices'), 10);
593
+		if (method_exists($this, 'admin_notices_' . $this->_current_view)) {
594
+			add_action('admin_notices', array($this, 'admin_notices_' . $this->_current_view), 15);
595
+		}
596
+		//load network admin_notices - global, page class, and view specific
597
+		add_action('network_admin_notices', array($this, 'network_admin_notices_global'), 5);
598
+		if (method_exists($this, 'network_admin_notices_' . $this->_current_view)) {
599
+			add_action('network_admin_notices', array($this, 'network_admin_notices_' . $this->_current_view));
600
+		}
601
+		//this will save any per_page screen options if they are present
602
+		$this->_set_per_page_screen_options();
603
+		//setup list table properties
604
+		$this->_set_list_table();
605
+		// child classes can "register" a metabox to be automatically handled via the _page_config array property.  However in some cases the metaboxes will need to be added within a route handling callback.
606
+		$this->_add_registered_meta_boxes();
607
+		$this->_add_screen_columns();
608
+		//add screen options - global, page child class, and view specific
609
+		$this->_add_global_screen_options();
610
+		$this->_add_screen_options();
611
+		if (method_exists($this, '_add_screen_options_' . $this->_current_view)) {
612
+			call_user_func(array($this, '_add_screen_options_' . $this->_current_view));
613
+		}
614
+		//add help tab(s) and tours- set via page_config and qtips.
615
+		$this->_add_help_tour();
616
+		$this->_add_help_tabs();
617
+		$this->_add_qtips();
618
+		//add feature_pointers - global, page child class, and view specific
619
+		$this->_add_feature_pointers();
620
+		$this->_add_global_feature_pointers();
621
+		if (method_exists($this, '_add_feature_pointer_' . $this->_current_view)) {
622
+			call_user_func(array($this, '_add_feature_pointer_' . $this->_current_view));
623
+		}
624
+		//enqueue scripts/styles - global, page class, and view specific
625
+		add_action('admin_enqueue_scripts', array($this, 'load_global_scripts_styles'), 5);
626
+		add_action('admin_enqueue_scripts', array($this, 'load_scripts_styles'), 10);
627
+		if (method_exists($this, 'load_scripts_styles_' . $this->_current_view)) {
628
+			add_action('admin_enqueue_scripts', array($this, 'load_scripts_styles_' . $this->_current_view), 15);
629
+		}
630
+		add_action('admin_enqueue_scripts', array($this, 'admin_footer_scripts_eei18n_js_strings'), 100);
631
+		//admin_print_footer_scripts - global, page child class, and view specific.  NOTE, despite the name, whenever possible, scripts should NOT be loaded using this.  In most cases that's doing_it_wrong().  But adding hidden container elements etc. is a good use case. Notice the late priority we're giving these
632
+		add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts_global'), 99);
633
+		add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts'), 100);
634
+		if (method_exists($this, 'admin_footer_scripts_' . $this->_current_view)) {
635
+			add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts_' . $this->_current_view), 101);
636
+		}
637
+		//admin footer scripts
638
+		add_action('admin_footer', array($this, 'admin_footer_global'), 99);
639
+		add_action('admin_footer', array($this, 'admin_footer'), 100);
640
+		if (method_exists($this, 'admin_footer_' . $this->_current_view)) {
641
+			add_action('admin_footer', array($this, 'admin_footer_' . $this->_current_view), 101);
642
+		}
643
+		do_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', $this->page_slug);
644
+		//targeted hook
645
+		do_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load__' . $this->page_slug . '__' . $this->_req_action);
646
+	}
647
+
648
+
649
+
650
+	/**
651
+	 * _set_defaults
652
+	 * This sets some global defaults for class properties.
653
+	 */
654
+	private function _set_defaults()
655
+	{
656
+		$this->_current_screen = $this->_admin_page_title = $this->_req_action = $this->_req_nonce = $this->_event = $this->_template_path = $this->_column_template_path = null;
657
+		$this->_nav_tabs = $this_views = $this->_page_routes = $this->_page_config = $this->_default_route_query_args = array();
658
+		$this->default_nav_tab_name = 'overview';
659
+		//init template args
660
+		$this->_template_args = array(
661
+				'admin_page_header'  => '',
662
+				'admin_page_content' => '',
663
+				'post_body_content'  => '',
664
+				'before_list_table'  => '',
665
+				'after_list_table'   => '',
666
+		);
667
+	}
668
+
669
+
670
+
671
+	/**
672
+	 * route_admin_request
673
+	 *
674
+	 * @see    _route_admin_request()
675
+	 * @access public
676
+	 * @return void|exception error
677
+	 */
678
+	public function route_admin_request()
679
+	{
680
+		try {
681
+			$this->_route_admin_request();
682
+		} catch (EE_Error $e) {
683
+			$e->get_error();
684
+		}
685
+	}
686
+
687
+
688
+
689
+	public function set_wp_page_slug($wp_page_slug)
690
+	{
691
+		$this->_wp_page_slug = $wp_page_slug;
692
+		//if in network admin then we need to append "-network" to the page slug. Why? Because that's how WP rolls...
693
+		if (is_network_admin()) {
694
+			$this->_wp_page_slug .= '-network';
695
+		}
696
+	}
697
+
698
+
699
+
700
+	/**
701
+	 * _verify_routes
702
+	 * All this method does is verify the incoming request and make sure that routes exist for it.  We do this early so we know if we need to drop out.
703
+	 *
704
+	 * @access protected
705
+	 * @return void
706
+	 */
707
+	protected function _verify_routes()
708
+	{
709
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
710
+		if ( ! $this->_current_page && ! defined('DOING_AJAX')) {
711
+			return false;
712
+		}
713
+		$this->_route = false;
714
+		$func = false;
715
+		$args = array();
716
+		// check that the page_routes array is not empty
717
+		if (empty($this->_page_routes)) {
718
+			// user error msg
719
+			$error_msg = sprintf(__('No page routes have been set for the %s admin page.', 'event_espresso'), $this->_admin_page_title);
720
+			// developer error msg
721
+			$error_msg .= '||' . $error_msg . __(' Make sure the "set_page_routes()" method exists, and is setting the "_page_routes" array properly.', 'event_espresso');
722
+			throw new EE_Error($error_msg);
723
+		}
724
+		// and that the requested page route exists
725
+		if (array_key_exists($this->_req_action, $this->_page_routes)) {
726
+			$this->_route = $this->_page_routes[$this->_req_action];
727
+			$this->_route_config = isset($this->_page_config[$this->_req_action]) ? $this->_page_config[$this->_req_action] : array();
728
+		} else {
729
+			// user error msg
730
+			$error_msg = sprintf(__('The requested page route does not exist for the %s admin page.', 'event_espresso'), $this->_admin_page_title);
731
+			// developer error msg
732
+			$error_msg .= '||' . $error_msg . sprintf(__(' Create a key in the "_page_routes" array named "%s" and set its value to the appropriate method.', 'event_espresso'), $this->_req_action);
733
+			throw new EE_Error($error_msg);
734
+		}
735
+		// and that a default route exists
736
+		if ( ! array_key_exists('default', $this->_page_routes)) {
737
+			// user error msg
738
+			$error_msg = sprintf(__('A default page route has not been set for the % admin page.', 'event_espresso'), $this->_admin_page_title);
739
+			// developer error msg
740
+			$error_msg .= '||' . $error_msg . __(' Create a key in the "_page_routes" array named "default" and set its value to your default page method.', 'event_espresso');
741
+			throw new EE_Error($error_msg);
742
+		}
743
+		//first lets' catch if the UI request has EVER been set.
744
+		if ($this->_is_UI_request === null) {
745
+			//lets set if this is a UI request or not.
746
+			$this->_is_UI_request = ( ! isset($this->_req_data['noheader']) || $this->_req_data['noheader'] !== true) ? true : false;
747
+			//wait a minute... we might have a noheader in the route array
748
+			$this->_is_UI_request = is_array($this->_route) && isset($this->_route['noheader']) && $this->_route['noheader'] ? false : $this->_is_UI_request;
749
+		}
750
+		$this->_set_current_labels();
751
+	}
752
+
753
+
754
+
755
+	/**
756
+	 * this method simply verifies a given route and makes sure its an actual route available for the loaded page
757
+	 *
758
+	 * @param  string $route the route name we're verifying
759
+	 * @return mixed  (bool|Exception)      we'll throw an exception if this isn't a valid route.
760
+	 */
761
+	protected function _verify_route($route)
762
+	{
763
+		if (array_key_exists($this->_req_action, $this->_page_routes)) {
764
+			return true;
765
+		} else {
766
+			// user error msg
767
+			$error_msg = sprintf(__('The given page route does not exist for the %s admin page.', 'event_espresso'), $this->_admin_page_title);
768
+			// developer error msg
769
+			$error_msg .= '||' . $error_msg . sprintf(__(' Check the route you are using in your method (%s) and make sure it matches a route set in your "_page_routes" array property', 'event_espresso'), $route);
770
+			throw new EE_Error($error_msg);
771
+		}
772
+	}
773
+
774
+
775
+
776
+	/**
777
+	 * perform nonce verification
778
+	 * This method has be encapsulated here so that any ajax requests that bypass normal routes can verify their nonces using this method (and save retyping!)
779
+	 *
780
+	 * @param  string $nonce     The nonce sent
781
+	 * @param  string $nonce_ref The nonce reference string (name0)
782
+	 * @return mixed (bool|die)
783
+	 */
784
+	protected function _verify_nonce($nonce, $nonce_ref)
785
+	{
786
+		// verify nonce against expected value
787
+		if ( ! wp_verify_nonce($nonce, $nonce_ref)) {
788
+			// these are not the droids you are looking for !!!
789
+			$msg = sprintf(__('%sNonce Fail.%s', 'event_espresso'), '<a href="http://www.youtube.com/watch?v=56_S0WeTkzs">', '</a>');
790
+			if (WP_DEBUG) {
791
+				$msg .= "\n  " . sprintf(__('In order to dynamically generate nonces for your actions, use the %s::add_query_args_and_nonce() method. May the Nonce be with you!', 'event_espresso'), __CLASS__);
792
+			}
793
+			if ( ! defined('DOING_AJAX')) {
794
+				wp_die($msg);
795
+			} else {
796
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
797
+				$this->_return_json();
798
+			}
799
+		}
800
+	}
801
+
802
+
803
+
804
+	/**
805
+	 * _route_admin_request()
806
+	 * Meat and potatoes of the class.  Basically, this dude checks out what's being requested and sees if theres are
807
+	 * some doodads to work the magic and handle the flingjangy. Translation:  Checks if the requested action is listed
808
+	 * in the page routes and then will try to load the corresponding method.
809
+	 *
810
+	 * @access protected
811
+	 * @return void
812
+	 * @throws \EE_Error
813
+	 */
814
+	protected function _route_admin_request()
815
+	{
816
+		if ( ! $this->_is_UI_request) {
817
+			$this->_verify_routes();
818
+		}
819
+		$nonce_check = isset($this->_route_config['require_nonce'])
820
+			? $this->_route_config['require_nonce']
821
+			: true;
822
+		if ($this->_req_action !== 'default' && $nonce_check) {
823
+			// set nonce from post data
824
+			$nonce = isset($this->_req_data[$this->_req_nonce])
825
+				? sanitize_text_field($this->_req_data[$this->_req_nonce])
826
+				: '';
827
+			$this->_verify_nonce($nonce, $this->_req_nonce);
828
+		}
829
+		//set the nav_tabs array but ONLY if this is  UI_request
830
+		if ($this->_is_UI_request) {
831
+			$this->_set_nav_tabs();
832
+		}
833
+		// grab callback function
834
+		$func = is_array($this->_route) ? $this->_route['func'] : $this->_route;
835
+		// check if callback has args
836
+		$args = is_array($this->_route) && isset($this->_route['args']) ? $this->_route['args'] : array();
837
+		$error_msg = '';
838
+		// action right before calling route
839
+		// (hook is something like 'AHEE__Registrations_Admin_Page__route_admin_request')
840
+		if ( ! did_action('AHEE__EE_Admin_Page__route_admin_request')) {
841
+			do_action('AHEE__EE_Admin_Page__route_admin_request', $this->_current_view, $this);
842
+		}
843
+		// right before calling the route, let's remove _wp_http_referer from the
844
+		// $_SERVER[REQUEST_URI] global (its now in _req_data for route processing).
845
+		$_SERVER['REQUEST_URI'] = remove_query_arg('_wp_http_referer', wp_unslash($_SERVER['REQUEST_URI']));
846
+		if ( ! empty($func)) {
847
+			if (is_array($func)) {
848
+				list($class, $method) = $func;
849
+			} else if (strpos($func, '::') !== false) {
850
+				list($class, $method) = explode('::', $func);
851
+			} else {
852
+				$class = $this;
853
+				$method = $func;
854
+			}
855
+			if ( ! (is_object($class) && $class === $this)) {
856
+				// send along this admin page object for access by addons.
857
+				$args['admin_page_object'] = $this;
858
+			}
859
+
860
+			if (
861
+				//is it a method on a class that doesn't work?
862
+				(
863
+					(
864
+						method_exists($class, $method)
865
+						&& call_user_func_array(array($class, $method), $args) === false
866
+					)
867
+					&& (
868
+						//is it a standalone function that doesn't work?
869
+						function_exists($method)
870
+						&& call_user_func_array($func, array_merge(array('admin_page_object' => $this), $args)) === false
871
+					)
872
+				)
873
+				|| (
874
+					//is it neither a class method NOR a standalone function?
875
+					! method_exists($class, $method)
876
+					&& ! function_exists($method)
877
+				)
878
+			) {
879
+				// user error msg
880
+				$error_msg = __('An error occurred. The  requested page route could not be found.', 'event_espresso');
881
+				// developer error msg
882
+				$error_msg .= '||';
883
+				$error_msg .= sprintf(
884
+					__(
885
+						'Page route "%s" could not be called. Check that the spelling for method names and actions in the "_page_routes" array are all correct.',
886
+						'event_espresso'
887
+					),
888
+					$method
889
+				);
890
+			}
891
+			if ( ! empty($error_msg)) {
892
+				throw new EE_Error($error_msg);
893
+			}
894
+		}
895
+		//if we've routed and this route has a no headers route AND a sent_headers_route, then we need to reset the routing properties to the new route.
896
+		//now if UI request is FALSE and noheader is true AND we have a headers_sent_route in the route array then let's set UI_request to true because the no header route has a second func after headers have been sent.
897
+		if ($this->_is_UI_request === false
898
+			&& is_array($this->_route)
899
+			&& ! empty($this->_route['headers_sent_route'])
900
+		) {
901
+			$this->_reset_routing_properties($this->_route['headers_sent_route']);
902
+		}
903
+	}
904
+
905
+
906
+
907
+	/**
908
+	 * This method just allows the resetting of page properties in the case where a no headers
909
+	 * route redirects to a headers route in its route config.
910
+	 *
911
+	 * @since   4.3.0
912
+	 * @param  string $new_route New (non header) route to redirect to.
913
+	 * @return   void
914
+	 */
915
+	protected function _reset_routing_properties($new_route)
916
+	{
917
+		$this->_is_UI_request = true;
918
+		//now we set the current route to whatever the headers_sent_route is set at
919
+		$this->_req_data['action'] = $new_route;
920
+		//rerun page setup
921
+		$this->_page_setup();
922
+	}
923
+
924
+
925
+
926
+	/**
927
+	 * _add_query_arg
928
+	 * adds nonce to array of arguments then calls WP add_query_arg function
929
+	 *(internally just uses EEH_URL's function with the same name)
930
+	 *
931
+	 * @access public
932
+	 * @param array  $args
933
+	 * @param string $url
934
+	 * @param bool   $sticky                  if true, then the existing Request params will be appended to the generated
935
+	 *                                        url in an associative array indexed by the key 'wp_referer';
936
+	 *                                        Example usage:
937
+	 *                                        If the current page is:
938
+	 *                                        http://mydomain.com/wp-admin/admin.php?page=espresso_registrations
939
+	 *                                        &action=default&event_id=20&month_range=March%202015
940
+	 *                                        &_wpnonce=5467821
941
+	 *                                        and you call:
942
+	 *                                        EE_Admin_Page::add_query_args_and_nonce(
943
+	 *                                        array(
944
+	 *                                        'action' => 'resend_something',
945
+	 *                                        'page=>espresso_registrations'
946
+	 *                                        ),
947
+	 *                                        $some_url,
948
+	 *                                        true
949
+	 *                                        );
950
+	 *                                        It will produce a url in this structure:
951
+	 *                                        http://{$some_url}/?page=espresso_registrations&action=resend_something
952
+	 *                                        &wp_referer[action]=default&wp_referer[event_id]=20&wpreferer[
953
+	 *                                        month_range]=March%202015
954
+	 * @param   bool $exclude_nonce           If true, the the nonce will be excluded from the generated nonce.
955
+	 * @return string
956
+	 */
957
+	public static function add_query_args_and_nonce($args = array(), $url = false, $sticky = false, $exclude_nonce = false)
958
+	{
959
+		//if there is a _wp_http_referer include the values from the request but only if sticky = true
960
+		if ($sticky) {
961
+			$request = $_REQUEST;
962
+			unset($request['_wp_http_referer']);
963
+			unset($request['wp_referer']);
964
+			foreach ($request as $key => $value) {
965
+				//do not add nonces
966
+				if (strpos($key, 'nonce') !== false) {
967
+					continue;
968
+				}
969
+				$args['wp_referer[' . $key . ']'] = $value;
970
+			}
971
+		}
972
+		return EEH_URL::add_query_args_and_nonce($args, $url, $exclude_nonce);
973
+	}
974
+
975
+
976
+
977
+	/**
978
+	 * This returns a generated link that will load the related help tab.
979
+	 *
980
+	 * @param  string $help_tab_id the id for the connected help tab
981
+	 * @param  string $icon_style  (optional) include css class for the style you want to use for the help icon.
982
+	 * @param  string $help_text   (optional) send help text you want to use for the link if default not to be used
983
+	 * @uses EEH_Template::get_help_tab_link()
984
+	 * @return string              generated link
985
+	 */
986
+	protected function _get_help_tab_link($help_tab_id, $icon_style = false, $help_text = false)
987
+	{
988
+		return EEH_Template::get_help_tab_link($help_tab_id, $this->page_slug, $this->_req_action, $icon_style, $help_text);
989
+	}
990
+
991
+
992
+
993
+	/**
994
+	 * _add_help_tabs
995
+	 * Note child classes define their help tabs within the page_config array.
996
+	 *
997
+	 * @link   http://codex.wordpress.org/Function_Reference/add_help_tab
998
+	 * @access protected
999
+	 * @return void
1000
+	 */
1001
+	protected function _add_help_tabs()
1002
+	{
1003
+		$tour_buttons = '';
1004
+		if (isset($this->_page_config[$this->_req_action])) {
1005
+			$config = $this->_page_config[$this->_req_action];
1006
+			//is there a help tour for the current route?  if there is let's setup the tour buttons
1007
+			if (isset($this->_help_tour[$this->_req_action])) {
1008
+				$tb = array();
1009
+				$tour_buttons = '<div class="ee-abs-container"><div class="ee-help-tour-restart-buttons">';
1010
+				foreach ($this->_help_tour['tours'] as $tour) {
1011
+					//if this is the end tour then we don't need to setup a button
1012
+					if ($tour instanceof EE_Help_Tour_final_stop) {
1013
+						continue;
1014
+					}
1015
+					$tb[] = '<button id="trigger-tour-' . $tour->get_slug() . '" class="button-primary trigger-ee-help-tour">' . $tour->get_label() . '</button>';
1016
+				}
1017
+				$tour_buttons .= implode('<br />', $tb);
1018
+				$tour_buttons .= '</div></div>';
1019
+			}
1020
+			// let's see if there is a help_sidebar set for the current route and we'll set that up for usage as well.
1021
+			if (is_array($config) && isset($config['help_sidebar'])) {
1022
+				//check that the callback given is valid
1023
+				if ( ! method_exists($this, $config['help_sidebar'])) {
1024
+					throw new EE_Error(sprintf(__('The _page_config array has a callback set for the "help_sidebar" option.  However the callback given (%s) is not a valid callback.  Doublecheck the spelling and make sure this method exists for the class %s',
1025
+							'event_espresso'), $config['help_sidebar'], get_class($this)));
1026
+				}
1027
+				$content = apply_filters('FHEE__' . get_class($this) . '__add_help_tabs__help_sidebar', call_user_func(array($this, $config['help_sidebar'])));
1028
+				$content .= $tour_buttons; //add help tour buttons.
1029
+				//do we have any help tours setup?  Cause if we do we want to add the buttons
1030
+				$this->_current_screen->set_help_sidebar($content);
1031
+			}
1032
+			//if we DON'T have config help sidebar and there ARE toure buttons then we'll just add the tour buttons to the sidebar.
1033
+			if ( ! isset($config['help_sidebar']) && ! empty($tour_buttons)) {
1034
+				$this->_current_screen->set_help_sidebar($tour_buttons);
1035
+			}
1036
+			//handle if no help_tabs are set so the sidebar will still show for the help tour buttons
1037
+			if ( ! isset($config['help_tabs']) && ! empty($tour_buttons)) {
1038
+				$_ht['id'] = $this->page_slug;
1039
+				$_ht['title'] = __('Help Tours', 'event_espresso');
1040
+				$_ht['content'] = '<p>' . __('The buttons to the right allow you to start/restart any help tours available for this page', 'event_espresso') . '</p>';
1041
+				$this->_current_screen->add_help_tab($_ht);
1042
+			}/**/
1043
+			if ( ! isset($config['help_tabs'])) {
1044
+				return;
1045
+			} //no help tabs for this route
1046
+			foreach ((array)$config['help_tabs'] as $tab_id => $cfg) {
1047
+				//we're here so there ARE help tabs!
1048
+				//make sure we've got what we need
1049
+				if ( ! isset($cfg['title'])) {
1050
+					throw new EE_Error(__('The _page_config array is not set up properly for help tabs.  It is missing a title', 'event_espresso'));
1051
+				}
1052
+				if ( ! isset($cfg['filename']) && ! isset($cfg['callback']) && ! isset($cfg['content'])) {
1053
+					throw new EE_Error(__('The _page_config array is not setup properly for help tabs. It is missing a either a filename reference, or a callback reference or a content reference so there is no way to know the content for the help tab',
1054
+							'event_espresso'));
1055
+				}
1056
+				//first priority goes to content.
1057
+				if ( ! empty($cfg['content'])) {
1058
+					$content = ! empty($cfg['content']) ? $cfg['content'] : null;
1059
+					//second priority goes to filename
1060
+				} else if ( ! empty($cfg['filename'])) {
1061
+					$file_path = $this->_get_dir() . '/help_tabs/' . $cfg['filename'] . '.help_tab.php';
1062
+					//it's possible that the file is located on decaf route (and above sets up for caf route, if this is the case then lets check decaf route too)
1063
+					$file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES . basename($this->_get_dir()) . '/help_tabs/' . $cfg['filename'] . '.help_tab.php' : $file_path;
1064
+					//if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1065
+					if ( ! is_readable($file_path) && ! isset($cfg['callback'])) {
1066
+						EE_Error::add_error(sprintf(__('The filename given for the help tab %s is not a valid file and there is no other configuration for the tab content.  Please check that the string you set for the help tab on this route (%s) is the correct spelling.  The file should be in %s',
1067
+								'event_espresso'), $tab_id, key($config), $file_path), __FILE__, __FUNCTION__, __LINE__);
1068
+						return;
1069
+					}
1070
+					$template_args['admin_page_obj'] = $this;
1071
+					$content = EEH_Template::display_template($file_path, $template_args, true);
1072
+				} else {
1073
+					$content = '';
1074
+				}
1075
+				//check if callback is valid
1076
+				if (empty($content) && ( ! isset($cfg['callback']) || ! method_exists($this, $cfg['callback']))) {
1077
+					EE_Error::add_error(sprintf(__('The callback given for a %s help tab on this page does not content OR a corresponding method for generating the content.  Check the spelling or make sure the method is present.',
1078
+							'event_espresso'), $cfg['title']), __FILE__, __FUNCTION__, __LINE__);
1079
+					return;
1080
+				}
1081
+				//setup config array for help tab method
1082
+				$id = $this->page_slug . '-' . $this->_req_action . '-' . $tab_id;
1083
+				$_ht = array(
1084
+						'id'       => $id,
1085
+						'title'    => $cfg['title'],
1086
+						'callback' => isset($cfg['callback']) && empty($content) ? array($this, $cfg['callback']) : null,
1087
+						'content'  => $content,
1088
+				);
1089
+				$this->_current_screen->add_help_tab($_ht);
1090
+			}
1091
+		}
1092
+	}
1093
+
1094
+
1095
+
1096
+	/**
1097
+	 * This basically checks loaded $_page_config property to see if there are any help_tours defined.  "help_tours" is an array with properties for setting up usage of the joyride plugin
1098
+	 *
1099
+	 * @link   http://zurb.com/playground/jquery-joyride-feature-tour-plugin
1100
+	 * @see    instructions regarding the format and construction of the "help_tour" array element is found in the _set_page_config() comments
1101
+	 * @access protected
1102
+	 * @return void
1103
+	 */
1104
+	protected function _add_help_tour()
1105
+	{
1106
+		$tours = array();
1107
+		$this->_help_tour = array();
1108
+		//exit early if help tours are turned off globally
1109
+		if ( ! EE_Registry::instance()->CFG->admin->help_tour_activation || (defined('EE_DISABLE_HELP_TOURS') && EE_DISABLE_HELP_TOURS)) {
1110
+			return;
1111
+		}
1112
+		//loop through _page_config to find any help_tour defined
1113
+		foreach ($this->_page_config as $route => $config) {
1114
+			//we're only going to set things up for this route
1115
+			if ($route !== $this->_req_action) {
1116
+				continue;
1117
+			}
1118
+			if (isset($config['help_tour'])) {
1119
+				foreach ($config['help_tour'] as $tour) {
1120
+					$file_path = $this->_get_dir() . '/help_tours/' . $tour . '.class.php';
1121
+					//let's see if we can get that file... if not its possible this is a decaf route not set in caffienated so lets try and get the caffeinated equivalent
1122
+					$file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES . basename($this->_get_dir()) . '/help_tours/' . $tour . '.class.php' : $file_path;
1123
+					//if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1124
+					if ( ! is_readable($file_path)) {
1125
+						EE_Error::add_error(sprintf(__('The file path given for the help tour (%s) is not a valid path.  Please check that the string you set for the help tour on this route (%s) is the correct spelling', 'event_espresso'),
1126
+								$file_path, $tour), __FILE__, __FUNCTION__, __LINE__);
1127
+						return;
1128
+					}
1129
+					require_once $file_path;
1130
+					if ( ! class_exists($tour)) {
1131
+						$error_msg[] = sprintf(__('Something went wrong with loading the %s Help Tour Class.', 'event_espresso'), $tour);
1132
+						$error_msg[] = $error_msg[0] . "\r\n" . sprintf(__('There is no class in place for the %s help tour.%s Make sure you have <strong>%s</strong> defined in the "help_tour" array for the %s route of the % admin page.',
1133
+										'event_espresso'), $tour, '<br />', $tour, $this->_req_action, get_class($this));
1134
+						throw new EE_Error(implode('||', $error_msg));
1135
+					}
1136
+					$a = new ReflectionClass($tour);
1137
+					$tour_obj = $a->newInstance($this->_is_caf);
1138
+					$tours[] = $tour_obj;
1139
+					$this->_help_tour[$route][] = EEH_Template::help_tour_stops_generator($tour_obj);
1140
+				}
1141
+				//let's inject the end tour stop element common to all pages... this will only get seen once per machine.
1142
+				$end_stop_tour = new EE_Help_Tour_final_stop($this->_is_caf);
1143
+				$tours[] = $end_stop_tour;
1144
+				$this->_help_tour[$route][] = EEH_Template::help_tour_stops_generator($end_stop_tour);
1145
+			}
1146
+		}
1147
+		if ( ! empty($tours)) {
1148
+			$this->_help_tour['tours'] = $tours;
1149
+		}
1150
+		//thats it!  Now that the $_help_tours property is set (or not) the scripts and html should be taken care of automatically.
1151
+	}
1152
+
1153
+
1154
+
1155
+	/**
1156
+	 * This simply sets up any qtips that have been defined in the page config
1157
+	 *
1158
+	 * @access protected
1159
+	 * @return void
1160
+	 */
1161
+	protected function _add_qtips()
1162
+	{
1163
+		if (isset($this->_route_config['qtips'])) {
1164
+			$qtips = (array)$this->_route_config['qtips'];
1165
+			//load qtip loader
1166
+			$path = array(
1167
+					$this->_get_dir() . '/qtips/',
1168
+					EE_ADMIN_PAGES . basename($this->_get_dir()) . '/qtips/',
1169
+			);
1170
+			EEH_Qtip_Loader::instance()->register($qtips, $path);
1171
+		}
1172
+	}
1173
+
1174
+
1175
+
1176
+	/**
1177
+	 * _set_nav_tabs
1178
+	 * This sets up the nav tabs from the page_routes array.  This method can be overwritten by child classes if you wish to add additional tabs or modify accordingly.
1179
+	 *
1180
+	 * @access protected
1181
+	 * @return void
1182
+	 */
1183
+	protected function _set_nav_tabs()
1184
+	{
1185
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1186
+		$i = 0;
1187
+		foreach ($this->_page_config as $slug => $config) {
1188
+			if ( ! is_array($config) || (is_array($config) && (isset($config['nav']) && ! $config['nav']) || ! isset($config['nav']))) {
1189
+				continue;
1190
+			} //no nav tab for this config
1191
+			//check for persistent flag
1192
+			if (isset($config['nav']['persistent']) && ! $config['nav']['persistent'] && $slug !== $this->_req_action) {
1193
+				continue;
1194
+			} //nav tab is only to appear when route requested.
1195
+			if ( ! $this->check_user_access($slug, true)) {
1196
+				continue;
1197
+			} //no nav tab becasue current user does not have access.
1198
+			$css_class = isset($config['css_class']) ? $config['css_class'] . ' ' : '';
1199
+			$this->_nav_tabs[$slug] = array(
1200
+					'url'       => isset($config['nav']['url']) ? $config['nav']['url'] : self::add_query_args_and_nonce(array('action' => $slug), $this->_admin_base_url),
1201
+					'link_text' => isset($config['nav']['label']) ? $config['nav']['label'] : ucwords(str_replace('_', ' ', $slug)),
1202
+					'css_class' => $this->_req_action == $slug ? $css_class . 'nav-tab-active' : $css_class,
1203
+					'order'     => isset($config['nav']['order']) ? $config['nav']['order'] : $i,
1204
+			);
1205
+			$i++;
1206
+		}
1207
+		//if $this->_nav_tabs is empty then lets set the default
1208
+		if (empty($this->_nav_tabs)) {
1209
+			$this->_nav_tabs[$this->default_nav_tab_name] = array(
1210
+					'url'       => $this->admin_base_url,
1211
+					'link_text' => ucwords(str_replace('_', ' ', $this->default_nav_tab_name)),
1212
+					'css_class' => 'nav-tab-active',
1213
+					'order'     => 10,
1214
+			);
1215
+		}
1216
+		//now let's sort the tabs according to order
1217
+		usort($this->_nav_tabs, array($this, '_sort_nav_tabs'));
1218
+	}
1219
+
1220
+
1221
+
1222
+	/**
1223
+	 * _set_current_labels
1224
+	 * This method modifies the _labels property with any optional specific labels indicated in the _page_routes property array
1225
+	 *
1226
+	 * @access private
1227
+	 * @return void
1228
+	 */
1229
+	private function _set_current_labels()
1230
+	{
1231
+		if (is_array($this->_route_config) && isset($this->_route_config['labels'])) {
1232
+			foreach ($this->_route_config['labels'] as $label => $text) {
1233
+				if (is_array($text)) {
1234
+					foreach ($text as $sublabel => $subtext) {
1235
+						$this->_labels[$label][$sublabel] = $subtext;
1236
+					}
1237
+				} else {
1238
+					$this->_labels[$label] = $text;
1239
+				}
1240
+			}
1241
+		}
1242
+	}
1243
+
1244
+
1245
+
1246
+	/**
1247
+	 *        verifies user access for this admin page
1248
+	 *
1249
+	 * @param string $route_to_check if present then the capability for the route matching this string is checked.
1250
+	 * @param bool   $verify_only    Default is FALSE which means if user check fails then wp_die().  Otherwise just return false if verify fail.
1251
+	 * @return        BOOL|wp_die()
1252
+	 */
1253
+	public function check_user_access($route_to_check = '', $verify_only = false)
1254
+	{
1255
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1256
+		$route_to_check = empty($route_to_check) ? $this->_req_action : $route_to_check;
1257
+		$capability = ! empty($route_to_check) && isset($this->_page_routes[$route_to_check]) && is_array($this->_page_routes[$route_to_check]) && ! empty($this->_page_routes[$route_to_check]['capability'])
1258
+				? $this->_page_routes[$route_to_check]['capability'] : null;
1259
+		if (empty($capability) && empty($route_to_check)) {
1260
+			$capability = is_array($this->_route) && empty($this->_route['capability']) ? 'manage_options' : $this->_route['capability'];
1261
+		} else {
1262
+			$capability = empty($capability) ? 'manage_options' : $capability;
1263
+		}
1264
+		$id = is_array($this->_route) && ! empty($this->_route['obj_id']) ? $this->_route['obj_id'] : 0;
1265
+		if (( ! function_exists('is_admin') || ! EE_Registry::instance()->CAP->current_user_can($capability, $this->page_slug . '_' . $route_to_check, $id)) && ! defined('DOING_AJAX')) {
1266
+			if ($verify_only) {
1267
+				return false;
1268
+			} else {
1269
+				if ( is_user_logged_in() ) {
1270
+					wp_die(__('You do not have access to this route.', 'event_espresso'));
1271
+				} else {
1272
+					return false;
1273
+				}
1274
+			}
1275
+		}
1276
+		return true;
1277
+	}
1278
+
1279
+
1280
+
1281
+	/**
1282
+	 * admin_init_global
1283
+	 * This runs all the code that we want executed within the WP admin_init hook.
1284
+	 * This method executes for ALL EE Admin pages.
1285
+	 *
1286
+	 * @access public
1287
+	 * @return void
1288
+	 */
1289
+	public function admin_init_global()
1290
+	{
1291
+	}
1292
+
1293
+
1294
+
1295
+	/**
1296
+	 * wp_loaded_global
1297
+	 * This runs all the code that we want executed within the WP wp_loaded hook.  This method is optional for an EE_Admin page and will execute on every EE Admin Page load
1298
+	 *
1299
+	 * @access public
1300
+	 * @return void
1301
+	 */
1302
+	public function wp_loaded()
1303
+	{
1304
+	}
1305
+
1306
+
1307
+
1308
+	/**
1309
+	 * admin_notices
1310
+	 * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply on ALL EE_Admin pages.
1311
+	 *
1312
+	 * @access public
1313
+	 * @return void
1314
+	 */
1315
+	public function admin_notices_global()
1316
+	{
1317
+		$this->_display_no_javascript_warning();
1318
+		$this->_display_espresso_notices();
1319
+	}
1320
+
1321
+
1322
+
1323
+	public function network_admin_notices_global()
1324
+	{
1325
+		$this->_display_no_javascript_warning();
1326
+		$this->_display_espresso_notices();
1327
+	}
1328
+
1329
+
1330
+
1331
+	/**
1332
+	 * admin_footer_scripts_global
1333
+	 * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method will apply on ALL EE_Admin pages.
1334
+	 *
1335
+	 * @access public
1336
+	 * @return void
1337
+	 */
1338
+	public function admin_footer_scripts_global()
1339
+	{
1340
+		$this->_add_admin_page_ajax_loading_img();
1341
+		$this->_add_admin_page_overlay();
1342
+		//if metaboxes are present we need to add the nonce field
1343
+		if ((isset($this->_route_config['metaboxes']) || (isset($this->_route_config['has_metaboxes']) && $this->_route_config['has_metaboxes']) || isset($this->_route_config['list_table']))) {
1344
+			wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
1345
+			wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
1346
+		}
1347
+	}
1348
+
1349
+
1350
+
1351
+	/**
1352
+	 * admin_footer_global
1353
+	 * Anything triggered by the wp 'admin_footer' wp hook should be put in here. This particluar method will apply on ALL EE_Admin Pages.
1354
+	 *
1355
+	 * @access  public
1356
+	 * @return  void
1357
+	 */
1358
+	public function admin_footer_global()
1359
+	{
1360
+		//dialog container for dialog helper
1361
+		$d_cont = '<div class="ee-admin-dialog-container auto-hide hidden">' . "\n";
1362
+		$d_cont .= '<div class="ee-notices"></div>';
1363
+		$d_cont .= '<div class="ee-admin-dialog-container-inner-content"></div>';
1364
+		$d_cont .= '</div>';
1365
+		echo $d_cont;
1366
+		//help tour stuff?
1367
+		if (isset($this->_help_tour[$this->_req_action])) {
1368
+			echo implode('<br />', $this->_help_tour[$this->_req_action]);
1369
+		}
1370
+		//current set timezone for timezone js
1371
+		echo '<span id="current_timezone" class="hidden">' . EEH_DTT_Helper::get_timezone() . '</span>';
1372
+	}
1373
+
1374
+
1375
+
1376
+	/**
1377
+	 * This function sees if there is a method for help popup content existing for the given route.  If there is then we'll use the retrieved array to output the content using the template.
1378
+	 * For child classes:
1379
+	 * If you want to have help popups then in your templates or your content you set "triggers" for the content using the "_set_help_trigger('help_trigger_id')" where "help_trigger_id" is what you will use later in your custom method for
1380
+	 * the help popup content on that page. Then in your Child_Admin_Page class you need to define a help popup method for the content in the format "_help_popup_content_{route_name}()"  So if you are setting help content for the
1381
+	 * 'edit_event' route you should have a method named "_help_popup_content_edit_route". In your defined "help_popup_content_..." method.  You must prepare and return an array in the following format array(
1382
+	 *    'help_trigger_id' => array(
1383
+	 *        'title' => __('localized title for popup', 'event_espresso'),
1384
+	 *        'content' => __('localized content for popup', 'event_espresso')
1385
+	 *    )
1386
+	 * );
1387
+	 * Then the EE_Admin_Parent will take care of making sure that is setup properly on the correct route.
1388
+	 *
1389
+	 * @access protected
1390
+	 * @return string content
1391
+	 */
1392
+	protected function _set_help_popup_content($help_array = array(), $display = false)
1393
+	{
1394
+		$content = '';
1395
+		$help_array = empty($help_array) ? $this->_get_help_content() : $help_array;
1396
+		$template_path = EE_ADMIN_TEMPLATE . 'admin_help_popup.template.php';
1397
+		//loop through the array and setup content
1398
+		foreach ($help_array as $trigger => $help) {
1399
+			//make sure the array is setup properly
1400
+			if ( ! isset($help['title']) || ! isset($help['content'])) {
1401
+				throw new EE_Error(__('Does not look like the popup content array has been setup correctly.  Might want to double check that.  Read the comments for the _get_help_popup_content method found in "EE_Admin_Page" class',
1402
+						'event_espresso'));
1403
+			}
1404
+			//we're good so let'd setup the template vars and then assign parsed template content to our content.
1405
+			$template_args = array(
1406
+					'help_popup_id'      => $trigger,
1407
+					'help_popup_title'   => $help['title'],
1408
+					'help_popup_content' => $help['content'],
1409
+			);
1410
+			$content .= EEH_Template::display_template($template_path, $template_args, true);
1411
+		}
1412
+		if ($display) {
1413
+			echo $content;
1414
+		} else {
1415
+			return $content;
1416
+		}
1417
+	}
1418
+
1419
+
1420
+
1421
+	/**
1422
+	 * All this does is retrive the help content array if set by the EE_Admin_Page child
1423
+	 *
1424
+	 * @access private
1425
+	 * @return array properly formatted array for help popup content
1426
+	 */
1427
+	private function _get_help_content()
1428
+	{
1429
+		//what is the method we're looking for?
1430
+		$method_name = '_help_popup_content_' . $this->_req_action;
1431
+		//if method doesn't exist let's get out.
1432
+		if ( ! method_exists($this, $method_name)) {
1433
+			return array();
1434
+		}
1435
+		//k we're good to go let's retrieve the help array
1436
+		$help_array = call_user_func(array($this, $method_name));
1437
+		//make sure we've got an array!
1438
+		if ( ! is_array($help_array)) {
1439
+			throw new EE_Error(__('Something went wrong with help popup content generation. Expecting an array and well, this ain\'t no array bub.', 'event_espresso'));
1440
+		}
1441
+		return $help_array;
1442
+	}
1443
+
1444
+
1445
+
1446
+	/**
1447
+	 * EE Admin Pages can use this to set a properly formatted trigger for a help popup.
1448
+	 * By default the trigger html is printed.  Otherwise it can be returned if the $display flag is set "false"
1449
+	 * See comments made on the _set_help_content method for understanding other parts to the help popup tool.
1450
+	 *
1451
+	 * @access protected
1452
+	 * @param string  $trigger_id reference for retrieving the trigger content for the popup
1453
+	 * @param boolean $display    if false then we return the trigger string
1454
+	 * @param array   $dimensions an array of dimensions for the box (array(h,w))
1455
+	 * @return string
1456
+	 */
1457
+	protected function _set_help_trigger($trigger_id, $display = true, $dimensions = array('400', '640'))
1458
+	{
1459
+		if (defined('DOING_AJAX')) {
1460
+			return;
1461
+		}
1462
+		//let's check and see if there is any content set for this popup.  If there isn't then we'll include a default title and content so that developers know something needs to be corrected
1463
+		$help_array = $this->_get_help_content();
1464
+		$help_content = '';
1465
+		if (empty($help_array) || ! isset($help_array[$trigger_id])) {
1466
+			$help_array[$trigger_id] = array(
1467
+					'title'   => __('Missing Content', 'event_espresso'),
1468
+					'content' => __('A trigger has been set that doesn\'t have any corresponding content. Make sure you have set the help content. (see the "_set_help_popup_content" method in the EE_Admin_Page for instructions.)',
1469
+							'event_espresso'),
1470
+			);
1471
+			$help_content = $this->_set_help_popup_content($help_array, false);
1472
+		}
1473
+		//let's setup the trigger
1474
+		$content = '<a class="ee-dialog" href="?height=' . $dimensions[0] . '&width=' . $dimensions[1] . '&inlineId=' . $trigger_id . '" target="_blank"><span class="question ee-help-popup-question"></span></a>';
1475
+		$content = $content . $help_content;
1476
+		if ($display) {
1477
+			echo $content;
1478
+		} else {
1479
+			return $content;
1480
+		}
1481
+	}
1482
+
1483
+
1484
+
1485
+	/**
1486
+	 * _add_global_screen_options
1487
+	 * Add any extra wp_screen_options within this method using built-in WP functions/methods for doing so.
1488
+	 * This particular method will add_screen_options on ALL EE_Admin Pages
1489
+	 *
1490
+	 * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
1491
+	 *         see also WP_Screen object documents...
1492
+	 * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
1493
+	 * @abstract
1494
+	 * @access private
1495
+	 * @return void
1496
+	 */
1497
+	private function _add_global_screen_options()
1498
+	{
1499
+	}
1500
+
1501
+
1502
+
1503
+	/**
1504
+	 * _add_global_feature_pointers
1505
+	 * This method is used for implementing any "feature pointers" (using built-in WP styling js).
1506
+	 * This particular method will implement feature pointers for ALL EE_Admin pages.
1507
+	 * Note: this is just a placeholder for now.  Implementation will come down the road
1508
+	 *
1509
+	 * @see    WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be extended) also see:
1510
+	 * @link   http://eamann.com/tech/wordpress-portland/
1511
+	 * @abstract
1512
+	 * @access protected
1513
+	 * @return void
1514
+	 */
1515
+	private function _add_global_feature_pointers()
1516
+	{
1517
+	}
1518
+
1519
+
1520
+
1521
+	/**
1522
+	 * load_global_scripts_styles
1523
+	 * The scripts and styles enqueued in here will be loaded on every EE Admin page
1524
+	 *
1525
+	 * @return void
1526
+	 */
1527
+	public function load_global_scripts_styles()
1528
+	{
1529
+		/** STYLES **/
1530
+		// add debugging styles
1531
+		if (WP_DEBUG) {
1532
+			add_action('admin_head', array($this, 'add_xdebug_style'));
1533
+		}
1534
+		//register all styles
1535
+		wp_register_style('espresso-ui-theme', EE_GLOBAL_ASSETS_URL . 'css/espresso-ui-theme/jquery-ui-1.10.3.custom.min.css', array(), EVENT_ESPRESSO_VERSION);
1536
+		wp_register_style('ee-admin-css', EE_ADMIN_URL . 'assets/ee-admin-page.css', array(), EVENT_ESPRESSO_VERSION);
1537
+		//helpers styles
1538
+		wp_register_style('ee-text-links', EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.css', array(), EVENT_ESPRESSO_VERSION);
1539
+		//enqueue global styles
1540
+		wp_enqueue_style('ee-admin-css');
1541
+		/** SCRIPTS **/
1542
+		//register all scripts
1543
+		wp_register_script('espresso_core', EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js', array('jquery'), EVENT_ESPRESSO_VERSION, true);
1544
+		wp_register_script('ee-dialog', EE_ADMIN_URL . 'assets/ee-dialog-helper.js', array('jquery', 'jquery-ui-draggable'), EVENT_ESPRESSO_VERSION, true);
1545
+		wp_register_script('ee_admin_js', EE_ADMIN_URL . 'assets/ee-admin-page.js', array('espresso_core', 'ee-parse-uri', 'ee-dialog'), EVENT_ESPRESSO_VERSION, true);
1546
+		wp_register_script('jquery-ui-timepicker-addon', EE_GLOBAL_ASSETS_URL . 'scripts/jquery-ui-timepicker-addon.js', array('jquery-ui-datepicker', 'jquery-ui-slider'), EVENT_ESPRESSO_VERSION, true);
1547
+		// register jQuery Validate - see /includes/functions/wp_hooks.php
1548
+		add_filter('FHEE_load_jquery_validate', '__return_true');
1549
+		add_filter('FHEE_load_joyride', '__return_true');
1550
+		//script for sorting tables
1551
+		wp_register_script('espresso_ajax_table_sorting', EE_ADMIN_URL . "assets/espresso_ajax_table_sorting.js", array('ee_admin_js', 'jquery-ui-sortable'), EVENT_ESPRESSO_VERSION, true);
1552
+		//script for parsing uri's
1553
+		wp_register_script('ee-parse-uri', EE_GLOBAL_ASSETS_URL . 'scripts/parseuri.js', array(), EVENT_ESPRESSO_VERSION, true);
1554
+		//and parsing associative serialized form elements
1555
+		wp_register_script('ee-serialize-full-array', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.serializefullarray.js', array('jquery'), EVENT_ESPRESSO_VERSION, true);
1556
+		//helpers scripts
1557
+		wp_register_script('ee-text-links', EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.js', array('jquery'), EVENT_ESPRESSO_VERSION, true);
1558
+		wp_register_script('ee-moment-core', EE_THIRD_PARTY_URL . 'moment/moment-with-locales.min.js', array(), EVENT_ESPRESSO_VERSION, true);
1559
+		wp_register_script('ee-moment', EE_THIRD_PARTY_URL . 'moment/moment-timezone-with-data.min.js', array('ee-moment-core'), EVENT_ESPRESSO_VERSION, true);
1560
+		wp_register_script('ee-datepicker', EE_ADMIN_URL . 'assets/ee-datepicker.js', array('jquery-ui-timepicker-addon', 'ee-moment'), EVENT_ESPRESSO_VERSION, true);
1561
+		//google charts
1562
+		wp_register_script('google-charts', 'https://www.gstatic.com/charts/loader.js', array(), EVENT_ESPRESSO_VERSION, false);
1563
+		//enqueue global scripts
1564
+		//taking care of metaboxes
1565
+		if ((isset($this->_route_config['metaboxes']) || isset($this->_route_config['has_metaboxes'])) && empty($this->_cpt_route)) {
1566
+			wp_enqueue_script('dashboard');
1567
+		}
1568
+		//enqueue thickbox for ee help popups.  default is to enqueue unless its explicitly set to false since we're assuming all EE pages will have popups
1569
+		if ( ! isset($this->_route_config['has_help_popups']) || (isset($this->_route_config['has_help_popups']) && $this->_route_config['has_help_popups'])) {
1570
+			wp_enqueue_script('ee_admin_js');
1571
+			wp_enqueue_style('ee-admin-css');
1572
+		}
1573
+		//localize script for ajax lazy loading
1574
+		$lazy_loader_container_ids = apply_filters('FHEE__EE_Admin_Page_Core__load_global_scripts_styles__loader_containers', array('espresso_news_post_box_content'));
1575
+		wp_localize_script('ee_admin_js', 'eeLazyLoadingContainers', $lazy_loader_container_ids);
1576
+		/**
1577
+		 * help tour stuff
1578
+		 */
1579
+		if ( ! empty($this->_help_tour)) {
1580
+			//register the js for kicking things off
1581
+			wp_enqueue_script('ee-help-tour', EE_ADMIN_URL . 'assets/ee-help-tour.js', array('jquery-joyride'), EVENT_ESPRESSO_VERSION, true);
1582
+			//setup tours for the js tour object
1583
+			foreach ($this->_help_tour['tours'] as $tour) {
1584
+				$tours[] = array(
1585
+						'id'      => $tour->get_slug(),
1586
+						'options' => $tour->get_options(),
1587
+				);
1588
+			}
1589
+			wp_localize_script('ee-help-tour', 'EE_HELP_TOUR', array('tours' => $tours));
1590
+			//admin_footer_global will take care of making sure our help_tour skeleton gets printed via the info stored in $this->_help_tour
1591
+		}
1592
+	}
1593
+
1594
+
1595
+
1596
+	/**
1597
+	 *        admin_footer_scripts_eei18n_js_strings
1598
+	 *
1599
+	 * @access        public
1600
+	 * @return        void
1601
+	 */
1602
+	public function admin_footer_scripts_eei18n_js_strings()
1603
+	{
1604
+		EE_Registry::$i18n_js_strings['ajax_url'] = WP_AJAX_URL;
1605
+		EE_Registry::$i18n_js_strings['confirm_delete'] = __('Are you absolutely sure you want to delete this item?\nThis action will delete ALL DATA associated with this item!!!\nThis can NOT be undone!!!', 'event_espresso');
1606
+		EE_Registry::$i18n_js_strings['January'] = __('January', 'event_espresso');
1607
+		EE_Registry::$i18n_js_strings['February'] = __('February', 'event_espresso');
1608
+		EE_Registry::$i18n_js_strings['March'] = __('March', 'event_espresso');
1609
+		EE_Registry::$i18n_js_strings['April'] = __('April', 'event_espresso');
1610
+		EE_Registry::$i18n_js_strings['May'] = __('May', 'event_espresso');
1611
+		EE_Registry::$i18n_js_strings['June'] = __('June', 'event_espresso');
1612
+		EE_Registry::$i18n_js_strings['July'] = __('July', 'event_espresso');
1613
+		EE_Registry::$i18n_js_strings['August'] = __('August', 'event_espresso');
1614
+		EE_Registry::$i18n_js_strings['September'] = __('September', 'event_espresso');
1615
+		EE_Registry::$i18n_js_strings['October'] = __('October', 'event_espresso');
1616
+		EE_Registry::$i18n_js_strings['November'] = __('November', 'event_espresso');
1617
+		EE_Registry::$i18n_js_strings['December'] = __('December', 'event_espresso');
1618
+		EE_Registry::$i18n_js_strings['Jan'] = __('Jan', 'event_espresso');
1619
+		EE_Registry::$i18n_js_strings['Feb'] = __('Feb', 'event_espresso');
1620
+		EE_Registry::$i18n_js_strings['Mar'] = __('Mar', 'event_espresso');
1621
+		EE_Registry::$i18n_js_strings['Apr'] = __('Apr', 'event_espresso');
1622
+		EE_Registry::$i18n_js_strings['May'] = __('May', 'event_espresso');
1623
+		EE_Registry::$i18n_js_strings['Jun'] = __('Jun', 'event_espresso');
1624
+		EE_Registry::$i18n_js_strings['Jul'] = __('Jul', 'event_espresso');
1625
+		EE_Registry::$i18n_js_strings['Aug'] = __('Aug', 'event_espresso');
1626
+		EE_Registry::$i18n_js_strings['Sep'] = __('Sep', 'event_espresso');
1627
+		EE_Registry::$i18n_js_strings['Oct'] = __('Oct', 'event_espresso');
1628
+		EE_Registry::$i18n_js_strings['Nov'] = __('Nov', 'event_espresso');
1629
+		EE_Registry::$i18n_js_strings['Dec'] = __('Dec', 'event_espresso');
1630
+		EE_Registry::$i18n_js_strings['Sunday'] = __('Sunday', 'event_espresso');
1631
+		EE_Registry::$i18n_js_strings['Monday'] = __('Monday', 'event_espresso');
1632
+		EE_Registry::$i18n_js_strings['Tuesday'] = __('Tuesday', 'event_espresso');
1633
+		EE_Registry::$i18n_js_strings['Wednesday'] = __('Wednesday', 'event_espresso');
1634
+		EE_Registry::$i18n_js_strings['Thursday'] = __('Thursday', 'event_espresso');
1635
+		EE_Registry::$i18n_js_strings['Friday'] = __('Friday', 'event_espresso');
1636
+		EE_Registry::$i18n_js_strings['Saturday'] = __('Saturday', 'event_espresso');
1637
+		EE_Registry::$i18n_js_strings['Sun'] = __('Sun', 'event_espresso');
1638
+		EE_Registry::$i18n_js_strings['Mon'] = __('Mon', 'event_espresso');
1639
+		EE_Registry::$i18n_js_strings['Tue'] = __('Tue', 'event_espresso');
1640
+		EE_Registry::$i18n_js_strings['Wed'] = __('Wed', 'event_espresso');
1641
+		EE_Registry::$i18n_js_strings['Thu'] = __('Thu', 'event_espresso');
1642
+		EE_Registry::$i18n_js_strings['Fri'] = __('Fri', 'event_espresso');
1643
+		EE_Registry::$i18n_js_strings['Sat'] = __('Sat', 'event_espresso');
1644
+		//setting on espresso_core instead of ee_admin_js because espresso_core is enqueued by the maintenance
1645
+		//admin page when in maintenance mode and ee_admin_js is not loaded then.  This works everywhere else because
1646
+		//espresso_core is listed as a dependency of ee_admin_js.
1647
+		wp_localize_script('espresso_core', 'eei18n', EE_Registry::$i18n_js_strings);
1648
+	}
1649
+
1650
+
1651
+
1652
+	/**
1653
+	 *        load enhanced xdebug styles for ppl with failing eyesight
1654
+	 *
1655
+	 * @access        public
1656
+	 * @return        void
1657
+	 */
1658
+	public function add_xdebug_style()
1659
+	{
1660
+		echo '<style>.xdebug-error { font-size:1.5em; }</style>';
1661
+	}
1662
+
1663
+
1664
+	/************************/
1665
+	/** LIST TABLE METHODS **/
1666
+	/************************/
1667
+	/**
1668
+	 * this sets up the list table if the current view requires it.
1669
+	 *
1670
+	 * @access protected
1671
+	 * @return void
1672
+	 */
1673
+	protected function _set_list_table()
1674
+	{
1675
+		//first is this a list_table view?
1676
+		if ( ! isset($this->_route_config['list_table'])) {
1677
+			return;
1678
+		} //not a list_table view so get out.
1679
+		//list table functions are per view specific (because some admin pages might have more than one listtable!)
1680
+		if (call_user_func(array($this, '_set_list_table_views_' . $this->_req_action)) === false) {
1681
+			//user error msg
1682
+			$error_msg = __('An error occurred. The requested list table views could not be found.', 'event_espresso');
1683
+			//developer error msg
1684
+			$error_msg .= '||' . sprintf(__('List table views for "%s" route could not be setup. Check that you have the corresponding method, "%s" set up for defining list_table_views for this route.', 'event_espresso'),
1685
+							$this->_req_action, '_set_list_table_views_' . $this->_req_action);
1686
+			throw new EE_Error($error_msg);
1687
+		}
1688
+		//let's provide the ability to filter the views per PAGE AND ROUTE, per PAGE, and globally
1689
+		$this->_views = apply_filters('FHEE_list_table_views_' . $this->page_slug . '_' . $this->_req_action, $this->_views);
1690
+		$this->_views = apply_filters('FHEE_list_table_views_' . $this->page_slug, $this->_views);
1691
+		$this->_views = apply_filters('FHEE_list_table_views', $this->_views);
1692
+		$this->_set_list_table_view();
1693
+		$this->_set_list_table_object();
1694
+	}
1695
+
1696
+
1697
+
1698
+	/**
1699
+	 *        set current view for List Table
1700
+	 *
1701
+	 * @access public
1702
+	 * @return array
1703
+	 */
1704
+	protected function _set_list_table_view()
1705
+	{
1706
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1707
+		// looking at active items or dumpster diving ?
1708
+		if ( ! isset($this->_req_data['status']) || ! array_key_exists($this->_req_data['status'], $this->_views)) {
1709
+			$this->_view = isset($this->_views['in_use']) ? 'in_use' : 'all';
1710
+		} else {
1711
+			$this->_view = sanitize_key($this->_req_data['status']);
1712
+		}
1713
+	}
1714
+
1715
+
1716
+
1717
+	/**
1718
+	 * _set_list_table_object
1719
+	 * WP_List_Table objects need to be loaded fairly early so automatic stuff WP does is taken care of.
1720
+	 *
1721
+	 * @throws \EE_Error
1722
+	 */
1723
+	protected function _set_list_table_object()
1724
+	{
1725
+		if (isset($this->_route_config['list_table'])) {
1726
+			if ( ! class_exists($this->_route_config['list_table'])) {
1727
+				throw new EE_Error(
1728
+						sprintf(
1729
+								__(
1730
+										'The %s class defined for the list table does not exist.  Please check the spelling of the class ref in the $_page_config property on %s.',
1731
+										'event_espresso'
1732
+								),
1733
+								$this->_route_config['list_table'],
1734
+								get_class($this)
1735
+						)
1736
+				);
1737
+			}
1738
+			$list_table = $this->_route_config['list_table'];
1739
+			$this->_list_table_object = new $list_table($this);
1740
+		}
1741
+	}
1742
+
1743
+
1744
+
1745
+	/**
1746
+	 * get_list_table_view_RLs - get it? View RL ?? VU-RL???  URL ??
1747
+	 *
1748
+	 * @param array $extra_query_args                     Optional. An array of extra query args to add to the generated
1749
+	 *                                                    urls.  The array should be indexed by the view it is being
1750
+	 *                                                    added to.
1751
+	 * @return array
1752
+	 */
1753
+	public function get_list_table_view_RLs($extra_query_args = array())
1754
+	{
1755
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1756
+		if (empty($this->_views)) {
1757
+			$this->_views = array();
1758
+		}
1759
+		// cycle thru views
1760
+		foreach ($this->_views as $key => $view) {
1761
+			$query_args = array();
1762
+			// check for current view
1763
+			$this->_views[$key]['class'] = $this->_view == $view['slug'] ? 'current' : '';
1764
+			$query_args['action'] = $this->_req_action;
1765
+			$query_args[$this->_req_action . '_nonce'] = wp_create_nonce($query_args['action'] . '_nonce');
1766
+			$query_args['status'] = $view['slug'];
1767
+			//merge any other arguments sent in.
1768
+			if (isset($extra_query_args[$view['slug']])) {
1769
+				$query_args = array_merge($query_args, $extra_query_args[$view['slug']]);
1770
+			}
1771
+			$this->_views[$key]['url'] = EE_Admin_Page::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1772
+		}
1773
+		return $this->_views;
1774
+	}
1775
+
1776
+
1777
+
1778
+	/**
1779
+	 * _entries_per_page_dropdown
1780
+	 * generates a drop down box for selecting the number of visiable rows in an admin page list table
1781
+	 *
1782
+	 * @todo   : Note: ideally this should be added to the screen options dropdown as that would be consistent with how WP does it.
1783
+	 * @access protected
1784
+	 * @param int $max_entries total number of rows in the table
1785
+	 * @return string
1786
+	 */
1787
+	protected function _entries_per_page_dropdown($max_entries = false)
1788
+	{
1789
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1790
+		$values = array(10, 25, 50, 100);
1791
+		$per_page = ( ! empty($this->_req_data['per_page'])) ? absint($this->_req_data['per_page']) : 10;
1792
+		if ($max_entries) {
1793
+			$values[] = $max_entries;
1794
+			sort($values);
1795
+		}
1796
+		$entries_per_page_dropdown = '
1797 1797
 			<div id="entries-per-page-dv" class="alignleft actions">
1798 1798
 				<label class="hide-if-no-js">
1799 1799
 					Show
1800 1800
 					<select id="entries-per-page-slct" name="entries-per-page-slct">';
1801
-        foreach ($values as $value) {
1802
-            if ($value < $max_entries) {
1803
-                $selected = $value == $per_page ? ' selected="' . $per_page . '"' : '';
1804
-                $entries_per_page_dropdown .= '
1801
+		foreach ($values as $value) {
1802
+			if ($value < $max_entries) {
1803
+				$selected = $value == $per_page ? ' selected="' . $per_page . '"' : '';
1804
+				$entries_per_page_dropdown .= '
1805 1805
 						<option value="' . $value . '"' . $selected . '>' . $value . '&nbsp;&nbsp;</option>';
1806
-            }
1807
-        }
1808
-        $selected = $max_entries == $per_page ? ' selected="' . $per_page . '"' : '';
1809
-        $entries_per_page_dropdown .= '
1806
+			}
1807
+		}
1808
+		$selected = $max_entries == $per_page ? ' selected="' . $per_page . '"' : '';
1809
+		$entries_per_page_dropdown .= '
1810 1810
 						<option value="' . $max_entries . '"' . $selected . '>All&nbsp;&nbsp;</option>';
1811
-        $entries_per_page_dropdown .= '
1811
+		$entries_per_page_dropdown .= '
1812 1812
 					</select>
1813 1813
 					entries
1814 1814
 				</label>
1815 1815
 				<input id="entries-per-page-btn" class="button-secondary" type="submit" value="Go" >
1816 1816
 			</div>
1817 1817
 		';
1818
-        return $entries_per_page_dropdown;
1819
-    }
1820
-
1821
-
1822
-
1823
-    /**
1824
-     *        _set_search_attributes
1825
-     *
1826
-     * @access        protected
1827
-     * @return        void
1828
-     */
1829
-    public function _set_search_attributes()
1830
-    {
1831
-        $this->_template_args['search']['btn_label'] = sprintf(__('Search %s', 'event_espresso'), empty($this->_search_btn_label) ? $this->page_label : $this->_search_btn_label);
1832
-        $this->_template_args['search']['callback'] = 'search_' . $this->page_slug;
1833
-    }
1834
-
1835
-    /*** END LIST TABLE METHODS **/
1836
-    /*****************************/
1837
-    /**
1838
-     *        _add_registered_metaboxes
1839
-     *        this loads any registered metaboxes via the 'metaboxes' index in the _page_config property array.
1840
-     *
1841
-     * @link   http://codex.wordpress.org/Function_Reference/add_meta_box
1842
-     * @access private
1843
-     * @return void
1844
-     */
1845
-    private function _add_registered_meta_boxes()
1846
-    {
1847
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1848
-        //we only add meta boxes if the page_route calls for it
1849
-        if (is_array($this->_route_config) && isset($this->_route_config['metaboxes'])
1850
-            && is_array(
1851
-                    $this->_route_config['metaboxes']
1852
-            )
1853
-        ) {
1854
-            // this simply loops through the callbacks provided
1855
-            // and checks if there is a corresponding callback registered by the child
1856
-            // if there is then we go ahead and process the metabox loader.
1857
-            foreach ($this->_route_config['metaboxes'] as $metabox_callback) {
1858
-                // first check for Closures
1859
-                if ($metabox_callback instanceof Closure) {
1860
-                    $result = $metabox_callback();
1861
-                } else if (is_array($metabox_callback) && isset($metabox_callback[0], $metabox_callback[1])) {
1862
-                    $result = call_user_func(array($metabox_callback[0], $metabox_callback[1]));
1863
-                } else {
1864
-                    $result = call_user_func(array($this, &$metabox_callback));
1865
-                }
1866
-                if ($result === false) {
1867
-                    // user error msg
1868
-                    $error_msg = __('An error occurred. The  requested metabox could not be found.', 'event_espresso');
1869
-                    // developer error msg
1870
-                    $error_msg .= '||' . sprintf(
1871
-                                    __(
1872
-                                            'The metabox with the string "%s" could not be called. Check that the spelling for method names and actions in the "_page_config[\'metaboxes\']" array are all correct.',
1873
-                                            'event_espresso'
1874
-                                    ),
1875
-                                    $metabox_callback
1876
-                            );
1877
-                    throw new EE_Error($error_msg);
1878
-                }
1879
-            }
1880
-        }
1881
-    }
1882
-
1883
-
1884
-
1885
-    /**
1886
-     * _add_screen_columns
1887
-     * This will check the _page_config array and if there is "columns" key index indicated, we'll set the template as the dynamic column template and we'll setup the column options for the page.
1888
-     *
1889
-     * @access private
1890
-     * @return void
1891
-     */
1892
-    private function _add_screen_columns()
1893
-    {
1894
-        if (
1895
-                is_array($this->_route_config)
1896
-                && isset($this->_route_config['columns'])
1897
-                && is_array($this->_route_config['columns'])
1898
-                && count($this->_route_config['columns']) === 2
1899
-        ) {
1900
-            add_screen_option('layout_columns', array('max' => (int)$this->_route_config['columns'][0], 'default' => (int)$this->_route_config['columns'][1]));
1901
-            $this->_template_args['num_columns'] = $this->_route_config['columns'][0];
1902
-            $screen_id = $this->_current_screen->id;
1903
-            $screen_columns = (int)get_user_option("screen_layout_$screen_id");
1904
-            $total_columns = ! empty($screen_columns) ? $screen_columns : $this->_route_config['columns'][1];
1905
-            $this->_template_args['current_screen_widget_class'] = 'columns-' . $total_columns;
1906
-            $this->_template_args['current_page'] = $this->_wp_page_slug;
1907
-            $this->_template_args['screen'] = $this->_current_screen;
1908
-            $this->_column_template_path = EE_ADMIN_TEMPLATE . 'admin_details_metabox_column_wrapper.template.php';
1909
-            //finally if we don't have has_metaboxes set in the route config let's make sure it IS set other wise the necessary hidden fields for this won't be loaded.
1910
-            $this->_route_config['has_metaboxes'] = true;
1911
-        }
1912
-    }
1913
-
1914
-
1915
-
1916
-    /**********************************/
1917
-    /** GLOBALLY AVAILABLE METABOXES **/
1918
-    /**
1919
-     * In this section we put any globally available EE metaboxes for all EE Admin pages.  They are called by simply referencing the callback in the _page_config array property.  This way you can be very specific about what pages these get
1920
-     * loaded on.
1921
-     */
1922
-    private function _espresso_news_post_box()
1923
-    {
1924
-        $news_box_title = apply_filters('FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title', __('New @ Event Espresso', 'event_espresso'));
1925
-        add_meta_box('espresso_news_post_box', $news_box_title, array(
1926
-                $this,
1927
-                'espresso_news_post_box',
1928
-        ), $this->_wp_page_slug, 'side');
1929
-    }
1930
-
1931
-
1932
-
1933
-    /**
1934
-     * Code for setting up espresso ratings request metabox.
1935
-     */
1936
-    protected function _espresso_ratings_request()
1937
-    {
1938
-        if ( ! apply_filters('FHEE_show_ratings_request_meta_box', true)) {
1939
-            return '';
1940
-        }
1941
-        $ratings_box_title = apply_filters('FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title', __('Keep Event Espresso Decaf Free', 'event_espresso'));
1942
-        add_meta_box('espresso_ratings_request', $ratings_box_title, array(
1943
-                $this,
1944
-                'espresso_ratings_request',
1945
-        ), $this->_wp_page_slug, 'side');
1946
-    }
1947
-
1948
-
1949
-
1950
-    /**
1951
-     * Code for setting up espresso ratings request metabox content.
1952
-     */
1953
-    public function espresso_ratings_request()
1954
-    {
1955
-        $template_path = EE_ADMIN_TEMPLATE . 'espresso_ratings_request_content.template.php';
1956
-        EEH_Template::display_template($template_path, array());
1957
-    }
1958
-
1959
-
1960
-
1961
-    public static function cached_rss_display($rss_id, $url)
1962
-    {
1963
-        $loading = '<p class="widget-loading hide-if-no-js">' . __('Loading&#8230;') . '</p><p class="hide-if-js">' . __('This widget requires JavaScript.') . '</p>';
1964
-        $doing_ajax = (defined('DOING_AJAX') && DOING_AJAX);
1965
-        $pre = '<div class="espresso-rss-display">' . "\n\t";
1966
-        $pre .= '<span id="' . $rss_id . '_url" class="hidden">' . $url . '</span>';
1967
-        $post = '</div>' . "\n";
1968
-        $cache_key = 'ee_rss_' . md5($rss_id);
1969
-        if (false != ($output = get_transient($cache_key))) {
1970
-            echo $pre . $output . $post;
1971
-            return true;
1972
-        }
1973
-        if ( ! $doing_ajax) {
1974
-            echo $pre . $loading . $post;
1975
-            return false;
1976
-        }
1977
-        ob_start();
1978
-        wp_widget_rss_output($url, array('show_date' => 0, 'items' => 5));
1979
-        set_transient($cache_key, ob_get_flush(), 12 * HOUR_IN_SECONDS);
1980
-        return true;
1981
-    }
1982
-
1983
-
1984
-
1985
-    public function espresso_news_post_box()
1986
-    {
1987
-        ?>
1818
+		return $entries_per_page_dropdown;
1819
+	}
1820
+
1821
+
1822
+
1823
+	/**
1824
+	 *        _set_search_attributes
1825
+	 *
1826
+	 * @access        protected
1827
+	 * @return        void
1828
+	 */
1829
+	public function _set_search_attributes()
1830
+	{
1831
+		$this->_template_args['search']['btn_label'] = sprintf(__('Search %s', 'event_espresso'), empty($this->_search_btn_label) ? $this->page_label : $this->_search_btn_label);
1832
+		$this->_template_args['search']['callback'] = 'search_' . $this->page_slug;
1833
+	}
1834
+
1835
+	/*** END LIST TABLE METHODS **/
1836
+	/*****************************/
1837
+	/**
1838
+	 *        _add_registered_metaboxes
1839
+	 *        this loads any registered metaboxes via the 'metaboxes' index in the _page_config property array.
1840
+	 *
1841
+	 * @link   http://codex.wordpress.org/Function_Reference/add_meta_box
1842
+	 * @access private
1843
+	 * @return void
1844
+	 */
1845
+	private function _add_registered_meta_boxes()
1846
+	{
1847
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1848
+		//we only add meta boxes if the page_route calls for it
1849
+		if (is_array($this->_route_config) && isset($this->_route_config['metaboxes'])
1850
+			&& is_array(
1851
+					$this->_route_config['metaboxes']
1852
+			)
1853
+		) {
1854
+			// this simply loops through the callbacks provided
1855
+			// and checks if there is a corresponding callback registered by the child
1856
+			// if there is then we go ahead and process the metabox loader.
1857
+			foreach ($this->_route_config['metaboxes'] as $metabox_callback) {
1858
+				// first check for Closures
1859
+				if ($metabox_callback instanceof Closure) {
1860
+					$result = $metabox_callback();
1861
+				} else if (is_array($metabox_callback) && isset($metabox_callback[0], $metabox_callback[1])) {
1862
+					$result = call_user_func(array($metabox_callback[0], $metabox_callback[1]));
1863
+				} else {
1864
+					$result = call_user_func(array($this, &$metabox_callback));
1865
+				}
1866
+				if ($result === false) {
1867
+					// user error msg
1868
+					$error_msg = __('An error occurred. The  requested metabox could not be found.', 'event_espresso');
1869
+					// developer error msg
1870
+					$error_msg .= '||' . sprintf(
1871
+									__(
1872
+											'The metabox with the string "%s" could not be called. Check that the spelling for method names and actions in the "_page_config[\'metaboxes\']" array are all correct.',
1873
+											'event_espresso'
1874
+									),
1875
+									$metabox_callback
1876
+							);
1877
+					throw new EE_Error($error_msg);
1878
+				}
1879
+			}
1880
+		}
1881
+	}
1882
+
1883
+
1884
+
1885
+	/**
1886
+	 * _add_screen_columns
1887
+	 * This will check the _page_config array and if there is "columns" key index indicated, we'll set the template as the dynamic column template and we'll setup the column options for the page.
1888
+	 *
1889
+	 * @access private
1890
+	 * @return void
1891
+	 */
1892
+	private function _add_screen_columns()
1893
+	{
1894
+		if (
1895
+				is_array($this->_route_config)
1896
+				&& isset($this->_route_config['columns'])
1897
+				&& is_array($this->_route_config['columns'])
1898
+				&& count($this->_route_config['columns']) === 2
1899
+		) {
1900
+			add_screen_option('layout_columns', array('max' => (int)$this->_route_config['columns'][0], 'default' => (int)$this->_route_config['columns'][1]));
1901
+			$this->_template_args['num_columns'] = $this->_route_config['columns'][0];
1902
+			$screen_id = $this->_current_screen->id;
1903
+			$screen_columns = (int)get_user_option("screen_layout_$screen_id");
1904
+			$total_columns = ! empty($screen_columns) ? $screen_columns : $this->_route_config['columns'][1];
1905
+			$this->_template_args['current_screen_widget_class'] = 'columns-' . $total_columns;
1906
+			$this->_template_args['current_page'] = $this->_wp_page_slug;
1907
+			$this->_template_args['screen'] = $this->_current_screen;
1908
+			$this->_column_template_path = EE_ADMIN_TEMPLATE . 'admin_details_metabox_column_wrapper.template.php';
1909
+			//finally if we don't have has_metaboxes set in the route config let's make sure it IS set other wise the necessary hidden fields for this won't be loaded.
1910
+			$this->_route_config['has_metaboxes'] = true;
1911
+		}
1912
+	}
1913
+
1914
+
1915
+
1916
+	/**********************************/
1917
+	/** GLOBALLY AVAILABLE METABOXES **/
1918
+	/**
1919
+	 * In this section we put any globally available EE metaboxes for all EE Admin pages.  They are called by simply referencing the callback in the _page_config array property.  This way you can be very specific about what pages these get
1920
+	 * loaded on.
1921
+	 */
1922
+	private function _espresso_news_post_box()
1923
+	{
1924
+		$news_box_title = apply_filters('FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title', __('New @ Event Espresso', 'event_espresso'));
1925
+		add_meta_box('espresso_news_post_box', $news_box_title, array(
1926
+				$this,
1927
+				'espresso_news_post_box',
1928
+		), $this->_wp_page_slug, 'side');
1929
+	}
1930
+
1931
+
1932
+
1933
+	/**
1934
+	 * Code for setting up espresso ratings request metabox.
1935
+	 */
1936
+	protected function _espresso_ratings_request()
1937
+	{
1938
+		if ( ! apply_filters('FHEE_show_ratings_request_meta_box', true)) {
1939
+			return '';
1940
+		}
1941
+		$ratings_box_title = apply_filters('FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title', __('Keep Event Espresso Decaf Free', 'event_espresso'));
1942
+		add_meta_box('espresso_ratings_request', $ratings_box_title, array(
1943
+				$this,
1944
+				'espresso_ratings_request',
1945
+		), $this->_wp_page_slug, 'side');
1946
+	}
1947
+
1948
+
1949
+
1950
+	/**
1951
+	 * Code for setting up espresso ratings request metabox content.
1952
+	 */
1953
+	public function espresso_ratings_request()
1954
+	{
1955
+		$template_path = EE_ADMIN_TEMPLATE . 'espresso_ratings_request_content.template.php';
1956
+		EEH_Template::display_template($template_path, array());
1957
+	}
1958
+
1959
+
1960
+
1961
+	public static function cached_rss_display($rss_id, $url)
1962
+	{
1963
+		$loading = '<p class="widget-loading hide-if-no-js">' . __('Loading&#8230;') . '</p><p class="hide-if-js">' . __('This widget requires JavaScript.') . '</p>';
1964
+		$doing_ajax = (defined('DOING_AJAX') && DOING_AJAX);
1965
+		$pre = '<div class="espresso-rss-display">' . "\n\t";
1966
+		$pre .= '<span id="' . $rss_id . '_url" class="hidden">' . $url . '</span>';
1967
+		$post = '</div>' . "\n";
1968
+		$cache_key = 'ee_rss_' . md5($rss_id);
1969
+		if (false != ($output = get_transient($cache_key))) {
1970
+			echo $pre . $output . $post;
1971
+			return true;
1972
+		}
1973
+		if ( ! $doing_ajax) {
1974
+			echo $pre . $loading . $post;
1975
+			return false;
1976
+		}
1977
+		ob_start();
1978
+		wp_widget_rss_output($url, array('show_date' => 0, 'items' => 5));
1979
+		set_transient($cache_key, ob_get_flush(), 12 * HOUR_IN_SECONDS);
1980
+		return true;
1981
+	}
1982
+
1983
+
1984
+
1985
+	public function espresso_news_post_box()
1986
+	{
1987
+		?>
1988 1988
         <div class="padding">
1989 1989
             <div id="espresso_news_post_box_content" class="infolinks">
1990 1990
                 <?php
1991
-                // Get RSS Feed(s)
1992
-                $feed_url = apply_filters('FHEE__EE_Admin_Page__espresso_news_post_box__feed_url', 'http://eventespresso.com/feed/');
1993
-                $url = urlencode($feed_url);
1994
-                self::cached_rss_display('espresso_news_post_box_content', $url);
1995
-                ?>
1991
+				// Get RSS Feed(s)
1992
+				$feed_url = apply_filters('FHEE__EE_Admin_Page__espresso_news_post_box__feed_url', 'http://eventespresso.com/feed/');
1993
+				$url = urlencode($feed_url);
1994
+				self::cached_rss_display('espresso_news_post_box_content', $url);
1995
+				?>
1996 1996
             </div>
1997 1997
             <?php do_action('AHEE__EE_Admin_Page__espresso_news_post_box__after_content'); ?>
1998 1998
         </div>
1999 1999
         <?php
2000
-    }
2001
-
2002
-
2003
-
2004
-    private function _espresso_links_post_box()
2005
-    {
2006
-        //Hiding until we actually have content to put in here...
2007
-        //add_meta_box('espresso_links_post_box', __('Helpful Plugin Links', 'event_espresso'), array( $this, 'espresso_links_post_box'), $this->_wp_page_slug, 'side');
2008
-    }
2009
-
2010
-
2011
-
2012
-    public function espresso_links_post_box()
2013
-    {
2014
-        //Hiding until we actually have content to put in here...
2015
-        //$templatepath = EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_links.template.php';
2016
-        //EEH_Template::display_template( $templatepath );
2017
-    }
2018
-
2019
-
2020
-
2021
-    protected function _espresso_sponsors_post_box()
2022
-    {
2023
-        $show_sponsors = apply_filters('FHEE_show_sponsors_meta_box', true);
2024
-        if ($show_sponsors) {
2025
-            add_meta_box('espresso_sponsors_post_box', __('Event Espresso Highlights', 'event_espresso'), array($this, 'espresso_sponsors_post_box'), $this->_wp_page_slug, 'side');
2026
-        }
2027
-    }
2028
-
2029
-
2030
-
2031
-    public function espresso_sponsors_post_box()
2032
-    {
2033
-        $templatepath = EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_sponsors.template.php';
2034
-        EEH_Template::display_template($templatepath);
2035
-    }
2036
-
2037
-
2038
-
2039
-    private function _publish_post_box()
2040
-    {
2041
-        $meta_box_ref = 'espresso_' . $this->page_slug . '_editor_overview';
2042
-        //if there is a array('label' => array('publishbox' => 'some title') ) present in the _page_config array then we'll use that for the metabox label.  Otherwise we'll just use publish (publishbox itself could be an array of labels indexed by routes)
2043
-        if ( ! empty($this->_labels['publishbox'])) {
2044
-            $box_label = is_array($this->_labels['publishbox']) ? $this->_labels['publishbox'][$this->_req_action] : $this->_labels['publishbox'];
2045
-        } else {
2046
-            $box_label = __('Publish', 'event_espresso');
2047
-        }
2048
-        $box_label = apply_filters('FHEE__EE_Admin_Page___publish_post_box__box_label', $box_label, $this->_req_action, $this);
2049
-        add_meta_box($meta_box_ref, $box_label, array($this, 'editor_overview'), $this->_current_screen->id, 'side', 'high');
2050
-    }
2051
-
2052
-
2053
-
2054
-    public function editor_overview()
2055
-    {
2056
-        //if we have extra content set let's add it in if not make sure its empty
2057
-        $this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content']) ? $this->_template_args['publish_box_extra_content'] : '';
2058
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_details_publish_metabox.template.php';
2059
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2060
-    }
2061
-
2062
-
2063
-    /** end of globally available metaboxes section **/
2064
-    /*************************************************/
2065
-    /**
2066
-     * Public wrapper for the protected method.  Allows plugins/addons to externally call the
2067
-     * protected method.
2068
-     *
2069
-     * @see   $this->_set_publish_post_box_vars for param details
2070
-     * @since 4.6.0
2071
-     */
2072
-    public function set_publish_post_box_vars($name = null, $id = false, $delete = false, $save_close_redirect_URL = null, $both_btns = true)
2073
-    {
2074
-        $this->_set_publish_post_box_vars($name, $id, $delete, $save_close_redirect_URL, $both_btns);
2075
-    }
2076
-
2077
-
2078
-
2079
-    /**
2080
-     * Sets the _template_args arguments used by the _publish_post_box shortcut
2081
-     * Note: currently there is no validation for this.  However if you want the delete button, the
2082
-     * save, and save and close buttons to work properly, then you will want to include a
2083
-     * values for the name and id arguments.
2084
-     *
2085
-     * @todo  Add in validation for name/id arguments.
2086
-     * @param    string  $name                    key used for the action ID (i.e. event_id)
2087
-     * @param    int     $id                      id attached to the item published
2088
-     * @param    string  $delete                  page route callback for the delete action
2089
-     * @param    string  $save_close_redirect_URL custom URL to redirect to after Save & Close has been completed
2090
-     * @param    boolean $both_btns               whether to display BOTH the "Save & Close" and "Save" buttons or just the Save button
2091
-     * @throws \EE_Error
2092
-     */
2093
-    protected function _set_publish_post_box_vars(
2094
-            $name = '',
2095
-            $id = 0,
2096
-            $delete = '',
2097
-            $save_close_redirect_URL = '',
2098
-            $both_btns = true
2099
-    ) {
2100
-        // if Save & Close, use a custom redirect URL or default to the main page?
2101
-        $save_close_redirect_URL = ! empty($save_close_redirect_URL) ? $save_close_redirect_URL : $this->_admin_base_url;
2102
-        // create the Save & Close and Save buttons
2103
-        $this->_set_save_buttons($both_btns, array(), array(), $save_close_redirect_URL);
2104
-        //if we have extra content set let's add it in if not make sure its empty
2105
-        $this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content']) ? $this->_template_args['publish_box_extra_content'] : '';
2106
-        if ($delete && ! empty($id)) {
2107
-            //make sure we have a default if just true is sent.
2108
-            $delete = ! empty($delete) ? $delete : 'delete';
2109
-            $delete_link_args = array($name => $id);
2110
-            $delete = $this->get_action_link_or_button(
2111
-                    $delete,
2112
-                    $delete,
2113
-                    $delete_link_args,
2114
-                    'submitdelete deletion',
2115
-                    '',
2116
-                    false
2117
-            );
2118
-        }
2119
-        $this->_template_args['publish_delete_link'] = ! empty($id) ? $delete : '';
2120
-        if ( ! empty($name) && ! empty($id)) {
2121
-            $hidden_field_arr[$name] = array(
2122
-                    'type'  => 'hidden',
2123
-                    'value' => $id,
2124
-            );
2125
-            $hf = $this->_generate_admin_form_fields($hidden_field_arr, 'array');
2126
-        } else {
2127
-            $hf = '';
2128
-        }
2129
-        // add hidden field
2130
-        $this->_template_args['publish_hidden_fields'] = ! empty($hf) ? $hf[$name]['field'] : $hf;
2131
-    }
2132
-
2133
-
2134
-
2135
-    /**
2136
-     *        displays an error message to ppl who have javascript disabled
2137
-     *
2138
-     * @access        private
2139
-     * @return        string
2140
-     */
2141
-    private function _display_no_javascript_warning()
2142
-    {
2143
-        ?>
2000
+	}
2001
+
2002
+
2003
+
2004
+	private function _espresso_links_post_box()
2005
+	{
2006
+		//Hiding until we actually have content to put in here...
2007
+		//add_meta_box('espresso_links_post_box', __('Helpful Plugin Links', 'event_espresso'), array( $this, 'espresso_links_post_box'), $this->_wp_page_slug, 'side');
2008
+	}
2009
+
2010
+
2011
+
2012
+	public function espresso_links_post_box()
2013
+	{
2014
+		//Hiding until we actually have content to put in here...
2015
+		//$templatepath = EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_links.template.php';
2016
+		//EEH_Template::display_template( $templatepath );
2017
+	}
2018
+
2019
+
2020
+
2021
+	protected function _espresso_sponsors_post_box()
2022
+	{
2023
+		$show_sponsors = apply_filters('FHEE_show_sponsors_meta_box', true);
2024
+		if ($show_sponsors) {
2025
+			add_meta_box('espresso_sponsors_post_box', __('Event Espresso Highlights', 'event_espresso'), array($this, 'espresso_sponsors_post_box'), $this->_wp_page_slug, 'side');
2026
+		}
2027
+	}
2028
+
2029
+
2030
+
2031
+	public function espresso_sponsors_post_box()
2032
+	{
2033
+		$templatepath = EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_sponsors.template.php';
2034
+		EEH_Template::display_template($templatepath);
2035
+	}
2036
+
2037
+
2038
+
2039
+	private function _publish_post_box()
2040
+	{
2041
+		$meta_box_ref = 'espresso_' . $this->page_slug . '_editor_overview';
2042
+		//if there is a array('label' => array('publishbox' => 'some title') ) present in the _page_config array then we'll use that for the metabox label.  Otherwise we'll just use publish (publishbox itself could be an array of labels indexed by routes)
2043
+		if ( ! empty($this->_labels['publishbox'])) {
2044
+			$box_label = is_array($this->_labels['publishbox']) ? $this->_labels['publishbox'][$this->_req_action] : $this->_labels['publishbox'];
2045
+		} else {
2046
+			$box_label = __('Publish', 'event_espresso');
2047
+		}
2048
+		$box_label = apply_filters('FHEE__EE_Admin_Page___publish_post_box__box_label', $box_label, $this->_req_action, $this);
2049
+		add_meta_box($meta_box_ref, $box_label, array($this, 'editor_overview'), $this->_current_screen->id, 'side', 'high');
2050
+	}
2051
+
2052
+
2053
+
2054
+	public function editor_overview()
2055
+	{
2056
+		//if we have extra content set let's add it in if not make sure its empty
2057
+		$this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content']) ? $this->_template_args['publish_box_extra_content'] : '';
2058
+		$template_path = EE_ADMIN_TEMPLATE . 'admin_details_publish_metabox.template.php';
2059
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2060
+	}
2061
+
2062
+
2063
+	/** end of globally available metaboxes section **/
2064
+	/*************************************************/
2065
+	/**
2066
+	 * Public wrapper for the protected method.  Allows plugins/addons to externally call the
2067
+	 * protected method.
2068
+	 *
2069
+	 * @see   $this->_set_publish_post_box_vars for param details
2070
+	 * @since 4.6.0
2071
+	 */
2072
+	public function set_publish_post_box_vars($name = null, $id = false, $delete = false, $save_close_redirect_URL = null, $both_btns = true)
2073
+	{
2074
+		$this->_set_publish_post_box_vars($name, $id, $delete, $save_close_redirect_URL, $both_btns);
2075
+	}
2076
+
2077
+
2078
+
2079
+	/**
2080
+	 * Sets the _template_args arguments used by the _publish_post_box shortcut
2081
+	 * Note: currently there is no validation for this.  However if you want the delete button, the
2082
+	 * save, and save and close buttons to work properly, then you will want to include a
2083
+	 * values for the name and id arguments.
2084
+	 *
2085
+	 * @todo  Add in validation for name/id arguments.
2086
+	 * @param    string  $name                    key used for the action ID (i.e. event_id)
2087
+	 * @param    int     $id                      id attached to the item published
2088
+	 * @param    string  $delete                  page route callback for the delete action
2089
+	 * @param    string  $save_close_redirect_URL custom URL to redirect to after Save & Close has been completed
2090
+	 * @param    boolean $both_btns               whether to display BOTH the "Save & Close" and "Save" buttons or just the Save button
2091
+	 * @throws \EE_Error
2092
+	 */
2093
+	protected function _set_publish_post_box_vars(
2094
+			$name = '',
2095
+			$id = 0,
2096
+			$delete = '',
2097
+			$save_close_redirect_URL = '',
2098
+			$both_btns = true
2099
+	) {
2100
+		// if Save & Close, use a custom redirect URL or default to the main page?
2101
+		$save_close_redirect_URL = ! empty($save_close_redirect_URL) ? $save_close_redirect_URL : $this->_admin_base_url;
2102
+		// create the Save & Close and Save buttons
2103
+		$this->_set_save_buttons($both_btns, array(), array(), $save_close_redirect_URL);
2104
+		//if we have extra content set let's add it in if not make sure its empty
2105
+		$this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content']) ? $this->_template_args['publish_box_extra_content'] : '';
2106
+		if ($delete && ! empty($id)) {
2107
+			//make sure we have a default if just true is sent.
2108
+			$delete = ! empty($delete) ? $delete : 'delete';
2109
+			$delete_link_args = array($name => $id);
2110
+			$delete = $this->get_action_link_or_button(
2111
+					$delete,
2112
+					$delete,
2113
+					$delete_link_args,
2114
+					'submitdelete deletion',
2115
+					'',
2116
+					false
2117
+			);
2118
+		}
2119
+		$this->_template_args['publish_delete_link'] = ! empty($id) ? $delete : '';
2120
+		if ( ! empty($name) && ! empty($id)) {
2121
+			$hidden_field_arr[$name] = array(
2122
+					'type'  => 'hidden',
2123
+					'value' => $id,
2124
+			);
2125
+			$hf = $this->_generate_admin_form_fields($hidden_field_arr, 'array');
2126
+		} else {
2127
+			$hf = '';
2128
+		}
2129
+		// add hidden field
2130
+		$this->_template_args['publish_hidden_fields'] = ! empty($hf) ? $hf[$name]['field'] : $hf;
2131
+	}
2132
+
2133
+
2134
+
2135
+	/**
2136
+	 *        displays an error message to ppl who have javascript disabled
2137
+	 *
2138
+	 * @access        private
2139
+	 * @return        string
2140
+	 */
2141
+	private function _display_no_javascript_warning()
2142
+	{
2143
+		?>
2144 2144
         <noscript>
2145 2145
             <div id="no-js-message" class="error">
2146 2146
                 <p style="font-size:1.3em;">
@@ -2150,1248 +2150,1248 @@  discard block
 block discarded – undo
2150 2150
             </div>
2151 2151
         </noscript>
2152 2152
         <?php
2153
-    }
2153
+	}
2154 2154
 
2155 2155
 
2156 2156
 
2157
-    /**
2158
-     *        displays espresso success and/or error notices
2159
-     *
2160
-     * @access        private
2161
-     * @return        string
2162
-     */
2163
-    private function _display_espresso_notices()
2164
-    {
2165
-        $notices = $this->_get_transient(true);
2166
-        echo stripslashes($notices);
2167
-    }
2157
+	/**
2158
+	 *        displays espresso success and/or error notices
2159
+	 *
2160
+	 * @access        private
2161
+	 * @return        string
2162
+	 */
2163
+	private function _display_espresso_notices()
2164
+	{
2165
+		$notices = $this->_get_transient(true);
2166
+		echo stripslashes($notices);
2167
+	}
2168 2168
 
2169 2169
 
2170 2170
 
2171
-    /**
2172
-     *        spinny things pacify the masses
2173
-     *
2174
-     * @access private
2175
-     * @return string
2176
-     */
2177
-    protected function _add_admin_page_ajax_loading_img()
2178
-    {
2179
-        ?>
2171
+	/**
2172
+	 *        spinny things pacify the masses
2173
+	 *
2174
+	 * @access private
2175
+	 * @return string
2176
+	 */
2177
+	protected function _add_admin_page_ajax_loading_img()
2178
+	{
2179
+		?>
2180 2180
         <div id="espresso-ajax-loading" class="ajax-loading-grey">
2181 2181
             <span class="ee-spinner ee-spin"></span><span class="hidden"><?php _e('loading...', 'event_espresso'); ?></span>
2182 2182
         </div>
2183 2183
         <?php
2184
-    }
2184
+	}
2185 2185
 
2186 2186
 
2187 2187
 
2188
-    /**
2189
-     *        add admin page overlay for modal boxes
2190
-     *
2191
-     * @access private
2192
-     * @return string
2193
-     */
2194
-    protected function _add_admin_page_overlay()
2195
-    {
2196
-        ?>
2188
+	/**
2189
+	 *        add admin page overlay for modal boxes
2190
+	 *
2191
+	 * @access private
2192
+	 * @return string
2193
+	 */
2194
+	protected function _add_admin_page_overlay()
2195
+	{
2196
+		?>
2197 2197
         <div id="espresso-admin-page-overlay-dv" class=""></div>
2198 2198
         <?php
2199
-    }
2200
-
2201
-
2202
-
2203
-    /**
2204
-     * facade for add_meta_box
2205
-     *
2206
-     * @param string  $action        where the metabox get's displayed
2207
-     * @param string  $title         Title of Metabox (output in metabox header)
2208
-     * @param string  $callback      If not empty and $create_fun is set to false then we'll use a custom callback instead of the one created in here.
2209
-     * @param array   $callback_args an array of args supplied for the metabox
2210
-     * @param string  $column        what metabox column
2211
-     * @param string  $priority      give this metabox a priority (using accepted priorities for wp meta boxes)
2212
-     * @param boolean $create_func   default is true.  Basically we can say we don't WANT to have the runtime function created but just set our own callback for wp's add_meta_box.
2213
-     */
2214
-    public function _add_admin_page_meta_box($action, $title, $callback, $callback_args, $column = 'normal', $priority = 'high', $create_func = true)
2215
-    {
2216
-        do_action('AHEE_log', __FILE__, __FUNCTION__, $callback);
2217
-        //if we have empty callback args and we want to automatically create the metabox callback then we need to make sure the callback args are generated.
2218
-        if (empty($callback_args) && $create_func) {
2219
-            $callback_args = array(
2220
-                    'template_path' => $this->_template_path,
2221
-                    'template_args' => $this->_template_args,
2222
-            );
2223
-        }
2224
-        //if $create_func is true (default) then we automatically create the function for displaying the actual meta box.  If false then we take the $callback reference passed through and use it instead (so callers can define their own callback function/method if they wish)
2225
-        $call_back_func = $create_func ? create_function('$post, $metabox',
2226
-                'do_action( "AHEE_log", __FILE__, __FUNCTION__, ""); echo EEH_Template::display_template( $metabox["args"]["template_path"], $metabox["args"]["template_args"], TRUE );') : $callback;
2227
-        add_meta_box(str_replace('_', '-', $action) . '-mbox', $title, $call_back_func, $this->_wp_page_slug, $column, $priority, $callback_args);
2228
-    }
2229
-
2230
-
2231
-
2232
-    /**
2233
-     * generates HTML wrapper for and admin details page that contains metaboxes in columns
2234
-     *
2235
-     * @return [type] [description]
2236
-     */
2237
-    public function display_admin_page_with_metabox_columns()
2238
-    {
2239
-        $this->_template_args['post_body_content'] = $this->_template_args['admin_page_content'];
2240
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_column_template_path, $this->_template_args, true);
2241
-        //the final wrapper
2242
-        $this->admin_page_wrapper();
2243
-    }
2244
-
2245
-
2246
-
2247
-    /**
2248
-     *        generates  HTML wrapper for an admin details page
2249
-     *
2250
-     * @access public
2251
-     * @return void
2252
-     */
2253
-    public function display_admin_page_with_sidebar()
2254
-    {
2255
-        $this->_display_admin_page(true);
2256
-    }
2257
-
2258
-
2259
-
2260
-    /**
2261
-     *        generates  HTML wrapper for an admin details page (except no sidebar)
2262
-     *
2263
-     * @access public
2264
-     * @return void
2265
-     */
2266
-    public function display_admin_page_with_no_sidebar()
2267
-    {
2268
-        $this->_display_admin_page();
2269
-    }
2270
-
2271
-
2272
-
2273
-    /**
2274
-     * generates HTML wrapper for an EE about admin page (no sidebar)
2275
-     *
2276
-     * @access public
2277
-     * @return void
2278
-     */
2279
-    public function display_about_admin_page()
2280
-    {
2281
-        $this->_display_admin_page(false, true);
2282
-    }
2283
-
2284
-
2285
-
2286
-    /**
2287
-     * display_admin_page
2288
-     * contains the code for actually displaying an admin page
2289
-     *
2290
-     * @access private
2291
-     * @param  boolean $sidebar true with sidebar, false without
2292
-     * @param  boolean $about   use the about admin wrapper instead of the default.
2293
-     * @return void
2294
-     */
2295
-    private function _display_admin_page($sidebar = false, $about = false)
2296
-    {
2297
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2298
-        //custom remove metaboxes hook to add or remove any metaboxes to/from Admin pages.
2299
-        do_action('AHEE__EE_Admin_Page___display_admin_page__modify_metaboxes');
2300
-        // set current wp page slug - looks like: event-espresso_page_event_categories
2301
-        // keep in mind "event-espresso" COULD be something else if the top level menu label has been translated.
2302
-        $this->_template_args['current_page'] = $this->_wp_page_slug;
2303
-        $this->_template_args['admin_page_wrapper_div_id'] = $this->_cpt_route
2304
-                ? 'poststuff'
2305
-                : 'espresso-default-admin';
2306
-        $template_path = $sidebar
2307
-                ? EE_ADMIN_TEMPLATE . 'admin_details_wrapper.template.php'
2308
-                : EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar.template.php';
2309
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2310
-            $template_path = EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar_ajax.template.php';
2311
-        }
2312
-        $template_path = ! empty($this->_column_template_path) ? $this->_column_template_path : $template_path;
2313
-        $this->_template_args['post_body_content'] = isset($this->_template_args['admin_page_content']) ? $this->_template_args['admin_page_content'] : '';
2314
-        $this->_template_args['before_admin_page_content'] = isset($this->_template_args['before_admin_page_content']) ? $this->_template_args['before_admin_page_content'] : '';
2315
-        $this->_template_args['after_admin_page_content'] = isset($this->_template_args['after_admin_page_content']) ? $this->_template_args['after_admin_page_content'] : '';
2316
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path, $this->_template_args, true);
2317
-        // the final template wrapper
2318
-        $this->admin_page_wrapper($about);
2319
-    }
2320
-
2321
-
2322
-
2323
-    /**
2324
-     * This is used to display caf preview pages.
2325
-     *
2326
-     * @since 4.3.2
2327
-     * @param string $utm_campaign_source what is the key used for google analytics link
2328
-     * @param bool   $display_sidebar     whether to use the sidebar template or the full template for the page.  TRUE = SHOW sidebar, FALSE = no sidebar. Default no sidebar.
2329
-     * @return void
2330
-     * @throws \EE_Error
2331
-     */
2332
-    public function display_admin_caf_preview_page($utm_campaign_source = '', $display_sidebar = true)
2333
-    {
2334
-        //let's generate a default preview action button if there isn't one already present.
2335
-        $this->_labels['buttons']['buy_now'] = __('Upgrade Now', 'event_espresso');
2336
-        $buy_now_url = add_query_arg(
2337
-                array(
2338
-                        'ee_ver'       => 'ee4',
2339
-                        'utm_source'   => 'ee4_plugin_admin',
2340
-                        'utm_medium'   => 'link',
2341
-                        'utm_campaign' => $utm_campaign_source,
2342
-                        'utm_content'  => 'buy_now_button',
2343
-                ),
2344
-                'http://eventespresso.com/pricing/'
2345
-        );
2346
-        $this->_template_args['preview_action_button'] = ! isset($this->_template_args['preview_action_button'])
2347
-                ? $this->get_action_link_or_button(
2348
-                        '',
2349
-                        'buy_now',
2350
-                        array(),
2351
-                        'button-primary button-large',
2352
-                        $buy_now_url,
2353
-                        true
2354
-                )
2355
-                : $this->_template_args['preview_action_button'];
2356
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_caf_full_page_preview.template.php';
2357
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
2358
-                $template_path,
2359
-                $this->_template_args,
2360
-                true
2361
-        );
2362
-        $this->_display_admin_page($display_sidebar);
2363
-    }
2364
-
2365
-
2366
-
2367
-    /**
2368
-     * display_admin_list_table_page_with_sidebar
2369
-     * generates HTML wrapper for an admin_page with list_table
2370
-     *
2371
-     * @access public
2372
-     * @return void
2373
-     */
2374
-    public function display_admin_list_table_page_with_sidebar()
2375
-    {
2376
-        $this->_display_admin_list_table_page(true);
2377
-    }
2378
-
2379
-
2380
-
2381
-    /**
2382
-     * display_admin_list_table_page_with_no_sidebar
2383
-     * generates HTML wrapper for an admin_page with list_table (but with no sidebar)
2384
-     *
2385
-     * @access public
2386
-     * @return void
2387
-     */
2388
-    public function display_admin_list_table_page_with_no_sidebar()
2389
-    {
2390
-        $this->_display_admin_list_table_page();
2391
-    }
2392
-
2393
-
2394
-
2395
-    /**
2396
-     * generates html wrapper for an admin_list_table page
2397
-     *
2398
-     * @access private
2399
-     * @param boolean $sidebar whether to display with sidebar or not.
2400
-     * @return void
2401
-     */
2402
-    private function _display_admin_list_table_page($sidebar = false)
2403
-    {
2404
-        //setup search attributes
2405
-        $this->_set_search_attributes();
2406
-        $this->_template_args['current_page'] = $this->_wp_page_slug;
2407
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_list_wrapper.template.php';
2408
-        $this->_template_args['table_url'] = defined('DOING_AJAX')
2409
-                ? add_query_arg(array('noheader' => 'true', 'route' => $this->_req_action), $this->_admin_base_url)
2410
-                : add_query_arg(array('route' => $this->_req_action), $this->_admin_base_url);
2411
-        $this->_template_args['list_table'] = $this->_list_table_object;
2412
-        $this->_template_args['current_route'] = $this->_req_action;
2413
-        $this->_template_args['list_table_class'] = get_class($this->_list_table_object);
2414
-        $ajax_sorting_callback = $this->_list_table_object->get_ajax_sorting_callback();
2415
-        if ( ! empty($ajax_sorting_callback)) {
2416
-            $sortable_list_table_form_fields = wp_nonce_field(
2417
-                    $ajax_sorting_callback . '_nonce',
2418
-                    $ajax_sorting_callback . '_nonce',
2419
-                    false,
2420
-                    false
2421
-            );
2422
-            //			$reorder_action = 'espresso_' . $ajax_sorting_callback . '_nonce';
2423
-            //			$sortable_list_table_form_fields = wp_nonce_field( $reorder_action, 'ajax_table_sort_nonce', FALSE, FALSE );
2424
-            $sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_page" name="ajax_table_sort_page" value="' . $this->page_slug . '" />';
2425
-            $sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_action" name="ajax_table_sort_action" value="' . $ajax_sorting_callback . '" />';
2426
-        } else {
2427
-            $sortable_list_table_form_fields = '';
2428
-        }
2429
-        $this->_template_args['sortable_list_table_form_fields'] = $sortable_list_table_form_fields;
2430
-        $hidden_form_fields = isset($this->_template_args['list_table_hidden_fields']) ? $this->_template_args['list_table_hidden_fields'] : '';
2431
-        $nonce_ref = $this->_req_action . '_nonce';
2432
-        $hidden_form_fields .= '<input type="hidden" name="' . $nonce_ref . '" value="' . wp_create_nonce($nonce_ref) . '">';
2433
-        $this->_template_args['list_table_hidden_fields'] = $hidden_form_fields;
2434
-        //display message about search results?
2435
-        $this->_template_args['before_list_table'] .= ! empty($this->_req_data['s'])
2436
-                ? '<p class="ee-search-results">' . sprintf(
2437
-                        __('Displaying search results for the search string: <strong><em>%s</em></strong>',
2438
-                                'event_espresso'),
2439
-                        trim($this->_req_data['s'], '%')
2440
-                ) . '</p>'
2441
-                : '';
2442
-        // filter before_list_table template arg
2443
-        $this->_template_args['before_list_table'] = implode(
2444
-                " \n",
2445
-                (array)apply_filters(
2446
-                        'FHEE__EE_Admin_Page___display_admin_list_table_page__before_list_table__template_arg',
2447
-                        (array)$this->_template_args['before_list_table'],
2448
-                        $this->page_slug,
2449
-                        $this->_req_data,
2450
-                        $this->_req_action
2451
-                )
2452
-        );
2453
-        // filter after_list_table template arg
2454
-        $this->_template_args['after_list_table'] = implode(
2455
-                " \n",
2456
-                (array)apply_filters(
2457
-                        'FHEE__EE_Admin_Page___display_admin_list_table_page__after_list_table__template_arg',
2458
-                        (array)$this->_template_args['after_list_table'],
2459
-                        $this->page_slug,
2460
-                        $this->_req_data,
2461
-                        $this->_req_action
2462
-                )
2463
-        );
2464
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
2465
-                $template_path,
2466
-                $this->_template_args,
2467
-                true
2468
-        );
2469
-        // the final template wrapper
2470
-        if ($sidebar) {
2471
-            $this->display_admin_page_with_sidebar();
2472
-        } else {
2473
-            $this->display_admin_page_with_no_sidebar();
2474
-        }
2475
-    }
2476
-
2477
-
2478
-
2479
-    /**
2480
-     * This just prepares a legend using the given items and the admin_details_legend.template.php file and returns the html string for the legend.
2481
-     * $items are expected in an array in the following format:
2482
-     * $legend_items = array(
2483
-     *        'item_id' => array(
2484
-     *            'icon' => 'http://url_to_icon_being_described.png',
2485
-     *            'desc' => __('localized description of item');
2486
-     *        )
2487
-     * );
2488
-     *
2489
-     * @param  array $items see above for format of array
2490
-     * @return string        html string of legend
2491
-     */
2492
-    protected function _display_legend($items)
2493
-    {
2494
-        $this->_template_args['items'] = apply_filters('FHEE__EE_Admin_Page___display_legend__items', (array)$items, $this);
2495
-        $legend_template = EE_ADMIN_TEMPLATE . 'admin_details_legend.template.php';
2496
-        return EEH_Template::display_template($legend_template, $this->_template_args, true);
2497
-    }
2498
-
2499
-
2500
-
2501
-    /**
2502
-     * this is used whenever we're DOING_AJAX to return a formatted json array that our calling javascript can expect
2503
-     *
2504
-     * @param bool $sticky_notices Used to indicate whether you want to ensure notices are added to a transient instead of displayed.
2505
-     *                             The returned json object is created from an array in the following format:
2506
-     *                             array(
2507
-     *                             'error' => FALSE, //(default FALSE), contains any errors and/or exceptions (exceptions return json early),
2508
-     *                             'success' => FALSE, //(default FALSE) - contains any special success message.
2509
-     *                             'notices' => '', // - contains any EE_Error formatted notices
2510
-     *                             'content' => 'string can be html', //this is a string of formatted content (can be html)
2511
-     *                             'data' => array() //this can be any key/value pairs that a method returns for later json parsing by the js. We're also going to include the template args with every package (so js can pick out any
2512
-     *                             specific template args that might be included in here)
2513
-     *                             )
2514
-     *                             The json object is populated by whatever is set in the $_template_args property.
2515
-     * @return void
2516
-     */
2517
-    protected function _return_json($sticky_notices = false)
2518
-    {
2519
-        //make sure any EE_Error notices have been handled.
2520
-        $this->_process_notices(array(), true, $sticky_notices);
2521
-        $data = isset($this->_template_args['data']) ? $this->_template_args['data'] : array();
2522
-        unset($this->_template_args['data']);
2523
-        $json = array(
2524
-                'error'     => isset($this->_template_args['error']) ? $this->_template_args['error'] : false,
2525
-                'success'   => isset($this->_template_args['success']) ? $this->_template_args['success'] : false,
2526
-                'errors'    => isset($this->_template_args['errors']) ? $this->_template_args['errors'] : false,
2527
-                'attention' => isset($this->_template_args['attention']) ? $this->_template_args['attention'] : false,
2528
-                'notices'   => EE_Error::get_notices(),
2529
-                'content'   => isset($this->_template_args['admin_page_content']) ? $this->_template_args['admin_page_content'] : '',
2530
-                'data'      => array_merge($data, array('template_args' => $this->_template_args)),
2531
-                'isEEajax'  => true //special flag so any ajax.Success methods in js can identify this return package as a EEajax package.
2532
-        );
2533
-        // make sure there are no php errors or headers_sent.  Then we can set correct json header.
2534
-        if (null === error_get_last() || ! headers_sent()) {
2535
-            header('Content-Type: application/json; charset=UTF-8');
2536
-        }
2537
-        echo wp_json_encode($json);
2538
-
2539
-        exit();
2540
-    }
2541
-
2542
-
2543
-
2544
-    /**
2545
-     * Simply a wrapper for the protected method so we can call this outside the class (ONLY when doing ajax)
2546
-     *
2547
-     * @return void
2548
-     * @throws EE_Error
2549
-     */
2550
-    public function return_json()
2551
-    {
2552
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2553
-            $this->_return_json();
2554
-        } else {
2555
-            throw new EE_Error(sprintf(__('The public %s method can only be called when DOING_AJAX = TRUE', 'event_espresso'), __FUNCTION__));
2556
-        }
2557
-    }
2558
-
2559
-
2560
-
2561
-    /**
2562
-     * This provides a way for child hook classes to send along themselves by reference so methods/properties within them can be accessed by EE_Admin_child pages. This is assigned to the $_hook_obj property.
2563
-     *
2564
-     * @param EE_Admin_Hooks $hook_obj This will be the object for the EE_Admin_Hooks child
2565
-     * @access   public
2566
-     */
2567
-    public function set_hook_object(EE_Admin_Hooks $hook_obj)
2568
-    {
2569
-        $this->_hook_obj = $hook_obj;
2570
-    }
2571
-
2572
-
2573
-
2574
-    /**
2575
-     *        generates  HTML wrapper with Tabbed nav for an admin page
2576
-     *
2577
-     * @access public
2578
-     * @param  boolean $about whether to use the special about page wrapper or default.
2579
-     * @return void
2580
-     */
2581
-    public function admin_page_wrapper($about = false)
2582
-    {
2583
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2584
-        $this->_nav_tabs = $this->_get_main_nav_tabs();
2585
-        $this->_template_args['nav_tabs'] = $this->_nav_tabs;
2586
-        $this->_template_args['admin_page_title'] = $this->_admin_page_title;
2587
-        $this->_template_args['before_admin_page_content'] = apply_filters('FHEE_before_admin_page_content' . $this->_current_page . $this->_current_view,
2588
-                isset($this->_template_args['before_admin_page_content']) ? $this->_template_args['before_admin_page_content'] : '');
2589
-        $this->_template_args['after_admin_page_content'] = apply_filters('FHEE_after_admin_page_content' . $this->_current_page . $this->_current_view,
2590
-                isset($this->_template_args['after_admin_page_content']) ? $this->_template_args['after_admin_page_content'] : '');
2591
-        $this->_template_args['after_admin_page_content'] .= $this->_set_help_popup_content();
2592
-        // load settings page wrapper template
2593
-        $template_path = ! defined('DOING_AJAX') ? EE_ADMIN_TEMPLATE . 'admin_wrapper.template.php' : EE_ADMIN_TEMPLATE . 'admin_wrapper_ajax.template.php';
2594
-        //about page?
2595
-        $template_path = $about ? EE_ADMIN_TEMPLATE . 'about_admin_wrapper.template.php' : $template_path;
2596
-        if (defined('DOING_AJAX')) {
2597
-            $this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path, $this->_template_args, true);
2598
-            $this->_return_json();
2599
-        } else {
2600
-            EEH_Template::display_template($template_path, $this->_template_args);
2601
-        }
2602
-    }
2603
-
2604
-
2605
-
2606
-    /**
2607
-     * This returns the admin_nav tabs html using the configuration in the _nav_tabs property
2608
-     *
2609
-     * @return string html
2610
-     */
2611
-    protected function _get_main_nav_tabs()
2612
-    {
2613
-        //let's generate the html using the EEH_Tabbed_Content helper.  We do this here so that it's possible for child classes to add in nav tabs dynamically at the last minute (rather than setting in the page_routes array)
2614
-        return EEH_Tabbed_Content::display_admin_nav_tabs($this->_nav_tabs);
2615
-    }
2616
-
2617
-
2618
-
2619
-    /**
2620
-     *        sort nav tabs
2621
-     *
2622
-     * @access public
2623
-     * @param $a
2624
-     * @param $b
2625
-     * @return int
2626
-     */
2627
-    private function _sort_nav_tabs($a, $b)
2628
-    {
2629
-        if ($a['order'] == $b['order']) {
2630
-            return 0;
2631
-        }
2632
-        return ($a['order'] < $b['order']) ? -1 : 1;
2633
-    }
2634
-
2635
-
2636
-
2637
-    /**
2638
-     *    generates HTML for the forms used on admin pages
2639
-     *
2640
-     * @access protected
2641
-     * @param    array $input_vars - array of input field details
2642
-     * @param string   $generator  (options are 'string' or 'array', basically use this to indicate which generator to use)
2643
-     * @return string
2644
-     * @uses   EEH_Form_Fields::get_form_fields (/helper/EEH_Form_Fields.helper.php)
2645
-     * @uses   EEH_Form_Fields::get_form_fields_array (/helper/EEH_Form_Fields.helper.php)
2646
-     */
2647
-    protected function _generate_admin_form_fields($input_vars = array(), $generator = 'string', $id = false)
2648
-    {
2649
-        $content = $generator == 'string' ? EEH_Form_Fields::get_form_fields($input_vars, $id) : EEH_Form_Fields::get_form_fields_array($input_vars);
2650
-        return $content;
2651
-    }
2652
-
2653
-
2654
-
2655
-    /**
2656
-     * generates the "Save" and "Save & Close" buttons for edit forms
2657
-     *
2658
-     * @access protected
2659
-     * @param bool             $both     if true then both buttons will be generated.  If false then just the "Save & Close" button.
2660
-     * @param array            $text     if included, generator will use the given text for the buttons ( array([0] => 'Save', [1] => 'save & close')
2661
-     * @param array            $actions  if included allows us to set the actions that each button will carry out (i.e. via the "name" value in the button).  We can also use this to just dump default actions by submitting some other value.
2662
-     * @param bool|string|null $referrer if false then we just do the default action on save and close.  Other wise it will use the $referrer string. IF null, then we don't do ANYTHING on save and close (normal form handling).
2663
-     */
2664
-    protected function _set_save_buttons($both = true, $text = array(), $actions = array(), $referrer = null)
2665
-    {
2666
-        //make sure $text and $actions are in an array
2667
-        $text = (array)$text;
2668
-        $actions = (array)$actions;
2669
-        $referrer_url = empty($referrer) ? '' : $referrer;
2670
-        $referrer_url = ! $referrer ? '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="' . $_SERVER['REQUEST_URI'] . '" />'
2671
-                : '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="' . $referrer . '" />';
2672
-        $button_text = ! empty($text) ? $text : array(__('Save', 'event_espresso'), __('Save and Close', 'event_espresso'));
2673
-        $default_names = array('save', 'save_and_close');
2674
-        //add in a hidden index for the current page (so save and close redirects properly)
2675
-        $this->_template_args['save_buttons'] = $referrer_url;
2676
-        foreach ($button_text as $key => $button) {
2677
-            $ref = $default_names[$key];
2678
-            $id = $this->_current_view . '_' . $ref;
2679
-            $name = ! empty($actions) ? $actions[$key] : $ref;
2680
-            $this->_template_args['save_buttons'] .= '<input type="submit" class="button-primary ' . $ref . '" value="' . $button . '" name="' . $name . '" id="' . $id . '" />';
2681
-            if ( ! $both) {
2682
-                break;
2683
-            }
2684
-        }
2685
-    }
2686
-
2687
-
2688
-
2689
-    /**
2690
-     * Wrapper for the protected function.  Allows plugins/addons to call this to set the form tags.
2691
-     *
2692
-     * @see   $this->_set_add_edit_form_tags() for details on params
2693
-     * @since 4.6.0
2694
-     * @param string $route
2695
-     * @param array  $additional_hidden_fields
2696
-     */
2697
-    public function set_add_edit_form_tags($route = '', $additional_hidden_fields = array())
2698
-    {
2699
-        $this->_set_add_edit_form_tags($route, $additional_hidden_fields);
2700
-    }
2701
-
2702
-
2703
-
2704
-    /**
2705
-     * set form open and close tags on add/edit pages.
2706
-     *
2707
-     * @access protected
2708
-     * @param string $route                    the route you want the form to direct to
2709
-     * @param array  $additional_hidden_fields any additional hidden fields required in the form header
2710
-     * @return void
2711
-     */
2712
-    protected function _set_add_edit_form_tags($route = '', $additional_hidden_fields = array())
2713
-    {
2714
-        if (empty($route)) {
2715
-            $user_msg = __('An error occurred. No action was set for this page\'s form.', 'event_espresso');
2716
-            $dev_msg = $user_msg . "\n" . sprintf(__('The $route argument is required for the %s->%s method.', 'event_espresso'), __FUNCTION__, __CLASS__);
2717
-            EE_Error::add_error($user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
2718
-        }
2719
-        // open form
2720
-        $this->_template_args['before_admin_page_content'] = '<form name="form" method="post" action="' . $this->_admin_base_url . '" id="' . $route . '_event_form" >';
2721
-        // add nonce
2722
-        $nonce = wp_nonce_field($route . '_nonce', $route . '_nonce', false, false);
2723
-        //		$nonce = wp_nonce_field( $route . '_nonce', '_wpnonce', FALSE, FALSE );
2724
-        $this->_template_args['before_admin_page_content'] .= "\n\t" . $nonce;
2725
-        // add REQUIRED form action
2726
-        $hidden_fields = array(
2727
-                'action' => array('type' => 'hidden', 'value' => $route),
2728
-        );
2729
-        // merge arrays
2730
-        $hidden_fields = is_array($additional_hidden_fields) ? array_merge($hidden_fields, $additional_hidden_fields) : $hidden_fields;
2731
-        // generate form fields
2732
-        $form_fields = $this->_generate_admin_form_fields($hidden_fields, 'array');
2733
-        // add fields to form
2734
-        foreach ((array)$form_fields as $field_name => $form_field) {
2735
-            $this->_template_args['before_admin_page_content'] .= "\n\t" . $form_field['field'];
2736
-        }
2737
-        // close form
2738
-        $this->_template_args['after_admin_page_content'] = '</form>';
2739
-    }
2740
-
2741
-
2742
-
2743
-    /**
2744
-     * Public Wrapper for _redirect_after_action() method since its
2745
-     * discovered it would be useful for external code to have access.
2746
-     *
2747
-     * @see   EE_Admin_Page::_redirect_after_action() for params.
2748
-     * @since 4.5.0
2749
-     */
2750
-    public function redirect_after_action($success = false, $what = 'item', $action_desc = 'processed', $query_args = array(), $override_overwrite = false)
2751
-    {
2752
-        $this->_redirect_after_action($success, $what, $action_desc, $query_args, $override_overwrite);
2753
-    }
2754
-
2755
-
2756
-
2757
-    /**
2758
-     *    _redirect_after_action
2759
-     *
2760
-     * @param int    $success            - whether success was for two or more records, or just one, or none
2761
-     * @param string $what               - what the action was performed on
2762
-     * @param string $action_desc        - what was done ie: updated, deleted, etc
2763
-     * @param array  $query_args         - an array of query_args to be added to the URL to redirect to after the admin action is completed
2764
-     * @param BOOL   $override_overwrite by default all EE_Error::success messages are overwritten, this allows you to override this so that they show.
2765
-     * @access protected
2766
-     * @return void
2767
-     */
2768
-    protected function _redirect_after_action($success = 0, $what = 'item', $action_desc = 'processed', $query_args = array(), $override_overwrite = false)
2769
-    {
2770
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2771
-        //class name for actions/filters.
2772
-        $classname = get_class($this);
2773
-        //set redirect url. Note if there is a "page" index in the $query_args then we go with vanilla admin.php route, otherwise we go with whatever is set as the _admin_base_url
2774
-        $redirect_url = isset($query_args['page']) ? admin_url('admin.php') : $this->_admin_base_url;
2775
-        $notices = EE_Error::get_notices(false);
2776
-        // overwrite default success messages //BUT ONLY if overwrite not overridden
2777
-        if ( ! $override_overwrite || ! empty($notices['errors'])) {
2778
-            EE_Error::overwrite_success();
2779
-        }
2780
-        if ( ! empty($what) && ! empty($action_desc)) {
2781
-            // how many records affected ? more than one record ? or just one ?
2782
-            if ($success > 1 && empty($notices['errors'])) {
2783
-                // set plural msg
2784
-                EE_Error::add_success(
2785
-                        sprintf(
2786
-                                __('The "%s" have been successfully %s.', 'event_espresso'),
2787
-                                $what,
2788
-                                $action_desc
2789
-                        ),
2790
-                        __FILE__, __FUNCTION__, __LINE__
2791
-                );
2792
-            } else if ($success == 1 && empty($notices['errors'])) {
2793
-                // set singular msg
2794
-                EE_Error::add_success(
2795
-                        sprintf(
2796
-                                __('The "%s" has been successfully %s.', 'event_espresso'),
2797
-                                $what,
2798
-                                $action_desc
2799
-                        ),
2800
-                        __FILE__, __FUNCTION__, __LINE__
2801
-                );
2802
-            }
2803
-        }
2804
-        // check that $query_args isn't something crazy
2805
-        if ( ! is_array($query_args)) {
2806
-            $query_args = array();
2807
-        }
2808
-        /**
2809
-         * Allow injecting actions before the query_args are modified for possible different
2810
-         * redirections on save and close actions
2811
-         *
2812
-         * @since 4.2.0
2813
-         * @param array $query_args       The original query_args array coming into the
2814
-         *                                method.
2815
-         */
2816
-        do_action('AHEE__' . $classname . '___redirect_after_action__before_redirect_modification_' . $this->_req_action, $query_args);
2817
-        //calculate where we're going (if we have a "save and close" button pushed)
2818
-        if (isset($this->_req_data['save_and_close']) && isset($this->_req_data['save_and_close_referrer'])) {
2819
-            // even though we have the save_and_close referrer, we need to parse the url for the action in order to generate a nonce
2820
-            $parsed_url = parse_url($this->_req_data['save_and_close_referrer']);
2821
-            // regenerate query args array from referrer URL
2822
-            parse_str($parsed_url['query'], $query_args);
2823
-            // correct page and action will be in the query args now
2824
-            $redirect_url = admin_url('admin.php');
2825
-        }
2826
-        //merge any default query_args set in _default_route_query_args property
2827
-        if ( ! empty($this->_default_route_query_args) && ! $this->_is_UI_request) {
2828
-            $args_to_merge = array();
2829
-            foreach ($this->_default_route_query_args as $query_param => $query_value) {
2830
-                //is there a wp_referer array in our _default_route_query_args property?
2831
-                if ($query_param == 'wp_referer') {
2832
-                    $query_value = (array)$query_value;
2833
-                    foreach ($query_value as $reference => $value) {
2834
-                        if (strpos($reference, 'nonce') !== false) {
2835
-                            continue;
2836
-                        }
2837
-                        //finally we will override any arguments in the referer with
2838
-                        //what might be set on the _default_route_query_args array.
2839
-                        if (isset($this->_default_route_query_args[$reference])) {
2840
-                            $args_to_merge[$reference] = urlencode($this->_default_route_query_args[$reference]);
2841
-                        } else {
2842
-                            $args_to_merge[$reference] = urlencode($value);
2843
-                        }
2844
-                    }
2845
-                    continue;
2846
-                }
2847
-                $args_to_merge[$query_param] = $query_value;
2848
-            }
2849
-            //now let's merge these arguments but override with what was specifically sent in to the
2850
-            //redirect.
2851
-            $query_args = array_merge($args_to_merge, $query_args);
2852
-        }
2853
-        $this->_process_notices($query_args);
2854
-        // generate redirect url
2855
-        // if redirecting to anything other than the main page, add a nonce
2856
-        if (isset($query_args['action'])) {
2857
-            // manually generate wp_nonce and merge that with the query vars becuz the wp_nonce_url function wrecks havoc on some vars
2858
-            $query_args['_wpnonce'] = wp_create_nonce($query_args['action'] . '_nonce');
2859
-        }
2860
-        //we're adding some hooks and filters in here for processing any things just before redirects (example: an admin page has done an insert or update and we want to run something after that).
2861
-        do_action('AHEE_redirect_' . $classname . $this->_req_action, $query_args);
2862
-        $redirect_url = apply_filters('FHEE_redirect_' . $classname . $this->_req_action, self::add_query_args_and_nonce($query_args, $redirect_url), $query_args);
2863
-        // check if we're doing ajax.  If we are then lets just return the results and js can handle how it wants.
2864
-        if (defined('DOING_AJAX')) {
2865
-            $default_data = array(
2866
-                    'close'        => true,
2867
-                    'redirect_url' => $redirect_url,
2868
-                    'where'        => 'main',
2869
-                    'what'         => 'append',
2870
-            );
2871
-            $this->_template_args['success'] = $success;
2872
-            $this->_template_args['data'] = ! empty($this->_template_args['data']) ? array_merge($default_data, $this->_template_args['data']) : $default_data;
2873
-            $this->_return_json();
2874
-        }
2875
-        wp_safe_redirect($redirect_url);
2876
-        exit();
2877
-    }
2878
-
2879
-
2880
-
2881
-    /**
2882
-     * process any notices before redirecting (or returning ajax request)
2883
-     * This method sets the $this->_template_args['notices'] attribute;
2884
-     *
2885
-     * @param  array $query_args        any query args that need to be used for notice transient ('action')
2886
-     * @param bool   $skip_route_verify This is typically used when we are processing notices REALLY early and page_routes haven't been defined yet.
2887
-     * @param bool   $sticky_notices    This is used to flag that regardless of whether this is doing_ajax or not, we still save a transient for the notice.
2888
-     * @return void
2889
-     */
2890
-    protected function _process_notices($query_args = array(), $skip_route_verify = false, $sticky_notices = true)
2891
-    {
2892
-        //first let's set individual error properties if doing_ajax and the properties aren't already set.
2893
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2894
-            $notices = EE_Error::get_notices(false);
2895
-            if (empty($this->_template_args['success'])) {
2896
-                $this->_template_args['success'] = isset($notices['success']) ? $notices['success'] : false;
2897
-            }
2898
-            if (empty($this->_template_args['errors'])) {
2899
-                $this->_template_args['errors'] = isset($notices['errors']) ? $notices['errors'] : false;
2900
-            }
2901
-            if (empty($this->_template_args['attention'])) {
2902
-                $this->_template_args['attention'] = isset($notices['attention']) ? $notices['attention'] : false;
2903
-            }
2904
-        }
2905
-        $this->_template_args['notices'] = EE_Error::get_notices();
2906
-        //IF this isn't ajax we need to create a transient for the notices using the route (however, overridden if $sticky_notices == true)
2907
-        if ( ! defined('DOING_AJAX') || $sticky_notices) {
2908
-            $route = isset($query_args['action']) ? $query_args['action'] : 'default';
2909
-            $this->_add_transient($route, $this->_template_args['notices'], true, $skip_route_verify);
2910
-        }
2911
-    }
2912
-
2913
-
2914
-
2915
-    /**
2916
-     * get_action_link_or_button
2917
-     * returns the button html for adding, editing, or deleting an item (depending on given type)
2918
-     *
2919
-     * @param string $action        use this to indicate which action the url is generated with.
2920
-     * @param string $type          accepted strings must be defined in the $_labels['button'] array(as the key) property.
2921
-     * @param array  $extra_request if the button requires extra params you can include them in $key=>$value pairs.
2922
-     * @param string $class         Use this to give the class for the button. Defaults to 'button-primary'
2923
-     * @param string $base_url      If this is not provided
2924
-     *                              the _admin_base_url will be used as the default for the button base_url.
2925
-     *                              Otherwise this value will be used.
2926
-     * @param bool   $exclude_nonce If true then no nonce will be in the generated button link.
2927
-     * @return string
2928
-     * @throws \EE_Error
2929
-     */
2930
-    public function get_action_link_or_button(
2931
-            $action,
2932
-            $type = 'add',
2933
-            $extra_request = array(),
2934
-            $class = 'button-primary',
2935
-            $base_url = '',
2936
-            $exclude_nonce = false
2937
-    ) {
2938
-        //first let's validate the action (if $base_url is FALSE otherwise validation will happen further along)
2939
-        if (empty($base_url) && ! isset($this->_page_routes[$action])) {
2940
-            throw new EE_Error(
2941
-                    sprintf(
2942
-                            __(
2943
-                                    'There is no page route for given action for the button.  This action was given: %s',
2944
-                                    'event_espresso'
2945
-                            ),
2946
-                            $action
2947
-                    )
2948
-            );
2949
-        }
2950
-        if ( ! isset($this->_labels['buttons'][$type])) {
2951
-            throw new EE_Error(
2952
-                    sprintf(
2953
-                            __(
2954
-                                    'There is no label for the given button type (%s). Labels are set in the <code>_page_config</code> property.',
2955
-                                    'event_espresso'
2956
-                            ),
2957
-                            $type
2958
-                    )
2959
-            );
2960
-        }
2961
-        //finally check user access for this button.
2962
-        $has_access = $this->check_user_access($action, true);
2963
-        if ( ! $has_access) {
2964
-            return '';
2965
-        }
2966
-        $_base_url = ! $base_url ? $this->_admin_base_url : $base_url;
2967
-        $query_args = array(
2968
-                'action' => $action,
2969
-        );
2970
-        //merge extra_request args but make sure our original action takes precedence and doesn't get overwritten.
2971
-        if ( ! empty($extra_request)) {
2972
-            $query_args = array_merge($extra_request, $query_args);
2973
-        }
2974
-        $url = self::add_query_args_and_nonce($query_args, $_base_url, false, $exclude_nonce);
2975
-        return EEH_Template::get_button_or_link($url, $this->_labels['buttons'][$type], $class);
2976
-    }
2977
-
2978
-
2979
-
2980
-    /**
2981
-     * _per_page_screen_option
2982
-     * Utility function for adding in a per_page_option in the screen_options_dropdown.
2983
-     *
2984
-     * @return void
2985
-     */
2986
-    protected function _per_page_screen_option()
2987
-    {
2988
-        $option = 'per_page';
2989
-        $args = array(
2990
-                'label'   => $this->_admin_page_title,
2991
-                'default' => 10,
2992
-                'option'  => $this->_current_page . '_' . $this->_current_view . '_per_page',
2993
-        );
2994
-        //ONLY add the screen option if the user has access to it.
2995
-        if ($this->check_user_access($this->_current_view, true)) {
2996
-            add_screen_option($option, $args);
2997
-        }
2998
-    }
2999
-
3000
-
3001
-
3002
-    /**
3003
-     * set_per_page_screen_option
3004
-     * All this does is make sure that WordPress saves any per_page screen options (if set) for the current page.
3005
-     * we have to do this rather than running inside the 'set-screen-options' hook because it runs earlier than admin_menu.
3006
-     *
3007
-     * @access private
3008
-     * @return void
3009
-     */
3010
-    private function _set_per_page_screen_options()
3011
-    {
3012
-        if (isset($_POST['wp_screen_options']) && is_array($_POST['wp_screen_options'])) {
3013
-            check_admin_referer('screen-options-nonce', 'screenoptionnonce');
3014
-            if ( ! $user = wp_get_current_user()) {
3015
-                return;
3016
-            }
3017
-            $option = $_POST['wp_screen_options']['option'];
3018
-            $value = $_POST['wp_screen_options']['value'];
3019
-            if ($option != sanitize_key($option)) {
3020
-                return;
3021
-            }
3022
-            $map_option = $option;
3023
-            $option = str_replace('-', '_', $option);
3024
-            switch ($map_option) {
3025
-                case $this->_current_page . '_' . $this->_current_view . '_per_page':
3026
-                    $value = (int)$value;
3027
-                    if ($value < 1 || $value > 999) {
3028
-                        return;
3029
-                    }
3030
-                    break;
3031
-                default:
3032
-                    $value = apply_filters('FHEE__EE_Admin_Page___set_per_page_screen_options__value', false, $option, $value);
3033
-                    if (false === $value) {
3034
-                        return;
3035
-                    }
3036
-                    break;
3037
-            }
3038
-            update_user_meta($user->ID, $option, $value);
3039
-            wp_safe_redirect(remove_query_arg(array('pagenum', 'apage', 'paged'), wp_get_referer()));
3040
-            exit;
3041
-        }
3042
-    }
3043
-
3044
-
3045
-
3046
-    /**
3047
-     * This just allows for setting the $_template_args property if it needs to be set outside the object
3048
-     *
3049
-     * @param array $data array that will be assigned to template args.
3050
-     */
3051
-    public function set_template_args($data)
3052
-    {
3053
-        $this->_template_args = array_merge($this->_template_args, (array)$data);
3054
-    }
3055
-
3056
-
3057
-
3058
-    /**
3059
-     * This makes available the WP transient system for temporarily moving data between routes
3060
-     *
3061
-     * @access protected
3062
-     * @param string $route             the route that should receive the transient
3063
-     * @param array  $data              the data that gets sent
3064
-     * @param bool   $notices           If this is for notices then we use this to indicate so, otherwise its just a normal route transient.
3065
-     * @param bool   $skip_route_verify Used to indicate we want to skip route verification.  This is usually ONLY used when we are adding a transient before page_routes have been defined.
3066
-     * @return void
3067
-     */
3068
-    protected function _add_transient($route, $data, $notices = false, $skip_route_verify = false)
3069
-    {
3070
-        $user_id = get_current_user_id();
3071
-        if ( ! $skip_route_verify) {
3072
-            $this->_verify_route($route);
3073
-        }
3074
-        //now let's set the string for what kind of transient we're setting
3075
-        $transient = $notices ? 'ee_rte_n_tx_' . $route . '_' . $user_id : 'rte_tx_' . $route . '_' . $user_id;
3076
-        $data = $notices ? array('notices' => $data) : $data;
3077
-        //is there already a transient for this route?  If there is then let's ADD to that transient
3078
-        $existing = is_multisite() && is_network_admin() ? get_site_transient($transient) : get_transient($transient);
3079
-        if ($existing) {
3080
-            $data = array_merge((array)$data, (array)$existing);
3081
-        }
3082
-        if (is_multisite() && is_network_admin()) {
3083
-            set_site_transient($transient, $data, 8);
3084
-        } else {
3085
-            set_transient($transient, $data, 8);
3086
-        }
3087
-    }
3088
-
3089
-
3090
-
3091
-    /**
3092
-     * this retrieves the temporary transient that has been set for moving data between routes.
3093
-     *
3094
-     * @param bool $notices true we get notices transient. False we just return normal route transient
3095
-     * @return mixed data
3096
-     */
3097
-    protected function _get_transient($notices = false, $route = false)
3098
-    {
3099
-        $user_id = get_current_user_id();
3100
-        $route = ! $route ? $this->_req_action : $route;
3101
-        $transient = $notices ? 'ee_rte_n_tx_' . $route . '_' . $user_id : 'rte_tx_' . $route . '_' . $user_id;
3102
-        $data = is_multisite() && is_network_admin() ? get_site_transient($transient) : get_transient($transient);
3103
-        //delete transient after retrieval (just in case it hasn't expired);
3104
-        if (is_multisite() && is_network_admin()) {
3105
-            delete_site_transient($transient);
3106
-        } else {
3107
-            delete_transient($transient);
3108
-        }
3109
-        return $notices && isset($data['notices']) ? $data['notices'] : $data;
3110
-    }
3111
-
3112
-
3113
-
3114
-    /**
3115
-     * The purpose of this method is just to run garbage collection on any EE transients that might have expired but would not be called later.
3116
-     * This will be assigned to run on a specific EE Admin page. (place the method in the default route callback on the EE_Admin page you want it run.)
3117
-     *
3118
-     * @return void
3119
-     */
3120
-    protected function _transient_garbage_collection()
3121
-    {
3122
-        global $wpdb;
3123
-        //retrieve all existing transients
3124
-        $query = "SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%rte_tx_%' OR option_name LIKE '%rte_n_tx_%'";
3125
-        if ($results = $wpdb->get_results($query)) {
3126
-            foreach ($results as $result) {
3127
-                $transient = str_replace('_transient_', '', $result->option_name);
3128
-                get_transient($transient);
3129
-                if (is_multisite() && is_network_admin()) {
3130
-                    get_site_transient($transient);
3131
-                }
3132
-            }
3133
-        }
3134
-    }
3135
-
3136
-
3137
-
3138
-    /**
3139
-     * get_view
3140
-     *
3141
-     * @access public
3142
-     * @return string content of _view property
3143
-     */
3144
-    public function get_view()
3145
-    {
3146
-        return $this->_view;
3147
-    }
3148
-
3149
-
3150
-
3151
-    /**
3152
-     * getter for the protected $_views property
3153
-     *
3154
-     * @return array
3155
-     */
3156
-    public function get_views()
3157
-    {
3158
-        return $this->_views;
3159
-    }
3160
-
3161
-
3162
-
3163
-    /**
3164
-     * get_current_page
3165
-     *
3166
-     * @access public
3167
-     * @return string _current_page property value
3168
-     */
3169
-    public function get_current_page()
3170
-    {
3171
-        return $this->_current_page;
3172
-    }
3173
-
3174
-
3175
-
3176
-    /**
3177
-     * get_current_view
3178
-     *
3179
-     * @access public
3180
-     * @return string _current_view property value
3181
-     */
3182
-    public function get_current_view()
3183
-    {
3184
-        return $this->_current_view;
3185
-    }
3186
-
3187
-
3188
-
3189
-    /**
3190
-     * get_current_screen
3191
-     *
3192
-     * @access public
3193
-     * @return object The current WP_Screen object
3194
-     */
3195
-    public function get_current_screen()
3196
-    {
3197
-        return $this->_current_screen;
3198
-    }
3199
-
3200
-
3201
-
3202
-    /**
3203
-     * get_current_page_view_url
3204
-     *
3205
-     * @access public
3206
-     * @return string This returns the url for the current_page_view.
3207
-     */
3208
-    public function get_current_page_view_url()
3209
-    {
3210
-        return $this->_current_page_view_url;
3211
-    }
3212
-
3213
-
3214
-
3215
-    /**
3216
-     * just returns the _req_data property
3217
-     *
3218
-     * @return array
3219
-     */
3220
-    public function get_request_data()
3221
-    {
3222
-        return $this->_req_data;
3223
-    }
3224
-
3225
-
3226
-
3227
-    /**
3228
-     * returns the _req_data protected property
3229
-     *
3230
-     * @return string
3231
-     */
3232
-    public function get_req_action()
3233
-    {
3234
-        return $this->_req_action;
3235
-    }
3236
-
3237
-
3238
-
3239
-    /**
3240
-     * @return bool  value of $_is_caf property
3241
-     */
3242
-    public function is_caf()
3243
-    {
3244
-        return $this->_is_caf;
3245
-    }
3246
-
3247
-
3248
-
3249
-    /**
3250
-     * @return mixed
3251
-     */
3252
-    public function default_espresso_metaboxes()
3253
-    {
3254
-        return $this->_default_espresso_metaboxes;
3255
-    }
3256
-
3257
-
3258
-
3259
-    /**
3260
-     * @return mixed
3261
-     */
3262
-    public function admin_base_url()
3263
-    {
3264
-        return $this->_admin_base_url;
3265
-    }
3266
-
3267
-
3268
-
3269
-    /**
3270
-     * @return mixed
3271
-     */
3272
-    public function wp_page_slug()
3273
-    {
3274
-        return $this->_wp_page_slug;
3275
-    }
3276
-
3277
-
3278
-
3279
-    /**
3280
-     * updates  espresso configuration settings
3281
-     *
3282
-     * @access    protected
3283
-     * @param string                   $tab
3284
-     * @param EE_Config_Base|EE_Config $config
3285
-     * @param string                   $file file where error occurred
3286
-     * @param string                   $func function  where error occurred
3287
-     * @param string                   $line line no where error occurred
3288
-     * @return boolean
3289
-     */
3290
-    protected function _update_espresso_configuration($tab, $config, $file = '', $func = '', $line = '')
3291
-    {
3292
-        //remove any options that are NOT going to be saved with the config settings.
3293
-        if (isset($config->core->ee_ueip_optin)) {
3294
-            $config->core->ee_ueip_has_notified = true;
3295
-            // TODO: remove the following two lines and make sure values are migrated from 3.1
3296
-            update_option('ee_ueip_optin', $config->core->ee_ueip_optin);
3297
-            update_option('ee_ueip_has_notified', true);
3298
-        }
3299
-        // and save it (note we're also doing the network save here)
3300
-        $net_saved = is_main_site() ? EE_Network_Config::instance()->update_config(false, false) : true;
3301
-        $config_saved = EE_Config::instance()->update_espresso_config(false, false);
3302
-        if ($config_saved && $net_saved) {
3303
-            EE_Error::add_success(sprintf(__('"%s" have been successfully updated.', 'event_espresso'), $tab));
3304
-            return true;
3305
-        } else {
3306
-            EE_Error::add_error(sprintf(__('The "%s" were not updated.', 'event_espresso'), $tab), $file, $func, $line);
3307
-            return false;
3308
-        }
3309
-    }
3310
-
3311
-
3312
-
3313
-    /**
3314
-     * Returns an array to be used for EE_FOrm_Fields.helper.php's select_input as the $values argument.
3315
-     *
3316
-     * @return array
3317
-     */
3318
-    public function get_yes_no_values()
3319
-    {
3320
-        return $this->_yes_no_values;
3321
-    }
3322
-
3323
-
3324
-
3325
-    protected function _get_dir()
3326
-    {
3327
-        $reflector = new ReflectionClass(get_class($this));
3328
-        return dirname($reflector->getFileName());
3329
-    }
3330
-
3331
-
3332
-
3333
-    /**
3334
-     * A helper for getting a "next link".
3335
-     *
3336
-     * @param string $url   The url to link to
3337
-     * @param string $class The class to use.
3338
-     * @return string
3339
-     */
3340
-    protected function _next_link($url, $class = 'dashicons dashicons-arrow-right')
3341
-    {
3342
-        return '<a class="' . $class . '" href="' . $url . '"></a>';
3343
-    }
3344
-
3345
-
3346
-
3347
-    /**
3348
-     * A helper for getting a "previous link".
3349
-     *
3350
-     * @param string $url   The url to link to
3351
-     * @param string $class The class to use.
3352
-     * @return string
3353
-     */
3354
-    protected function _previous_link($url, $class = 'dashicons dashicons-arrow-left')
3355
-    {
3356
-        return '<a class="' . $class . '" href="' . $url . '"></a>';
3357
-    }
3358
-
3359
-
3360
-
3361
-
3362
-
3363
-
3364
-
3365
-    //below are some messages related methods that should be available across the EE_Admin system.  Note, these methods are NOT page specific
3366
-    /**
3367
-     * This processes an request to resend a registration and assumes we have a _REG_ID for doing so. So if the caller knows that the _REG_ID isn't in the req_data array but CAN obtain it, the caller should ADD the _REG_ID to the _req_data
3368
-     * array.
3369
-     *
3370
-     * @return bool success/fail
3371
-     */
3372
-    protected function _process_resend_registration()
3373
-    {
3374
-        $this->_template_args['success'] = EED_Messages::process_resend($this->_req_data);
3375
-        do_action('AHEE__EE_Admin_Page___process_resend_registration', $this->_template_args['success'], $this->_req_data);
3376
-        return $this->_template_args['success'];
3377
-    }
3378
-
3379
-
3380
-
3381
-    /**
3382
-     * This automatically processes any payment message notifications when manual payment has been applied.
3383
-     *
3384
-     * @access protected
3385
-     * @param \EE_Payment $payment
3386
-     * @return bool success/fail
3387
-     */
3388
-    protected function _process_payment_notification(EE_Payment $payment)
3389
-    {
3390
-        add_filter('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', '__return_true');
3391
-        do_action('AHEE__EE_Admin_Page___process_admin_payment_notification', $payment);
3392
-        $this->_template_args['success'] = apply_filters('FHEE__EE_Admin_Page___process_admin_payment_notification__success', false, $payment);
3393
-        return $this->_template_args['success'];
3394
-    }
2199
+	}
2200
+
2201
+
2202
+
2203
+	/**
2204
+	 * facade for add_meta_box
2205
+	 *
2206
+	 * @param string  $action        where the metabox get's displayed
2207
+	 * @param string  $title         Title of Metabox (output in metabox header)
2208
+	 * @param string  $callback      If not empty and $create_fun is set to false then we'll use a custom callback instead of the one created in here.
2209
+	 * @param array   $callback_args an array of args supplied for the metabox
2210
+	 * @param string  $column        what metabox column
2211
+	 * @param string  $priority      give this metabox a priority (using accepted priorities for wp meta boxes)
2212
+	 * @param boolean $create_func   default is true.  Basically we can say we don't WANT to have the runtime function created but just set our own callback for wp's add_meta_box.
2213
+	 */
2214
+	public function _add_admin_page_meta_box($action, $title, $callback, $callback_args, $column = 'normal', $priority = 'high', $create_func = true)
2215
+	{
2216
+		do_action('AHEE_log', __FILE__, __FUNCTION__, $callback);
2217
+		//if we have empty callback args and we want to automatically create the metabox callback then we need to make sure the callback args are generated.
2218
+		if (empty($callback_args) && $create_func) {
2219
+			$callback_args = array(
2220
+					'template_path' => $this->_template_path,
2221
+					'template_args' => $this->_template_args,
2222
+			);
2223
+		}
2224
+		//if $create_func is true (default) then we automatically create the function for displaying the actual meta box.  If false then we take the $callback reference passed through and use it instead (so callers can define their own callback function/method if they wish)
2225
+		$call_back_func = $create_func ? create_function('$post, $metabox',
2226
+				'do_action( "AHEE_log", __FILE__, __FUNCTION__, ""); echo EEH_Template::display_template( $metabox["args"]["template_path"], $metabox["args"]["template_args"], TRUE );') : $callback;
2227
+		add_meta_box(str_replace('_', '-', $action) . '-mbox', $title, $call_back_func, $this->_wp_page_slug, $column, $priority, $callback_args);
2228
+	}
2229
+
2230
+
2231
+
2232
+	/**
2233
+	 * generates HTML wrapper for and admin details page that contains metaboxes in columns
2234
+	 *
2235
+	 * @return [type] [description]
2236
+	 */
2237
+	public function display_admin_page_with_metabox_columns()
2238
+	{
2239
+		$this->_template_args['post_body_content'] = $this->_template_args['admin_page_content'];
2240
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_column_template_path, $this->_template_args, true);
2241
+		//the final wrapper
2242
+		$this->admin_page_wrapper();
2243
+	}
2244
+
2245
+
2246
+
2247
+	/**
2248
+	 *        generates  HTML wrapper for an admin details page
2249
+	 *
2250
+	 * @access public
2251
+	 * @return void
2252
+	 */
2253
+	public function display_admin_page_with_sidebar()
2254
+	{
2255
+		$this->_display_admin_page(true);
2256
+	}
2257
+
2258
+
2259
+
2260
+	/**
2261
+	 *        generates  HTML wrapper for an admin details page (except no sidebar)
2262
+	 *
2263
+	 * @access public
2264
+	 * @return void
2265
+	 */
2266
+	public function display_admin_page_with_no_sidebar()
2267
+	{
2268
+		$this->_display_admin_page();
2269
+	}
2270
+
2271
+
2272
+
2273
+	/**
2274
+	 * generates HTML wrapper for an EE about admin page (no sidebar)
2275
+	 *
2276
+	 * @access public
2277
+	 * @return void
2278
+	 */
2279
+	public function display_about_admin_page()
2280
+	{
2281
+		$this->_display_admin_page(false, true);
2282
+	}
2283
+
2284
+
2285
+
2286
+	/**
2287
+	 * display_admin_page
2288
+	 * contains the code for actually displaying an admin page
2289
+	 *
2290
+	 * @access private
2291
+	 * @param  boolean $sidebar true with sidebar, false without
2292
+	 * @param  boolean $about   use the about admin wrapper instead of the default.
2293
+	 * @return void
2294
+	 */
2295
+	private function _display_admin_page($sidebar = false, $about = false)
2296
+	{
2297
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2298
+		//custom remove metaboxes hook to add or remove any metaboxes to/from Admin pages.
2299
+		do_action('AHEE__EE_Admin_Page___display_admin_page__modify_metaboxes');
2300
+		// set current wp page slug - looks like: event-espresso_page_event_categories
2301
+		// keep in mind "event-espresso" COULD be something else if the top level menu label has been translated.
2302
+		$this->_template_args['current_page'] = $this->_wp_page_slug;
2303
+		$this->_template_args['admin_page_wrapper_div_id'] = $this->_cpt_route
2304
+				? 'poststuff'
2305
+				: 'espresso-default-admin';
2306
+		$template_path = $sidebar
2307
+				? EE_ADMIN_TEMPLATE . 'admin_details_wrapper.template.php'
2308
+				: EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar.template.php';
2309
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2310
+			$template_path = EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar_ajax.template.php';
2311
+		}
2312
+		$template_path = ! empty($this->_column_template_path) ? $this->_column_template_path : $template_path;
2313
+		$this->_template_args['post_body_content'] = isset($this->_template_args['admin_page_content']) ? $this->_template_args['admin_page_content'] : '';
2314
+		$this->_template_args['before_admin_page_content'] = isset($this->_template_args['before_admin_page_content']) ? $this->_template_args['before_admin_page_content'] : '';
2315
+		$this->_template_args['after_admin_page_content'] = isset($this->_template_args['after_admin_page_content']) ? $this->_template_args['after_admin_page_content'] : '';
2316
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path, $this->_template_args, true);
2317
+		// the final template wrapper
2318
+		$this->admin_page_wrapper($about);
2319
+	}
2320
+
2321
+
2322
+
2323
+	/**
2324
+	 * This is used to display caf preview pages.
2325
+	 *
2326
+	 * @since 4.3.2
2327
+	 * @param string $utm_campaign_source what is the key used for google analytics link
2328
+	 * @param bool   $display_sidebar     whether to use the sidebar template or the full template for the page.  TRUE = SHOW sidebar, FALSE = no sidebar. Default no sidebar.
2329
+	 * @return void
2330
+	 * @throws \EE_Error
2331
+	 */
2332
+	public function display_admin_caf_preview_page($utm_campaign_source = '', $display_sidebar = true)
2333
+	{
2334
+		//let's generate a default preview action button if there isn't one already present.
2335
+		$this->_labels['buttons']['buy_now'] = __('Upgrade Now', 'event_espresso');
2336
+		$buy_now_url = add_query_arg(
2337
+				array(
2338
+						'ee_ver'       => 'ee4',
2339
+						'utm_source'   => 'ee4_plugin_admin',
2340
+						'utm_medium'   => 'link',
2341
+						'utm_campaign' => $utm_campaign_source,
2342
+						'utm_content'  => 'buy_now_button',
2343
+				),
2344
+				'http://eventespresso.com/pricing/'
2345
+		);
2346
+		$this->_template_args['preview_action_button'] = ! isset($this->_template_args['preview_action_button'])
2347
+				? $this->get_action_link_or_button(
2348
+						'',
2349
+						'buy_now',
2350
+						array(),
2351
+						'button-primary button-large',
2352
+						$buy_now_url,
2353
+						true
2354
+				)
2355
+				: $this->_template_args['preview_action_button'];
2356
+		$template_path = EE_ADMIN_TEMPLATE . 'admin_caf_full_page_preview.template.php';
2357
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
2358
+				$template_path,
2359
+				$this->_template_args,
2360
+				true
2361
+		);
2362
+		$this->_display_admin_page($display_sidebar);
2363
+	}
2364
+
2365
+
2366
+
2367
+	/**
2368
+	 * display_admin_list_table_page_with_sidebar
2369
+	 * generates HTML wrapper for an admin_page with list_table
2370
+	 *
2371
+	 * @access public
2372
+	 * @return void
2373
+	 */
2374
+	public function display_admin_list_table_page_with_sidebar()
2375
+	{
2376
+		$this->_display_admin_list_table_page(true);
2377
+	}
2378
+
2379
+
2380
+
2381
+	/**
2382
+	 * display_admin_list_table_page_with_no_sidebar
2383
+	 * generates HTML wrapper for an admin_page with list_table (but with no sidebar)
2384
+	 *
2385
+	 * @access public
2386
+	 * @return void
2387
+	 */
2388
+	public function display_admin_list_table_page_with_no_sidebar()
2389
+	{
2390
+		$this->_display_admin_list_table_page();
2391
+	}
2392
+
2393
+
2394
+
2395
+	/**
2396
+	 * generates html wrapper for an admin_list_table page
2397
+	 *
2398
+	 * @access private
2399
+	 * @param boolean $sidebar whether to display with sidebar or not.
2400
+	 * @return void
2401
+	 */
2402
+	private function _display_admin_list_table_page($sidebar = false)
2403
+	{
2404
+		//setup search attributes
2405
+		$this->_set_search_attributes();
2406
+		$this->_template_args['current_page'] = $this->_wp_page_slug;
2407
+		$template_path = EE_ADMIN_TEMPLATE . 'admin_list_wrapper.template.php';
2408
+		$this->_template_args['table_url'] = defined('DOING_AJAX')
2409
+				? add_query_arg(array('noheader' => 'true', 'route' => $this->_req_action), $this->_admin_base_url)
2410
+				: add_query_arg(array('route' => $this->_req_action), $this->_admin_base_url);
2411
+		$this->_template_args['list_table'] = $this->_list_table_object;
2412
+		$this->_template_args['current_route'] = $this->_req_action;
2413
+		$this->_template_args['list_table_class'] = get_class($this->_list_table_object);
2414
+		$ajax_sorting_callback = $this->_list_table_object->get_ajax_sorting_callback();
2415
+		if ( ! empty($ajax_sorting_callback)) {
2416
+			$sortable_list_table_form_fields = wp_nonce_field(
2417
+					$ajax_sorting_callback . '_nonce',
2418
+					$ajax_sorting_callback . '_nonce',
2419
+					false,
2420
+					false
2421
+			);
2422
+			//			$reorder_action = 'espresso_' . $ajax_sorting_callback . '_nonce';
2423
+			//			$sortable_list_table_form_fields = wp_nonce_field( $reorder_action, 'ajax_table_sort_nonce', FALSE, FALSE );
2424
+			$sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_page" name="ajax_table_sort_page" value="' . $this->page_slug . '" />';
2425
+			$sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_action" name="ajax_table_sort_action" value="' . $ajax_sorting_callback . '" />';
2426
+		} else {
2427
+			$sortable_list_table_form_fields = '';
2428
+		}
2429
+		$this->_template_args['sortable_list_table_form_fields'] = $sortable_list_table_form_fields;
2430
+		$hidden_form_fields = isset($this->_template_args['list_table_hidden_fields']) ? $this->_template_args['list_table_hidden_fields'] : '';
2431
+		$nonce_ref = $this->_req_action . '_nonce';
2432
+		$hidden_form_fields .= '<input type="hidden" name="' . $nonce_ref . '" value="' . wp_create_nonce($nonce_ref) . '">';
2433
+		$this->_template_args['list_table_hidden_fields'] = $hidden_form_fields;
2434
+		//display message about search results?
2435
+		$this->_template_args['before_list_table'] .= ! empty($this->_req_data['s'])
2436
+				? '<p class="ee-search-results">' . sprintf(
2437
+						__('Displaying search results for the search string: <strong><em>%s</em></strong>',
2438
+								'event_espresso'),
2439
+						trim($this->_req_data['s'], '%')
2440
+				) . '</p>'
2441
+				: '';
2442
+		// filter before_list_table template arg
2443
+		$this->_template_args['before_list_table'] = implode(
2444
+				" \n",
2445
+				(array)apply_filters(
2446
+						'FHEE__EE_Admin_Page___display_admin_list_table_page__before_list_table__template_arg',
2447
+						(array)$this->_template_args['before_list_table'],
2448
+						$this->page_slug,
2449
+						$this->_req_data,
2450
+						$this->_req_action
2451
+				)
2452
+		);
2453
+		// filter after_list_table template arg
2454
+		$this->_template_args['after_list_table'] = implode(
2455
+				" \n",
2456
+				(array)apply_filters(
2457
+						'FHEE__EE_Admin_Page___display_admin_list_table_page__after_list_table__template_arg',
2458
+						(array)$this->_template_args['after_list_table'],
2459
+						$this->page_slug,
2460
+						$this->_req_data,
2461
+						$this->_req_action
2462
+				)
2463
+		);
2464
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
2465
+				$template_path,
2466
+				$this->_template_args,
2467
+				true
2468
+		);
2469
+		// the final template wrapper
2470
+		if ($sidebar) {
2471
+			$this->display_admin_page_with_sidebar();
2472
+		} else {
2473
+			$this->display_admin_page_with_no_sidebar();
2474
+		}
2475
+	}
2476
+
2477
+
2478
+
2479
+	/**
2480
+	 * This just prepares a legend using the given items and the admin_details_legend.template.php file and returns the html string for the legend.
2481
+	 * $items are expected in an array in the following format:
2482
+	 * $legend_items = array(
2483
+	 *        'item_id' => array(
2484
+	 *            'icon' => 'http://url_to_icon_being_described.png',
2485
+	 *            'desc' => __('localized description of item');
2486
+	 *        )
2487
+	 * );
2488
+	 *
2489
+	 * @param  array $items see above for format of array
2490
+	 * @return string        html string of legend
2491
+	 */
2492
+	protected function _display_legend($items)
2493
+	{
2494
+		$this->_template_args['items'] = apply_filters('FHEE__EE_Admin_Page___display_legend__items', (array)$items, $this);
2495
+		$legend_template = EE_ADMIN_TEMPLATE . 'admin_details_legend.template.php';
2496
+		return EEH_Template::display_template($legend_template, $this->_template_args, true);
2497
+	}
2498
+
2499
+
2500
+
2501
+	/**
2502
+	 * this is used whenever we're DOING_AJAX to return a formatted json array that our calling javascript can expect
2503
+	 *
2504
+	 * @param bool $sticky_notices Used to indicate whether you want to ensure notices are added to a transient instead of displayed.
2505
+	 *                             The returned json object is created from an array in the following format:
2506
+	 *                             array(
2507
+	 *                             'error' => FALSE, //(default FALSE), contains any errors and/or exceptions (exceptions return json early),
2508
+	 *                             'success' => FALSE, //(default FALSE) - contains any special success message.
2509
+	 *                             'notices' => '', // - contains any EE_Error formatted notices
2510
+	 *                             'content' => 'string can be html', //this is a string of formatted content (can be html)
2511
+	 *                             'data' => array() //this can be any key/value pairs that a method returns for later json parsing by the js. We're also going to include the template args with every package (so js can pick out any
2512
+	 *                             specific template args that might be included in here)
2513
+	 *                             )
2514
+	 *                             The json object is populated by whatever is set in the $_template_args property.
2515
+	 * @return void
2516
+	 */
2517
+	protected function _return_json($sticky_notices = false)
2518
+	{
2519
+		//make sure any EE_Error notices have been handled.
2520
+		$this->_process_notices(array(), true, $sticky_notices);
2521
+		$data = isset($this->_template_args['data']) ? $this->_template_args['data'] : array();
2522
+		unset($this->_template_args['data']);
2523
+		$json = array(
2524
+				'error'     => isset($this->_template_args['error']) ? $this->_template_args['error'] : false,
2525
+				'success'   => isset($this->_template_args['success']) ? $this->_template_args['success'] : false,
2526
+				'errors'    => isset($this->_template_args['errors']) ? $this->_template_args['errors'] : false,
2527
+				'attention' => isset($this->_template_args['attention']) ? $this->_template_args['attention'] : false,
2528
+				'notices'   => EE_Error::get_notices(),
2529
+				'content'   => isset($this->_template_args['admin_page_content']) ? $this->_template_args['admin_page_content'] : '',
2530
+				'data'      => array_merge($data, array('template_args' => $this->_template_args)),
2531
+				'isEEajax'  => true //special flag so any ajax.Success methods in js can identify this return package as a EEajax package.
2532
+		);
2533
+		// make sure there are no php errors or headers_sent.  Then we can set correct json header.
2534
+		if (null === error_get_last() || ! headers_sent()) {
2535
+			header('Content-Type: application/json; charset=UTF-8');
2536
+		}
2537
+		echo wp_json_encode($json);
2538
+
2539
+		exit();
2540
+	}
2541
+
2542
+
2543
+
2544
+	/**
2545
+	 * Simply a wrapper for the protected method so we can call this outside the class (ONLY when doing ajax)
2546
+	 *
2547
+	 * @return void
2548
+	 * @throws EE_Error
2549
+	 */
2550
+	public function return_json()
2551
+	{
2552
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2553
+			$this->_return_json();
2554
+		} else {
2555
+			throw new EE_Error(sprintf(__('The public %s method can only be called when DOING_AJAX = TRUE', 'event_espresso'), __FUNCTION__));
2556
+		}
2557
+	}
2558
+
2559
+
2560
+
2561
+	/**
2562
+	 * This provides a way for child hook classes to send along themselves by reference so methods/properties within them can be accessed by EE_Admin_child pages. This is assigned to the $_hook_obj property.
2563
+	 *
2564
+	 * @param EE_Admin_Hooks $hook_obj This will be the object for the EE_Admin_Hooks child
2565
+	 * @access   public
2566
+	 */
2567
+	public function set_hook_object(EE_Admin_Hooks $hook_obj)
2568
+	{
2569
+		$this->_hook_obj = $hook_obj;
2570
+	}
2571
+
2572
+
2573
+
2574
+	/**
2575
+	 *        generates  HTML wrapper with Tabbed nav for an admin page
2576
+	 *
2577
+	 * @access public
2578
+	 * @param  boolean $about whether to use the special about page wrapper or default.
2579
+	 * @return void
2580
+	 */
2581
+	public function admin_page_wrapper($about = false)
2582
+	{
2583
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2584
+		$this->_nav_tabs = $this->_get_main_nav_tabs();
2585
+		$this->_template_args['nav_tabs'] = $this->_nav_tabs;
2586
+		$this->_template_args['admin_page_title'] = $this->_admin_page_title;
2587
+		$this->_template_args['before_admin_page_content'] = apply_filters('FHEE_before_admin_page_content' . $this->_current_page . $this->_current_view,
2588
+				isset($this->_template_args['before_admin_page_content']) ? $this->_template_args['before_admin_page_content'] : '');
2589
+		$this->_template_args['after_admin_page_content'] = apply_filters('FHEE_after_admin_page_content' . $this->_current_page . $this->_current_view,
2590
+				isset($this->_template_args['after_admin_page_content']) ? $this->_template_args['after_admin_page_content'] : '');
2591
+		$this->_template_args['after_admin_page_content'] .= $this->_set_help_popup_content();
2592
+		// load settings page wrapper template
2593
+		$template_path = ! defined('DOING_AJAX') ? EE_ADMIN_TEMPLATE . 'admin_wrapper.template.php' : EE_ADMIN_TEMPLATE . 'admin_wrapper_ajax.template.php';
2594
+		//about page?
2595
+		$template_path = $about ? EE_ADMIN_TEMPLATE . 'about_admin_wrapper.template.php' : $template_path;
2596
+		if (defined('DOING_AJAX')) {
2597
+			$this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path, $this->_template_args, true);
2598
+			$this->_return_json();
2599
+		} else {
2600
+			EEH_Template::display_template($template_path, $this->_template_args);
2601
+		}
2602
+	}
2603
+
2604
+
2605
+
2606
+	/**
2607
+	 * This returns the admin_nav tabs html using the configuration in the _nav_tabs property
2608
+	 *
2609
+	 * @return string html
2610
+	 */
2611
+	protected function _get_main_nav_tabs()
2612
+	{
2613
+		//let's generate the html using the EEH_Tabbed_Content helper.  We do this here so that it's possible for child classes to add in nav tabs dynamically at the last minute (rather than setting in the page_routes array)
2614
+		return EEH_Tabbed_Content::display_admin_nav_tabs($this->_nav_tabs);
2615
+	}
2616
+
2617
+
2618
+
2619
+	/**
2620
+	 *        sort nav tabs
2621
+	 *
2622
+	 * @access public
2623
+	 * @param $a
2624
+	 * @param $b
2625
+	 * @return int
2626
+	 */
2627
+	private function _sort_nav_tabs($a, $b)
2628
+	{
2629
+		if ($a['order'] == $b['order']) {
2630
+			return 0;
2631
+		}
2632
+		return ($a['order'] < $b['order']) ? -1 : 1;
2633
+	}
2634
+
2635
+
2636
+
2637
+	/**
2638
+	 *    generates HTML for the forms used on admin pages
2639
+	 *
2640
+	 * @access protected
2641
+	 * @param    array $input_vars - array of input field details
2642
+	 * @param string   $generator  (options are 'string' or 'array', basically use this to indicate which generator to use)
2643
+	 * @return string
2644
+	 * @uses   EEH_Form_Fields::get_form_fields (/helper/EEH_Form_Fields.helper.php)
2645
+	 * @uses   EEH_Form_Fields::get_form_fields_array (/helper/EEH_Form_Fields.helper.php)
2646
+	 */
2647
+	protected function _generate_admin_form_fields($input_vars = array(), $generator = 'string', $id = false)
2648
+	{
2649
+		$content = $generator == 'string' ? EEH_Form_Fields::get_form_fields($input_vars, $id) : EEH_Form_Fields::get_form_fields_array($input_vars);
2650
+		return $content;
2651
+	}
2652
+
2653
+
2654
+
2655
+	/**
2656
+	 * generates the "Save" and "Save & Close" buttons for edit forms
2657
+	 *
2658
+	 * @access protected
2659
+	 * @param bool             $both     if true then both buttons will be generated.  If false then just the "Save & Close" button.
2660
+	 * @param array            $text     if included, generator will use the given text for the buttons ( array([0] => 'Save', [1] => 'save & close')
2661
+	 * @param array            $actions  if included allows us to set the actions that each button will carry out (i.e. via the "name" value in the button).  We can also use this to just dump default actions by submitting some other value.
2662
+	 * @param bool|string|null $referrer if false then we just do the default action on save and close.  Other wise it will use the $referrer string. IF null, then we don't do ANYTHING on save and close (normal form handling).
2663
+	 */
2664
+	protected function _set_save_buttons($both = true, $text = array(), $actions = array(), $referrer = null)
2665
+	{
2666
+		//make sure $text and $actions are in an array
2667
+		$text = (array)$text;
2668
+		$actions = (array)$actions;
2669
+		$referrer_url = empty($referrer) ? '' : $referrer;
2670
+		$referrer_url = ! $referrer ? '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="' . $_SERVER['REQUEST_URI'] . '" />'
2671
+				: '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="' . $referrer . '" />';
2672
+		$button_text = ! empty($text) ? $text : array(__('Save', 'event_espresso'), __('Save and Close', 'event_espresso'));
2673
+		$default_names = array('save', 'save_and_close');
2674
+		//add in a hidden index for the current page (so save and close redirects properly)
2675
+		$this->_template_args['save_buttons'] = $referrer_url;
2676
+		foreach ($button_text as $key => $button) {
2677
+			$ref = $default_names[$key];
2678
+			$id = $this->_current_view . '_' . $ref;
2679
+			$name = ! empty($actions) ? $actions[$key] : $ref;
2680
+			$this->_template_args['save_buttons'] .= '<input type="submit" class="button-primary ' . $ref . '" value="' . $button . '" name="' . $name . '" id="' . $id . '" />';
2681
+			if ( ! $both) {
2682
+				break;
2683
+			}
2684
+		}
2685
+	}
2686
+
2687
+
2688
+
2689
+	/**
2690
+	 * Wrapper for the protected function.  Allows plugins/addons to call this to set the form tags.
2691
+	 *
2692
+	 * @see   $this->_set_add_edit_form_tags() for details on params
2693
+	 * @since 4.6.0
2694
+	 * @param string $route
2695
+	 * @param array  $additional_hidden_fields
2696
+	 */
2697
+	public function set_add_edit_form_tags($route = '', $additional_hidden_fields = array())
2698
+	{
2699
+		$this->_set_add_edit_form_tags($route, $additional_hidden_fields);
2700
+	}
2701
+
2702
+
2703
+
2704
+	/**
2705
+	 * set form open and close tags on add/edit pages.
2706
+	 *
2707
+	 * @access protected
2708
+	 * @param string $route                    the route you want the form to direct to
2709
+	 * @param array  $additional_hidden_fields any additional hidden fields required in the form header
2710
+	 * @return void
2711
+	 */
2712
+	protected function _set_add_edit_form_tags($route = '', $additional_hidden_fields = array())
2713
+	{
2714
+		if (empty($route)) {
2715
+			$user_msg = __('An error occurred. No action was set for this page\'s form.', 'event_espresso');
2716
+			$dev_msg = $user_msg . "\n" . sprintf(__('The $route argument is required for the %s->%s method.', 'event_espresso'), __FUNCTION__, __CLASS__);
2717
+			EE_Error::add_error($user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
2718
+		}
2719
+		// open form
2720
+		$this->_template_args['before_admin_page_content'] = '<form name="form" method="post" action="' . $this->_admin_base_url . '" id="' . $route . '_event_form" >';
2721
+		// add nonce
2722
+		$nonce = wp_nonce_field($route . '_nonce', $route . '_nonce', false, false);
2723
+		//		$nonce = wp_nonce_field( $route . '_nonce', '_wpnonce', FALSE, FALSE );
2724
+		$this->_template_args['before_admin_page_content'] .= "\n\t" . $nonce;
2725
+		// add REQUIRED form action
2726
+		$hidden_fields = array(
2727
+				'action' => array('type' => 'hidden', 'value' => $route),
2728
+		);
2729
+		// merge arrays
2730
+		$hidden_fields = is_array($additional_hidden_fields) ? array_merge($hidden_fields, $additional_hidden_fields) : $hidden_fields;
2731
+		// generate form fields
2732
+		$form_fields = $this->_generate_admin_form_fields($hidden_fields, 'array');
2733
+		// add fields to form
2734
+		foreach ((array)$form_fields as $field_name => $form_field) {
2735
+			$this->_template_args['before_admin_page_content'] .= "\n\t" . $form_field['field'];
2736
+		}
2737
+		// close form
2738
+		$this->_template_args['after_admin_page_content'] = '</form>';
2739
+	}
2740
+
2741
+
2742
+
2743
+	/**
2744
+	 * Public Wrapper for _redirect_after_action() method since its
2745
+	 * discovered it would be useful for external code to have access.
2746
+	 *
2747
+	 * @see   EE_Admin_Page::_redirect_after_action() for params.
2748
+	 * @since 4.5.0
2749
+	 */
2750
+	public function redirect_after_action($success = false, $what = 'item', $action_desc = 'processed', $query_args = array(), $override_overwrite = false)
2751
+	{
2752
+		$this->_redirect_after_action($success, $what, $action_desc, $query_args, $override_overwrite);
2753
+	}
2754
+
2755
+
2756
+
2757
+	/**
2758
+	 *    _redirect_after_action
2759
+	 *
2760
+	 * @param int    $success            - whether success was for two or more records, or just one, or none
2761
+	 * @param string $what               - what the action was performed on
2762
+	 * @param string $action_desc        - what was done ie: updated, deleted, etc
2763
+	 * @param array  $query_args         - an array of query_args to be added to the URL to redirect to after the admin action is completed
2764
+	 * @param BOOL   $override_overwrite by default all EE_Error::success messages are overwritten, this allows you to override this so that they show.
2765
+	 * @access protected
2766
+	 * @return void
2767
+	 */
2768
+	protected function _redirect_after_action($success = 0, $what = 'item', $action_desc = 'processed', $query_args = array(), $override_overwrite = false)
2769
+	{
2770
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2771
+		//class name for actions/filters.
2772
+		$classname = get_class($this);
2773
+		//set redirect url. Note if there is a "page" index in the $query_args then we go with vanilla admin.php route, otherwise we go with whatever is set as the _admin_base_url
2774
+		$redirect_url = isset($query_args['page']) ? admin_url('admin.php') : $this->_admin_base_url;
2775
+		$notices = EE_Error::get_notices(false);
2776
+		// overwrite default success messages //BUT ONLY if overwrite not overridden
2777
+		if ( ! $override_overwrite || ! empty($notices['errors'])) {
2778
+			EE_Error::overwrite_success();
2779
+		}
2780
+		if ( ! empty($what) && ! empty($action_desc)) {
2781
+			// how many records affected ? more than one record ? or just one ?
2782
+			if ($success > 1 && empty($notices['errors'])) {
2783
+				// set plural msg
2784
+				EE_Error::add_success(
2785
+						sprintf(
2786
+								__('The "%s" have been successfully %s.', 'event_espresso'),
2787
+								$what,
2788
+								$action_desc
2789
+						),
2790
+						__FILE__, __FUNCTION__, __LINE__
2791
+				);
2792
+			} else if ($success == 1 && empty($notices['errors'])) {
2793
+				// set singular msg
2794
+				EE_Error::add_success(
2795
+						sprintf(
2796
+								__('The "%s" has been successfully %s.', 'event_espresso'),
2797
+								$what,
2798
+								$action_desc
2799
+						),
2800
+						__FILE__, __FUNCTION__, __LINE__
2801
+				);
2802
+			}
2803
+		}
2804
+		// check that $query_args isn't something crazy
2805
+		if ( ! is_array($query_args)) {
2806
+			$query_args = array();
2807
+		}
2808
+		/**
2809
+		 * Allow injecting actions before the query_args are modified for possible different
2810
+		 * redirections on save and close actions
2811
+		 *
2812
+		 * @since 4.2.0
2813
+		 * @param array $query_args       The original query_args array coming into the
2814
+		 *                                method.
2815
+		 */
2816
+		do_action('AHEE__' . $classname . '___redirect_after_action__before_redirect_modification_' . $this->_req_action, $query_args);
2817
+		//calculate where we're going (if we have a "save and close" button pushed)
2818
+		if (isset($this->_req_data['save_and_close']) && isset($this->_req_data['save_and_close_referrer'])) {
2819
+			// even though we have the save_and_close referrer, we need to parse the url for the action in order to generate a nonce
2820
+			$parsed_url = parse_url($this->_req_data['save_and_close_referrer']);
2821
+			// regenerate query args array from referrer URL
2822
+			parse_str($parsed_url['query'], $query_args);
2823
+			// correct page and action will be in the query args now
2824
+			$redirect_url = admin_url('admin.php');
2825
+		}
2826
+		//merge any default query_args set in _default_route_query_args property
2827
+		if ( ! empty($this->_default_route_query_args) && ! $this->_is_UI_request) {
2828
+			$args_to_merge = array();
2829
+			foreach ($this->_default_route_query_args as $query_param => $query_value) {
2830
+				//is there a wp_referer array in our _default_route_query_args property?
2831
+				if ($query_param == 'wp_referer') {
2832
+					$query_value = (array)$query_value;
2833
+					foreach ($query_value as $reference => $value) {
2834
+						if (strpos($reference, 'nonce') !== false) {
2835
+							continue;
2836
+						}
2837
+						//finally we will override any arguments in the referer with
2838
+						//what might be set on the _default_route_query_args array.
2839
+						if (isset($this->_default_route_query_args[$reference])) {
2840
+							$args_to_merge[$reference] = urlencode($this->_default_route_query_args[$reference]);
2841
+						} else {
2842
+							$args_to_merge[$reference] = urlencode($value);
2843
+						}
2844
+					}
2845
+					continue;
2846
+				}
2847
+				$args_to_merge[$query_param] = $query_value;
2848
+			}
2849
+			//now let's merge these arguments but override with what was specifically sent in to the
2850
+			//redirect.
2851
+			$query_args = array_merge($args_to_merge, $query_args);
2852
+		}
2853
+		$this->_process_notices($query_args);
2854
+		// generate redirect url
2855
+		// if redirecting to anything other than the main page, add a nonce
2856
+		if (isset($query_args['action'])) {
2857
+			// manually generate wp_nonce and merge that with the query vars becuz the wp_nonce_url function wrecks havoc on some vars
2858
+			$query_args['_wpnonce'] = wp_create_nonce($query_args['action'] . '_nonce');
2859
+		}
2860
+		//we're adding some hooks and filters in here for processing any things just before redirects (example: an admin page has done an insert or update and we want to run something after that).
2861
+		do_action('AHEE_redirect_' . $classname . $this->_req_action, $query_args);
2862
+		$redirect_url = apply_filters('FHEE_redirect_' . $classname . $this->_req_action, self::add_query_args_and_nonce($query_args, $redirect_url), $query_args);
2863
+		// check if we're doing ajax.  If we are then lets just return the results and js can handle how it wants.
2864
+		if (defined('DOING_AJAX')) {
2865
+			$default_data = array(
2866
+					'close'        => true,
2867
+					'redirect_url' => $redirect_url,
2868
+					'where'        => 'main',
2869
+					'what'         => 'append',
2870
+			);
2871
+			$this->_template_args['success'] = $success;
2872
+			$this->_template_args['data'] = ! empty($this->_template_args['data']) ? array_merge($default_data, $this->_template_args['data']) : $default_data;
2873
+			$this->_return_json();
2874
+		}
2875
+		wp_safe_redirect($redirect_url);
2876
+		exit();
2877
+	}
2878
+
2879
+
2880
+
2881
+	/**
2882
+	 * process any notices before redirecting (or returning ajax request)
2883
+	 * This method sets the $this->_template_args['notices'] attribute;
2884
+	 *
2885
+	 * @param  array $query_args        any query args that need to be used for notice transient ('action')
2886
+	 * @param bool   $skip_route_verify This is typically used when we are processing notices REALLY early and page_routes haven't been defined yet.
2887
+	 * @param bool   $sticky_notices    This is used to flag that regardless of whether this is doing_ajax or not, we still save a transient for the notice.
2888
+	 * @return void
2889
+	 */
2890
+	protected function _process_notices($query_args = array(), $skip_route_verify = false, $sticky_notices = true)
2891
+	{
2892
+		//first let's set individual error properties if doing_ajax and the properties aren't already set.
2893
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2894
+			$notices = EE_Error::get_notices(false);
2895
+			if (empty($this->_template_args['success'])) {
2896
+				$this->_template_args['success'] = isset($notices['success']) ? $notices['success'] : false;
2897
+			}
2898
+			if (empty($this->_template_args['errors'])) {
2899
+				$this->_template_args['errors'] = isset($notices['errors']) ? $notices['errors'] : false;
2900
+			}
2901
+			if (empty($this->_template_args['attention'])) {
2902
+				$this->_template_args['attention'] = isset($notices['attention']) ? $notices['attention'] : false;
2903
+			}
2904
+		}
2905
+		$this->_template_args['notices'] = EE_Error::get_notices();
2906
+		//IF this isn't ajax we need to create a transient for the notices using the route (however, overridden if $sticky_notices == true)
2907
+		if ( ! defined('DOING_AJAX') || $sticky_notices) {
2908
+			$route = isset($query_args['action']) ? $query_args['action'] : 'default';
2909
+			$this->_add_transient($route, $this->_template_args['notices'], true, $skip_route_verify);
2910
+		}
2911
+	}
2912
+
2913
+
2914
+
2915
+	/**
2916
+	 * get_action_link_or_button
2917
+	 * returns the button html for adding, editing, or deleting an item (depending on given type)
2918
+	 *
2919
+	 * @param string $action        use this to indicate which action the url is generated with.
2920
+	 * @param string $type          accepted strings must be defined in the $_labels['button'] array(as the key) property.
2921
+	 * @param array  $extra_request if the button requires extra params you can include them in $key=>$value pairs.
2922
+	 * @param string $class         Use this to give the class for the button. Defaults to 'button-primary'
2923
+	 * @param string $base_url      If this is not provided
2924
+	 *                              the _admin_base_url will be used as the default for the button base_url.
2925
+	 *                              Otherwise this value will be used.
2926
+	 * @param bool   $exclude_nonce If true then no nonce will be in the generated button link.
2927
+	 * @return string
2928
+	 * @throws \EE_Error
2929
+	 */
2930
+	public function get_action_link_or_button(
2931
+			$action,
2932
+			$type = 'add',
2933
+			$extra_request = array(),
2934
+			$class = 'button-primary',
2935
+			$base_url = '',
2936
+			$exclude_nonce = false
2937
+	) {
2938
+		//first let's validate the action (if $base_url is FALSE otherwise validation will happen further along)
2939
+		if (empty($base_url) && ! isset($this->_page_routes[$action])) {
2940
+			throw new EE_Error(
2941
+					sprintf(
2942
+							__(
2943
+									'There is no page route for given action for the button.  This action was given: %s',
2944
+									'event_espresso'
2945
+							),
2946
+							$action
2947
+					)
2948
+			);
2949
+		}
2950
+		if ( ! isset($this->_labels['buttons'][$type])) {
2951
+			throw new EE_Error(
2952
+					sprintf(
2953
+							__(
2954
+									'There is no label for the given button type (%s). Labels are set in the <code>_page_config</code> property.',
2955
+									'event_espresso'
2956
+							),
2957
+							$type
2958
+					)
2959
+			);
2960
+		}
2961
+		//finally check user access for this button.
2962
+		$has_access = $this->check_user_access($action, true);
2963
+		if ( ! $has_access) {
2964
+			return '';
2965
+		}
2966
+		$_base_url = ! $base_url ? $this->_admin_base_url : $base_url;
2967
+		$query_args = array(
2968
+				'action' => $action,
2969
+		);
2970
+		//merge extra_request args but make sure our original action takes precedence and doesn't get overwritten.
2971
+		if ( ! empty($extra_request)) {
2972
+			$query_args = array_merge($extra_request, $query_args);
2973
+		}
2974
+		$url = self::add_query_args_and_nonce($query_args, $_base_url, false, $exclude_nonce);
2975
+		return EEH_Template::get_button_or_link($url, $this->_labels['buttons'][$type], $class);
2976
+	}
2977
+
2978
+
2979
+
2980
+	/**
2981
+	 * _per_page_screen_option
2982
+	 * Utility function for adding in a per_page_option in the screen_options_dropdown.
2983
+	 *
2984
+	 * @return void
2985
+	 */
2986
+	protected function _per_page_screen_option()
2987
+	{
2988
+		$option = 'per_page';
2989
+		$args = array(
2990
+				'label'   => $this->_admin_page_title,
2991
+				'default' => 10,
2992
+				'option'  => $this->_current_page . '_' . $this->_current_view . '_per_page',
2993
+		);
2994
+		//ONLY add the screen option if the user has access to it.
2995
+		if ($this->check_user_access($this->_current_view, true)) {
2996
+			add_screen_option($option, $args);
2997
+		}
2998
+	}
2999
+
3000
+
3001
+
3002
+	/**
3003
+	 * set_per_page_screen_option
3004
+	 * All this does is make sure that WordPress saves any per_page screen options (if set) for the current page.
3005
+	 * we have to do this rather than running inside the 'set-screen-options' hook because it runs earlier than admin_menu.
3006
+	 *
3007
+	 * @access private
3008
+	 * @return void
3009
+	 */
3010
+	private function _set_per_page_screen_options()
3011
+	{
3012
+		if (isset($_POST['wp_screen_options']) && is_array($_POST['wp_screen_options'])) {
3013
+			check_admin_referer('screen-options-nonce', 'screenoptionnonce');
3014
+			if ( ! $user = wp_get_current_user()) {
3015
+				return;
3016
+			}
3017
+			$option = $_POST['wp_screen_options']['option'];
3018
+			$value = $_POST['wp_screen_options']['value'];
3019
+			if ($option != sanitize_key($option)) {
3020
+				return;
3021
+			}
3022
+			$map_option = $option;
3023
+			$option = str_replace('-', '_', $option);
3024
+			switch ($map_option) {
3025
+				case $this->_current_page . '_' . $this->_current_view . '_per_page':
3026
+					$value = (int)$value;
3027
+					if ($value < 1 || $value > 999) {
3028
+						return;
3029
+					}
3030
+					break;
3031
+				default:
3032
+					$value = apply_filters('FHEE__EE_Admin_Page___set_per_page_screen_options__value', false, $option, $value);
3033
+					if (false === $value) {
3034
+						return;
3035
+					}
3036
+					break;
3037
+			}
3038
+			update_user_meta($user->ID, $option, $value);
3039
+			wp_safe_redirect(remove_query_arg(array('pagenum', 'apage', 'paged'), wp_get_referer()));
3040
+			exit;
3041
+		}
3042
+	}
3043
+
3044
+
3045
+
3046
+	/**
3047
+	 * This just allows for setting the $_template_args property if it needs to be set outside the object
3048
+	 *
3049
+	 * @param array $data array that will be assigned to template args.
3050
+	 */
3051
+	public function set_template_args($data)
3052
+	{
3053
+		$this->_template_args = array_merge($this->_template_args, (array)$data);
3054
+	}
3055
+
3056
+
3057
+
3058
+	/**
3059
+	 * This makes available the WP transient system for temporarily moving data between routes
3060
+	 *
3061
+	 * @access protected
3062
+	 * @param string $route             the route that should receive the transient
3063
+	 * @param array  $data              the data that gets sent
3064
+	 * @param bool   $notices           If this is for notices then we use this to indicate so, otherwise its just a normal route transient.
3065
+	 * @param bool   $skip_route_verify Used to indicate we want to skip route verification.  This is usually ONLY used when we are adding a transient before page_routes have been defined.
3066
+	 * @return void
3067
+	 */
3068
+	protected function _add_transient($route, $data, $notices = false, $skip_route_verify = false)
3069
+	{
3070
+		$user_id = get_current_user_id();
3071
+		if ( ! $skip_route_verify) {
3072
+			$this->_verify_route($route);
3073
+		}
3074
+		//now let's set the string for what kind of transient we're setting
3075
+		$transient = $notices ? 'ee_rte_n_tx_' . $route . '_' . $user_id : 'rte_tx_' . $route . '_' . $user_id;
3076
+		$data = $notices ? array('notices' => $data) : $data;
3077
+		//is there already a transient for this route?  If there is then let's ADD to that transient
3078
+		$existing = is_multisite() && is_network_admin() ? get_site_transient($transient) : get_transient($transient);
3079
+		if ($existing) {
3080
+			$data = array_merge((array)$data, (array)$existing);
3081
+		}
3082
+		if (is_multisite() && is_network_admin()) {
3083
+			set_site_transient($transient, $data, 8);
3084
+		} else {
3085
+			set_transient($transient, $data, 8);
3086
+		}
3087
+	}
3088
+
3089
+
3090
+
3091
+	/**
3092
+	 * this retrieves the temporary transient that has been set for moving data between routes.
3093
+	 *
3094
+	 * @param bool $notices true we get notices transient. False we just return normal route transient
3095
+	 * @return mixed data
3096
+	 */
3097
+	protected function _get_transient($notices = false, $route = false)
3098
+	{
3099
+		$user_id = get_current_user_id();
3100
+		$route = ! $route ? $this->_req_action : $route;
3101
+		$transient = $notices ? 'ee_rte_n_tx_' . $route . '_' . $user_id : 'rte_tx_' . $route . '_' . $user_id;
3102
+		$data = is_multisite() && is_network_admin() ? get_site_transient($transient) : get_transient($transient);
3103
+		//delete transient after retrieval (just in case it hasn't expired);
3104
+		if (is_multisite() && is_network_admin()) {
3105
+			delete_site_transient($transient);
3106
+		} else {
3107
+			delete_transient($transient);
3108
+		}
3109
+		return $notices && isset($data['notices']) ? $data['notices'] : $data;
3110
+	}
3111
+
3112
+
3113
+
3114
+	/**
3115
+	 * The purpose of this method is just to run garbage collection on any EE transients that might have expired but would not be called later.
3116
+	 * This will be assigned to run on a specific EE Admin page. (place the method in the default route callback on the EE_Admin page you want it run.)
3117
+	 *
3118
+	 * @return void
3119
+	 */
3120
+	protected function _transient_garbage_collection()
3121
+	{
3122
+		global $wpdb;
3123
+		//retrieve all existing transients
3124
+		$query = "SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%rte_tx_%' OR option_name LIKE '%rte_n_tx_%'";
3125
+		if ($results = $wpdb->get_results($query)) {
3126
+			foreach ($results as $result) {
3127
+				$transient = str_replace('_transient_', '', $result->option_name);
3128
+				get_transient($transient);
3129
+				if (is_multisite() && is_network_admin()) {
3130
+					get_site_transient($transient);
3131
+				}
3132
+			}
3133
+		}
3134
+	}
3135
+
3136
+
3137
+
3138
+	/**
3139
+	 * get_view
3140
+	 *
3141
+	 * @access public
3142
+	 * @return string content of _view property
3143
+	 */
3144
+	public function get_view()
3145
+	{
3146
+		return $this->_view;
3147
+	}
3148
+
3149
+
3150
+
3151
+	/**
3152
+	 * getter for the protected $_views property
3153
+	 *
3154
+	 * @return array
3155
+	 */
3156
+	public function get_views()
3157
+	{
3158
+		return $this->_views;
3159
+	}
3160
+
3161
+
3162
+
3163
+	/**
3164
+	 * get_current_page
3165
+	 *
3166
+	 * @access public
3167
+	 * @return string _current_page property value
3168
+	 */
3169
+	public function get_current_page()
3170
+	{
3171
+		return $this->_current_page;
3172
+	}
3173
+
3174
+
3175
+
3176
+	/**
3177
+	 * get_current_view
3178
+	 *
3179
+	 * @access public
3180
+	 * @return string _current_view property value
3181
+	 */
3182
+	public function get_current_view()
3183
+	{
3184
+		return $this->_current_view;
3185
+	}
3186
+
3187
+
3188
+
3189
+	/**
3190
+	 * get_current_screen
3191
+	 *
3192
+	 * @access public
3193
+	 * @return object The current WP_Screen object
3194
+	 */
3195
+	public function get_current_screen()
3196
+	{
3197
+		return $this->_current_screen;
3198
+	}
3199
+
3200
+
3201
+
3202
+	/**
3203
+	 * get_current_page_view_url
3204
+	 *
3205
+	 * @access public
3206
+	 * @return string This returns the url for the current_page_view.
3207
+	 */
3208
+	public function get_current_page_view_url()
3209
+	{
3210
+		return $this->_current_page_view_url;
3211
+	}
3212
+
3213
+
3214
+
3215
+	/**
3216
+	 * just returns the _req_data property
3217
+	 *
3218
+	 * @return array
3219
+	 */
3220
+	public function get_request_data()
3221
+	{
3222
+		return $this->_req_data;
3223
+	}
3224
+
3225
+
3226
+
3227
+	/**
3228
+	 * returns the _req_data protected property
3229
+	 *
3230
+	 * @return string
3231
+	 */
3232
+	public function get_req_action()
3233
+	{
3234
+		return $this->_req_action;
3235
+	}
3236
+
3237
+
3238
+
3239
+	/**
3240
+	 * @return bool  value of $_is_caf property
3241
+	 */
3242
+	public function is_caf()
3243
+	{
3244
+		return $this->_is_caf;
3245
+	}
3246
+
3247
+
3248
+
3249
+	/**
3250
+	 * @return mixed
3251
+	 */
3252
+	public function default_espresso_metaboxes()
3253
+	{
3254
+		return $this->_default_espresso_metaboxes;
3255
+	}
3256
+
3257
+
3258
+
3259
+	/**
3260
+	 * @return mixed
3261
+	 */
3262
+	public function admin_base_url()
3263
+	{
3264
+		return $this->_admin_base_url;
3265
+	}
3266
+
3267
+
3268
+
3269
+	/**
3270
+	 * @return mixed
3271
+	 */
3272
+	public function wp_page_slug()
3273
+	{
3274
+		return $this->_wp_page_slug;
3275
+	}
3276
+
3277
+
3278
+
3279
+	/**
3280
+	 * updates  espresso configuration settings
3281
+	 *
3282
+	 * @access    protected
3283
+	 * @param string                   $tab
3284
+	 * @param EE_Config_Base|EE_Config $config
3285
+	 * @param string                   $file file where error occurred
3286
+	 * @param string                   $func function  where error occurred
3287
+	 * @param string                   $line line no where error occurred
3288
+	 * @return boolean
3289
+	 */
3290
+	protected function _update_espresso_configuration($tab, $config, $file = '', $func = '', $line = '')
3291
+	{
3292
+		//remove any options that are NOT going to be saved with the config settings.
3293
+		if (isset($config->core->ee_ueip_optin)) {
3294
+			$config->core->ee_ueip_has_notified = true;
3295
+			// TODO: remove the following two lines and make sure values are migrated from 3.1
3296
+			update_option('ee_ueip_optin', $config->core->ee_ueip_optin);
3297
+			update_option('ee_ueip_has_notified', true);
3298
+		}
3299
+		// and save it (note we're also doing the network save here)
3300
+		$net_saved = is_main_site() ? EE_Network_Config::instance()->update_config(false, false) : true;
3301
+		$config_saved = EE_Config::instance()->update_espresso_config(false, false);
3302
+		if ($config_saved && $net_saved) {
3303
+			EE_Error::add_success(sprintf(__('"%s" have been successfully updated.', 'event_espresso'), $tab));
3304
+			return true;
3305
+		} else {
3306
+			EE_Error::add_error(sprintf(__('The "%s" were not updated.', 'event_espresso'), $tab), $file, $func, $line);
3307
+			return false;
3308
+		}
3309
+	}
3310
+
3311
+
3312
+
3313
+	/**
3314
+	 * Returns an array to be used for EE_FOrm_Fields.helper.php's select_input as the $values argument.
3315
+	 *
3316
+	 * @return array
3317
+	 */
3318
+	public function get_yes_no_values()
3319
+	{
3320
+		return $this->_yes_no_values;
3321
+	}
3322
+
3323
+
3324
+
3325
+	protected function _get_dir()
3326
+	{
3327
+		$reflector = new ReflectionClass(get_class($this));
3328
+		return dirname($reflector->getFileName());
3329
+	}
3330
+
3331
+
3332
+
3333
+	/**
3334
+	 * A helper for getting a "next link".
3335
+	 *
3336
+	 * @param string $url   The url to link to
3337
+	 * @param string $class The class to use.
3338
+	 * @return string
3339
+	 */
3340
+	protected function _next_link($url, $class = 'dashicons dashicons-arrow-right')
3341
+	{
3342
+		return '<a class="' . $class . '" href="' . $url . '"></a>';
3343
+	}
3344
+
3345
+
3346
+
3347
+	/**
3348
+	 * A helper for getting a "previous link".
3349
+	 *
3350
+	 * @param string $url   The url to link to
3351
+	 * @param string $class The class to use.
3352
+	 * @return string
3353
+	 */
3354
+	protected function _previous_link($url, $class = 'dashicons dashicons-arrow-left')
3355
+	{
3356
+		return '<a class="' . $class . '" href="' . $url . '"></a>';
3357
+	}
3358
+
3359
+
3360
+
3361
+
3362
+
3363
+
3364
+
3365
+	//below are some messages related methods that should be available across the EE_Admin system.  Note, these methods are NOT page specific
3366
+	/**
3367
+	 * This processes an request to resend a registration and assumes we have a _REG_ID for doing so. So if the caller knows that the _REG_ID isn't in the req_data array but CAN obtain it, the caller should ADD the _REG_ID to the _req_data
3368
+	 * array.
3369
+	 *
3370
+	 * @return bool success/fail
3371
+	 */
3372
+	protected function _process_resend_registration()
3373
+	{
3374
+		$this->_template_args['success'] = EED_Messages::process_resend($this->_req_data);
3375
+		do_action('AHEE__EE_Admin_Page___process_resend_registration', $this->_template_args['success'], $this->_req_data);
3376
+		return $this->_template_args['success'];
3377
+	}
3378
+
3379
+
3380
+
3381
+	/**
3382
+	 * This automatically processes any payment message notifications when manual payment has been applied.
3383
+	 *
3384
+	 * @access protected
3385
+	 * @param \EE_Payment $payment
3386
+	 * @return bool success/fail
3387
+	 */
3388
+	protected function _process_payment_notification(EE_Payment $payment)
3389
+	{
3390
+		add_filter('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', '__return_true');
3391
+		do_action('AHEE__EE_Admin_Page___process_admin_payment_notification', $payment);
3392
+		$this->_template_args['success'] = apply_filters('FHEE__EE_Admin_Page___process_admin_payment_notification__success', false, $payment);
3393
+		return $this->_template_args['success'];
3394
+	}
3395 3395
 
3396 3396
 
3397 3397
 }
Please login to merge, or discard this patch.
core/admin/EE_Admin_Page_CPT.core.php 2 patches
Indentation   +1386 added lines, -1386 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -24,445 +24,445 @@  discard block
 block discarded – undo
24 24
 {
25 25
 
26 26
 
27
-    /**
28
-     * This gets set in _setup_cpt
29
-     * It will contain the object for the custom post type.
30
-     *
31
-     * @var object
32
-     */
33
-    protected $_cpt_object;
34
-
35
-
36
-
37
-    /**
38
-     * a boolean flag to set whether the current route is a cpt route or not.
39
-     *
40
-     * @var bool
41
-     */
42
-    protected $_cpt_route = false;
43
-
44
-
45
-
46
-    /**
47
-     * This property allows cpt classes to define multiple routes as cpt routes.
48
-     * //in this array we define what the custom post type for this route is.
49
-     * array(
50
-     * 'route_name' => 'custom_post_type_slug'
51
-     * )
52
-     *
53
-     * @var array
54
-     */
55
-    protected $_cpt_routes = array();
56
-
27
+	/**
28
+	 * This gets set in _setup_cpt
29
+	 * It will contain the object for the custom post type.
30
+	 *
31
+	 * @var object
32
+	 */
33
+	protected $_cpt_object;
34
+
35
+
36
+
37
+	/**
38
+	 * a boolean flag to set whether the current route is a cpt route or not.
39
+	 *
40
+	 * @var bool
41
+	 */
42
+	protected $_cpt_route = false;
43
+
44
+
45
+
46
+	/**
47
+	 * This property allows cpt classes to define multiple routes as cpt routes.
48
+	 * //in this array we define what the custom post type for this route is.
49
+	 * array(
50
+	 * 'route_name' => 'custom_post_type_slug'
51
+	 * )
52
+	 *
53
+	 * @var array
54
+	 */
55
+	protected $_cpt_routes = array();
56
+
57 57
 
58 58
 
59
-    /**
60
-     * This simply defines what the corresponding routes WP will be redirected to after completing a post save/update.
61
-     * in this format:
62
-     * array(
63
-     * 'post_type_slug' => 'edit_route'
64
-     * )
65
-     *
66
-     * @var array
67
-     */
68
-    protected $_cpt_edit_routes = array();
69
-
70
-
71
-
72
-    /**
73
-     * If child classes set the name of their main model via the $_cpt_obj_models property, EE_Admin_Page_CPT will
74
-     * attempt to retrieve the related object model for the edit pages and assign it to _cpt_page_object. the
75
-     * _cpt_model_names property should be in the following format: array(
76
-     * 'route_defined_by_action_param' => 'Model_Name')
77
-     *
78
-     * @var array $_cpt_model_names
79
-     */
80
-    protected $_cpt_model_names = array();
81
-
82
-
83
-    /**
84
-     * @var EE_CPT_Base
85
-     */
86
-    protected $_cpt_model_obj = false;
87
-
88
-
89
-
90
-    /**
91
-     * This will hold an array of autosave containers that will be used to obtain input values and hook into the WP
92
-     * autosave so we can save our inputs on the save_post hook!  Children classes should add to this array by using
93
-     * the _register_autosave_containers() method so that we don't override any other containers already registered.
94
-     * Registration of containers should be done before load_page_dependencies() is run.
95
-     *
96
-     * @var array()
97
-     */
98
-    protected $_autosave_containers = array();
99
-    protected $_autosave_fields = array();
100
-
101
-    /**
102
-     * Array mapping from admin actions to their equivalent wp core pages for custom post types. So when a user visits
103
-     * a page for an action, it will appear as if they were visiting the wp core page for that custom post type
104
-     *
105
-     * @var array
106
-     */
107
-    protected $_pagenow_map = null;
108
-
109
-
110
-
111
-    /**
112
-     * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
113
-     * saved.  Child classes are required to declare this method.  Typically you would use this to save any additional
114
-     * data. Keep in mind also that "save_post" runs on EVERY post update to the database. ALSO very important.  When a
115
-     * post transitions from scheduled to published, the save_post action is fired but you will NOT have any _POST data
116
-     * containing any extra info you may have from other meta saves.  So MAKE sure that you handle this accordingly.
117
-     *
118
-     * @access protected
119
-     * @abstract
120
-     * @param  string $post_id The ID of the cpt that was saved (so you can link relationally)
121
-     * @param  object $post    The post object of the cpt that was saved.
122
-     * @return void
123
-     */
124
-    abstract protected function _insert_update_cpt_item($post_id, $post);
125
-
126
-
127
-
128
-    /**
129
-     * This is hooked into the WordPress do_action('trashed_post') hook and runs after a cpt has been trashed.
130
-     *
131
-     * @abstract
132
-     * @access public
133
-     * @param  string $post_id The ID of the cpt that was trashed
134
-     * @return void
135
-     */
136
-    abstract public function trash_cpt_item($post_id);
137
-
138
-
139
-
140
-    /**
141
-     * This is hooked into the WordPress do_action('untrashed_post') hook and runs after a cpt has been untrashed
142
-     *
143
-     * @param  string $post_id theID of the cpt that was untrashed
144
-     * @return void
145
-     */
146
-    abstract public function restore_cpt_item($post_id);
147
-
148
-
149
-
150
-    /**
151
-     * This is hooked into the WordPress do_action('delete_cpt_item') hook and runs after a cpt has been fully deleted
152
-     * from the db
153
-     *
154
-     * @param  string $post_id the ID of the cpt that was deleted
155
-     * @return void
156
-     */
157
-    abstract public function delete_cpt_item($post_id);
158
-
159
-
160
-
161
-    /**
162
-     * Just utilizing the method EE_Admin exposes for doing things before page setup.
163
-     *
164
-     * @access protected
165
-     * @return void
166
-     */
167
-    protected function _before_page_setup()
168
-    {
169
-        $page = isset($this->_req_data['page']) ? $this->_req_data['page'] : $this->page_slug;
170
-        $this->_cpt_routes = array_merge(array(
171
-            'create_new' => $this->page_slug,
172
-            'edit'       => $this->page_slug,
173
-            'trash'      => $this->page_slug,
174
-        ), $this->_cpt_routes);
175
-        //let's see if the current route has a value for cpt_object_slug if it does we use that instead of the page
176
-        $this->_cpt_object = isset($this->_req_data['action']) && isset($this->_cpt_routes[$this->_req_data['action']])
177
-            ? get_post_type_object($this->_cpt_routes[$this->_req_data['action']])
178
-            : get_post_type_object($page);
179
-        //tweak pagenow for page loading.
180
-        if ( ! $this->_pagenow_map) {
181
-            $this->_pagenow_map = array(
182
-                'create_new' => 'post-new.php',
183
-                'edit'       => 'post.php',
184
-                'trash'      => 'post.php',
185
-            );
186
-        }
187
-        add_action('current_screen', array($this, 'modify_pagenow'));
188
-        //TODO the below will need to be reworked to account for the cpt routes that are NOT based off of page but action param.
189
-        //get current page from autosave
190
-        $current_page = isset($this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page'])
191
-            ? $this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page']
192
-            : null;
193
-        $this->_current_page = isset($this->_req_data['current_page'])
194
-            ? $this->_req_data['current_page']
195
-            : $current_page;
196
-        //autosave... make sure its only for the correct page
197
-        if ( ! empty($this->_current_page) && $this->_current_page == $this->page_slug) {
198
-            //setup autosave ajax hook
199
-            //add_action('wp_ajax_ee-autosave', array( $this, 'do_extra_autosave_stuff' ), 10 ); //TODO reactivate when 4.2 autosave is implemented
200
-        }
201
-    }
202
-
203
-
204
-
205
-    /**
206
-     * Simply ensure that we simulate the correct post route for cpt screens
207
-     *
208
-     * @param WP_Screen $current_screen
209
-     * @return void
210
-     */
211
-    public function modify_pagenow($current_screen)
212
-    {
213
-        global $pagenow, $hook_suffix;
214
-        //possibly reset pagenow.
215
-        if ( ! empty($this->_req_data['page'])
216
-             && $this->_req_data['page'] == $this->page_slug
217
-             && ! empty($this->_req_data['action'])
218
-             && isset($this->_pagenow_map[$this->_req_data['action']])
219
-        ) {
220
-            $pagenow = $this->_pagenow_map[$this->_req_data['action']];
221
-            $hook_suffix = $pagenow;
222
-        }
223
-    }
224
-
225
-
226
-
227
-    /**
228
-     * This method is used to register additional autosave containers to the _autosave_containers property.
229
-     *
230
-     * @todo We should automate this at some point by creating a wrapper for add_post_metabox and in our wrapper we
231
-     *       automatically register the id for the post metabox as a container.
232
-     * @param  array $ids an array of ids for containers that hold form inputs we want autosave to pickup.  Typically
233
-     *                    you would send along the id of a metabox container.
234
-     * @return void
235
-     */
236
-    protected function _register_autosave_containers($ids)
237
-    {
238
-        $this->_autosave_containers = array_merge($this->_autosave_fields, (array)$ids);
239
-    }
240
-
241
-
242
-
243
-    /**
244
-     * Something nifty.  We're going to loop through all the registered metaboxes and if the CALLBACK is an instance of
245
-     * EE_Admin_Page OR EE_Admin_Hooks, then we'll add the id to our _autosave_containers array.
246
-     */
247
-    protected function _set_autosave_containers()
248
-    {
249
-        global $wp_meta_boxes;
250
-        $containers = array();
251
-        if (empty($wp_meta_boxes)) {
252
-            return;
253
-        }
254
-        $current_metaboxes = isset($wp_meta_boxes[$this->page_slug]) ? $wp_meta_boxes[$this->page_slug] : array();
255
-        foreach ($current_metaboxes as $box_context) {
256
-            foreach ($box_context as $box_details) {
257
-                foreach ($box_details as $box) {
258
-                    if (is_array($box['callback'])
259
-                        && ($box['callback'][0] instanceof EE_Admin_Page
260
-                            || $box['callback'][0] instanceof EE_Admin_Hooks)
261
-                    ) {
262
-                        $containers[] = $box['id'];
263
-                    }
264
-                }
265
-            }
266
-        }
267
-        $this->_autosave_containers = array_merge($this->_autosave_containers, $containers);
268
-        //add hidden inputs container
269
-        $this->_autosave_containers[] = 'ee-cpt-hidden-inputs';
270
-    }
271
-
272
-
273
-
274
-    protected function _load_autosave_scripts_styles()
275
-    {
276
-        /*wp_register_script('cpt-autosave', EE_ADMIN_URL . 'assets/ee-cpt-autosave.js', array('ee-serialize-full-array', 'event_editor_js'), EVENT_ESPRESSO_VERSION, TRUE );
59
+	/**
60
+	 * This simply defines what the corresponding routes WP will be redirected to after completing a post save/update.
61
+	 * in this format:
62
+	 * array(
63
+	 * 'post_type_slug' => 'edit_route'
64
+	 * )
65
+	 *
66
+	 * @var array
67
+	 */
68
+	protected $_cpt_edit_routes = array();
69
+
70
+
71
+
72
+	/**
73
+	 * If child classes set the name of their main model via the $_cpt_obj_models property, EE_Admin_Page_CPT will
74
+	 * attempt to retrieve the related object model for the edit pages and assign it to _cpt_page_object. the
75
+	 * _cpt_model_names property should be in the following format: array(
76
+	 * 'route_defined_by_action_param' => 'Model_Name')
77
+	 *
78
+	 * @var array $_cpt_model_names
79
+	 */
80
+	protected $_cpt_model_names = array();
81
+
82
+
83
+	/**
84
+	 * @var EE_CPT_Base
85
+	 */
86
+	protected $_cpt_model_obj = false;
87
+
88
+
89
+
90
+	/**
91
+	 * This will hold an array of autosave containers that will be used to obtain input values and hook into the WP
92
+	 * autosave so we can save our inputs on the save_post hook!  Children classes should add to this array by using
93
+	 * the _register_autosave_containers() method so that we don't override any other containers already registered.
94
+	 * Registration of containers should be done before load_page_dependencies() is run.
95
+	 *
96
+	 * @var array()
97
+	 */
98
+	protected $_autosave_containers = array();
99
+	protected $_autosave_fields = array();
100
+
101
+	/**
102
+	 * Array mapping from admin actions to their equivalent wp core pages for custom post types. So when a user visits
103
+	 * a page for an action, it will appear as if they were visiting the wp core page for that custom post type
104
+	 *
105
+	 * @var array
106
+	 */
107
+	protected $_pagenow_map = null;
108
+
109
+
110
+
111
+	/**
112
+	 * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
113
+	 * saved.  Child classes are required to declare this method.  Typically you would use this to save any additional
114
+	 * data. Keep in mind also that "save_post" runs on EVERY post update to the database. ALSO very important.  When a
115
+	 * post transitions from scheduled to published, the save_post action is fired but you will NOT have any _POST data
116
+	 * containing any extra info you may have from other meta saves.  So MAKE sure that you handle this accordingly.
117
+	 *
118
+	 * @access protected
119
+	 * @abstract
120
+	 * @param  string $post_id The ID of the cpt that was saved (so you can link relationally)
121
+	 * @param  object $post    The post object of the cpt that was saved.
122
+	 * @return void
123
+	 */
124
+	abstract protected function _insert_update_cpt_item($post_id, $post);
125
+
126
+
127
+
128
+	/**
129
+	 * This is hooked into the WordPress do_action('trashed_post') hook and runs after a cpt has been trashed.
130
+	 *
131
+	 * @abstract
132
+	 * @access public
133
+	 * @param  string $post_id The ID of the cpt that was trashed
134
+	 * @return void
135
+	 */
136
+	abstract public function trash_cpt_item($post_id);
137
+
138
+
139
+
140
+	/**
141
+	 * This is hooked into the WordPress do_action('untrashed_post') hook and runs after a cpt has been untrashed
142
+	 *
143
+	 * @param  string $post_id theID of the cpt that was untrashed
144
+	 * @return void
145
+	 */
146
+	abstract public function restore_cpt_item($post_id);
147
+
148
+
149
+
150
+	/**
151
+	 * This is hooked into the WordPress do_action('delete_cpt_item') hook and runs after a cpt has been fully deleted
152
+	 * from the db
153
+	 *
154
+	 * @param  string $post_id the ID of the cpt that was deleted
155
+	 * @return void
156
+	 */
157
+	abstract public function delete_cpt_item($post_id);
158
+
159
+
160
+
161
+	/**
162
+	 * Just utilizing the method EE_Admin exposes for doing things before page setup.
163
+	 *
164
+	 * @access protected
165
+	 * @return void
166
+	 */
167
+	protected function _before_page_setup()
168
+	{
169
+		$page = isset($this->_req_data['page']) ? $this->_req_data['page'] : $this->page_slug;
170
+		$this->_cpt_routes = array_merge(array(
171
+			'create_new' => $this->page_slug,
172
+			'edit'       => $this->page_slug,
173
+			'trash'      => $this->page_slug,
174
+		), $this->_cpt_routes);
175
+		//let's see if the current route has a value for cpt_object_slug if it does we use that instead of the page
176
+		$this->_cpt_object = isset($this->_req_data['action']) && isset($this->_cpt_routes[$this->_req_data['action']])
177
+			? get_post_type_object($this->_cpt_routes[$this->_req_data['action']])
178
+			: get_post_type_object($page);
179
+		//tweak pagenow for page loading.
180
+		if ( ! $this->_pagenow_map) {
181
+			$this->_pagenow_map = array(
182
+				'create_new' => 'post-new.php',
183
+				'edit'       => 'post.php',
184
+				'trash'      => 'post.php',
185
+			);
186
+		}
187
+		add_action('current_screen', array($this, 'modify_pagenow'));
188
+		//TODO the below will need to be reworked to account for the cpt routes that are NOT based off of page but action param.
189
+		//get current page from autosave
190
+		$current_page = isset($this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page'])
191
+			? $this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page']
192
+			: null;
193
+		$this->_current_page = isset($this->_req_data['current_page'])
194
+			? $this->_req_data['current_page']
195
+			: $current_page;
196
+		//autosave... make sure its only for the correct page
197
+		if ( ! empty($this->_current_page) && $this->_current_page == $this->page_slug) {
198
+			//setup autosave ajax hook
199
+			//add_action('wp_ajax_ee-autosave', array( $this, 'do_extra_autosave_stuff' ), 10 ); //TODO reactivate when 4.2 autosave is implemented
200
+		}
201
+	}
202
+
203
+
204
+
205
+	/**
206
+	 * Simply ensure that we simulate the correct post route for cpt screens
207
+	 *
208
+	 * @param WP_Screen $current_screen
209
+	 * @return void
210
+	 */
211
+	public function modify_pagenow($current_screen)
212
+	{
213
+		global $pagenow, $hook_suffix;
214
+		//possibly reset pagenow.
215
+		if ( ! empty($this->_req_data['page'])
216
+			 && $this->_req_data['page'] == $this->page_slug
217
+			 && ! empty($this->_req_data['action'])
218
+			 && isset($this->_pagenow_map[$this->_req_data['action']])
219
+		) {
220
+			$pagenow = $this->_pagenow_map[$this->_req_data['action']];
221
+			$hook_suffix = $pagenow;
222
+		}
223
+	}
224
+
225
+
226
+
227
+	/**
228
+	 * This method is used to register additional autosave containers to the _autosave_containers property.
229
+	 *
230
+	 * @todo We should automate this at some point by creating a wrapper for add_post_metabox and in our wrapper we
231
+	 *       automatically register the id for the post metabox as a container.
232
+	 * @param  array $ids an array of ids for containers that hold form inputs we want autosave to pickup.  Typically
233
+	 *                    you would send along the id of a metabox container.
234
+	 * @return void
235
+	 */
236
+	protected function _register_autosave_containers($ids)
237
+	{
238
+		$this->_autosave_containers = array_merge($this->_autosave_fields, (array)$ids);
239
+	}
240
+
241
+
242
+
243
+	/**
244
+	 * Something nifty.  We're going to loop through all the registered metaboxes and if the CALLBACK is an instance of
245
+	 * EE_Admin_Page OR EE_Admin_Hooks, then we'll add the id to our _autosave_containers array.
246
+	 */
247
+	protected function _set_autosave_containers()
248
+	{
249
+		global $wp_meta_boxes;
250
+		$containers = array();
251
+		if (empty($wp_meta_boxes)) {
252
+			return;
253
+		}
254
+		$current_metaboxes = isset($wp_meta_boxes[$this->page_slug]) ? $wp_meta_boxes[$this->page_slug] : array();
255
+		foreach ($current_metaboxes as $box_context) {
256
+			foreach ($box_context as $box_details) {
257
+				foreach ($box_details as $box) {
258
+					if (is_array($box['callback'])
259
+						&& ($box['callback'][0] instanceof EE_Admin_Page
260
+							|| $box['callback'][0] instanceof EE_Admin_Hooks)
261
+					) {
262
+						$containers[] = $box['id'];
263
+					}
264
+				}
265
+			}
266
+		}
267
+		$this->_autosave_containers = array_merge($this->_autosave_containers, $containers);
268
+		//add hidden inputs container
269
+		$this->_autosave_containers[] = 'ee-cpt-hidden-inputs';
270
+	}
271
+
272
+
273
+
274
+	protected function _load_autosave_scripts_styles()
275
+	{
276
+		/*wp_register_script('cpt-autosave', EE_ADMIN_URL . 'assets/ee-cpt-autosave.js', array('ee-serialize-full-array', 'event_editor_js'), EVENT_ESPRESSO_VERSION, TRUE );
277 277
         wp_enqueue_script('cpt-autosave');/**/ //todo re-enable when we start doing autosave again in 4.2
278 278
 
279
-        //filter _autosave_containers
280
-        $containers = apply_filters('FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
281
-            $this->_autosave_containers, $this);
282
-        $containers = apply_filters('FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
283
-            $containers, $this);
284
-
285
-        wp_localize_script('event_editor_js', 'EE_AUTOSAVE_IDS',
286
-            $containers); //todo once we enable autosaves, this needs to be switched to localize with "cpt-autosave"
287
-
288
-        $unsaved_data_msg = array(
289
-            'eventmsg'     => sprintf(__("The changes you made to this %s will be lost if you navigate away from this page.",
290
-                'event_espresso'), $this->_cpt_object->labels->singular_name),
291
-            'inputChanged' => 0,
292
-        );
293
-        wp_localize_script('event_editor_js', 'UNSAVED_DATA_MSG', $unsaved_data_msg);
294
-    }
295
-
296
-
297
-
298
-    public function load_page_dependencies()
299
-    {
300
-        try {
301
-            $this->_load_page_dependencies();
302
-        } catch (EE_Error $e) {
303
-            $e->get_error();
304
-        }
305
-    }
306
-
307
-
308
-
309
-    /**
310
-     * overloading the EE_Admin_Page parent load_page_dependencies so we can get the cpt stuff added in appropriately
311
-     *
312
-     * @access protected
313
-     * @return void
314
-     */
315
-    protected function _load_page_dependencies()
316
-    {
317
-        //we only add stuff if this is a cpt_route!
318
-        if ( ! $this->_cpt_route) {
319
-            parent::_load_page_dependencies();
320
-            return;
321
-        }
322
-        //now let's do some automatic filters into the wp_system and we'll check to make sure the CHILD class automatically has the required methods in place.
323
-        //the following filters are for setting all the redirects on DEFAULT WP custom post type actions
324
-        //let's add a hidden input to the post-edit form so we know when we have to trigger our custom redirects!  Otherwise the redirects will happen on ALL post saves which wouldn't be good of course!
325
-        add_action('edit_form_after_title', array($this, 'cpt_post_form_hidden_input'));
326
-        //inject our Admin page nav tabs...
327
-        //let's make sure the nav tabs are set if they aren't already
328
-        //if ( empty( $this->_nav_tabs ) ) $this->_set_nav_tabs();
329
-        add_action('post_edit_form_tag', array($this, 'inject_nav_tabs'));
330
-        //modify the post_updated messages array
331
-        add_action('post_updated_messages', array($this, 'post_update_messages'), 10);
332
-        //add shortlink button to cpt edit screens.  We can do this as a universal thing BECAUSE, cpts use the same format for shortlinks as posts!
333
-        add_filter('pre_get_shortlink', array($this, 'add_shortlink_button_to_editor'), 10, 4);
334
-        //This basically allows us to change the title of the "publish" metabox area on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
335
-        if ( ! empty($this->_labels['publishbox'])) {
336
-            $box_label = is_array($this->_labels['publishbox'])
337
-                         && isset($this->_labels['publishbox'][$this->_req_action])
338
-                ? $this->_labels['publishbox'][$this->_req_action] : $this->_labels['publishbox'];
339
-            remove_meta_box('submitdiv', __('Publish'), 'post_submit_meta_box', $this->_cpt_routes[$this->_req_action],
340
-                'side', 'core');
341
-            add_meta_box('submitdiv', $box_label, 'post_submit_meta_box', $this->_cpt_routes[$this->_req_action],
342
-                'side', 'core');
343
-        }
344
-        //let's add page_templates metabox if this cpt added support for it.
345
-        if ($this->_supports_page_templates($this->_cpt_object->name)) {
346
-            add_meta_box('page_templates', __('Page Template', 'event_espresso'),
347
-                array($this, 'page_template_meta_box'), $this->_cpt_routes[$this->_req_action], 'side', 'default');
348
-        }
349
-        //this is a filter that allows the addition of extra html after the permalink field on the wp post edit-form
350
-        if (method_exists($this, 'extra_permalink_field_buttons')) {
351
-            add_filter('get_sample_permalink_html', array($this, 'extra_permalink_field_buttons'), 10, 4);
352
-        }
353
-        //add preview button
354
-        add_filter('get_sample_permalink_html', array($this, 'preview_button_html'), 5, 4);
355
-        //insert our own post_stati dropdown
356
-        add_action('post_submitbox_misc_actions', array($this, 'custom_post_stati_dropdown'), 10);
357
-        //This allows adding additional information to the publish post submitbox on the wp post edit form
358
-        if (method_exists($this, 'extra_misc_actions_publish_box')) {
359
-            add_action('post_submitbox_misc_actions', array($this, 'extra_misc_actions_publish_box'), 10);
360
-        }
361
-        //This allows for adding additional stuff after the title field on the wp post edit form.  This is also before the wp_editor for post description field.
362
-        if (method_exists($this, 'edit_form_after_title')) {
363
-            add_action('edit_form_after_title', array($this, 'edit_form_after_title'), 10);
364
-        }
365
-        /**
366
-         * Filtering WP's esc_url to capture urls pointing to core wp routes so they point to our route.
367
-         */
368
-        add_filter('clean_url', array($this, 'switch_core_wp_urls_with_ours'), 10, 3);
369
-        parent::_load_page_dependencies();
370
-        //notice we are ALSO going to load the pagenow hook set for this route (see _before_page_setup for the reset of the pagenow global ). This is for any plugins that are doing things properly and hooking into the load page hook for core wp cpt routes.
371
-        global $pagenow;
372
-        do_action('load-' . $pagenow);
373
-        $this->modify_current_screen();
374
-        add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
375
-        //we route REALLY early.
376
-        try {
377
-            $this->_route_admin_request();
378
-        } catch (EE_Error $e) {
379
-            $e->get_error();
380
-        }
381
-    }
382
-
383
-
384
-
385
-    /**
386
-     * Since we don't want users going to default core wp routes, this will check any wp urls run through the
387
-     * esc_url() method and if we see a url matching a pattern for our routes, we'll modify it to point to OUR
388
-     * route instead.
389
-     *
390
-     * @param string $good_protocol_url The escaped url.
391
-     * @param string $original_url      The original url.
392
-     * @param string $_context          The context sendt to the esc_url method.
393
-     * @return string possibly a new url for our route.
394
-     */
395
-    public function switch_core_wp_urls_with_ours($good_protocol_url, $original_url, $_context)
396
-    {
397
-        $routes_to_match = array(
398
-            0 => array(
399
-                'edit.php?post_type=espresso_attendees',
400
-                'admin.php?page=espresso_registrations&action=contact_list',
401
-            ),
402
-            1 => array(
403
-                'edit.php?post_type=' . $this->_cpt_object->name,
404
-                'admin.php?page=' . $this->_cpt_object->name,
405
-            ),
406
-        );
407
-        foreach ($routes_to_match as $route_matches) {
408
-            if (strpos($good_protocol_url, $route_matches[0]) !== false) {
409
-                return str_replace($route_matches[0], $route_matches[1], $good_protocol_url);
410
-            }
411
-        }
412
-        return $good_protocol_url;
413
-    }
414
-
415
-
416
-
417
-    /**
418
-     * Determine whether the current cpt supports page templates or not.
419
-     *
420
-     * @since %VER%
421
-     * @param string $cpt_name The cpt slug we're checking on.
422
-     * @return bool True supported, false not.
423
-     */
424
-    private function _supports_page_templates($cpt_name)
425
-    {
426
-
427
-        $cpt_args = EE_Register_CPTs::get_CPTs();
428
-        $cpt_args = isset($cpt_args[$cpt_name]) ? $cpt_args[$cpt_name]['args'] : array();
429
-        $cpt_has_support = ! empty($cpt_args['page_templates']);
430
-
431
-        //if the installed version of WP is > 4.7 we do some additional checks.
432
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
433
-            $post_templates = wp_get_theme()->get_post_templates();
434
-            //if there are $post_templates for this cpt, then we return false for this method because
435
-            //that means we aren't going to load our page template manager and leave that up to the native
436
-            //cpt template manager.
437
-            $cpt_has_support = ! isset($post_templates[$cpt_name]) ? $cpt_has_support : false;
438
-        }
439
-
440
-        return $cpt_has_support;
441
-    }
442
-
443
-
444
-    /**
445
-     * Callback for the page_templates metabox selector.
446
-     *
447
-     * @since %VER%
448
-     * @return string html
449
-     */
450
-    public function page_template_meta_box()
451
-    {
452
-        global $post;
453
-        $template = '';
454
-
455
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
456
-            $page_template_count = count(get_page_templates());
457
-        } else {
458
-            $page_template_count = count(get_page_templates($post));
459
-        };
460
-
461
-        if ($page_template_count) {
462
-            $page_template = get_post_meta($post->ID, '_wp_page_template', true);
463
-            $template      = ! empty($page_template) ? $page_template : '';
464
-        }
465
-        ?>
279
+		//filter _autosave_containers
280
+		$containers = apply_filters('FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
281
+			$this->_autosave_containers, $this);
282
+		$containers = apply_filters('FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
283
+			$containers, $this);
284
+
285
+		wp_localize_script('event_editor_js', 'EE_AUTOSAVE_IDS',
286
+			$containers); //todo once we enable autosaves, this needs to be switched to localize with "cpt-autosave"
287
+
288
+		$unsaved_data_msg = array(
289
+			'eventmsg'     => sprintf(__("The changes you made to this %s will be lost if you navigate away from this page.",
290
+				'event_espresso'), $this->_cpt_object->labels->singular_name),
291
+			'inputChanged' => 0,
292
+		);
293
+		wp_localize_script('event_editor_js', 'UNSAVED_DATA_MSG', $unsaved_data_msg);
294
+	}
295
+
296
+
297
+
298
+	public function load_page_dependencies()
299
+	{
300
+		try {
301
+			$this->_load_page_dependencies();
302
+		} catch (EE_Error $e) {
303
+			$e->get_error();
304
+		}
305
+	}
306
+
307
+
308
+
309
+	/**
310
+	 * overloading the EE_Admin_Page parent load_page_dependencies so we can get the cpt stuff added in appropriately
311
+	 *
312
+	 * @access protected
313
+	 * @return void
314
+	 */
315
+	protected function _load_page_dependencies()
316
+	{
317
+		//we only add stuff if this is a cpt_route!
318
+		if ( ! $this->_cpt_route) {
319
+			parent::_load_page_dependencies();
320
+			return;
321
+		}
322
+		//now let's do some automatic filters into the wp_system and we'll check to make sure the CHILD class automatically has the required methods in place.
323
+		//the following filters are for setting all the redirects on DEFAULT WP custom post type actions
324
+		//let's add a hidden input to the post-edit form so we know when we have to trigger our custom redirects!  Otherwise the redirects will happen on ALL post saves which wouldn't be good of course!
325
+		add_action('edit_form_after_title', array($this, 'cpt_post_form_hidden_input'));
326
+		//inject our Admin page nav tabs...
327
+		//let's make sure the nav tabs are set if they aren't already
328
+		//if ( empty( $this->_nav_tabs ) ) $this->_set_nav_tabs();
329
+		add_action('post_edit_form_tag', array($this, 'inject_nav_tabs'));
330
+		//modify the post_updated messages array
331
+		add_action('post_updated_messages', array($this, 'post_update_messages'), 10);
332
+		//add shortlink button to cpt edit screens.  We can do this as a universal thing BECAUSE, cpts use the same format for shortlinks as posts!
333
+		add_filter('pre_get_shortlink', array($this, 'add_shortlink_button_to_editor'), 10, 4);
334
+		//This basically allows us to change the title of the "publish" metabox area on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
335
+		if ( ! empty($this->_labels['publishbox'])) {
336
+			$box_label = is_array($this->_labels['publishbox'])
337
+						 && isset($this->_labels['publishbox'][$this->_req_action])
338
+				? $this->_labels['publishbox'][$this->_req_action] : $this->_labels['publishbox'];
339
+			remove_meta_box('submitdiv', __('Publish'), 'post_submit_meta_box', $this->_cpt_routes[$this->_req_action],
340
+				'side', 'core');
341
+			add_meta_box('submitdiv', $box_label, 'post_submit_meta_box', $this->_cpt_routes[$this->_req_action],
342
+				'side', 'core');
343
+		}
344
+		//let's add page_templates metabox if this cpt added support for it.
345
+		if ($this->_supports_page_templates($this->_cpt_object->name)) {
346
+			add_meta_box('page_templates', __('Page Template', 'event_espresso'),
347
+				array($this, 'page_template_meta_box'), $this->_cpt_routes[$this->_req_action], 'side', 'default');
348
+		}
349
+		//this is a filter that allows the addition of extra html after the permalink field on the wp post edit-form
350
+		if (method_exists($this, 'extra_permalink_field_buttons')) {
351
+			add_filter('get_sample_permalink_html', array($this, 'extra_permalink_field_buttons'), 10, 4);
352
+		}
353
+		//add preview button
354
+		add_filter('get_sample_permalink_html', array($this, 'preview_button_html'), 5, 4);
355
+		//insert our own post_stati dropdown
356
+		add_action('post_submitbox_misc_actions', array($this, 'custom_post_stati_dropdown'), 10);
357
+		//This allows adding additional information to the publish post submitbox on the wp post edit form
358
+		if (method_exists($this, 'extra_misc_actions_publish_box')) {
359
+			add_action('post_submitbox_misc_actions', array($this, 'extra_misc_actions_publish_box'), 10);
360
+		}
361
+		//This allows for adding additional stuff after the title field on the wp post edit form.  This is also before the wp_editor for post description field.
362
+		if (method_exists($this, 'edit_form_after_title')) {
363
+			add_action('edit_form_after_title', array($this, 'edit_form_after_title'), 10);
364
+		}
365
+		/**
366
+		 * Filtering WP's esc_url to capture urls pointing to core wp routes so they point to our route.
367
+		 */
368
+		add_filter('clean_url', array($this, 'switch_core_wp_urls_with_ours'), 10, 3);
369
+		parent::_load_page_dependencies();
370
+		//notice we are ALSO going to load the pagenow hook set for this route (see _before_page_setup for the reset of the pagenow global ). This is for any plugins that are doing things properly and hooking into the load page hook for core wp cpt routes.
371
+		global $pagenow;
372
+		do_action('load-' . $pagenow);
373
+		$this->modify_current_screen();
374
+		add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
375
+		//we route REALLY early.
376
+		try {
377
+			$this->_route_admin_request();
378
+		} catch (EE_Error $e) {
379
+			$e->get_error();
380
+		}
381
+	}
382
+
383
+
384
+
385
+	/**
386
+	 * Since we don't want users going to default core wp routes, this will check any wp urls run through the
387
+	 * esc_url() method and if we see a url matching a pattern for our routes, we'll modify it to point to OUR
388
+	 * route instead.
389
+	 *
390
+	 * @param string $good_protocol_url The escaped url.
391
+	 * @param string $original_url      The original url.
392
+	 * @param string $_context          The context sendt to the esc_url method.
393
+	 * @return string possibly a new url for our route.
394
+	 */
395
+	public function switch_core_wp_urls_with_ours($good_protocol_url, $original_url, $_context)
396
+	{
397
+		$routes_to_match = array(
398
+			0 => array(
399
+				'edit.php?post_type=espresso_attendees',
400
+				'admin.php?page=espresso_registrations&action=contact_list',
401
+			),
402
+			1 => array(
403
+				'edit.php?post_type=' . $this->_cpt_object->name,
404
+				'admin.php?page=' . $this->_cpt_object->name,
405
+			),
406
+		);
407
+		foreach ($routes_to_match as $route_matches) {
408
+			if (strpos($good_protocol_url, $route_matches[0]) !== false) {
409
+				return str_replace($route_matches[0], $route_matches[1], $good_protocol_url);
410
+			}
411
+		}
412
+		return $good_protocol_url;
413
+	}
414
+
415
+
416
+
417
+	/**
418
+	 * Determine whether the current cpt supports page templates or not.
419
+	 *
420
+	 * @since %VER%
421
+	 * @param string $cpt_name The cpt slug we're checking on.
422
+	 * @return bool True supported, false not.
423
+	 */
424
+	private function _supports_page_templates($cpt_name)
425
+	{
426
+
427
+		$cpt_args = EE_Register_CPTs::get_CPTs();
428
+		$cpt_args = isset($cpt_args[$cpt_name]) ? $cpt_args[$cpt_name]['args'] : array();
429
+		$cpt_has_support = ! empty($cpt_args['page_templates']);
430
+
431
+		//if the installed version of WP is > 4.7 we do some additional checks.
432
+		if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
433
+			$post_templates = wp_get_theme()->get_post_templates();
434
+			//if there are $post_templates for this cpt, then we return false for this method because
435
+			//that means we aren't going to load our page template manager and leave that up to the native
436
+			//cpt template manager.
437
+			$cpt_has_support = ! isset($post_templates[$cpt_name]) ? $cpt_has_support : false;
438
+		}
439
+
440
+		return $cpt_has_support;
441
+	}
442
+
443
+
444
+	/**
445
+	 * Callback for the page_templates metabox selector.
446
+	 *
447
+	 * @since %VER%
448
+	 * @return string html
449
+	 */
450
+	public function page_template_meta_box()
451
+	{
452
+		global $post;
453
+		$template = '';
454
+
455
+		if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
456
+			$page_template_count = count(get_page_templates());
457
+		} else {
458
+			$page_template_count = count(get_page_templates($post));
459
+		};
460
+
461
+		if ($page_template_count) {
462
+			$page_template = get_post_meta($post->ID, '_wp_page_template', true);
463
+			$template      = ! empty($page_template) ? $page_template : '';
464
+		}
465
+		?>
466 466
         <p><strong><?php _e('Template') ?></strong></p>
467 467
         <label class="screen-reader-text" for="page_template"><?php _e('Page Template') ?></label><select
468 468
             name="page_template" id="page_template">
@@ -470,435 +470,435 @@  discard block
 block discarded – undo
470 470
         <?php page_template_dropdown($template); ?>
471 471
     </select>
472 472
         <?php
473
-    }
474
-
475
-
476
-
477
-    /**
478
-     * if this post is a draft or scheduled post then we provide a preview button for user to click
479
-     * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
480
-     *
481
-     * @param  string $return    the current html
482
-     * @param  int    $id        the post id for the page
483
-     * @param  string $new_title What the title is
484
-     * @param  string $new_slug  what the slug is
485
-     * @return string            The new html string for the permalink area
486
-     */
487
-    public function preview_button_html($return, $id, $new_title, $new_slug)
488
-    {
489
-        $post = get_post($id);
490
-        if ('publish' != get_post_status($post)) {
491
-            $return .= '<span_id="view-post-btn"><a target="_blank" href="'
492
-                       . get_preview_post_link($id)
493
-                       . '" class="button button-small">'
494
-                       . __('Preview', 'event_espresso')
495
-                       . '</a></span>'
496
-                       . "\n";
497
-        }
498
-        return $return;
499
-    }
500
-
501
-
502
-
503
-    /**
504
-     * add our custom post stati dropdown on the wp post page for this cpt
505
-     *
506
-     * @return string html for dropdown
507
-     */
508
-    public function custom_post_stati_dropdown()
509
-    {
510
-
511
-        $statuses         = $this->_cpt_model_obj->get_custom_post_statuses();
512
-        $cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
513
-            ? $statuses[$this->_cpt_model_obj->status()]
514
-            : '';
515
-        $template_args    = array(
516
-            'cur_status'            => $this->_cpt_model_obj->status(),
517
-            'statuses'              => $statuses,
518
-            'cur_status_label'      => $cur_status_label,
519
-            'localized_status_save' => sprintf(__('Save %s', 'event_espresso'), $cur_status_label),
520
-        );
521
-        //we'll add a trash post status (WP doesn't add one for some reason)
522
-        if ($this->_cpt_model_obj->status() == 'trash') {
523
-            $template_args['cur_status_label'] = __('Trashed', 'event_espresso');
524
-            $statuses['trash']                 = __('Trashed', 'event_espresso');
525
-            $template_args['statuses']         = $statuses;
526
-        }
527
-
528
-        $template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
529
-        EEH_Template::display_template($template, $template_args);
530
-    }
531
-
532
-
533
-
534
-    public function setup_autosave_hooks()
535
-    {
536
-        $this->_set_autosave_containers();
537
-        $this->_load_autosave_scripts_styles();
538
-    }
539
-
540
-
541
-
542
-    /**
543
-     * This is run on all WordPress autosaves AFTER the autosave is complete and sends along a $_POST object (available
544
-     * in $this->_req_data) containing: post_ID of the saved post autosavenonce for the saved post We'll do the check
545
-     * for the nonce in here, but then this method looks for two things:
546
-     * 1. Execute a method (if exists) matching 'ee_autosave_' and appended with the given route. OR
547
-     * 2. do_actions() for global or class specific actions that have been registered (for plugins/addons not in an
548
-     * EE_Admin_Page class. PLEASE NOTE: Data will be returned using the _return_json() object and so the
549
-     * $_template_args property should be used to hold the $data array.  We're expecting the following things set in
550
-     * template args.
551
-     *    1. $template_args['error'] = IF there is an error you can add the message in here.
552
-     *    2. $template_args['data']['items'] = an array of items that are setup in key index pairs of 'where_values_go'
553
-     *    => 'values_to_add'.  In other words, for the datetime metabox we'll have something like
554
-     *    $this->_template_args['data']['items'] = array(
555
-     *        'event-datetime-ids' => '1,2,3';
556
-     *    );
557
-     *    Keep in mind the following things:
558
-     *    - "where" index is for the input with the id as that string.
559
-     *    - "what" index is what will be used for the value of that input.
560
-     *
561
-     * @return void
562
-     */
563
-    public function do_extra_autosave_stuff()
564
-    {
565
-        //next let's check for the autosave nonce (we'll use _verify_nonce )
566
-        $nonce = isset($this->_req_data['autosavenonce']) ? $this->_req_data['autosavenonce'] : null;
567
-        $this->_verify_nonce($nonce, 'autosave');
568
-        //make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
569
-        if ( ! defined('DOING_AUTOSAVE')) {
570
-            define('DOING_AUTOSAVE', true);
571
-        }
572
-        //if we made it here then the nonce checked out.  Let's run our methods and actions
573
-        if (method_exists($this, '_ee_autosave_' . $this->_current_view)) {
574
-            call_user_func(array($this, '_ee_autosave_' . $this->_current_view));
575
-        } else {
576
-            $this->_template_args['success'] = true;
577
-        }
578
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
579
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
580
-        //now let's return json
581
-        $this->_return_json();
582
-    }
583
-
584
-
585
-
586
-    /**
587
-     * This takes care of setting up default routes and pages that utilize the core WP admin pages.
588
-     * Child classes can override the defaults (in cases for adding metaboxes etc.)
589
-     * but take care that you include the defaults here otherwise your core WP admin pages for the cpt won't work!
590
-     *
591
-     * @access protected
592
-     * @throws EE_Error
593
-     * @return void
594
-     */
595
-    protected function _extend_page_config_for_cpt()
596
-    {
597
-        //before doing anything we need to make sure this runs ONLY when the loaded page matches the set page_slug
598
-        if ((isset($this->_req_data['page']) && $this->_req_data['page'] != $this->page_slug)) {
599
-            return;
600
-        }
601
-        //set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
602
-        if ( ! empty($this->_cpt_object)) {
603
-            $this->_page_routes = array_merge(array(
604
-                'create_new' => '_create_new_cpt_item',
605
-                'edit'       => '_edit_cpt_item',
606
-            ), $this->_page_routes);
607
-            $this->_page_config = array_merge(array(
608
-                'create_new' => array(
609
-                    'nav'           => array(
610
-                        'label' => $this->_cpt_object->labels->add_new_item,
611
-                        'order' => 5,
612
-                    ),
613
-                    'require_nonce' => false,
614
-                ),
615
-                'edit'       => array(
616
-                    'nav'           => array(
617
-                        'label'      => $this->_cpt_object->labels->edit_item,
618
-                        'order'      => 5,
619
-                        'persistent' => false,
620
-                        'url'        => '',
621
-                    ),
622
-                    'require_nonce' => false,
623
-                ),
624
-            ),
625
-                $this->_page_config
626
-            );
627
-        }
628
-        //load the next section only if this is a matching cpt route as set in the cpt routes array.
629
-        if ( ! isset($this->_cpt_routes[$this->_req_action])) {
630
-            return;
631
-        }
632
-        $this->_cpt_route = isset($this->_cpt_routes[$this->_req_action]) ? true : false;
633
-        //add_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', array( $this, 'modify_current_screen') );
634
-        if (empty($this->_cpt_object)) {
635
-            $msg = sprintf(__('This page has been set as being related to a registered custom post type, however, the custom post type object could not be retrieved. There are two possible reasons for this:  1. The "%s" does not match a registered post type. or 2. The custom post type is not registered for the "%s" action as indexed in the "$_cpt_routes" property on this class (%s).'),
636
-                $this->page_slug, $this->_req_action, get_class($this));
637
-            throw new EE_Error($msg);
638
-        }
639
-        if ($this->_cpt_route) {
640
-            $id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
641
-            $this->_set_model_object($id);
642
-        }
643
-    }
644
-
645
-
646
-
647
-    /**
648
-     * Sets the _cpt_model_object property using what has been set for the _cpt_model_name and a given id.
649
-     *
650
-     * @access protected
651
-     * @param int  $id The id to retrieve the model object for. If empty we set a default object.
652
-     * @param bool $ignore_route_check
653
-     */
654
-    protected function _set_model_object($id = null, $ignore_route_check = false)
655
-    {
656
-        $model = null;
657
-        if (
658
-            empty($this->_cpt_model_names)
659
-            || (
660
-                ! $ignore_route_check
661
-                && ! isset($this->_cpt_routes[$this->_req_action])
662
-            ) || (
663
-                $this->_cpt_model_obj instanceof EE_CPT_Base
664
-                && $this->_cpt_model_obj->ID() === $id
665
-            )
666
-        ) {
667
-            //get out cuz we either don't have a model name OR the object has already been set and it has the same id as what has been sent.
668
-            return;
669
-        }
670
-        //if ignore_route_check is true, then get the model name via EE_Register_CPTs
671
-        if ($ignore_route_check) {
672
-            $model_names = EE_Register_CPTs::get_cpt_model_names();
673
-            $post_type   = get_post_type($id);
674
-            if (isset($model_names[$post_type])) {
675
-                $model = EE_Registry::instance()->load_model($model_names[$post_type]);
676
-            }
677
-        } else {
678
-            $model = EE_Registry::instance()->load_model($this->_cpt_model_names[$this->_req_action]);
679
-        }
680
-        if ($model instanceof EEM_Base) {
681
-            $this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
682
-        }
683
-        do_action('AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object');
684
-    }
685
-
686
-
687
-
688
-    /**
689
-     * admin_init_global
690
-     * This runs all the code that we want executed within the WP admin_init hook.
691
-     * This method executes for ALL EE Admin pages.
692
-     *
693
-     * @access public
694
-     * @return void
695
-     */
696
-    public function admin_init_global()
697
-    {
698
-        $post = isset($this->_req_data['post']) ? get_post($this->_req_data['post']) : null;
699
-        //its possible this is a new save so let's catch that instead
700
-        $post = isset($this->_req_data['post_ID']) ? get_post($this->_req_data['post_ID']) : $post;
701
-        $post_type = $post ? $post->post_type : false;
702
-        $current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route']
703
-            : 'shouldneverwork';
704
-        $route_to_check = $post_type && isset($this->_cpt_routes[$current_route]) ? $this->_cpt_routes[$current_route]
705
-            : '';
706
-        add_filter('get_delete_post_link', array($this, 'modify_delete_post_link'), 10, 3);
707
-        add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 3);
708
-        if ($post_type === $route_to_check) {
709
-            add_filter('redirect_post_location', array($this, 'cpt_post_location_redirect'), 10, 2);
710
-            //catch trashed wp redirect
711
-            add_filter('wp_redirect', array($this, 'cpt_trash_post_location_redirect'), 10, 2);
712
-        }
713
-        //now let's filter redirect if we're on a revision page and the revision is for an event CPT.
714
-        $revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
715
-        if ( ! empty($revision)) {
716
-            $action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
717
-            //doing a restore?
718
-            if ( ! empty($action) && $action == 'restore') {
719
-                //get post for revision
720
-                $rev_post = get_post($revision);
721
-                $rev_parent = get_post($rev_post->post_parent);
722
-                //only do our redirect filter AND our restore revision action if the post_type for the parent is one of our cpts.
723
-                if ($rev_parent && $rev_parent->post_type == $this->page_slug) {
724
-                    add_filter('wp_redirect', array($this, 'revision_redirect'), 10, 2);
725
-                    //restores of revisions
726
-                    add_action('wp_restore_post_revision', array($this, 'restore_revision'), 10, 2);
727
-                }
728
-            }
729
-        }
730
-        //NOTE we ONLY want to run these hooks if we're on the right class for the given post type.  Otherwise we could see some really freaky things happen!
731
-        if ($post_type && $post_type === $route_to_check) {
732
-            //$post_id, $post
733
-            add_action('save_post', array($this, 'insert_update'), 10, 3);
734
-            //$post_id
735
-            add_action('trashed_post', array($this, 'before_trash_cpt_item'), 10);
736
-            add_action('trashed_post', array($this, 'dont_permanently_delete_ee_cpts'), 10);
737
-            add_action('untrashed_post', array($this, 'before_restore_cpt_item'), 10);
738
-            add_action('after_delete_post', array($this, 'before_delete_cpt_item'), 10);
739
-        }
740
-    }
741
-
742
-
743
-
744
-    /**
745
-     * Callback for the WordPress trashed_post hook.
746
-     * Execute some basic checks before calling the trash_cpt_item declared in the child class.
747
-     *
748
-     * @param int $post_id
749
-     */
750
-    public function before_trash_cpt_item($post_id)
751
-    {
752
-        $this->_set_model_object($post_id, true);
753
-        //if our cpt object isn't existent then get out immediately.
754
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
755
-            return;
756
-        }
757
-        $this->trash_cpt_item($post_id);
758
-    }
759
-
760
-
761
-
762
-    /**
763
-     * Callback for the WordPress untrashed_post hook.
764
-     * Execute some basic checks before calling the restore_cpt_method in the child class.
765
-     *
766
-     * @param $post_id
767
-     */
768
-    public function before_restore_cpt_item($post_id)
769
-    {
770
-        $this->_set_model_object($post_id, true);
771
-        //if our cpt object isn't existent then get out immediately.
772
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
773
-            return;
774
-        }
775
-        $this->restore_cpt_item($post_id);
776
-    }
777
-
778
-
779
-
780
-    /**
781
-     * Callback for the WordPress after_delete_post hook.
782
-     * Execute some basic checks before calling the delete_cpt_item method in the child class.
783
-     *
784
-     * @param $post_id
785
-     */
786
-    public function before_delete_cpt_item($post_id)
787
-    {
788
-        $this->_set_model_object($post_id, true);
789
-        //if our cpt object isn't existent then get out immediately.
790
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
791
-            return;
792
-        }
793
-        $this->delete_cpt_item($post_id);
794
-    }
795
-
796
-
797
-
798
-    /**
799
-     * This simply verifies if the cpt_model_object is instantiated for the given page and throws an error message
800
-     * accordingly.
801
-     *
802
-     * @access public
803
-     * @throws EE_Error
804
-     * @return void
805
-     */
806
-    public function verify_cpt_object()
807
-    {
808
-        $label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
809
-        // verify event object
810
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
811
-            throw new EE_Error(sprintf(__('Something has gone wrong with the page load because we are unable to set up the object for the %1$s.  This usually happens when the given id for the page route is NOT for the correct custom post type for this page',
812
-                'event_espresso'), $label));
813
-        }
814
-        //if auto-draft then throw an error
815
-        if ($this->_cpt_model_obj->get('status') == 'auto-draft') {
816
-            EE_Error::overwrite_errors();
817
-            EE_Error::add_error(sprintf(__('This %1$s was saved without a title, description, or excerpt which means that none of the extra details you added were saved properly.  All autodrafts will show up in the "draft" view of your event list table.  You can delete them from there. Please click the "Add %1$s" button to refresh and restart.'),
818
-                $label), __FILE__, __FUNCTION__, __LINE__);
819
-        }
820
-    }
821
-
822
-
823
-
824
-    /**
825
-     * admin_footer_scripts_global
826
-     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
827
-     * will apply on ALL EE_Admin pages.
828
-     *
829
-     * @access public
830
-     * @return void
831
-     */
832
-    public function admin_footer_scripts_global()
833
-    {
834
-        $this->_add_admin_page_ajax_loading_img();
835
-        $this->_add_admin_page_overlay();
836
-    }
837
-
838
-
839
-
840
-    /**
841
-     * add in any global scripts for cpt routes
842
-     *
843
-     * @return void
844
-     */
845
-    public function load_global_scripts_styles()
846
-    {
847
-        parent::load_global_scripts_styles();
848
-        if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
849
-            //setup custom post status object for localize script but only if we've got a cpt object
850
-            $statuses = $this->_cpt_model_obj->get_custom_post_statuses();
851
-            if ( ! empty($statuses)) {
852
-                //get ALL statuses!
853
-                $statuses = $this->_cpt_model_obj->get_all_post_statuses();
854
-                //setup object
855
-                $ee_cpt_statuses = array();
856
-                foreach ($statuses as $status => $label) {
857
-                    $ee_cpt_statuses[$status] = array(
858
-                        'label'      => $label,
859
-                        'save_label' => sprintf(__('Save as %s', 'event_espresso'), $label),
860
-                    );
861
-                }
862
-                wp_localize_script('ee_admin_js', 'eeCPTstatuses', $ee_cpt_statuses);
863
-            }
864
-        }
865
-    }
866
-
867
-
868
-
869
-    /**
870
-     * This is a wrapper for the insert/update routes for cpt items so we can add things that are common to ALL
871
-     * insert/updates
872
-     *
873
-     * @param  int     $post_id ID of post being updated
874
-     * @param  WP_Post $post    Post object from WP
875
-     * @param  bool    $update  Whether this is an update or a new save.
876
-     * @return void
877
-     */
878
-    public function insert_update($post_id, $post, $update)
879
-    {
880
-        //make sure that if this is a revision OR trash action that we don't do any updates!
881
-        if (
882
-            isset($this->_req_data['action'])
883
-            && (
884
-                $this->_req_data['action'] == 'restore'
885
-                || $this->_req_data['action'] == 'trash'
886
-            )
887
-        ) {
888
-            return;
889
-        }
890
-        $this->_set_model_object($post_id, true);
891
-        //if our cpt object is not instantiated and its NOT the same post_id as what is triggering this callback, then exit.
892
-        if ($update
893
-            && (
894
-                ! $this->_cpt_model_obj instanceof EE_CPT_Base
895
-                || $this->_cpt_model_obj->ID() !== $post_id
896
-            )
897
-        ) {
898
-            return;
899
-        }
900
-        //check for autosave and update our req_data property accordingly.
901
-        /*if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE && isset( $this->_req_data['ee_autosave_data'] ) ) {
473
+	}
474
+
475
+
476
+
477
+	/**
478
+	 * if this post is a draft or scheduled post then we provide a preview button for user to click
479
+	 * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
480
+	 *
481
+	 * @param  string $return    the current html
482
+	 * @param  int    $id        the post id for the page
483
+	 * @param  string $new_title What the title is
484
+	 * @param  string $new_slug  what the slug is
485
+	 * @return string            The new html string for the permalink area
486
+	 */
487
+	public function preview_button_html($return, $id, $new_title, $new_slug)
488
+	{
489
+		$post = get_post($id);
490
+		if ('publish' != get_post_status($post)) {
491
+			$return .= '<span_id="view-post-btn"><a target="_blank" href="'
492
+					   . get_preview_post_link($id)
493
+					   . '" class="button button-small">'
494
+					   . __('Preview', 'event_espresso')
495
+					   . '</a></span>'
496
+					   . "\n";
497
+		}
498
+		return $return;
499
+	}
500
+
501
+
502
+
503
+	/**
504
+	 * add our custom post stati dropdown on the wp post page for this cpt
505
+	 *
506
+	 * @return string html for dropdown
507
+	 */
508
+	public function custom_post_stati_dropdown()
509
+	{
510
+
511
+		$statuses         = $this->_cpt_model_obj->get_custom_post_statuses();
512
+		$cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
513
+			? $statuses[$this->_cpt_model_obj->status()]
514
+			: '';
515
+		$template_args    = array(
516
+			'cur_status'            => $this->_cpt_model_obj->status(),
517
+			'statuses'              => $statuses,
518
+			'cur_status_label'      => $cur_status_label,
519
+			'localized_status_save' => sprintf(__('Save %s', 'event_espresso'), $cur_status_label),
520
+		);
521
+		//we'll add a trash post status (WP doesn't add one for some reason)
522
+		if ($this->_cpt_model_obj->status() == 'trash') {
523
+			$template_args['cur_status_label'] = __('Trashed', 'event_espresso');
524
+			$statuses['trash']                 = __('Trashed', 'event_espresso');
525
+			$template_args['statuses']         = $statuses;
526
+		}
527
+
528
+		$template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
529
+		EEH_Template::display_template($template, $template_args);
530
+	}
531
+
532
+
533
+
534
+	public function setup_autosave_hooks()
535
+	{
536
+		$this->_set_autosave_containers();
537
+		$this->_load_autosave_scripts_styles();
538
+	}
539
+
540
+
541
+
542
+	/**
543
+	 * This is run on all WordPress autosaves AFTER the autosave is complete and sends along a $_POST object (available
544
+	 * in $this->_req_data) containing: post_ID of the saved post autosavenonce for the saved post We'll do the check
545
+	 * for the nonce in here, but then this method looks for two things:
546
+	 * 1. Execute a method (if exists) matching 'ee_autosave_' and appended with the given route. OR
547
+	 * 2. do_actions() for global or class specific actions that have been registered (for plugins/addons not in an
548
+	 * EE_Admin_Page class. PLEASE NOTE: Data will be returned using the _return_json() object and so the
549
+	 * $_template_args property should be used to hold the $data array.  We're expecting the following things set in
550
+	 * template args.
551
+	 *    1. $template_args['error'] = IF there is an error you can add the message in here.
552
+	 *    2. $template_args['data']['items'] = an array of items that are setup in key index pairs of 'where_values_go'
553
+	 *    => 'values_to_add'.  In other words, for the datetime metabox we'll have something like
554
+	 *    $this->_template_args['data']['items'] = array(
555
+	 *        'event-datetime-ids' => '1,2,3';
556
+	 *    );
557
+	 *    Keep in mind the following things:
558
+	 *    - "where" index is for the input with the id as that string.
559
+	 *    - "what" index is what will be used for the value of that input.
560
+	 *
561
+	 * @return void
562
+	 */
563
+	public function do_extra_autosave_stuff()
564
+	{
565
+		//next let's check for the autosave nonce (we'll use _verify_nonce )
566
+		$nonce = isset($this->_req_data['autosavenonce']) ? $this->_req_data['autosavenonce'] : null;
567
+		$this->_verify_nonce($nonce, 'autosave');
568
+		//make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
569
+		if ( ! defined('DOING_AUTOSAVE')) {
570
+			define('DOING_AUTOSAVE', true);
571
+		}
572
+		//if we made it here then the nonce checked out.  Let's run our methods and actions
573
+		if (method_exists($this, '_ee_autosave_' . $this->_current_view)) {
574
+			call_user_func(array($this, '_ee_autosave_' . $this->_current_view));
575
+		} else {
576
+			$this->_template_args['success'] = true;
577
+		}
578
+		do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
579
+		do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
580
+		//now let's return json
581
+		$this->_return_json();
582
+	}
583
+
584
+
585
+
586
+	/**
587
+	 * This takes care of setting up default routes and pages that utilize the core WP admin pages.
588
+	 * Child classes can override the defaults (in cases for adding metaboxes etc.)
589
+	 * but take care that you include the defaults here otherwise your core WP admin pages for the cpt won't work!
590
+	 *
591
+	 * @access protected
592
+	 * @throws EE_Error
593
+	 * @return void
594
+	 */
595
+	protected function _extend_page_config_for_cpt()
596
+	{
597
+		//before doing anything we need to make sure this runs ONLY when the loaded page matches the set page_slug
598
+		if ((isset($this->_req_data['page']) && $this->_req_data['page'] != $this->page_slug)) {
599
+			return;
600
+		}
601
+		//set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
602
+		if ( ! empty($this->_cpt_object)) {
603
+			$this->_page_routes = array_merge(array(
604
+				'create_new' => '_create_new_cpt_item',
605
+				'edit'       => '_edit_cpt_item',
606
+			), $this->_page_routes);
607
+			$this->_page_config = array_merge(array(
608
+				'create_new' => array(
609
+					'nav'           => array(
610
+						'label' => $this->_cpt_object->labels->add_new_item,
611
+						'order' => 5,
612
+					),
613
+					'require_nonce' => false,
614
+				),
615
+				'edit'       => array(
616
+					'nav'           => array(
617
+						'label'      => $this->_cpt_object->labels->edit_item,
618
+						'order'      => 5,
619
+						'persistent' => false,
620
+						'url'        => '',
621
+					),
622
+					'require_nonce' => false,
623
+				),
624
+			),
625
+				$this->_page_config
626
+			);
627
+		}
628
+		//load the next section only if this is a matching cpt route as set in the cpt routes array.
629
+		if ( ! isset($this->_cpt_routes[$this->_req_action])) {
630
+			return;
631
+		}
632
+		$this->_cpt_route = isset($this->_cpt_routes[$this->_req_action]) ? true : false;
633
+		//add_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', array( $this, 'modify_current_screen') );
634
+		if (empty($this->_cpt_object)) {
635
+			$msg = sprintf(__('This page has been set as being related to a registered custom post type, however, the custom post type object could not be retrieved. There are two possible reasons for this:  1. The "%s" does not match a registered post type. or 2. The custom post type is not registered for the "%s" action as indexed in the "$_cpt_routes" property on this class (%s).'),
636
+				$this->page_slug, $this->_req_action, get_class($this));
637
+			throw new EE_Error($msg);
638
+		}
639
+		if ($this->_cpt_route) {
640
+			$id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
641
+			$this->_set_model_object($id);
642
+		}
643
+	}
644
+
645
+
646
+
647
+	/**
648
+	 * Sets the _cpt_model_object property using what has been set for the _cpt_model_name and a given id.
649
+	 *
650
+	 * @access protected
651
+	 * @param int  $id The id to retrieve the model object for. If empty we set a default object.
652
+	 * @param bool $ignore_route_check
653
+	 */
654
+	protected function _set_model_object($id = null, $ignore_route_check = false)
655
+	{
656
+		$model = null;
657
+		if (
658
+			empty($this->_cpt_model_names)
659
+			|| (
660
+				! $ignore_route_check
661
+				&& ! isset($this->_cpt_routes[$this->_req_action])
662
+			) || (
663
+				$this->_cpt_model_obj instanceof EE_CPT_Base
664
+				&& $this->_cpt_model_obj->ID() === $id
665
+			)
666
+		) {
667
+			//get out cuz we either don't have a model name OR the object has already been set and it has the same id as what has been sent.
668
+			return;
669
+		}
670
+		//if ignore_route_check is true, then get the model name via EE_Register_CPTs
671
+		if ($ignore_route_check) {
672
+			$model_names = EE_Register_CPTs::get_cpt_model_names();
673
+			$post_type   = get_post_type($id);
674
+			if (isset($model_names[$post_type])) {
675
+				$model = EE_Registry::instance()->load_model($model_names[$post_type]);
676
+			}
677
+		} else {
678
+			$model = EE_Registry::instance()->load_model($this->_cpt_model_names[$this->_req_action]);
679
+		}
680
+		if ($model instanceof EEM_Base) {
681
+			$this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
682
+		}
683
+		do_action('AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object');
684
+	}
685
+
686
+
687
+
688
+	/**
689
+	 * admin_init_global
690
+	 * This runs all the code that we want executed within the WP admin_init hook.
691
+	 * This method executes for ALL EE Admin pages.
692
+	 *
693
+	 * @access public
694
+	 * @return void
695
+	 */
696
+	public function admin_init_global()
697
+	{
698
+		$post = isset($this->_req_data['post']) ? get_post($this->_req_data['post']) : null;
699
+		//its possible this is a new save so let's catch that instead
700
+		$post = isset($this->_req_data['post_ID']) ? get_post($this->_req_data['post_ID']) : $post;
701
+		$post_type = $post ? $post->post_type : false;
702
+		$current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route']
703
+			: 'shouldneverwork';
704
+		$route_to_check = $post_type && isset($this->_cpt_routes[$current_route]) ? $this->_cpt_routes[$current_route]
705
+			: '';
706
+		add_filter('get_delete_post_link', array($this, 'modify_delete_post_link'), 10, 3);
707
+		add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 3);
708
+		if ($post_type === $route_to_check) {
709
+			add_filter('redirect_post_location', array($this, 'cpt_post_location_redirect'), 10, 2);
710
+			//catch trashed wp redirect
711
+			add_filter('wp_redirect', array($this, 'cpt_trash_post_location_redirect'), 10, 2);
712
+		}
713
+		//now let's filter redirect if we're on a revision page and the revision is for an event CPT.
714
+		$revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
715
+		if ( ! empty($revision)) {
716
+			$action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
717
+			//doing a restore?
718
+			if ( ! empty($action) && $action == 'restore') {
719
+				//get post for revision
720
+				$rev_post = get_post($revision);
721
+				$rev_parent = get_post($rev_post->post_parent);
722
+				//only do our redirect filter AND our restore revision action if the post_type for the parent is one of our cpts.
723
+				if ($rev_parent && $rev_parent->post_type == $this->page_slug) {
724
+					add_filter('wp_redirect', array($this, 'revision_redirect'), 10, 2);
725
+					//restores of revisions
726
+					add_action('wp_restore_post_revision', array($this, 'restore_revision'), 10, 2);
727
+				}
728
+			}
729
+		}
730
+		//NOTE we ONLY want to run these hooks if we're on the right class for the given post type.  Otherwise we could see some really freaky things happen!
731
+		if ($post_type && $post_type === $route_to_check) {
732
+			//$post_id, $post
733
+			add_action('save_post', array($this, 'insert_update'), 10, 3);
734
+			//$post_id
735
+			add_action('trashed_post', array($this, 'before_trash_cpt_item'), 10);
736
+			add_action('trashed_post', array($this, 'dont_permanently_delete_ee_cpts'), 10);
737
+			add_action('untrashed_post', array($this, 'before_restore_cpt_item'), 10);
738
+			add_action('after_delete_post', array($this, 'before_delete_cpt_item'), 10);
739
+		}
740
+	}
741
+
742
+
743
+
744
+	/**
745
+	 * Callback for the WordPress trashed_post hook.
746
+	 * Execute some basic checks before calling the trash_cpt_item declared in the child class.
747
+	 *
748
+	 * @param int $post_id
749
+	 */
750
+	public function before_trash_cpt_item($post_id)
751
+	{
752
+		$this->_set_model_object($post_id, true);
753
+		//if our cpt object isn't existent then get out immediately.
754
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
755
+			return;
756
+		}
757
+		$this->trash_cpt_item($post_id);
758
+	}
759
+
760
+
761
+
762
+	/**
763
+	 * Callback for the WordPress untrashed_post hook.
764
+	 * Execute some basic checks before calling the restore_cpt_method in the child class.
765
+	 *
766
+	 * @param $post_id
767
+	 */
768
+	public function before_restore_cpt_item($post_id)
769
+	{
770
+		$this->_set_model_object($post_id, true);
771
+		//if our cpt object isn't existent then get out immediately.
772
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
773
+			return;
774
+		}
775
+		$this->restore_cpt_item($post_id);
776
+	}
777
+
778
+
779
+
780
+	/**
781
+	 * Callback for the WordPress after_delete_post hook.
782
+	 * Execute some basic checks before calling the delete_cpt_item method in the child class.
783
+	 *
784
+	 * @param $post_id
785
+	 */
786
+	public function before_delete_cpt_item($post_id)
787
+	{
788
+		$this->_set_model_object($post_id, true);
789
+		//if our cpt object isn't existent then get out immediately.
790
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
791
+			return;
792
+		}
793
+		$this->delete_cpt_item($post_id);
794
+	}
795
+
796
+
797
+
798
+	/**
799
+	 * This simply verifies if the cpt_model_object is instantiated for the given page and throws an error message
800
+	 * accordingly.
801
+	 *
802
+	 * @access public
803
+	 * @throws EE_Error
804
+	 * @return void
805
+	 */
806
+	public function verify_cpt_object()
807
+	{
808
+		$label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
809
+		// verify event object
810
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
811
+			throw new EE_Error(sprintf(__('Something has gone wrong with the page load because we are unable to set up the object for the %1$s.  This usually happens when the given id for the page route is NOT for the correct custom post type for this page',
812
+				'event_espresso'), $label));
813
+		}
814
+		//if auto-draft then throw an error
815
+		if ($this->_cpt_model_obj->get('status') == 'auto-draft') {
816
+			EE_Error::overwrite_errors();
817
+			EE_Error::add_error(sprintf(__('This %1$s was saved without a title, description, or excerpt which means that none of the extra details you added were saved properly.  All autodrafts will show up in the "draft" view of your event list table.  You can delete them from there. Please click the "Add %1$s" button to refresh and restart.'),
818
+				$label), __FILE__, __FUNCTION__, __LINE__);
819
+		}
820
+	}
821
+
822
+
823
+
824
+	/**
825
+	 * admin_footer_scripts_global
826
+	 * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
827
+	 * will apply on ALL EE_Admin pages.
828
+	 *
829
+	 * @access public
830
+	 * @return void
831
+	 */
832
+	public function admin_footer_scripts_global()
833
+	{
834
+		$this->_add_admin_page_ajax_loading_img();
835
+		$this->_add_admin_page_overlay();
836
+	}
837
+
838
+
839
+
840
+	/**
841
+	 * add in any global scripts for cpt routes
842
+	 *
843
+	 * @return void
844
+	 */
845
+	public function load_global_scripts_styles()
846
+	{
847
+		parent::load_global_scripts_styles();
848
+		if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
849
+			//setup custom post status object for localize script but only if we've got a cpt object
850
+			$statuses = $this->_cpt_model_obj->get_custom_post_statuses();
851
+			if ( ! empty($statuses)) {
852
+				//get ALL statuses!
853
+				$statuses = $this->_cpt_model_obj->get_all_post_statuses();
854
+				//setup object
855
+				$ee_cpt_statuses = array();
856
+				foreach ($statuses as $status => $label) {
857
+					$ee_cpt_statuses[$status] = array(
858
+						'label'      => $label,
859
+						'save_label' => sprintf(__('Save as %s', 'event_espresso'), $label),
860
+					);
861
+				}
862
+				wp_localize_script('ee_admin_js', 'eeCPTstatuses', $ee_cpt_statuses);
863
+			}
864
+		}
865
+	}
866
+
867
+
868
+
869
+	/**
870
+	 * This is a wrapper for the insert/update routes for cpt items so we can add things that are common to ALL
871
+	 * insert/updates
872
+	 *
873
+	 * @param  int     $post_id ID of post being updated
874
+	 * @param  WP_Post $post    Post object from WP
875
+	 * @param  bool    $update  Whether this is an update or a new save.
876
+	 * @return void
877
+	 */
878
+	public function insert_update($post_id, $post, $update)
879
+	{
880
+		//make sure that if this is a revision OR trash action that we don't do any updates!
881
+		if (
882
+			isset($this->_req_data['action'])
883
+			&& (
884
+				$this->_req_data['action'] == 'restore'
885
+				|| $this->_req_data['action'] == 'trash'
886
+			)
887
+		) {
888
+			return;
889
+		}
890
+		$this->_set_model_object($post_id, true);
891
+		//if our cpt object is not instantiated and its NOT the same post_id as what is triggering this callback, then exit.
892
+		if ($update
893
+			&& (
894
+				! $this->_cpt_model_obj instanceof EE_CPT_Base
895
+				|| $this->_cpt_model_obj->ID() !== $post_id
896
+			)
897
+		) {
898
+			return;
899
+		}
900
+		//check for autosave and update our req_data property accordingly.
901
+		/*if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE && isset( $this->_req_data['ee_autosave_data'] ) ) {
902 902
             foreach( (array) $this->_req_data['ee_autosave_data'] as $id => $values ) {
903 903
 
904 904
                 foreach ( (array) $values as $key => $value ) {
@@ -908,536 +908,536 @@  discard block
 block discarded – undo
908 908
 
909 909
         }/**/ //TODO reactivate after autosave is implemented in 4.2
910 910
 
911
-        //take care of updating any selected page_template IF this cpt supports it.
912
-        if ($this->_supports_page_templates($post->post_type) && ! empty($this->_req_data['page_template'])) {
913
-            //wp version aware.
914
-            if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
915
-                $page_templates = wp_get_theme()->get_page_templates();
916
-            } else {
917
-                $post->page_template = $this->_req_data['page_template'];
918
-                $page_templates      = wp_get_theme()->get_page_templates($post);
919
-            }
920
-            if ('default' != $this->_req_data['page_template'] && ! isset($page_templates[$this->_req_data['page_template']])) {
921
-                EE_Error::add_error(__('Invalid Page Template.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
922
-            } else {
923
-                update_post_meta($post_id, '_wp_page_template', $this->_req_data['page_template']);
924
-            }
925
-        }
926
-        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
927
-            return;
928
-        } //TODO we'll remove this after reimplementing autosave in 4.2
929
-        $this->_insert_update_cpt_item($post_id, $post);
930
-    }
931
-
932
-
933
-
934
-    /**
935
-     * This hooks into the wp_trash_post() function and removes the `_wp_trash_meta_status` and `_wp_trash_meta_time`
936
-     * post meta IF the trashed post is one of our CPT's - note this method should only be called with our cpt routes
937
-     * so we don't have to check for our CPT.
938
-     *
939
-     * @param  int $post_id ID of the post
940
-     * @return void
941
-     */
942
-    public function dont_permanently_delete_ee_cpts($post_id)
943
-    {
944
-        //only do this if we're actually processing one of our CPTs
945
-        //if our cpt object isn't existent then get out immediately.
946
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
947
-            return;
948
-        }
949
-        delete_post_meta($post_id, '_wp_trash_meta_status');
950
-        delete_post_meta($post_id, '_wp_trash_meta_time');
951
-        //our cpts may have comments so let's take care of that too
952
-        delete_post_meta($post_id, '_wp_trash_meta_comments_status');
953
-    }
954
-
955
-
956
-
957
-    /**
958
-     * This is a wrapper for the restore_cpt_revision route for cpt items so we can make sure that when a revision is
959
-     * triggered that we restore related items.  In order to work cpt classes MUST have a restore_cpt_revision method
960
-     * in them.  We also have our OWN action in here so addons can hook into the restore process easily.
961
-     *
962
-     * @param  int $post_id     ID of cpt item
963
-     * @param  int $revision_id ID of revision being restored
964
-     * @return void
965
-     */
966
-    public function restore_revision($post_id, $revision_id)
967
-    {
968
-        $this->_restore_cpt_item($post_id, $revision_id);
969
-        //global action
970
-        do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
971
-        //class specific action so you can limit hooking into a specific page.
972
-        do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
973
-    }
974
-
975
-
976
-
977
-    /**
978
-     * @see restore_revision() for details
979
-     * @param  int $post_id     ID of cpt item
980
-     * @param  int $revision_id ID of revision for item
981
-     * @return void
982
-     */
983
-    abstract protected function _restore_cpt_item($post_id, $revision_id);
984
-
985
-
986
-
987
-    /**
988
-     * Execution of this method is added to the end of the load_page_dependencies method in the parent
989
-     * so that we can fix a bug where default core metaboxes were not being called in the sidebar.
990
-     * To fix we have to reset the current_screen using the page_slug
991
-     * (which is identical - or should be - to our registered_post_type id.)
992
-     * Also, since the core WP file loads the admin_header.php for WP
993
-     * (and there are a bunch of other things edit-form-advanced.php loads that need to happen really early)
994
-     * we need to load it NOW, hence our _route_admin_request in here. (Otherwise screen options won't be set).
995
-     *
996
-     * @return void
997
-     */
998
-    public function modify_current_screen()
999
-    {
1000
-        //ONLY do this if the current page_route IS a cpt route
1001
-        if ( ! $this->_cpt_route) {
1002
-            return;
1003
-        }
1004
-        //routing things REALLY early b/c this is a cpt admin page
1005
-        set_current_screen($this->_cpt_routes[$this->_req_action]);
1006
-        $this->_current_screen       = get_current_screen();
1007
-        $this->_current_screen->base = 'event-espresso';
1008
-        $this->_add_help_tabs(); //we make sure we add any help tabs back in!
1009
-        /*try {
911
+		//take care of updating any selected page_template IF this cpt supports it.
912
+		if ($this->_supports_page_templates($post->post_type) && ! empty($this->_req_data['page_template'])) {
913
+			//wp version aware.
914
+			if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
915
+				$page_templates = wp_get_theme()->get_page_templates();
916
+			} else {
917
+				$post->page_template = $this->_req_data['page_template'];
918
+				$page_templates      = wp_get_theme()->get_page_templates($post);
919
+			}
920
+			if ('default' != $this->_req_data['page_template'] && ! isset($page_templates[$this->_req_data['page_template']])) {
921
+				EE_Error::add_error(__('Invalid Page Template.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
922
+			} else {
923
+				update_post_meta($post_id, '_wp_page_template', $this->_req_data['page_template']);
924
+			}
925
+		}
926
+		if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
927
+			return;
928
+		} //TODO we'll remove this after reimplementing autosave in 4.2
929
+		$this->_insert_update_cpt_item($post_id, $post);
930
+	}
931
+
932
+
933
+
934
+	/**
935
+	 * This hooks into the wp_trash_post() function and removes the `_wp_trash_meta_status` and `_wp_trash_meta_time`
936
+	 * post meta IF the trashed post is one of our CPT's - note this method should only be called with our cpt routes
937
+	 * so we don't have to check for our CPT.
938
+	 *
939
+	 * @param  int $post_id ID of the post
940
+	 * @return void
941
+	 */
942
+	public function dont_permanently_delete_ee_cpts($post_id)
943
+	{
944
+		//only do this if we're actually processing one of our CPTs
945
+		//if our cpt object isn't existent then get out immediately.
946
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
947
+			return;
948
+		}
949
+		delete_post_meta($post_id, '_wp_trash_meta_status');
950
+		delete_post_meta($post_id, '_wp_trash_meta_time');
951
+		//our cpts may have comments so let's take care of that too
952
+		delete_post_meta($post_id, '_wp_trash_meta_comments_status');
953
+	}
954
+
955
+
956
+
957
+	/**
958
+	 * This is a wrapper for the restore_cpt_revision route for cpt items so we can make sure that when a revision is
959
+	 * triggered that we restore related items.  In order to work cpt classes MUST have a restore_cpt_revision method
960
+	 * in them.  We also have our OWN action in here so addons can hook into the restore process easily.
961
+	 *
962
+	 * @param  int $post_id     ID of cpt item
963
+	 * @param  int $revision_id ID of revision being restored
964
+	 * @return void
965
+	 */
966
+	public function restore_revision($post_id, $revision_id)
967
+	{
968
+		$this->_restore_cpt_item($post_id, $revision_id);
969
+		//global action
970
+		do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
971
+		//class specific action so you can limit hooking into a specific page.
972
+		do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
973
+	}
974
+
975
+
976
+
977
+	/**
978
+	 * @see restore_revision() for details
979
+	 * @param  int $post_id     ID of cpt item
980
+	 * @param  int $revision_id ID of revision for item
981
+	 * @return void
982
+	 */
983
+	abstract protected function _restore_cpt_item($post_id, $revision_id);
984
+
985
+
986
+
987
+	/**
988
+	 * Execution of this method is added to the end of the load_page_dependencies method in the parent
989
+	 * so that we can fix a bug where default core metaboxes were not being called in the sidebar.
990
+	 * To fix we have to reset the current_screen using the page_slug
991
+	 * (which is identical - or should be - to our registered_post_type id.)
992
+	 * Also, since the core WP file loads the admin_header.php for WP
993
+	 * (and there are a bunch of other things edit-form-advanced.php loads that need to happen really early)
994
+	 * we need to load it NOW, hence our _route_admin_request in here. (Otherwise screen options won't be set).
995
+	 *
996
+	 * @return void
997
+	 */
998
+	public function modify_current_screen()
999
+	{
1000
+		//ONLY do this if the current page_route IS a cpt route
1001
+		if ( ! $this->_cpt_route) {
1002
+			return;
1003
+		}
1004
+		//routing things REALLY early b/c this is a cpt admin page
1005
+		set_current_screen($this->_cpt_routes[$this->_req_action]);
1006
+		$this->_current_screen       = get_current_screen();
1007
+		$this->_current_screen->base = 'event-espresso';
1008
+		$this->_add_help_tabs(); //we make sure we add any help tabs back in!
1009
+		/*try {
1010 1010
             $this->_route_admin_request();
1011 1011
         } catch ( EE_Error $e ) {
1012 1012
             $e->get_error();
1013 1013
         }/**/
1014
-    }
1015
-
1016
-
1017
-
1018
-    /**
1019
-     * This allows child classes to modify the default editor title that appears when people add a new or edit an
1020
-     * existing CPT item.     * This uses the _labels property set by the child class via _define_page_props. Just make
1021
-     * sure you have a key in _labels property that equals 'editor_title' and the value can be whatever you want the
1022
-     * default to be.
1023
-     *
1024
-     * @param string $title The new title (or existing if there is no editor_title defined)
1025
-     * @return string
1026
-     */
1027
-    public function add_custom_editor_default_title($title)
1028
-    {
1029
-        return isset($this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]])
1030
-            ? $this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]]
1031
-            : $title;
1032
-    }
1033
-
1034
-
1035
-
1036
-    /**
1037
-     * hooks into the wp_get_shortlink button and makes sure that the shortlink gets generated
1038
-     *
1039
-     * @param string $shortlink   The already generated shortlink
1040
-     * @param int    $id          Post ID for this item
1041
-     * @param string $context     The context for the link
1042
-     * @param bool   $allow_slugs Whether to allow post slugs in the shortlink.
1043
-     * @return string
1044
-     */
1045
-    public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1046
-    {
1047
-        if ( ! empty($id) && '' != get_option('permalink_structure')) {
1048
-            $post = get_post($id);
1049
-            if (isset($post->post_type) && $this->page_slug == $post->post_type) {
1050
-                $shortlink = home_url('?p=' . $post->ID);
1051
-            }
1052
-        }
1053
-        return $shortlink;
1054
-    }
1055
-
1056
-
1057
-
1058
-    /**
1059
-     * overriding the parent route_admin_request method so we DON'T run the route twice on cpt core page loads (it's
1060
-     * already run in modify_current_screen())
1061
-     *
1062
-     * @return void
1063
-     */
1064
-    public function route_admin_request()
1065
-    {
1066
-        if ($this->_cpt_route) {
1067
-            return;
1068
-        }
1069
-        try {
1070
-            $this->_route_admin_request();
1071
-        } catch (EE_Error $e) {
1072
-            $e->get_error();
1073
-        }
1074
-    }
1075
-
1076
-
1077
-
1078
-    /**
1079
-     * Add a hidden form input to cpt core pages so that we know to do redirects to our routes on saves
1080
-     *
1081
-     * @return string html
1082
-     */
1083
-    public function cpt_post_form_hidden_input()
1084
-    {
1085
-        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1086
-        //we're also going to add the route value and the current page so we can direct autosave parsing correctly
1087
-        echo '<div id="ee-cpt-hidden-inputs">';
1088
-        echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1089
-        echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1090
-        echo '</div>';
1091
-    }
1092
-
1093
-
1094
-
1095
-    /**
1096
-     * This allows us to redirect the location of revision restores when they happen so it goes to our CPT routes.
1097
-     *
1098
-     * @param  string $location Original location url
1099
-     * @param  int    $status   Status for http header
1100
-     * @return string           new (or original) url to redirect to.
1101
-     */
1102
-    public function revision_redirect($location, $status)
1103
-    {
1104
-        //get revision
1105
-        $rev_id = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
1106
-        //can't do anything without revision so let's get out if not present
1107
-        if (empty($rev_id)) {
1108
-            return $location;
1109
-        }
1110
-        //get rev_post_data
1111
-        $rev = get_post($rev_id);
1112
-        $admin_url = $this->_admin_base_url;
1113
-        $query_args = array(
1114
-            'action'   => 'edit',
1115
-            'post'     => $rev->post_parent,
1116
-            'revision' => $rev_id,
1117
-            'message'  => 5,
1118
-        );
1119
-        $this->_process_notices($query_args, true);
1120
-        return self::add_query_args_and_nonce($query_args, $admin_url);
1121
-    }
1122
-
1123
-
1124
-
1125
-    /**
1126
-     * Modify the edit post link generated by wp core function so that EE CPTs get setup differently.
1127
-     *
1128
-     * @param  string $link    the original generated link
1129
-     * @param  int    $id      post id
1130
-     * @param  string $context optional, defaults to display.  How to write the '&'
1131
-     * @return string          the link
1132
-     */
1133
-    public function modify_edit_post_link($link, $id, $context)
1134
-    {
1135
-        $post = get_post($id);
1136
-        if ( ! isset($this->_req_data['action'])
1137
-             || ! isset($this->_cpt_routes[$this->_req_data['action']])
1138
-             || $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1139
-        ) {
1140
-            return $link;
1141
-        }
1142
-        $query_args = array(
1143
-            'action' => isset($this->_cpt_edit_routes[$post->post_type])
1144
-                ? $this->_cpt_edit_routes[$post->post_type]
1145
-                : 'edit',
1146
-            'post'   => $id,
1147
-        );
1148
-        return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1149
-    }
1150
-
1151
-
1152
-
1153
-    /**
1154
-     * Modify the trash link on our cpt edit pages so it has the required query var for triggering redirect properly on
1155
-     * our routes.
1156
-     *
1157
-     * @param  string $delete_link  original delete link
1158
-     * @param  int    $post_id      id of cpt object
1159
-     * @param  bool   $force_delete whether this is forcing a hard delete instead of trash
1160
-     * @return string               new delete link
1161
-     */
1162
-    public function modify_delete_post_link($delete_link, $post_id, $force_delete)
1163
-    {
1164
-        $post = get_post($post_id);
1165
-        if ( ! isset($this->_req_data['action'])
1166
-             || (isset($this->_cpt_routes[$this->_req_data['action']])
1167
-                 && $post->post_type !== $this->_cpt_routes[$this->_req_data['action']])
1168
-        ) {
1169
-            return $delete_link;
1170
-        }
1171
-        return add_query_arg(array('current_route' => 'trash'), $delete_link);
1172
-    }
1173
-
1174
-
1175
-
1176
-    /**
1177
-     * This hooks into the wp_redirect filter and if trashed is detected, then we'll redirect to the appropriate EE
1178
-     * route
1179
-     *
1180
-     * @param  string $location url
1181
-     * @param  string $status   status
1182
-     * @return string           url to redirect to
1183
-     */
1184
-    public function cpt_trash_post_location_redirect($location, $status)
1185
-    {
1186
-        if (isset($this->_req_data['action']) && $this->_req_data['action'] !== 'trash' && empty($this->_req_data['post'])) {
1187
-            return $location;
1188
-        }
1189
-
1190
-        $post              = get_post($this->_req_data['post']);
1191
-        $query_args        = array('action' => 'default');
1192
-        $this->_cpt_object = get_post_type_object($post->post_type);
1193
-        EE_Error::add_success(sprintf(__('%s trashed.', 'event_espresso'), $this->_cpt_object->labels->singular_name));
1194
-        $this->_process_notices($query_args, true);
1195
-        return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1196
-    }
1197
-
1198
-
1199
-
1200
-    /**
1201
-     * This is the callback for the 'redirect_post_location' filter in wp-admin/post.php
1202
-     * so that we can hijack the default redirect locations for wp custom post types
1203
-     * that WE'RE using and send back to OUR routes.  This should only be hooked in on the right route.
1204
-     *
1205
-     * @param  string $location This is the incoming currently set redirect location
1206
-     * @param  string $post_id  This is the 'ID' value of the wp_posts table
1207
-     * @return string           the new location to redirect to
1208
-     */
1209
-    public function cpt_post_location_redirect($location, $post_id)
1210
-    {
1211
-        //we DO have a match so let's setup the url
1212
-        //we have to get the post to determine our route
1213
-        $post       = get_post($post_id);
1214
-        $edit_route = $this->_cpt_edit_routes[$post->post_type];
1215
-        //shared query_args
1216
-        $query_args = array('action' => $edit_route, 'post' => $post_id);
1217
-        $admin_url  = $this->_admin_base_url;
1218
-        if (isset($this->_req_data['save']) || isset($this->_req_data['publish'])) {
1219
-            $status = get_post_status($post_id);
1220
-            if (isset($this->_req_data['publish'])) {
1221
-                switch ($status) {
1222
-                    case 'pending':
1223
-                        $message = 8;
1224
-                        break;
1225
-                    case 'future':
1226
-                        $message = 9;
1227
-                        break;
1228
-                    default:
1229
-                        $message = 6;
1230
-                }
1231
-            } else {
1232
-                $message = 'draft' == $status ? 10 : 1;
1233
-            }
1234
-        } else if (isset($this->_req_data['addmeta']) && $this->_req_data['addmeta']) {
1235
-            $message = 2;
1236
-            //			$append = '#postcustom';
1237
-        } else if (isset($this->_req_data['deletemeta']) && $this->_req_data['deletemeta']) {
1238
-            $message = 3;
1239
-            //			$append = '#postcustom';
1240
-        } elseif ($this->_req_data['action'] == 'post-quickpress-save-cont') {
1241
-            $message = 7;
1242
-        } else {
1243
-            $message = 4;
1244
-        }
1245
-        //change the message if the post type is not viewable on the frontend
1246
-        $this->_cpt_object = get_post_type_object($post->post_type);
1247
-        $message           = $message === 1 && ! $this->_cpt_object->publicly_queryable ? 4 : $message;
1248
-        $query_args = array_merge(array('message' => $message), $query_args);
1249
-        $this->_process_notices($query_args, true);
1250
-        return self::add_query_args_and_nonce($query_args, $admin_url);
1251
-    }
1252
-
1253
-
1254
-
1255
-    /**
1256
-     * This method is called to inject nav tabs on core WP cpt pages
1257
-     *
1258
-     * @access public
1259
-     * @return string html
1260
-     */
1261
-    public function inject_nav_tabs()
1262
-    {
1263
-        //can we hijack and insert the nav_tabs?
1264
-        $nav_tabs = $this->_get_main_nav_tabs();
1265
-        //first close off existing form tag
1266
-        $html = '>';
1267
-        $html .= $nav_tabs;
1268
-        //now let's handle the remaining tag ( missing ">" is CORRECT )
1269
-        $html .= '<span></span';
1270
-        echo $html;
1271
-    }
1272
-
1273
-
1274
-
1275
-    /**
1276
-     * This just sets up the post update messages when an update form is loaded
1277
-     *
1278
-     * @access public
1279
-     * @param  array $messages the original messages array
1280
-     * @return array           the new messages array
1281
-     */
1282
-    public function post_update_messages($messages)
1283
-    {
1284
-        global $post;
1285
-        $id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1286
-        $id = empty($id) && is_object($post) ? $post->ID : null;
1287
-        //		$post_type = $post ? $post->post_type : false;
1288
-        /*$current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route'] : 'shouldneverwork';
1014
+	}
1015
+
1016
+
1017
+
1018
+	/**
1019
+	 * This allows child classes to modify the default editor title that appears when people add a new or edit an
1020
+	 * existing CPT item.     * This uses the _labels property set by the child class via _define_page_props. Just make
1021
+	 * sure you have a key in _labels property that equals 'editor_title' and the value can be whatever you want the
1022
+	 * default to be.
1023
+	 *
1024
+	 * @param string $title The new title (or existing if there is no editor_title defined)
1025
+	 * @return string
1026
+	 */
1027
+	public function add_custom_editor_default_title($title)
1028
+	{
1029
+		return isset($this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]])
1030
+			? $this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]]
1031
+			: $title;
1032
+	}
1033
+
1034
+
1035
+
1036
+	/**
1037
+	 * hooks into the wp_get_shortlink button and makes sure that the shortlink gets generated
1038
+	 *
1039
+	 * @param string $shortlink   The already generated shortlink
1040
+	 * @param int    $id          Post ID for this item
1041
+	 * @param string $context     The context for the link
1042
+	 * @param bool   $allow_slugs Whether to allow post slugs in the shortlink.
1043
+	 * @return string
1044
+	 */
1045
+	public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1046
+	{
1047
+		if ( ! empty($id) && '' != get_option('permalink_structure')) {
1048
+			$post = get_post($id);
1049
+			if (isset($post->post_type) && $this->page_slug == $post->post_type) {
1050
+				$shortlink = home_url('?p=' . $post->ID);
1051
+			}
1052
+		}
1053
+		return $shortlink;
1054
+	}
1055
+
1056
+
1057
+
1058
+	/**
1059
+	 * overriding the parent route_admin_request method so we DON'T run the route twice on cpt core page loads (it's
1060
+	 * already run in modify_current_screen())
1061
+	 *
1062
+	 * @return void
1063
+	 */
1064
+	public function route_admin_request()
1065
+	{
1066
+		if ($this->_cpt_route) {
1067
+			return;
1068
+		}
1069
+		try {
1070
+			$this->_route_admin_request();
1071
+		} catch (EE_Error $e) {
1072
+			$e->get_error();
1073
+		}
1074
+	}
1075
+
1076
+
1077
+
1078
+	/**
1079
+	 * Add a hidden form input to cpt core pages so that we know to do redirects to our routes on saves
1080
+	 *
1081
+	 * @return string html
1082
+	 */
1083
+	public function cpt_post_form_hidden_input()
1084
+	{
1085
+		echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1086
+		//we're also going to add the route value and the current page so we can direct autosave parsing correctly
1087
+		echo '<div id="ee-cpt-hidden-inputs">';
1088
+		echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1089
+		echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1090
+		echo '</div>';
1091
+	}
1092
+
1093
+
1094
+
1095
+	/**
1096
+	 * This allows us to redirect the location of revision restores when they happen so it goes to our CPT routes.
1097
+	 *
1098
+	 * @param  string $location Original location url
1099
+	 * @param  int    $status   Status for http header
1100
+	 * @return string           new (or original) url to redirect to.
1101
+	 */
1102
+	public function revision_redirect($location, $status)
1103
+	{
1104
+		//get revision
1105
+		$rev_id = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
1106
+		//can't do anything without revision so let's get out if not present
1107
+		if (empty($rev_id)) {
1108
+			return $location;
1109
+		}
1110
+		//get rev_post_data
1111
+		$rev = get_post($rev_id);
1112
+		$admin_url = $this->_admin_base_url;
1113
+		$query_args = array(
1114
+			'action'   => 'edit',
1115
+			'post'     => $rev->post_parent,
1116
+			'revision' => $rev_id,
1117
+			'message'  => 5,
1118
+		);
1119
+		$this->_process_notices($query_args, true);
1120
+		return self::add_query_args_and_nonce($query_args, $admin_url);
1121
+	}
1122
+
1123
+
1124
+
1125
+	/**
1126
+	 * Modify the edit post link generated by wp core function so that EE CPTs get setup differently.
1127
+	 *
1128
+	 * @param  string $link    the original generated link
1129
+	 * @param  int    $id      post id
1130
+	 * @param  string $context optional, defaults to display.  How to write the '&'
1131
+	 * @return string          the link
1132
+	 */
1133
+	public function modify_edit_post_link($link, $id, $context)
1134
+	{
1135
+		$post = get_post($id);
1136
+		if ( ! isset($this->_req_data['action'])
1137
+			 || ! isset($this->_cpt_routes[$this->_req_data['action']])
1138
+			 || $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1139
+		) {
1140
+			return $link;
1141
+		}
1142
+		$query_args = array(
1143
+			'action' => isset($this->_cpt_edit_routes[$post->post_type])
1144
+				? $this->_cpt_edit_routes[$post->post_type]
1145
+				: 'edit',
1146
+			'post'   => $id,
1147
+		);
1148
+		return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1149
+	}
1150
+
1151
+
1152
+
1153
+	/**
1154
+	 * Modify the trash link on our cpt edit pages so it has the required query var for triggering redirect properly on
1155
+	 * our routes.
1156
+	 *
1157
+	 * @param  string $delete_link  original delete link
1158
+	 * @param  int    $post_id      id of cpt object
1159
+	 * @param  bool   $force_delete whether this is forcing a hard delete instead of trash
1160
+	 * @return string               new delete link
1161
+	 */
1162
+	public function modify_delete_post_link($delete_link, $post_id, $force_delete)
1163
+	{
1164
+		$post = get_post($post_id);
1165
+		if ( ! isset($this->_req_data['action'])
1166
+			 || (isset($this->_cpt_routes[$this->_req_data['action']])
1167
+				 && $post->post_type !== $this->_cpt_routes[$this->_req_data['action']])
1168
+		) {
1169
+			return $delete_link;
1170
+		}
1171
+		return add_query_arg(array('current_route' => 'trash'), $delete_link);
1172
+	}
1173
+
1174
+
1175
+
1176
+	/**
1177
+	 * This hooks into the wp_redirect filter and if trashed is detected, then we'll redirect to the appropriate EE
1178
+	 * route
1179
+	 *
1180
+	 * @param  string $location url
1181
+	 * @param  string $status   status
1182
+	 * @return string           url to redirect to
1183
+	 */
1184
+	public function cpt_trash_post_location_redirect($location, $status)
1185
+	{
1186
+		if (isset($this->_req_data['action']) && $this->_req_data['action'] !== 'trash' && empty($this->_req_data['post'])) {
1187
+			return $location;
1188
+		}
1189
+
1190
+		$post              = get_post($this->_req_data['post']);
1191
+		$query_args        = array('action' => 'default');
1192
+		$this->_cpt_object = get_post_type_object($post->post_type);
1193
+		EE_Error::add_success(sprintf(__('%s trashed.', 'event_espresso'), $this->_cpt_object->labels->singular_name));
1194
+		$this->_process_notices($query_args, true);
1195
+		return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1196
+	}
1197
+
1198
+
1199
+
1200
+	/**
1201
+	 * This is the callback for the 'redirect_post_location' filter in wp-admin/post.php
1202
+	 * so that we can hijack the default redirect locations for wp custom post types
1203
+	 * that WE'RE using and send back to OUR routes.  This should only be hooked in on the right route.
1204
+	 *
1205
+	 * @param  string $location This is the incoming currently set redirect location
1206
+	 * @param  string $post_id  This is the 'ID' value of the wp_posts table
1207
+	 * @return string           the new location to redirect to
1208
+	 */
1209
+	public function cpt_post_location_redirect($location, $post_id)
1210
+	{
1211
+		//we DO have a match so let's setup the url
1212
+		//we have to get the post to determine our route
1213
+		$post       = get_post($post_id);
1214
+		$edit_route = $this->_cpt_edit_routes[$post->post_type];
1215
+		//shared query_args
1216
+		$query_args = array('action' => $edit_route, 'post' => $post_id);
1217
+		$admin_url  = $this->_admin_base_url;
1218
+		if (isset($this->_req_data['save']) || isset($this->_req_data['publish'])) {
1219
+			$status = get_post_status($post_id);
1220
+			if (isset($this->_req_data['publish'])) {
1221
+				switch ($status) {
1222
+					case 'pending':
1223
+						$message = 8;
1224
+						break;
1225
+					case 'future':
1226
+						$message = 9;
1227
+						break;
1228
+					default:
1229
+						$message = 6;
1230
+				}
1231
+			} else {
1232
+				$message = 'draft' == $status ? 10 : 1;
1233
+			}
1234
+		} else if (isset($this->_req_data['addmeta']) && $this->_req_data['addmeta']) {
1235
+			$message = 2;
1236
+			//			$append = '#postcustom';
1237
+		} else if (isset($this->_req_data['deletemeta']) && $this->_req_data['deletemeta']) {
1238
+			$message = 3;
1239
+			//			$append = '#postcustom';
1240
+		} elseif ($this->_req_data['action'] == 'post-quickpress-save-cont') {
1241
+			$message = 7;
1242
+		} else {
1243
+			$message = 4;
1244
+		}
1245
+		//change the message if the post type is not viewable on the frontend
1246
+		$this->_cpt_object = get_post_type_object($post->post_type);
1247
+		$message           = $message === 1 && ! $this->_cpt_object->publicly_queryable ? 4 : $message;
1248
+		$query_args = array_merge(array('message' => $message), $query_args);
1249
+		$this->_process_notices($query_args, true);
1250
+		return self::add_query_args_and_nonce($query_args, $admin_url);
1251
+	}
1252
+
1253
+
1254
+
1255
+	/**
1256
+	 * This method is called to inject nav tabs on core WP cpt pages
1257
+	 *
1258
+	 * @access public
1259
+	 * @return string html
1260
+	 */
1261
+	public function inject_nav_tabs()
1262
+	{
1263
+		//can we hijack and insert the nav_tabs?
1264
+		$nav_tabs = $this->_get_main_nav_tabs();
1265
+		//first close off existing form tag
1266
+		$html = '>';
1267
+		$html .= $nav_tabs;
1268
+		//now let's handle the remaining tag ( missing ">" is CORRECT )
1269
+		$html .= '<span></span';
1270
+		echo $html;
1271
+	}
1272
+
1273
+
1274
+
1275
+	/**
1276
+	 * This just sets up the post update messages when an update form is loaded
1277
+	 *
1278
+	 * @access public
1279
+	 * @param  array $messages the original messages array
1280
+	 * @return array           the new messages array
1281
+	 */
1282
+	public function post_update_messages($messages)
1283
+	{
1284
+		global $post;
1285
+		$id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1286
+		$id = empty($id) && is_object($post) ? $post->ID : null;
1287
+		//		$post_type = $post ? $post->post_type : false;
1288
+		/*$current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route'] : 'shouldneverwork';
1289 1289
 
1290 1290
         $route_to_check = $post_type && isset( $this->_cpt_routes[$current_route]) ? $this->_cpt_routes[$current_route] : '';/**/
1291
-        $messages[$post->post_type] = array(
1292
-            0 => '', //Unused. Messages start at index 1.
1293
-            1 => sprintf(
1294
-                __('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1295
-                $this->_cpt_object->labels->singular_name,
1296
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1297
-                '</a>'
1298
-            ),
1299
-            2 => __('Custom field updated'),
1300
-            3 => __('Custom field deleted.'),
1301
-            4 => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1302
-            5 => isset($_GET['revision']) ? sprintf(__('%s restored to revision from %s', 'event_espresso'),
1303
-                $this->_cpt_object->labels->singular_name, wp_post_revision_title((int)$_GET['revision'], false))
1304
-                : false,
1305
-            6 => sprintf(
1306
-                __('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1307
-                $this->_cpt_object->labels->singular_name,
1308
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1309
-                '</a>'
1310
-            ),
1311
-            7 => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1312
-            8 => sprintf(
1313
-                __('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1314
-                $this->_cpt_object->labels->singular_name,
1315
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1316
-                '</a>'
1317
-            ),
1318
-            9 => sprintf(
1319
-                __('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1320
-                $this->_cpt_object->labels->singular_name,
1321
-                '<strong>' . date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)) . '</strong>',
1322
-                '<a target="_blank" href="' . esc_url(get_permalink($id)),
1323
-                '</a>'
1324
-            ),
1325
-            10 => sprintf(
1326
-                __('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1327
-                $this->_cpt_object->labels->singular_name,
1328
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1329
-                '</a>'
1330
-            ),
1331
-        );
1332
-        return $messages;
1333
-    }
1334
-
1335
-
1336
-
1337
-    /**
1338
-     * default method for the 'create_new' route for cpt admin pages.
1339
-     * For reference what to include in here, see wp-admin/post-new.php
1340
-     *
1341
-     * @access  protected
1342
-     * @return string template for add new cpt form
1343
-     */
1344
-    protected function _create_new_cpt_item()
1345
-    {
1346
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1347
-        $post_type        = $this->_cpt_routes[$this->_req_action];
1348
-        $post_type_object = $this->_cpt_object;
1349
-        $title            = $post_type_object->labels->add_new_item;
1350
-        $editing          = true;
1351
-        wp_enqueue_script('autosave');
1352
-        $post    = $post = get_default_post_to_edit($this->_cpt_routes[$this->_req_action], true);
1353
-        $post_ID = $post->ID;
1354
-        $is_IE   = $is_IE;
1355
-        add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1356
-        //modify the default editor title field with default title.
1357
-        add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1358
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1359
-    }
1360
-
1361
-
1362
-
1363
-    public function add_new_admin_page_global()
1364
-    {
1365
-        $admin_page = ! empty($this->_req_data['post']) ? 'post-php' : 'post-new-php';
1366
-        ?>
1291
+		$messages[$post->post_type] = array(
1292
+			0 => '', //Unused. Messages start at index 1.
1293
+			1 => sprintf(
1294
+				__('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1295
+				$this->_cpt_object->labels->singular_name,
1296
+				'<a href="' . esc_url(get_permalink($id)) . '">',
1297
+				'</a>'
1298
+			),
1299
+			2 => __('Custom field updated'),
1300
+			3 => __('Custom field deleted.'),
1301
+			4 => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1302
+			5 => isset($_GET['revision']) ? sprintf(__('%s restored to revision from %s', 'event_espresso'),
1303
+				$this->_cpt_object->labels->singular_name, wp_post_revision_title((int)$_GET['revision'], false))
1304
+				: false,
1305
+			6 => sprintf(
1306
+				__('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1307
+				$this->_cpt_object->labels->singular_name,
1308
+				'<a href="' . esc_url(get_permalink($id)) . '">',
1309
+				'</a>'
1310
+			),
1311
+			7 => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1312
+			8 => sprintf(
1313
+				__('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1314
+				$this->_cpt_object->labels->singular_name,
1315
+				'<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1316
+				'</a>'
1317
+			),
1318
+			9 => sprintf(
1319
+				__('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1320
+				$this->_cpt_object->labels->singular_name,
1321
+				'<strong>' . date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)) . '</strong>',
1322
+				'<a target="_blank" href="' . esc_url(get_permalink($id)),
1323
+				'</a>'
1324
+			),
1325
+			10 => sprintf(
1326
+				__('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1327
+				$this->_cpt_object->labels->singular_name,
1328
+				'<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1329
+				'</a>'
1330
+			),
1331
+		);
1332
+		return $messages;
1333
+	}
1334
+
1335
+
1336
+
1337
+	/**
1338
+	 * default method for the 'create_new' route for cpt admin pages.
1339
+	 * For reference what to include in here, see wp-admin/post-new.php
1340
+	 *
1341
+	 * @access  protected
1342
+	 * @return string template for add new cpt form
1343
+	 */
1344
+	protected function _create_new_cpt_item()
1345
+	{
1346
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1347
+		$post_type        = $this->_cpt_routes[$this->_req_action];
1348
+		$post_type_object = $this->_cpt_object;
1349
+		$title            = $post_type_object->labels->add_new_item;
1350
+		$editing          = true;
1351
+		wp_enqueue_script('autosave');
1352
+		$post    = $post = get_default_post_to_edit($this->_cpt_routes[$this->_req_action], true);
1353
+		$post_ID = $post->ID;
1354
+		$is_IE   = $is_IE;
1355
+		add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1356
+		//modify the default editor title field with default title.
1357
+		add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1358
+		include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1359
+	}
1360
+
1361
+
1362
+
1363
+	public function add_new_admin_page_global()
1364
+	{
1365
+		$admin_page = ! empty($this->_req_data['post']) ? 'post-php' : 'post-new-php';
1366
+		?>
1367 1367
         <script type="text/javascript">
1368 1368
             adminpage = '<?php echo $admin_page; ?>';
1369 1369
         </script>
1370 1370
         <?php
1371
-    }
1372
-
1373
-
1374
-
1375
-    /**
1376
-     * default method for the 'edit' route for cpt admin pages
1377
-     * For reference on what to put in here, refer to wp-admin/post.php
1378
-     *
1379
-     * @access protected
1380
-     * @return string   template for edit cpt form
1381
-     */
1382
-    protected function _edit_cpt_item()
1383
-    {
1384
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1385
-        $post_id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1386
-        $post = ! empty($post_id) ? get_post($post_id, OBJECT, 'edit') : null;
1387
-        if (empty ($post)) {
1388
-            wp_die(__('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?'));
1389
-        }
1390
-        if ( ! empty($_GET['get-post-lock'])) {
1391
-            wp_set_post_lock($post_id);
1392
-            wp_redirect(get_edit_post_link($post_id, 'url'));
1393
-            exit();
1394
-        }
1395
-
1396
-        // template vars
1397
-        $editing          = true;
1398
-        $post_ID          = $post_id;
1399
-        $post_type        = $this->_cpt_routes[$this->_req_action];
1400
-        $post_type_object = $this->_cpt_object;
1401
-
1402
-        if ( ! wp_check_post_lock($post->ID)) {
1403
-            $active_post_lock = wp_set_post_lock($post->ID);
1404
-            //wp_enqueue_script('autosave');
1405
-        }
1406
-        $title = $this->_cpt_object->labels->edit_item;
1407
-        add_action('admin_footer', '_admin_notice_post_locked');
1408
-        if (isset($this->_cpt_routes[$this->_req_data['action']])
1409
-            && ! isset($this->_labels['hide_add_button_on_cpt_route'][$this->_req_data['action']])
1410
-        ) {
1411
-            $create_new_action = apply_filters('FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
1412
-                'create_new', $this);
1413
-            $post_new_file = EE_Admin_Page::add_query_args_and_nonce(array(
1414
-                'action' => $create_new_action,
1415
-                'page'   => $this->page_slug,
1416
-            ), 'admin.php');
1417
-        }
1418
-        if (post_type_supports($this->_cpt_routes[$this->_req_action], 'comments')) {
1419
-            wp_enqueue_script('admin-comments');
1420
-            enqueue_comment_hotkeys_js();
1421
-        }
1422
-        add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1423
-        //modify the default editor title field with default title.
1424
-        add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1425
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1426
-    }
1427
-
1428
-
1429
-
1430
-    /**
1431
-     * some getters
1432
-     */
1433
-    /**
1434
-     * This returns the protected _cpt_model_obj property
1435
-     *
1436
-     * @return EE_CPT_Base
1437
-     */
1438
-    public function get_cpt_model_obj()
1439
-    {
1440
-        return $this->_cpt_model_obj;
1441
-    }
1371
+	}
1372
+
1373
+
1374
+
1375
+	/**
1376
+	 * default method for the 'edit' route for cpt admin pages
1377
+	 * For reference on what to put in here, refer to wp-admin/post.php
1378
+	 *
1379
+	 * @access protected
1380
+	 * @return string   template for edit cpt form
1381
+	 */
1382
+	protected function _edit_cpt_item()
1383
+	{
1384
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1385
+		$post_id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1386
+		$post = ! empty($post_id) ? get_post($post_id, OBJECT, 'edit') : null;
1387
+		if (empty ($post)) {
1388
+			wp_die(__('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?'));
1389
+		}
1390
+		if ( ! empty($_GET['get-post-lock'])) {
1391
+			wp_set_post_lock($post_id);
1392
+			wp_redirect(get_edit_post_link($post_id, 'url'));
1393
+			exit();
1394
+		}
1395
+
1396
+		// template vars
1397
+		$editing          = true;
1398
+		$post_ID          = $post_id;
1399
+		$post_type        = $this->_cpt_routes[$this->_req_action];
1400
+		$post_type_object = $this->_cpt_object;
1401
+
1402
+		if ( ! wp_check_post_lock($post->ID)) {
1403
+			$active_post_lock = wp_set_post_lock($post->ID);
1404
+			//wp_enqueue_script('autosave');
1405
+		}
1406
+		$title = $this->_cpt_object->labels->edit_item;
1407
+		add_action('admin_footer', '_admin_notice_post_locked');
1408
+		if (isset($this->_cpt_routes[$this->_req_data['action']])
1409
+			&& ! isset($this->_labels['hide_add_button_on_cpt_route'][$this->_req_data['action']])
1410
+		) {
1411
+			$create_new_action = apply_filters('FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
1412
+				'create_new', $this);
1413
+			$post_new_file = EE_Admin_Page::add_query_args_and_nonce(array(
1414
+				'action' => $create_new_action,
1415
+				'page'   => $this->page_slug,
1416
+			), 'admin.php');
1417
+		}
1418
+		if (post_type_supports($this->_cpt_routes[$this->_req_action], 'comments')) {
1419
+			wp_enqueue_script('admin-comments');
1420
+			enqueue_comment_hotkeys_js();
1421
+		}
1422
+		add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1423
+		//modify the default editor title field with default title.
1424
+		add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1425
+		include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1426
+	}
1427
+
1428
+
1429
+
1430
+	/**
1431
+	 * some getters
1432
+	 */
1433
+	/**
1434
+	 * This returns the protected _cpt_model_obj property
1435
+	 *
1436
+	 * @return EE_CPT_Base
1437
+	 */
1438
+	public function get_cpt_model_obj()
1439
+	{
1440
+		return $this->_cpt_model_obj;
1441
+	}
1442 1442
 
1443 1443
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
      */
236 236
     protected function _register_autosave_containers($ids)
237 237
     {
238
-        $this->_autosave_containers = array_merge($this->_autosave_fields, (array)$ids);
238
+        $this->_autosave_containers = array_merge($this->_autosave_fields, (array) $ids);
239 239
     }
240 240
 
241 241
 
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
         //filter _autosave_containers
280 280
         $containers = apply_filters('FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
281 281
             $this->_autosave_containers, $this);
282
-        $containers = apply_filters('FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
282
+        $containers = apply_filters('FHEE__EE_Admin_Page_CPT__'.get_class($this).'___load_autosave_scripts_styles__containers',
283 283
             $containers, $this);
284 284
 
285 285
         wp_localize_script('event_editor_js', 'EE_AUTOSAVE_IDS',
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
         parent::_load_page_dependencies();
370 370
         //notice we are ALSO going to load the pagenow hook set for this route (see _before_page_setup for the reset of the pagenow global ). This is for any plugins that are doing things properly and hooking into the load page hook for core wp cpt routes.
371 371
         global $pagenow;
372
-        do_action('load-' . $pagenow);
372
+        do_action('load-'.$pagenow);
373 373
         $this->modify_current_screen();
374 374
         add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
375 375
         //we route REALLY early.
@@ -400,8 +400,8 @@  discard block
 block discarded – undo
400 400
                 'admin.php?page=espresso_registrations&action=contact_list',
401 401
             ),
402 402
             1 => array(
403
-                'edit.php?post_type=' . $this->_cpt_object->name,
404
-                'admin.php?page=' . $this->_cpt_object->name,
403
+                'edit.php?post_type='.$this->_cpt_object->name,
404
+                'admin.php?page='.$this->_cpt_object->name,
405 405
             ),
406 406
         );
407 407
         foreach ($routes_to_match as $route_matches) {
@@ -429,7 +429,7 @@  discard block
 block discarded – undo
429 429
         $cpt_has_support = ! empty($cpt_args['page_templates']);
430 430
 
431 431
         //if the installed version of WP is > 4.7 we do some additional checks.
432
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
432
+        if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
433 433
             $post_templates = wp_get_theme()->get_post_templates();
434 434
             //if there are $post_templates for this cpt, then we return false for this method because
435 435
             //that means we aren't going to load our page template manager and leave that up to the native
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
         global $post;
453 453
         $template = '';
454 454
 
455
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
455
+        if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
456 456
             $page_template_count = count(get_page_templates());
457 457
         } else {
458 458
             $page_template_count = count(get_page_templates($post));
@@ -525,7 +525,7 @@  discard block
 block discarded – undo
525 525
             $template_args['statuses']         = $statuses;
526 526
         }
527 527
 
528
-        $template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
528
+        $template = EE_ADMIN_TEMPLATE.'status_dropdown.template.php';
529 529
         EEH_Template::display_template($template, $template_args);
530 530
     }
531 531
 
@@ -570,13 +570,13 @@  discard block
 block discarded – undo
570 570
             define('DOING_AUTOSAVE', true);
571 571
         }
572 572
         //if we made it here then the nonce checked out.  Let's run our methods and actions
573
-        if (method_exists($this, '_ee_autosave_' . $this->_current_view)) {
574
-            call_user_func(array($this, '_ee_autosave_' . $this->_current_view));
573
+        if (method_exists($this, '_ee_autosave_'.$this->_current_view)) {
574
+            call_user_func(array($this, '_ee_autosave_'.$this->_current_view));
575 575
         } else {
576 576
             $this->_template_args['success'] = true;
577 577
         }
578 578
         do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
579
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
579
+        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_'.get_class($this), $this);
580 580
         //now let's return json
581 581
         $this->_return_json();
582 582
     }
@@ -969,7 +969,7 @@  discard block
 block discarded – undo
969 969
         //global action
970 970
         do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
971 971
         //class specific action so you can limit hooking into a specific page.
972
-        do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
972
+        do_action('AHEE_EE_Admin_Page_CPT_'.get_class($this).'__restore_revision', $post_id, $revision_id);
973 973
     }
974 974
 
975 975
 
@@ -1047,7 +1047,7 @@  discard block
 block discarded – undo
1047 1047
         if ( ! empty($id) && '' != get_option('permalink_structure')) {
1048 1048
             $post = get_post($id);
1049 1049
             if (isset($post->post_type) && $this->page_slug == $post->post_type) {
1050
-                $shortlink = home_url('?p=' . $post->ID);
1050
+                $shortlink = home_url('?p='.$post->ID);
1051 1051
             }
1052 1052
         }
1053 1053
         return $shortlink;
@@ -1082,11 +1082,11 @@  discard block
 block discarded – undo
1082 1082
      */
1083 1083
     public function cpt_post_form_hidden_input()
1084 1084
     {
1085
-        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1085
+        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="'.$this->_admin_base_url.'" />';
1086 1086
         //we're also going to add the route value and the current page so we can direct autosave parsing correctly
1087 1087
         echo '<div id="ee-cpt-hidden-inputs">';
1088
-        echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1089
-        echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1088
+        echo '<input type="hidden" id="current_route" name="current_route" value="'.$this->_current_view.'" />';
1089
+        echo '<input type="hidden" id="current_page" name="current_page" value="'.$this->page_slug.'" />';
1090 1090
         echo '</div>';
1091 1091
     }
1092 1092
 
@@ -1293,39 +1293,39 @@  discard block
 block discarded – undo
1293 1293
             1 => sprintf(
1294 1294
                 __('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1295 1295
                 $this->_cpt_object->labels->singular_name,
1296
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1296
+                '<a href="'.esc_url(get_permalink($id)).'">',
1297 1297
                 '</a>'
1298 1298
             ),
1299 1299
             2 => __('Custom field updated'),
1300 1300
             3 => __('Custom field deleted.'),
1301 1301
             4 => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1302 1302
             5 => isset($_GET['revision']) ? sprintf(__('%s restored to revision from %s', 'event_espresso'),
1303
-                $this->_cpt_object->labels->singular_name, wp_post_revision_title((int)$_GET['revision'], false))
1303
+                $this->_cpt_object->labels->singular_name, wp_post_revision_title((int) $_GET['revision'], false))
1304 1304
                 : false,
1305 1305
             6 => sprintf(
1306 1306
                 __('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1307 1307
                 $this->_cpt_object->labels->singular_name,
1308
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1308
+                '<a href="'.esc_url(get_permalink($id)).'">',
1309 1309
                 '</a>'
1310 1310
             ),
1311 1311
             7 => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1312 1312
             8 => sprintf(
1313 1313
                 __('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1314 1314
                 $this->_cpt_object->labels->singular_name,
1315
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1315
+                '<a target="_blank" href="'.esc_url(add_query_arg('preview', 'true', get_permalink($id))).'">',
1316 1316
                 '</a>'
1317 1317
             ),
1318 1318
             9 => sprintf(
1319 1319
                 __('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1320 1320
                 $this->_cpt_object->labels->singular_name,
1321
-                '<strong>' . date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)) . '</strong>',
1322
-                '<a target="_blank" href="' . esc_url(get_permalink($id)),
1321
+                '<strong>'.date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)).'</strong>',
1322
+                '<a target="_blank" href="'.esc_url(get_permalink($id)),
1323 1323
                 '</a>'
1324 1324
             ),
1325 1325
             10 => sprintf(
1326 1326
                 __('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1327 1327
                 $this->_cpt_object->labels->singular_name,
1328
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1328
+                '<a target="_blank" href="'.esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1329 1329
                 '</a>'
1330 1330
             ),
1331 1331
         );
@@ -1355,7 +1355,7 @@  discard block
 block discarded – undo
1355 1355
         add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1356 1356
         //modify the default editor title field with default title.
1357 1357
         add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1358
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1358
+        include_once WP_ADMIN_PATH.'edit-form-advanced.php';
1359 1359
     }
1360 1360
 
1361 1361
 
@@ -1422,7 +1422,7 @@  discard block
 block discarded – undo
1422 1422
         add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1423 1423
         //modify the default editor title field with default title.
1424 1424
         add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1425
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1425
+        include_once WP_ADMIN_PATH.'edit-form-advanced.php';
1426 1426
     }
1427 1427
 
1428 1428
 
Please login to merge, or discard this patch.
core/EE_Config.core.php 1 patch
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -2211,7 +2211,7 @@  discard block
 block discarded – undo
2211 2211
 		$table_analysis = EE_Registry::instance()->create( 'TableAnalysis', array(), true );
2212 2212
 		// get country code from organization settings or use default
2213 2213
 		$ORG_CNT = isset( EE_Registry::instance()->CFG->organization )
2214
-		           && EE_Registry::instance()->CFG->organization instanceof EE_Organization_Config
2214
+				   && EE_Registry::instance()->CFG->organization instanceof EE_Organization_Config
2215 2215
 			? EE_Registry::instance()->CFG->organization->CNT_ISO
2216 2216
 			: '';
2217 2217
 		// but override if requested
@@ -2521,12 +2521,12 @@  discard block
 block discarded – undo
2521 2521
 	public $help_tour_activation;
2522 2522
 
2523 2523
 	/**
2524
-     * adds extra layer of encoding to session data to prevent serialization errors
2525
-     * but is incompatible with some server configuration errors
2526
-     * if you get "500 internal server errors" during registration, try turning this on
2527
-     * if you get PHP fatal errors regarding base 64 methods not defined, then turn this off
2528
-     *
2529
-     * @var boolean $encode_session_data
2524
+	 * adds extra layer of encoding to session data to prevent serialization errors
2525
+	 * but is incompatible with some server configuration errors
2526
+	 * if you get "500 internal server errors" during registration, try turning this on
2527
+	 * if you get PHP fatal errors regarding base 64 methods not defined, then turn this off
2528
+	 *
2529
+	 * @var boolean $encode_session_data
2530 2530
 	 */
2531 2531
 	private $encode_session_data = false;
2532 2532
 
@@ -2591,21 +2591,21 @@  discard block
 block discarded – undo
2591 2591
 
2592 2592
 
2593 2593
 
2594
-    /**
2595
-     * @return boolean
2596
-     */
2597
-    public function encode_session_data() {
2598
-        return filter_var( $this->encode_session_data, FILTER_VALIDATE_BOOLEAN );
2599
-    }
2594
+	/**
2595
+	 * @return boolean
2596
+	 */
2597
+	public function encode_session_data() {
2598
+		return filter_var( $this->encode_session_data, FILTER_VALIDATE_BOOLEAN );
2599
+	}
2600 2600
 
2601 2601
 
2602 2602
 
2603
-    /**
2604
-     * @param boolean $encode_session_data
2605
-     */
2606
-    public function set_encode_session_data( $encode_session_data ) {
2607
-        $this->encode_session_data = filter_var( $encode_session_data, FILTER_VALIDATE_BOOLEAN );
2608
-    }
2603
+	/**
2604
+	 * @param boolean $encode_session_data
2605
+	 */
2606
+	public function set_encode_session_data( $encode_session_data ) {
2607
+		$this->encode_session_data = filter_var( $encode_session_data, FILTER_VALIDATE_BOOLEAN );
2608
+	}
2609 2609
 
2610 2610
 
2611 2611
 
@@ -2649,13 +2649,13 @@  discard block
 block discarded – undo
2649 2649
 	public $current_espresso_theme;
2650 2650
 
2651 2651
 	/**
2652
-	* @var EE_Ticket_Selector_Config $EED_Ticket_Selector
2653
-	*/
2652
+	 * @var EE_Ticket_Selector_Config $EED_Ticket_Selector
2653
+	 */
2654 2654
 	public $EED_Ticket_Selector;
2655 2655
 
2656 2656
 	/**
2657
-	* @var EE_Event_Single_Config $EED_Event_Single
2658
-	*/
2657
+	 * @var EE_Event_Single_Config $EED_Event_Single
2658
+	 */
2659 2659
 	public $EED_Event_Single;
2660 2660
 
2661 2661
 	/**
@@ -2896,16 +2896,16 @@  discard block
 block discarded – undo
2896 2896
  */
2897 2897
 class EE_Ticket_Selector_Config extends EE_Config_Base {
2898 2898
 
2899
-    /**
2900
-     * constant to indicate that a datetime selector should NEVER be shown for ticket selectors
2901
-     */
2902
-    const DO_NOT_SHOW_DATETIME_SELECTOR = 'no_datetime_selector';
2899
+	/**
2900
+	 * constant to indicate that a datetime selector should NEVER be shown for ticket selectors
2901
+	 */
2902
+	const DO_NOT_SHOW_DATETIME_SELECTOR = 'no_datetime_selector';
2903 2903
 
2904
-    /**
2905
-     * constant to indicate that a datetime selector should only be shown for ticket selectors
2906
-     * when the number of datetimes for the event matches the value set for $datetime_selector_threshold
2907
-     */
2908
-    const MAYBE_SHOW_DATETIME_SELECTOR = 'maybe_datetime_selector';
2904
+	/**
2905
+	 * constant to indicate that a datetime selector should only be shown for ticket selectors
2906
+	 * when the number of datetimes for the event matches the value set for $datetime_selector_threshold
2907
+	 */
2908
+	const MAYBE_SHOW_DATETIME_SELECTOR = 'maybe_datetime_selector';
2909 2909
 
2910 2910
 	/**
2911 2911
 	 * @var boolean $show_ticket_sale_columns
@@ -2944,7 +2944,7 @@  discard block
 block discarded – undo
2944 2944
 	 *    class constructor
2945 2945
 	 */
2946 2946
 	public function __construct() {
2947
-        $this->show_ticket_sale_columns = true;
2947
+		$this->show_ticket_sale_columns = true;
2948 2948
 		$this->show_ticket_details = true;
2949 2949
 		$this->show_expired_tickets = true;
2950 2950
 		$this->show_datetime_selector = \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
@@ -2953,91 +2953,91 @@  discard block
 block discarded – undo
2953 2953
 
2954 2954
 
2955 2955
 
2956
-    /**
2957
-     * returns true if a datetime selector should be displayed
2958
-     *
2959
-     * @param array $datetimes
2960
-     * @return bool
2961
-     */
2962
-    public function showDatetimeSelector(array $datetimes)
2963
-    {
2964
-        // if the settings are NOT: don't show OR below threshold, THEN active = true
2965
-        return ! (
2966
-            $this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR
2967
-           || (
2968
-               $this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR
2969
-               && count($datetimes) < $this->getDatetimeSelectorThreshold()
2970
-           )
2971
-        );
2972
-    }
2973
-
2974
-
2975
-    /**
2976
-     * @return string
2977
-     */
2978
-    public function getShowDatetimeSelector()
2979
-    {
2980
-        return $this->show_datetime_selector;
2981
-    }
2956
+	/**
2957
+	 * returns true if a datetime selector should be displayed
2958
+	 *
2959
+	 * @param array $datetimes
2960
+	 * @return bool
2961
+	 */
2962
+	public function showDatetimeSelector(array $datetimes)
2963
+	{
2964
+		// if the settings are NOT: don't show OR below threshold, THEN active = true
2965
+		return ! (
2966
+			$this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR
2967
+		   || (
2968
+			   $this->getShowDatetimeSelector() === \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR
2969
+			   && count($datetimes) < $this->getDatetimeSelectorThreshold()
2970
+		   )
2971
+		);
2972
+	}
2973
+
2974
+
2975
+	/**
2976
+	 * @return string
2977
+	 */
2978
+	public function getShowDatetimeSelector()
2979
+	{
2980
+		return $this->show_datetime_selector;
2981
+	}
2982 2982
 
2983 2983
 
2984 2984
 
2985
-    /**
2986
-     * @param bool $keys_only
2987
-     * @return array
2988
-     */
2989
-    public function getShowDatetimeSelectorOptions($keys_only = true)
2990
-    {
2991
-        return $keys_only
2992
-            ? array(
2993
-                \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR,
2994
-                \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR,
2995
-            )
2996
-            : array(
2997
-                \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR => esc_html__(
2998
-                    'Do not show datetime selector', 'event_espresso'
2999
-                ),
3000
-                \EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR => esc_html__(
3001
-                    'Maybe show datetime selector', 'event_espresso'
3002
-                ),
3003
-            );
3004
-    }
3005
-
3006
-
3007
-
3008
-    /**
3009
-     * @param string $show_datetime_selector
3010
-     */
3011
-    public function setShowDatetimeSelector($show_datetime_selector)
3012
-    {
3013
-        $this->show_datetime_selector = in_array(
3014
-            $show_datetime_selector,
3015
-            $this->getShowDatetimeSelectorOptions()
3016
-        )
3017
-            ? $show_datetime_selector
3018
-            : \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
3019
-    }
2985
+	/**
2986
+	 * @param bool $keys_only
2987
+	 * @return array
2988
+	 */
2989
+	public function getShowDatetimeSelectorOptions($keys_only = true)
2990
+	{
2991
+		return $keys_only
2992
+			? array(
2993
+				\EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR,
2994
+				\EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR,
2995
+			)
2996
+			: array(
2997
+				\EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR => esc_html__(
2998
+					'Do not show datetime selector', 'event_espresso'
2999
+				),
3000
+				\EE_Ticket_Selector_Config::MAYBE_SHOW_DATETIME_SELECTOR => esc_html__(
3001
+					'Maybe show datetime selector', 'event_espresso'
3002
+				),
3003
+			);
3004
+	}
3020 3005
 
3021 3006
 
3022 3007
 
3023
-    /**
3024
-     * @return int
3025
-     */
3026
-    public function getDatetimeSelectorThreshold()
3027
-    {
3028
-        return $this->datetime_selector_threshold;
3029
-    }
3008
+	/**
3009
+	 * @param string $show_datetime_selector
3010
+	 */
3011
+	public function setShowDatetimeSelector($show_datetime_selector)
3012
+	{
3013
+		$this->show_datetime_selector = in_array(
3014
+			$show_datetime_selector,
3015
+			$this->getShowDatetimeSelectorOptions()
3016
+		)
3017
+			? $show_datetime_selector
3018
+			: \EE_Ticket_Selector_Config::DO_NOT_SHOW_DATETIME_SELECTOR;
3019
+	}
3030 3020
 
3031 3021
 
3032 3022
 
3033
-    /**
3034
-     * @param int $datetime_selector_threshold
3035
-     */
3036
-    public function setDatetimeSelectorThreshold($datetime_selector_threshold)
3037
-    {
3038
-        $datetime_selector_threshold = absint($datetime_selector_threshold);
3039
-        $this->datetime_selector_threshold = $datetime_selector_threshold ? $datetime_selector_threshold : 3;
3040
-    }
3023
+	/**
3024
+	 * @return int
3025
+	 */
3026
+	public function getDatetimeSelectorThreshold()
3027
+	{
3028
+		return $this->datetime_selector_threshold;
3029
+	}
3030
+
3031
+
3032
+
3033
+	/**
3034
+	 * @param int $datetime_selector_threshold
3035
+	 */
3036
+	public function setDatetimeSelectorThreshold($datetime_selector_threshold)
3037
+	{
3038
+		$datetime_selector_threshold = absint($datetime_selector_threshold);
3039
+		$this->datetime_selector_threshold = $datetime_selector_threshold ? $datetime_selector_threshold : 3;
3040
+	}
3041 3041
 
3042 3042
 
3043 3043
 }
@@ -3100,8 +3100,8 @@  discard block
 block discarded – undo
3100 3100
 	 */
3101 3101
 	public function max_input_vars_limit_check( $input_count = 0 ) {
3102 3102
 		if ( ! empty( $this->php->max_input_vars )
3103
-		     && ( $input_count >= $this->php->max_input_vars )
3104
-		     && ( PHP_MAJOR_VERSION >= 5 && PHP_MINOR_VERSION >= 3 && PHP_RELEASE_VERSION >= 9 )
3103
+			 && ( $input_count >= $this->php->max_input_vars )
3104
+			 && ( PHP_MAJOR_VERSION >= 5 && PHP_MINOR_VERSION >= 3 && PHP_RELEASE_VERSION >= 9 )
3105 3105
 		) {
3106 3106
 			return sprintf(
3107 3107
 				__(
@@ -3145,22 +3145,22 @@  discard block
 block discarded – undo
3145 3145
 class EE_Tax_Config extends EE_Config_Base
3146 3146
 {
3147 3147
 
3148
-    /*
3148
+	/*
3149 3149
      * flag to indicate whether or not to display ticket prices with the taxes included
3150 3150
      *
3151 3151
      * @var boolean $prices_displayed_including_taxes
3152 3152
      */
3153
-    public $prices_displayed_including_taxes;
3153
+	public $prices_displayed_including_taxes;
3154 3154
 
3155 3155
 
3156 3156
 
3157
-    /**
3158
-     *    class constructor
3159
-     */
3160
-    public function __construct()
3161
-    {
3162
-        $this->prices_displayed_including_taxes = true;
3163
-    }
3157
+	/**
3158
+	 *    class constructor
3159
+	 */
3160
+	public function __construct()
3161
+	{
3162
+		$this->prices_displayed_including_taxes = true;
3163
+	}
3164 3164
 }
3165 3165
 
3166 3166
 
Please login to merge, or discard this patch.