Completed
Branch FET-10260-expose-default-query... (766314)
by
unknown
149:02 queued 136:36
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/db_models/EEM_Base.model.php 2 patches
Spacing   +147 added lines, -147 removed lines patch added patch discarded remove patch
@@ -466,8 +466,8 @@  discard block
 block discarded – undo
466 466
     protected function __construct($timezone = null)
467 467
     {
468 468
         // check that the model has not been loaded too soon
469
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
470
-            throw new EE_Error (
469
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
470
+            throw new EE_Error(
471 471
                 sprintf(
472 472
                     __('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.',
473 473
                         'event_espresso'),
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
          *
488 488
          * @var EE_Table_Base[] $_tables
489 489
          */
490
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
490
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
491 491
         foreach ($this->_tables as $table_alias => $table_obj) {
492 492
             /** @var $table_obj EE_Table_Base */
493 493
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -502,10 +502,10 @@  discard block
 block discarded – undo
502 502
          *
503 503
          * @param EE_Model_Field_Base[] $_fields
504 504
          */
505
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
505
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
506 506
         $this->_invalidate_field_caches();
507 507
         foreach ($this->_fields as $table_alias => $fields_for_table) {
508
-            if (! array_key_exists($table_alias, $this->_tables)) {
508
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
509 509
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
510 510
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
511 511
             }
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
          *
534 534
          * @param EE_Model_Relation_Base[] $_model_relations
535 535
          */
536
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
536
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
537 537
             $this->_model_relations);
538 538
         foreach ($this->_model_relations as $model_name => $relation_obj) {
539 539
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -545,12 +545,12 @@  discard block
 block discarded – undo
545 545
         }
546 546
         $this->set_timezone($timezone);
547 547
         //finalize default where condition strategy, or set default
548
-        if (! $this->_default_where_conditions_strategy) {
548
+        if ( ! $this->_default_where_conditions_strategy) {
549 549
             //nothing was set during child constructor, so set default
550 550
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
551 551
         }
552 552
         $this->_default_where_conditions_strategy->_finalize_construct($this);
553
-        if (! $this->_minimum_where_conditions_strategy) {
553
+        if ( ! $this->_minimum_where_conditions_strategy) {
554 554
             //nothing was set during child constructor, so set default
555 555
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
556 556
         }
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
         //initialize the standard cap restriction generators if none were specified by the child constructor
564 564
         if ($this->_cap_restriction_generators !== false) {
565 565
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
566
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
566
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
567 567
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
568 568
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
569 569
                         new EE_Restriction_Generator_Protected(),
@@ -576,10 +576,10 @@  discard block
 block discarded – undo
576 576
         //if there are cap restriction generators, use them to make the default cap restrictions
577 577
         if ($this->_cap_restriction_generators !== false) {
578 578
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
579
-                if (! $generator_object) {
579
+                if ( ! $generator_object) {
580 580
                     continue;
581 581
                 }
582
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
582
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
583 583
                     throw new EE_Error(
584 584
                         sprintf(
585 585
                             __('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.',
@@ -590,12 +590,12 @@  discard block
 block discarded – undo
590 590
                     );
591 591
                 }
592 592
                 $action = $this->cap_action_for_context($context);
593
-                if (! $generator_object->construction_finalized()) {
593
+                if ( ! $generator_object->construction_finalized()) {
594 594
                     $generator_object->_construct_finalize($this, $action);
595 595
                 }
596 596
             }
597 597
         }
598
-        do_action('AHEE__' . get_class($this) . '__construct__end');
598
+        do_action('AHEE__'.get_class($this).'__construct__end');
599 599
     }
600 600
 
601 601
 
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
      */
631 631
     public static function set_model_query_blog_id($blog_id = 0)
632 632
     {
633
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
633
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
634 634
     }
635 635
 
636 636
 
@@ -660,7 +660,7 @@  discard block
 block discarded – undo
660 660
     public static function instance($timezone = null)
661 661
     {
662 662
         // check if instance of Espresso_model already exists
663
-        if (! static::$_instance instanceof static) {
663
+        if ( ! static::$_instance instanceof static) {
664 664
             // instantiate Espresso_model
665 665
             static::$_instance = new static($timezone);
666 666
         }
@@ -691,7 +691,7 @@  discard block
 block discarded – undo
691 691
             foreach ($r->getDefaultProperties() as $property => $value) {
692 692
                 //don't set instance to null like it was originally,
693 693
                 //but it's static anyways, and we're ignoring static properties (for now at least)
694
-                if (! isset($static_properties[$property])) {
694
+                if ( ! isset($static_properties[$property])) {
695 695
                     static::$_instance->{$property} = $value;
696 696
                 }
697 697
             }
@@ -714,7 +714,7 @@  discard block
 block discarded – undo
714 714
      */
715 715
     public function status_array($translated = false)
716 716
     {
717
-        if (! array_key_exists('Status', $this->_model_relations)) {
717
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
718 718
             return array();
719 719
         }
720 720
         $model_name = $this->get_this_model_name();
@@ -917,17 +917,17 @@  discard block
 block discarded – undo
917 917
     public function wp_user_field_name()
918 918
     {
919 919
         try {
920
-            if (! empty($this->_model_chain_to_wp_user)) {
920
+            if ( ! empty($this->_model_chain_to_wp_user)) {
921 921
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
922 922
                 $last_model_name = end($models_to_follow_to_wp_users);
923 923
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
924
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
924
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
925 925
             } else {
926 926
                 $model_with_fk_to_wp_users = $this;
927 927
                 $model_chain_to_wp_user = '';
928 928
             }
929 929
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
930
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
930
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
931 931
         } catch (EE_Error $e) {
932 932
             return false;
933 933
         }
@@ -999,12 +999,12 @@  discard block
 block discarded – undo
999 999
         // remember the custom selections, if any, and type cast as array
1000 1000
         // (unless $columns_to_select is an object, then just set as an empty array)
1001 1001
         // Note: (array) 'some string' === array( 'some string' )
1002
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1002
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1003 1003
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1004 1004
         $select_expressions = $columns_to_select !== null
1005 1005
             ? $this->_construct_select_from_input($columns_to_select)
1006 1006
             : $this->_construct_default_select_sql($model_query_info);
1007
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1007
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1008 1008
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1009 1009
     }
1010 1010
 
@@ -1049,7 +1049,7 @@  discard block
 block discarded – undo
1049 1049
         if (is_array($columns_to_select)) {
1050 1050
             $select_sql_array = array();
1051 1051
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1052
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1052
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1053 1053
                     throw new EE_Error(
1054 1054
                         sprintf(
1055 1055
                             __(
@@ -1061,7 +1061,7 @@  discard block
 block discarded – undo
1061 1061
                         )
1062 1062
                     );
1063 1063
                 }
1064
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1064
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1065 1065
                     throw new EE_Error(
1066 1066
                         sprintf(
1067 1067
                             __(
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
      */
1134 1134
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1135 1135
     {
1136
-        if (! isset($query_params[0])) {
1136
+        if ( ! isset($query_params[0])) {
1137 1137
             $query_params[0] = array();
1138 1138
         }
1139 1139
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1158,7 +1158,7 @@  discard block
 block discarded – undo
1158 1158
      */
1159 1159
     public function get_one($query_params = array())
1160 1160
     {
1161
-        if (! is_array($query_params)) {
1161
+        if ( ! is_array($query_params)) {
1162 1162
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1163 1163
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1164 1164
                     gettype($query_params)), '4.6.0');
@@ -1326,7 +1326,7 @@  discard block
 block discarded – undo
1326 1326
                 return array();
1327 1327
             }
1328 1328
         }
1329
-        if (! is_array($query_params)) {
1329
+        if ( ! is_array($query_params)) {
1330 1330
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1331 1331
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1332 1332
                     gettype($query_params)), '4.6.0');
@@ -1336,7 +1336,7 @@  discard block
 block discarded – undo
1336 1336
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1337 1337
         $query_params['limit'] = $limit;
1338 1338
         //set direction
1339
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1339
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1340 1340
         $query_params['order_by'] = $operand === '>'
1341 1341
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1342 1342
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1415,7 +1415,7 @@  discard block
 block discarded – undo
1415 1415
     {
1416 1416
         $field_settings = $this->field_settings_for($field_name);
1417 1417
         //if not a valid EE_Datetime_Field then throw error
1418
-        if (! $field_settings instanceof EE_Datetime_Field) {
1418
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1419 1419
             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.',
1420 1420
                 'event_espresso'), $field_name));
1421 1421
         }
@@ -1560,7 +1560,7 @@  discard block
 block discarded – undo
1560 1560
      */
1561 1561
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1562 1562
     {
1563
-        if (! is_array($query_params)) {
1563
+        if ( ! is_array($query_params)) {
1564 1564
             EE_Error::doing_it_wrong('EEM_Base::update',
1565 1565
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1566 1566
                     gettype($query_params)), '4.6.0');
@@ -1582,7 +1582,7 @@  discard block
 block discarded – undo
1582 1582
          * @param EEM_Base $model           the model being queried
1583 1583
          * @param array    $query_params    see EEM_Base::get_all()
1584 1584
          */
1585
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1585
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1586 1586
             $query_params);
1587 1587
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1588 1588
         //to do that, for each table, verify that it's PK isn't null.
@@ -1596,7 +1596,7 @@  discard block
 block discarded – undo
1596 1596
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1597 1597
         foreach ($wpdb_select_results as $wpdb_result) {
1598 1598
             // type cast stdClass as array
1599
-            $wpdb_result = (array)$wpdb_result;
1599
+            $wpdb_result = (array) $wpdb_result;
1600 1600
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1601 1601
             if ($this->has_primary_key_field()) {
1602 1602
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1613,13 +1613,13 @@  discard block
 block discarded – undo
1613 1613
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1614 1614
                     //if there is no private key for this table on the results, it means there's no entry
1615 1615
                     //in this table, right? so insert a row in the current table, using any fields available
1616
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1616
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1617 1617
                            && $wpdb_result[$this_table_pk_column])
1618 1618
                     ) {
1619 1619
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1620 1620
                             $main_table_pk_value);
1621 1621
                         //if we died here, report the error
1622
-                        if (! $success) {
1622
+                        if ( ! $success) {
1623 1623
                             return false;
1624 1624
                         }
1625 1625
                     }
@@ -1650,7 +1650,7 @@  discard block
 block discarded – undo
1650 1650
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1651 1651
                 }
1652 1652
             }
1653
-            if (! $model_objs_affected_ids) {
1653
+            if ( ! $model_objs_affected_ids) {
1654 1654
                 //wait wait wait- if nothing was affected let's stop here
1655 1655
                 return 0;
1656 1656
             }
@@ -1677,7 +1677,7 @@  discard block
 block discarded – undo
1677 1677
                . $model_query_info->get_full_join_sql()
1678 1678
                . " SET "
1679 1679
                . $this->_construct_update_sql($fields_n_values)
1680
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1680
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1681 1681
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1682 1682
         /**
1683 1683
          * Action called after a model update call has been made.
@@ -1688,7 +1688,7 @@  discard block
 block discarded – undo
1688 1688
          * @param int      $rows_affected
1689 1689
          */
1690 1690
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1691
-        return $rows_affected;//how many supposedly got updated
1691
+        return $rows_affected; //how many supposedly got updated
1692 1692
     }
1693 1693
 
1694 1694
 
@@ -1716,7 +1716,7 @@  discard block
 block discarded – undo
1716 1716
         }
1717 1717
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1718 1718
         $select_expressions = $field->get_qualified_column();
1719
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1719
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1720 1720
         return $this->_do_wpdb_query('get_col', array($SQL));
1721 1721
     }
1722 1722
 
@@ -1734,7 +1734,7 @@  discard block
 block discarded – undo
1734 1734
     {
1735 1735
         $query_params['limit'] = 1;
1736 1736
         $col = $this->get_col($query_params, $field_to_select);
1737
-        if (! empty($col)) {
1737
+        if ( ! empty($col)) {
1738 1738
             return reset($col);
1739 1739
         } else {
1740 1740
             return null;
@@ -1766,7 +1766,7 @@  discard block
 block discarded – undo
1766 1766
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1767 1767
             $value_sql = $prepared_value === null ? 'NULL'
1768 1768
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1769
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1769
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1770 1770
         }
1771 1771
         return implode(",", $cols_n_values);
1772 1772
     }
@@ -1898,7 +1898,7 @@  discard block
 block discarded – undo
1898 1898
          * @param int      $rows_deleted
1899 1899
          */
1900 1900
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1901
-        return $rows_deleted;//how many supposedly got deleted
1901
+        return $rows_deleted; //how many supposedly got deleted
1902 1902
     }
1903 1903
 
1904 1904
 
@@ -1991,7 +1991,7 @@  discard block
 block discarded – undo
1991 1991
                     $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
1992 1992
                 }
1993 1993
                 //other tables
1994
-                if (! empty($other_tables)) {
1994
+                if ( ! empty($other_tables)) {
1995 1995
                     foreach ($other_tables as $ot) {
1996 1996
                         //first check if we've got the foreign key column here.
1997 1997
                         if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
@@ -2014,7 +2014,7 @@  discard block
 block discarded – undo
2014 2014
             foreach ($deletes as $column => $values) {
2015 2015
                 //make sure we have unique $values;
2016 2016
                 $values = array_unique($values);
2017
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2017
+                $query[] = $column.' IN('.implode(",", $values).')';
2018 2018
             }
2019 2019
             return ! empty($query) ? implode(' AND ', $query) : '';
2020 2020
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2030,7 +2030,7 @@  discard block
 block discarded – undo
2030 2030
                                                            . $delete_object[$cpk_field->get_qualified_column()];
2031 2031
                     }
2032 2032
                 }
2033
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2033
+                $ways_to_identify_a_row[] = "(".implode(" AND ", $values_for_each_cpk_for_a_row).")";
2034 2034
             }
2035 2035
             return implode(" OR ", $ways_to_identify_a_row);
2036 2036
         } else {
@@ -2079,9 +2079,9 @@  discard block
 block discarded – undo
2079 2079
                 $column_to_count = '*';
2080 2080
             }
2081 2081
         }
2082
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2083
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2084
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2082
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2083
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2084
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2085 2085
     }
2086 2086
 
2087 2087
 
@@ -2103,13 +2103,13 @@  discard block
 block discarded – undo
2103 2103
             $field_obj = $this->get_primary_key_field();
2104 2104
         }
2105 2105
         $column_to_count = $field_obj->get_qualified_column();
2106
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2106
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2107 2107
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2108 2108
         $data_type = $field_obj->get_wpdb_data_type();
2109 2109
         if ($data_type === '%d' || $data_type === '%s') {
2110
-            return (float)$return_value;
2110
+            return (float) $return_value;
2111 2111
         } else {//must be %f
2112
-            return (float)$return_value;
2112
+            return (float) $return_value;
2113 2113
         }
2114 2114
     }
2115 2115
 
@@ -2130,13 +2130,13 @@  discard block
 block discarded – undo
2130 2130
         //if we're in maintenance mode level 2, DON'T run any queries
2131 2131
         //because level 2 indicates the database needs updating and
2132 2132
         //is probably out of sync with the code
2133
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2133
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2134 2134
             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.",
2135 2135
                 "event_espresso")));
2136 2136
         }
2137 2137
         /** @type WPDB $wpdb */
2138 2138
         global $wpdb;
2139
-        if (! method_exists($wpdb, $wpdb_method)) {
2139
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2140 2140
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2141 2141
                 'event_espresso'), $wpdb_method));
2142 2142
         }
@@ -2148,7 +2148,7 @@  discard block
 block discarded – undo
2148 2148
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2149 2149
         if (WP_DEBUG) {
2150 2150
             $wpdb->show_errors($old_show_errors_value);
2151
-            if (! empty($wpdb->last_error)) {
2151
+            if ( ! empty($wpdb->last_error)) {
2152 2152
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2153 2153
             } elseif ($result === false) {
2154 2154
                 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"',
@@ -2208,7 +2208,7 @@  discard block
 block discarded – undo
2208 2208
                     return $result;
2209 2209
                     break;
2210 2210
             }
2211
-            if (! empty($error_message)) {
2211
+            if ( ! empty($error_message)) {
2212 2212
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2213 2213
                 trigger_error($error_message);
2214 2214
             }
@@ -2284,11 +2284,11 @@  discard block
 block discarded – undo
2284 2284
      */
2285 2285
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2286 2286
     {
2287
-        return " FROM " . $model_query_info->get_full_join_sql() .
2288
-               $model_query_info->get_where_sql() .
2289
-               $model_query_info->get_group_by_sql() .
2290
-               $model_query_info->get_having_sql() .
2291
-               $model_query_info->get_order_by_sql() .
2287
+        return " FROM ".$model_query_info->get_full_join_sql().
2288
+               $model_query_info->get_where_sql().
2289
+               $model_query_info->get_group_by_sql().
2290
+               $model_query_info->get_having_sql().
2291
+               $model_query_info->get_order_by_sql().
2292 2292
                $model_query_info->get_limit_sql();
2293 2293
     }
2294 2294
 
@@ -2484,12 +2484,12 @@  discard block
 block discarded – undo
2484 2484
         $related_model = $this->get_related_model_obj($model_name);
2485 2485
         //we're just going to use the query params on the related model's normal get_all query,
2486 2486
         //except add a condition to say to match the current mod
2487
-        if (! isset($query_params['default_where_conditions'])) {
2487
+        if ( ! isset($query_params['default_where_conditions'])) {
2488 2488
             $query_params['default_where_conditions'] = 'none';
2489 2489
         }
2490 2490
         $this_model_name = $this->get_this_model_name();
2491 2491
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2492
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2492
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2493 2493
         return $related_model->count($query_params, $field_to_count, $distinct);
2494 2494
     }
2495 2495
 
@@ -2509,7 +2509,7 @@  discard block
 block discarded – undo
2509 2509
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2510 2510
     {
2511 2511
         $related_model = $this->get_related_model_obj($model_name);
2512
-        if (! is_array($query_params)) {
2512
+        if ( ! is_array($query_params)) {
2513 2513
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2514 2514
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2515 2515
                     gettype($query_params)), '4.6.0');
@@ -2517,12 +2517,12 @@  discard block
 block discarded – undo
2517 2517
         }
2518 2518
         //we're just going to use the query params on the related model's normal get_all query,
2519 2519
         //except add a condition to say to match the current mod
2520
-        if (! isset($query_params['default_where_conditions'])) {
2520
+        if ( ! isset($query_params['default_where_conditions'])) {
2521 2521
             $query_params['default_where_conditions'] = 'none';
2522 2522
         }
2523 2523
         $this_model_name = $this->get_this_model_name();
2524 2524
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2525
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2525
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2526 2526
         return $related_model->sum($query_params, $field_to_sum);
2527 2527
     }
2528 2528
 
@@ -2576,7 +2576,7 @@  discard block
 block discarded – undo
2576 2576
                 $field_with_model_name = $field;
2577 2577
             }
2578 2578
         }
2579
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2579
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2580 2580
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2581 2581
                 $this->get_this_model_name()));
2582 2582
         }
@@ -2609,7 +2609,7 @@  discard block
 block discarded – undo
2609 2609
          * @param array    $fields_n_values keys are the fields and values are their new values
2610 2610
          * @param EEM_Base $model           the model used
2611 2611
          */
2612
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2612
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2613 2613
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2614 2614
             $main_table = $this->_get_main_table();
2615 2615
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2717,7 +2717,7 @@  discard block
 block discarded – undo
2717 2717
         }
2718 2718
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2719 2719
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2720
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2720
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2721 2721
         }
2722 2722
         //if there is nothing to base this search on, then we shouldn't find anything
2723 2723
         if (empty($query_params)) {
@@ -2797,7 +2797,7 @@  discard block
 block discarded – undo
2797 2797
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2798 2798
             //so add the fk to the main table as a column
2799 2799
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2800
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2800
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2801 2801
         }
2802 2802
         //insert the new entry
2803 2803
         $result = $this->_do_wpdb_query('insert',
@@ -2836,7 +2836,7 @@  discard block
 block discarded – undo
2836 2836
     protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2837 2837
     {
2838 2838
         //if this field doesn't allow nullable, don't allow it
2839
-        if (! $field_obj->is_nullable()
2839
+        if ( ! $field_obj->is_nullable()
2840 2840
             && (
2841 2841
                 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2842 2842
         ) {
@@ -2999,7 +2999,7 @@  discard block
 block discarded – undo
2999 2999
                     $query_info_carrier,
3000 3000
                     'group_by'
3001 3001
                 );
3002
-            } elseif (! empty ($query_params['group_by'])) {
3002
+            } elseif ( ! empty ($query_params['group_by'])) {
3003 3003
                 $this->_extract_related_model_info_from_query_param(
3004 3004
                     $query_params['group_by'],
3005 3005
                     $query_info_carrier,
@@ -3021,7 +3021,7 @@  discard block
 block discarded – undo
3021 3021
                     $query_info_carrier,
3022 3022
                     'order_by'
3023 3023
                 );
3024
-            } elseif (! empty($query_params['order_by'])) {
3024
+            } elseif ( ! empty($query_params['order_by'])) {
3025 3025
                 $this->_extract_related_model_info_from_query_param(
3026 3026
                     $query_params['order_by'],
3027 3027
                     $query_info_carrier,
@@ -3056,8 +3056,8 @@  discard block
 block discarded – undo
3056 3056
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3057 3057
         $query_param_type
3058 3058
     ) {
3059
-        if (! empty($sub_query_params)) {
3060
-            $sub_query_params = (array)$sub_query_params;
3059
+        if ( ! empty($sub_query_params)) {
3060
+            $sub_query_params = (array) $sub_query_params;
3061 3061
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3062 3062
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3063 3063
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3068,7 +3068,7 @@  discard block
 block discarded – undo
3068 3068
                 //of array('Registration.TXN_ID'=>23)
3069 3069
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3070 3070
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3071
-                    if (! is_array($possibly_array_of_params)) {
3071
+                    if ( ! is_array($possibly_array_of_params)) {
3072 3072
                         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'))",
3073 3073
                             "event_espresso"),
3074 3074
                             $param, $possibly_array_of_params));
@@ -3084,7 +3084,7 @@  discard block
 block discarded – undo
3084 3084
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3085 3085
                     //indicating that $possible_array_of_params[1] is actually a field name,
3086 3086
                     //from which we should extract query parameters!
3087
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3087
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3088 3088
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3089 3089
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3090 3090
                     }
@@ -3114,8 +3114,8 @@  discard block
 block discarded – undo
3114 3114
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3115 3115
         $query_param_type
3116 3116
     ) {
3117
-        if (! empty($sub_query_params)) {
3118
-            if (! is_array($sub_query_params)) {
3117
+        if ( ! empty($sub_query_params)) {
3118
+            if ( ! is_array($sub_query_params)) {
3119 3119
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3120 3120
                     $sub_query_params));
3121 3121
             }
@@ -3144,7 +3144,7 @@  discard block
 block discarded – undo
3144 3144
      */
3145 3145
     public function _create_model_query_info_carrier($query_params)
3146 3146
     {
3147
-        if (! is_array($query_params)) {
3147
+        if ( ! is_array($query_params)) {
3148 3148
             EE_Error::doing_it_wrong(
3149 3149
                 'EEM_Base::_create_model_query_info_carrier',
3150 3150
                 sprintf(
@@ -3220,7 +3220,7 @@  discard block
 block discarded – undo
3220 3220
         //set limit
3221 3221
         if (array_key_exists('limit', $query_params)) {
3222 3222
             if (is_array($query_params['limit'])) {
3223
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3223
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3224 3224
                     $e = sprintf(
3225 3225
                         __(
3226 3226
                             "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)",
@@ -3228,12 +3228,12 @@  discard block
 block discarded – undo
3228 3228
                         ),
3229 3229
                         http_build_query($query_params['limit'])
3230 3230
                     );
3231
-                    throw new EE_Error($e . "|" . $e);
3231
+                    throw new EE_Error($e."|".$e);
3232 3232
                 }
3233 3233
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3234
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3235
-            } elseif (! empty ($query_params['limit'])) {
3236
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3234
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3235
+            } elseif ( ! empty ($query_params['limit'])) {
3236
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3237 3237
             }
3238 3238
         }
3239 3239
         //set order by
@@ -3265,10 +3265,10 @@  discard block
 block discarded – undo
3265 3265
                 $order_array = array();
3266 3266
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3267 3267
                     $order = $this->_extract_order($order);
3268
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3268
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3269 3269
                 }
3270
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3271
-            } elseif (! empty ($query_params['order_by'])) {
3270
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3271
+            } elseif ( ! empty ($query_params['order_by'])) {
3272 3272
                 $this->_extract_related_model_info_from_query_param(
3273 3273
                     $query_params['order_by'],
3274 3274
                     $query_object,
@@ -3279,18 +3279,18 @@  discard block
 block discarded – undo
3279 3279
                     ? $this->_extract_order($query_params['order'])
3280 3280
                     : 'DESC';
3281 3281
                 $query_object->set_order_by_sql(
3282
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3282
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3283 3283
                 );
3284 3284
             }
3285 3285
         }
3286 3286
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3287
-        if (! array_key_exists('order_by', $query_params)
3287
+        if ( ! array_key_exists('order_by', $query_params)
3288 3288
             && array_key_exists('order', $query_params)
3289 3289
             && ! empty($query_params['order'])
3290 3290
         ) {
3291 3291
             $pk_field = $this->get_primary_key_field();
3292 3292
             $order = $this->_extract_order($query_params['order']);
3293
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3293
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3294 3294
         }
3295 3295
         //set group by
3296 3296
         if (array_key_exists('group_by', $query_params)) {
@@ -3300,10 +3300,10 @@  discard block
 block discarded – undo
3300 3300
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3301 3301
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3302 3302
                 }
3303
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3304
-            } elseif (! empty ($query_params['group_by'])) {
3303
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3304
+            } elseif ( ! empty ($query_params['group_by'])) {
3305 3305
                 $query_object->set_group_by_sql(
3306
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3306
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3307 3307
                 );
3308 3308
             }
3309 3309
         }
@@ -3313,7 +3313,7 @@  discard block
 block discarded – undo
3313 3313
         }
3314 3314
         //now, just verify they didn't pass anything wack
3315 3315
         foreach ($query_params as $query_key => $query_value) {
3316
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3316
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3317 3317
                 throw new EE_Error(
3318 3318
                     sprintf(
3319 3319
                         __(
@@ -3413,7 +3413,7 @@  discard block
 block discarded – undo
3413 3413
             'minimum',
3414 3414
             'none',
3415 3415
         );
3416
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3416
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3417 3417
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3418 3418
                 "event_espresso"), $use_default_where_conditions,
3419 3419
                 implode(", ", $allowed_used_default_where_conditions_values)));
@@ -3466,7 +3466,7 @@  discard block
 block discarded – undo
3466 3466
     ) {
3467 3467
         $null_friendly_where_conditions = array();
3468 3468
         $none_overridden = true;
3469
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3469
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3470 3470
         foreach ($default_where_conditions as $key => $val) {
3471 3471
             if (isset($provided_where_conditions[$key])) {
3472 3472
                 $none_overridden = false;
@@ -3584,7 +3584,7 @@  discard block
 block discarded – undo
3584 3584
             foreach ($tables as $table_obj) {
3585 3585
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3586 3586
                                        . $table_obj->get_fully_qualified_pk_column();
3587
-                if (! in_array($qualified_pk_column, $selects)) {
3587
+                if ( ! in_array($qualified_pk_column, $selects)) {
3588 3588
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3589 3589
                 }
3590 3590
             }
@@ -3670,9 +3670,9 @@  discard block
 block discarded – undo
3670 3670
         //and
3671 3671
         //check if it's a field on a related model
3672 3672
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3673
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3673
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3674 3674
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3675
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3675
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3676 3676
                 if ($query_param === '') {
3677 3677
                     //nothing left to $query_param
3678 3678
                     //we should actually end in a field name, not a model like this!
@@ -3758,7 +3758,7 @@  discard block
 block discarded – undo
3758 3758
     {
3759 3759
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3760 3760
         if ($SQL) {
3761
-            return " WHERE " . $SQL;
3761
+            return " WHERE ".$SQL;
3762 3762
         } else {
3763 3763
             return '';
3764 3764
         }
@@ -3778,7 +3778,7 @@  discard block
 block discarded – undo
3778 3778
     {
3779 3779
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3780 3780
         if ($SQL) {
3781
-            return " HAVING " . $SQL;
3781
+            return " HAVING ".$SQL;
3782 3782
         } else {
3783 3783
             return '';
3784 3784
         }
@@ -3798,11 +3798,11 @@  discard block
 block discarded – undo
3798 3798
      */
3799 3799
     protected function _get_field_on_model($field_name, $model_name)
3800 3800
     {
3801
-        $model_class = 'EEM_' . $model_name;
3802
-        $model_filepath = $model_class . ".model.php";
3801
+        $model_class = 'EEM_'.$model_name;
3802
+        $model_filepath = $model_class.".model.php";
3803 3803
         if (is_readable($model_filepath)) {
3804 3804
             require_once($model_filepath);
3805
-            $model_instance = call_user_func($model_name . "::instance");
3805
+            $model_instance = call_user_func($model_name."::instance");
3806 3806
             /* @var $model_instance EEM_Base */
3807 3807
             return $model_instance->field_settings_for($field_name);
3808 3808
         } else {
@@ -3826,7 +3826,7 @@  discard block
 block discarded – undo
3826 3826
     {
3827 3827
         $where_clauses = array();
3828 3828
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3829
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3829
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
3830 3830
             if (in_array($query_param, $this->_logic_query_param_keys)) {
3831 3831
                 switch ($query_param) {
3832 3832
                     case 'not':
@@ -3854,7 +3854,7 @@  discard block
 block discarded – undo
3854 3854
             } else {
3855 3855
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
3856 3856
                 //if it's not a normal field, maybe it's a custom selection?
3857
-                if (! $field_obj) {
3857
+                if ( ! $field_obj) {
3858 3858
                     if (isset($this->_custom_selections[$query_param][1])) {
3859 3859
                         $field_obj = $this->_custom_selections[$query_param][1];
3860 3860
                     } else {
@@ -3863,7 +3863,7 @@  discard block
 block discarded – undo
3863 3863
                     }
3864 3864
                 }
3865 3865
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3866
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3866
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
3867 3867
             }
3868 3868
         }
3869 3869
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -3884,7 +3884,7 @@  discard block
 block discarded – undo
3884 3884
         if ($field) {
3885 3885
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3886 3886
                 $query_param);
3887
-            return $table_alias_prefix . $field->get_qualified_column();
3887
+            return $table_alias_prefix.$field->get_qualified_column();
3888 3888
         } elseif (array_key_exists($query_param, $this->_custom_selections)) {
3889 3889
             //maybe it's custom selection item?
3890 3890
             //if so, just use it as the "column name"
@@ -3931,7 +3931,7 @@  discard block
 block discarded – undo
3931 3931
     {
3932 3932
         if (is_array($op_and_value)) {
3933 3933
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
3934
-            if (! $operator) {
3934
+            if ( ! $operator) {
3935 3935
                 $php_array_like_string = array();
3936 3936
                 foreach ($op_and_value as $key => $value) {
3937 3937
                     $php_array_like_string[] = "$key=>$value";
@@ -3953,13 +3953,13 @@  discard block
 block discarded – undo
3953 3953
         }
3954 3954
         //check to see if the value is actually another field
3955 3955
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3956
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
3956
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
3957 3957
         } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
3958 3958
             //in this case, the value should be an array, or at least a comma-separated list
3959 3959
             //it will need to handle a little differently
3960 3960
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
3961 3961
             //note: $cleaned_value has already been run through $wpdb->prepare()
3962
-            return $operator . SP . $cleaned_value;
3962
+            return $operator.SP.$cleaned_value;
3963 3963
         } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
3964 3964
             //the value should be an array with count of two.
3965 3965
             if (count($value) !== 2) {
@@ -3974,7 +3974,7 @@  discard block
 block discarded – undo
3974 3974
                 );
3975 3975
             }
3976 3976
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
3977
-            return $operator . SP . $cleaned_value;
3977
+            return $operator.SP.$cleaned_value;
3978 3978
         } elseif (in_array($operator, $this->_null_style_operators)) {
3979 3979
             if ($value !== null) {
3980 3980
                 throw new EE_Error(
@@ -3992,9 +3992,9 @@  discard block
 block discarded – undo
3992 3992
         } elseif ($operator === 'LIKE' && ! is_array($value)) {
3993 3993
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
3994 3994
             //remove other junk. So just treat it as a string.
3995
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
3996
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3997
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
3995
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
3996
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3997
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
3998 3998
         } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3999 3999
             throw new EE_Error(
4000 4000
                 sprintf(
@@ -4006,7 +4006,7 @@  discard block
 block discarded – undo
4006 4006
                     $operator
4007 4007
                 )
4008 4008
             );
4009
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4009
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4010 4010
             throw new EE_Error(
4011 4011
                 sprintf(
4012 4012
                     __(
@@ -4047,7 +4047,7 @@  discard block
 block discarded – undo
4047 4047
         foreach ($values as $value) {
4048 4048
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4049 4049
         }
4050
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4050
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4051 4051
     }
4052 4052
 
4053 4053
 
@@ -4088,7 +4088,7 @@  discard block
 block discarded – undo
4088 4088
                                 . $main_table->get_table_name()
4089 4089
                                 . " WHERE FALSE";
4090 4090
         }
4091
-        return "(" . implode(",", $cleaned_values) . ")";
4091
+        return "(".implode(",", $cleaned_values).")";
4092 4092
     }
4093 4093
 
4094 4094
 
@@ -4107,7 +4107,7 @@  discard block
 block discarded – undo
4107 4107
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4108 4108
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4109 4109
         } else {//$field_obj should really just be a data type
4110
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4110
+            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4111 4111
                 throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4112 4112
                     $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4113 4113
             }
@@ -4191,11 +4191,11 @@  discard block
 block discarded – undo
4191 4191
             if ($table_obj instanceof EE_Primary_Table) {
4192 4192
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4193 4193
                     ? $table_obj->get_select_join_limit($limit)
4194
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4194
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4195 4195
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4196 4196
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4197 4197
                     ? $table_obj->get_select_join_limit_join($limit)
4198
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4198
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4199 4199
             }
4200 4200
         }
4201 4201
         return $SQL;
@@ -4283,12 +4283,12 @@  discard block
 block discarded – undo
4283 4283
      */
4284 4284
     public function get_related_model_obj($model_name)
4285 4285
     {
4286
-        $model_classname = "EEM_" . $model_name;
4287
-        if (! class_exists($model_classname)) {
4286
+        $model_classname = "EEM_".$model_name;
4287
+        if ( ! class_exists($model_classname)) {
4288 4288
             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",
4289 4289
                 'event_espresso'), $model_name, $model_classname));
4290 4290
         }
4291
-        return call_user_func($model_classname . "::instance");
4291
+        return call_user_func($model_classname."::instance");
4292 4292
     }
4293 4293
 
4294 4294
 
@@ -4335,7 +4335,7 @@  discard block
 block discarded – undo
4335 4335
     public function related_settings_for($relation_name)
4336 4336
     {
4337 4337
         $relatedModels = $this->relation_settings();
4338
-        if (! array_key_exists($relation_name, $relatedModels)) {
4338
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4339 4339
             throw new EE_Error(
4340 4340
                 sprintf(
4341 4341
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4362,7 +4362,7 @@  discard block
 block discarded – undo
4362 4362
     public function field_settings_for($fieldName)
4363 4363
     {
4364 4364
         $fieldSettings = $this->field_settings(true);
4365
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4365
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4366 4366
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4367 4367
                 get_class($this)));
4368 4368
         }
@@ -4437,7 +4437,7 @@  discard block
 block discarded – undo
4437 4437
                     break;
4438 4438
                 }
4439 4439
             }
4440
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4440
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4441 4441
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4442 4442
                     get_class($this)));
4443 4443
             }
@@ -4496,7 +4496,7 @@  discard block
 block discarded – undo
4496 4496
      */
4497 4497
     public function get_foreign_key_to($model_name)
4498 4498
     {
4499
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4499
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4500 4500
             foreach ($this->field_settings() as $field) {
4501 4501
                 if (
4502 4502
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4506,7 +4506,7 @@  discard block
 block discarded – undo
4506 4506
                     break;
4507 4507
                 }
4508 4508
             }
4509
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4509
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4510 4510
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4511 4511
                     'event_espresso'), $model_name, get_class($this)));
4512 4512
             }
@@ -4557,7 +4557,7 @@  discard block
 block discarded – undo
4557 4557
                 foreach ($this->_fields as $fields_corresponding_to_table) {
4558 4558
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4559 4559
                         /** @var $field_obj EE_Model_Field_Base */
4560
-                        if (! $field_obj->is_db_only_field()) {
4560
+                        if ( ! $field_obj->is_db_only_field()) {
4561 4561
                             $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4562 4562
                         }
4563 4563
                     }
@@ -4587,7 +4587,7 @@  discard block
 block discarded – undo
4587 4587
         $count_if_model_has_no_primary_key = 0;
4588 4588
         $has_primary_key = $this->has_primary_key_field();
4589 4589
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4590
-        foreach ((array)$rows as $row) {
4590
+        foreach ((array) $rows as $row) {
4591 4591
             if (empty($row)) {
4592 4592
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4593 4593
                 return array();
@@ -4605,7 +4605,7 @@  discard block
 block discarded – undo
4605 4605
                 }
4606 4606
             }
4607 4607
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4608
-            if (! $classInstance) {
4608
+            if ( ! $classInstance) {
4609 4609
                 throw new EE_Error(
4610 4610
                     sprintf(
4611 4611
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -4674,7 +4674,7 @@  discard block
 block discarded – undo
4674 4674
      */
4675 4675
     public function instantiate_class_from_array_or_object($cols_n_values)
4676 4676
     {
4677
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4677
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4678 4678
             $cols_n_values = get_object_vars($cols_n_values);
4679 4679
         }
4680 4680
         $primary_key = null;
@@ -4699,7 +4699,7 @@  discard block
 block discarded – undo
4699 4699
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4700 4700
         if ($primary_key) {
4701 4701
             $classInstance = $this->get_from_entity_map($primary_key);
4702
-            if (! $classInstance) {
4702
+            if ( ! $classInstance) {
4703 4703
                 $classInstance = EE_Registry::instance()
4704 4704
                                             ->load_class($className,
4705 4705
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -4750,12 +4750,12 @@  discard block
 block discarded – undo
4750 4750
     public function add_to_entity_map(EE_Base_Class $object)
4751 4751
     {
4752 4752
         $className = $this->_get_class_name();
4753
-        if (! $object instanceof $className) {
4753
+        if ( ! $object instanceof $className) {
4754 4754
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4755 4755
                 is_object($object) ? get_class($object) : $object, $className));
4756 4756
         }
4757 4757
         /** @var $object EE_Base_Class */
4758
-        if (! $object->ID()) {
4758
+        if ( ! $object->ID()) {
4759 4759
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4760 4760
                 "event_espresso"), get_class($this)));
4761 4761
         }
@@ -4825,7 +4825,7 @@  discard block
 block discarded – undo
4825 4825
             //there is a primary key on this table and its not set. Use defaults for all its columns
4826 4826
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
4827 4827
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4828
-                    if (! $field_obj->is_db_only_field()) {
4828
+                    if ( ! $field_obj->is_db_only_field()) {
4829 4829
                         //prepare field as if its coming from db
4830 4830
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4831 4831
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -4834,7 +4834,7 @@  discard block
 block discarded – undo
4834 4834
             } else {
4835 4835
                 //the table's rows existed. Use their values
4836 4836
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4837
-                    if (! $field_obj->is_db_only_field()) {
4837
+                    if ( ! $field_obj->is_db_only_field()) {
4838 4838
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4839 4839
                             $cols_n_values, $field_obj->get_qualified_column(),
4840 4840
                             $field_obj->get_table_column()
@@ -4951,7 +4951,7 @@  discard block
 block discarded – undo
4951 4951
      */
4952 4952
     private function _get_class_name()
4953 4953
     {
4954
-        return "EE_" . $this->get_this_model_name();
4954
+        return "EE_".$this->get_this_model_name();
4955 4955
     }
4956 4956
 
4957 4957
 
@@ -4966,7 +4966,7 @@  discard block
 block discarded – undo
4966 4966
      */
4967 4967
     public function item_name($quantity = 1)
4968 4968
     {
4969
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
4969
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
4970 4970
     }
4971 4971
 
4972 4972
 
@@ -4999,7 +4999,7 @@  discard block
 block discarded – undo
4999 4999
     {
5000 5000
         $className = get_class($this);
5001 5001
         $tagName = "FHEE__{$className}__{$methodName}";
5002
-        if (! has_filter($tagName)) {
5002
+        if ( ! has_filter($tagName)) {
5003 5003
             throw new EE_Error(
5004 5004
                 sprintf(
5005 5005
                     __('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 );',
@@ -5225,7 +5225,7 @@  discard block
 block discarded – undo
5225 5225
         $key_vals_in_combined_pk = array();
5226 5226
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5227 5227
         foreach ($key_fields as $key_field_name => $field_obj) {
5228
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5228
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5229 5229
                 return null;
5230 5230
             }
5231 5231
         }
@@ -5246,7 +5246,7 @@  discard block
 block discarded – undo
5246 5246
     {
5247 5247
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5248 5248
         foreach ($keys_it_should_have as $key) {
5249
-            if (! isset($key_vals[$key])) {
5249
+            if ( ! isset($key_vals[$key])) {
5250 5250
                 return false;
5251 5251
             }
5252 5252
         }
@@ -5300,7 +5300,7 @@  discard block
 block discarded – undo
5300 5300
      */
5301 5301
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5302 5302
     {
5303
-        if (! is_array($query_params)) {
5303
+        if ( ! is_array($query_params)) {
5304 5304
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5305 5305
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5306 5306
                     gettype($query_params)), '4.6.0');
@@ -5392,7 +5392,7 @@  discard block
 block discarded – undo
5392 5392
      */
5393 5393
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5394 5394
     {
5395
-        if (! $this->has_primary_key_field()) {
5395
+        if ( ! $this->has_primary_key_field()) {
5396 5396
             if (WP_DEBUG) {
5397 5397
                 EE_Error::add_error(
5398 5398
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5405,7 +5405,7 @@  discard block
 block discarded – undo
5405 5405
         $IDs = array();
5406 5406
         foreach ($model_objects as $model_object) {
5407 5407
             $id = $model_object->ID();
5408
-            if (! $id) {
5408
+            if ( ! $id) {
5409 5409
                 if ($filter_out_empty_ids) {
5410 5410
                     continue;
5411 5411
                 }
@@ -5501,8 +5501,8 @@  discard block
 block discarded – undo
5501 5501
         $missing_caps = array();
5502 5502
         $cap_restrictions = $this->cap_restrictions($context);
5503 5503
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5504
-            if (! EE_Capabilities::instance()
5505
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5504
+            if ( ! EE_Capabilities::instance()
5505
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5506 5506
             ) {
5507 5507
                 $missing_caps[$cap] = $restriction_if_no_cap;
5508 5508
             }
Please login to merge, or discard this patch.
Indentation   +5678 added lines, -5678 removed lines patch added patch discarded remove patch
@@ -29,5686 +29,5686 @@
 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 (
3474
-        in_array(
3475
-            $use_default_where_conditions,
3476
-            array(
3477
-                EEM_Base::default_where_conditions_all,
3478
-                EEM_Base::default_where_conditions_this_only,
3479
-                EEM_Base::default_where_conditions_minimum_others,
3480
-            ),
3481
-            true
3482
-        )
3483
-        ) {
3484
-            $universal_query_params = $this->_get_default_where_conditions();
3485
-        } else if ($use_default_where_conditions === EEM_Base::default_where_conditions_minimum_all) {
3486
-            $universal_query_params = $this->_get_minimum_where_conditions();
3487
-        }
3488
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3489
-            $related_model = $this->get_related_model_obj($model_name);
3490
-            if (
3491
-            in_array(
3492
-                $use_default_where_conditions,
3493
-                array(
3494
-                    EEM_Base::default_where_conditions_all,
3495
-                    EEM_Base::default_where_conditions_others_only,
3496
-                ),
3497
-                true
3498
-            )
3499
-            ) {
3500
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3501
-            } elseif (
3502
-            in_array(
3503
-                $use_default_where_conditions,
3504
-                array(
3505
-                    EEM_Base::default_where_conditions_minimum_others,
3506
-                    EEM_Base::default_where_conditions_minimum_all,
3507
-                ),
3508
-                true
3509
-            )
3510
-            ) {
3511
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3512
-            } else {
3513
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3514
-                continue;
3515
-            }
3516
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3517
-                $related_model_universal_where_params,
3518
-                $where_query_params,
3519
-                $related_model,
3520
-                $model_relation_path
3521
-            );
3522
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3523
-                $universal_query_params,
3524
-                $overrides
3525
-            );
3526
-        }
3527
-        return $universal_query_params;
3528
-    }
3529
-
3530
-
3531
-
3532
-    /**
3533
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3534
-     * then we also add a special where condition which allows for that model's primary key
3535
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3536
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3537
-     *
3538
-     * @param array    $default_where_conditions
3539
-     * @param array    $provided_where_conditions
3540
-     * @param EEM_Base $model
3541
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3542
-     * @return array like EEM_Base::get_all's $query_params[0]
3543
-     * @throws \EE_Error
3544
-     */
3545
-    private function _override_defaults_or_make_null_friendly(
3546
-        $default_where_conditions,
3547
-        $provided_where_conditions,
3548
-        $model,
3549
-        $model_relation_path
3550
-    ) {
3551
-        $null_friendly_where_conditions = array();
3552
-        $none_overridden = true;
3553
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3554
-        foreach ($default_where_conditions as $key => $val) {
3555
-            if (isset($provided_where_conditions[$key])) {
3556
-                $none_overridden = false;
3557
-            } else {
3558
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3559
-            }
3560
-        }
3561
-        if ($none_overridden && $default_where_conditions) {
3562
-            if ($model->has_primary_key_field()) {
3563
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3564
-                                                                                . "."
3565
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3566
-            }/*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 (
3474
+		in_array(
3475
+			$use_default_where_conditions,
3476
+			array(
3477
+				EEM_Base::default_where_conditions_all,
3478
+				EEM_Base::default_where_conditions_this_only,
3479
+				EEM_Base::default_where_conditions_minimum_others,
3480
+			),
3481
+			true
3482
+		)
3483
+		) {
3484
+			$universal_query_params = $this->_get_default_where_conditions();
3485
+		} else if ($use_default_where_conditions === EEM_Base::default_where_conditions_minimum_all) {
3486
+			$universal_query_params = $this->_get_minimum_where_conditions();
3487
+		}
3488
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3489
+			$related_model = $this->get_related_model_obj($model_name);
3490
+			if (
3491
+			in_array(
3492
+				$use_default_where_conditions,
3493
+				array(
3494
+					EEM_Base::default_where_conditions_all,
3495
+					EEM_Base::default_where_conditions_others_only,
3496
+				),
3497
+				true
3498
+			)
3499
+			) {
3500
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3501
+			} elseif (
3502
+			in_array(
3503
+				$use_default_where_conditions,
3504
+				array(
3505
+					EEM_Base::default_where_conditions_minimum_others,
3506
+					EEM_Base::default_where_conditions_minimum_all,
3507
+				),
3508
+				true
3509
+			)
3510
+			) {
3511
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3512
+			} else {
3513
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3514
+				continue;
3515
+			}
3516
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3517
+				$related_model_universal_where_params,
3518
+				$where_query_params,
3519
+				$related_model,
3520
+				$model_relation_path
3521
+			);
3522
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3523
+				$universal_query_params,
3524
+				$overrides
3525
+			);
3526
+		}
3527
+		return $universal_query_params;
3528
+	}
3529
+
3530
+
3531
+
3532
+	/**
3533
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3534
+	 * then we also add a special where condition which allows for that model's primary key
3535
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3536
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3537
+	 *
3538
+	 * @param array    $default_where_conditions
3539
+	 * @param array    $provided_where_conditions
3540
+	 * @param EEM_Base $model
3541
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3542
+	 * @return array like EEM_Base::get_all's $query_params[0]
3543
+	 * @throws \EE_Error
3544
+	 */
3545
+	private function _override_defaults_or_make_null_friendly(
3546
+		$default_where_conditions,
3547
+		$provided_where_conditions,
3548
+		$model,
3549
+		$model_relation_path
3550
+	) {
3551
+		$null_friendly_where_conditions = array();
3552
+		$none_overridden = true;
3553
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3554
+		foreach ($default_where_conditions as $key => $val) {
3555
+			if (isset($provided_where_conditions[$key])) {
3556
+				$none_overridden = false;
3557
+			} else {
3558
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3559
+			}
3560
+		}
3561
+		if ($none_overridden && $default_where_conditions) {
3562
+			if ($model->has_primary_key_field()) {
3563
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3564
+																				. "."
3565
+																				. $model->primary_key_name()] = array('IS NULL');
3566
+			}/*else{
3567 3567
 				//@todo NO PK, use other defaults
3568 3568
 			}*/
3569
-        }
3570
-        return $null_friendly_where_conditions;
3571
-    }
3572
-
3573
-
3574
-
3575
-    /**
3576
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3577
-     * default where conditions on all get_all, update, and delete queries done by this model.
3578
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3579
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3580
-     *
3581
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3582
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3583
-     */
3584
-    private function _get_default_where_conditions($model_relation_path = null)
3585
-    {
3586
-        if ($this->_ignore_where_strategy) {
3587
-            return array();
3588
-        }
3589
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3590
-    }
3591
-
3592
-
3593
-
3594
-    /**
3595
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3596
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3597
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3598
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3599
-     * Similar to _get_default_where_conditions
3600
-     *
3601
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3602
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3603
-     */
3604
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3605
-    {
3606
-        if ($this->_ignore_where_strategy) {
3607
-            return array();
3608
-        }
3609
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3610
-    }
3611
-
3612
-
3613
-
3614
-    /**
3615
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3616
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3617
-     *
3618
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3619
-     * @return string
3620
-     * @throws \EE_Error
3621
-     */
3622
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3623
-    {
3624
-        $selects = $this->_get_columns_to_select_for_this_model();
3625
-        foreach (
3626
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3627
-            $name_of_other_model_included
3628
-        ) {
3629
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3630
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3631
-            foreach ($other_model_selects as $key => $value) {
3632
-                $selects[] = $value;
3633
-            }
3634
-        }
3635
-        return implode(", ", $selects);
3636
-    }
3637
-
3638
-
3639
-
3640
-    /**
3641
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3642
-     * So that's going to be the columns for all the fields on the model
3643
-     *
3644
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3645
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3646
-     */
3647
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3648
-    {
3649
-        $fields = $this->field_settings();
3650
-        $selects = array();
3651
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3652
-            $this->get_this_model_name());
3653
-        foreach ($fields as $field_obj) {
3654
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3655
-                         . $field_obj->get_table_alias()
3656
-                         . "."
3657
-                         . $field_obj->get_table_column()
3658
-                         . " AS '"
3659
-                         . $table_alias_with_model_relation_chain_prefix
3660
-                         . $field_obj->get_table_alias()
3661
-                         . "."
3662
-                         . $field_obj->get_table_column()
3663
-                         . "'";
3664
-        }
3665
-        //make sure we are also getting the PKs of each table
3666
-        $tables = $this->get_tables();
3667
-        if (count($tables) > 1) {
3668
-            foreach ($tables as $table_obj) {
3669
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3670
-                                       . $table_obj->get_fully_qualified_pk_column();
3671
-                if (! in_array($qualified_pk_column, $selects)) {
3672
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3673
-                }
3674
-            }
3675
-        }
3676
-        return $selects;
3677
-    }
3678
-
3679
-
3680
-
3681
-    /**
3682
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3683
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3684
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3685
-     * SQL for joining, and the data types
3686
-     *
3687
-     * @param null|string                 $original_query_param
3688
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3689
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3690
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3691
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3692
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3693
-     *                                                          or 'Registration's
3694
-     * @param string                      $original_query_param what it originally was (eg
3695
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3696
-     *                                                          matches $query_param
3697
-     * @throws EE_Error
3698
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3699
-     */
3700
-    private function _extract_related_model_info_from_query_param(
3701
-        $query_param,
3702
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3703
-        $query_param_type,
3704
-        $original_query_param = null
3705
-    ) {
3706
-        if ($original_query_param === null) {
3707
-            $original_query_param = $query_param;
3708
-        }
3709
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3710
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3711
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3712
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3713
-        //check to see if we have a field on this model
3714
-        $this_model_fields = $this->field_settings(true);
3715
-        if (array_key_exists($query_param, $this_model_fields)) {
3716
-            if ($allow_fields) {
3717
-                return;
3718
-            } else {
3719
-                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",
3720
-                    "event_espresso"),
3721
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3722
-            }
3723
-        } //check if this is a special logic query param
3724
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3725
-            if ($allow_logic_query_params) {
3726
-                return;
3727
-            } else {
3728
-                throw new EE_Error(
3729
-                    sprintf(
3730
-                        __('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',
3731
-                            'event_espresso'),
3732
-                        implode('", "', $this->_logic_query_param_keys),
3733
-                        $query_param,
3734
-                        get_class($this),
3735
-                        '<br />',
3736
-                        "\t"
3737
-                        . ' $passed_in_query_info = <pre>'
3738
-                        . print_r($passed_in_query_info, true)
3739
-                        . '</pre>'
3740
-                        . "\n\t"
3741
-                        . ' $query_param_type = '
3742
-                        . $query_param_type
3743
-                        . "\n\t"
3744
-                        . ' $original_query_param = '
3745
-                        . $original_query_param
3746
-                    )
3747
-                );
3748
-            }
3749
-        } //check if it's a custom selection
3750
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3751
-            return;
3752
-        }
3753
-        //check if has a model name at the beginning
3754
-        //and
3755
-        //check if it's a field on a related model
3756
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3757
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3758
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3759
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3760
-                if ($query_param === '') {
3761
-                    //nothing left to $query_param
3762
-                    //we should actually end in a field name, not a model like this!
3763
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3764
-                        "event_espresso"),
3765
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3766
-                } else {
3767
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3768
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3769
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3770
-                    return;
3771
-                }
3772
-            } elseif ($query_param === $valid_related_model_name) {
3773
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3774
-                return;
3775
-            }
3776
-        }
3777
-        //ok so $query_param didn't start with a model name
3778
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3779
-        //it's wack, that's what it is
3780
-        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",
3781
-            "event_espresso"),
3782
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3783
-    }
3784
-
3785
-
3786
-
3787
-    /**
3788
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3789
-     * and store it on $passed_in_query_info
3790
-     *
3791
-     * @param string                      $model_name
3792
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3793
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3794
-     *                                                          model and $model_name. Eg, if we are querying Event,
3795
-     *                                                          and are adding a join to 'Payment' with the original
3796
-     *                                                          query param key
3797
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3798
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3799
-     *                                                          Payment wants to add default query params so that it
3800
-     *                                                          will know what models to prepend onto its default query
3801
-     *                                                          params or in case it wants to rename tables (in case
3802
-     *                                                          there are multiple joins to the same table)
3803
-     * @return void
3804
-     * @throws \EE_Error
3805
-     */
3806
-    private function _add_join_to_model(
3807
-        $model_name,
3808
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3809
-        $original_query_param
3810
-    ) {
3811
-        $relation_obj = $this->related_settings_for($model_name);
3812
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3813
-        //check if the relation is HABTM, because then we're essentially doing two joins
3814
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3815
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3816
-            $join_model_obj = $relation_obj->get_join_model();
3817
-            //replace the model specified with the join model for this relation chain, whi
3818
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3819
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3820
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3821
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3822
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3823
-            $passed_in_query_info->merge($new_query_info);
3824
-        }
3825
-        //now just join to the other table pointed to by the relation object, and add its data types
3826
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3827
-            array($model_relation_chain => $model_name),
3828
-            $relation_obj->get_join_statement($model_relation_chain));
3829
-        $passed_in_query_info->merge($new_query_info);
3830
-    }
3831
-
3832
-
3833
-
3834
-    /**
3835
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3836
-     *
3837
-     * @param array $where_params like EEM_Base::get_all
3838
-     * @return string of SQL
3839
-     * @throws \EE_Error
3840
-     */
3841
-    private function _construct_where_clause($where_params)
3842
-    {
3843
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3844
-        if ($SQL) {
3845
-            return " WHERE " . $SQL;
3846
-        } else {
3847
-            return '';
3848
-        }
3849
-    }
3850
-
3851
-
3852
-
3853
-    /**
3854
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3855
-     * and should be passed HAVING parameters, not WHERE parameters
3856
-     *
3857
-     * @param array $having_params
3858
-     * @return string
3859
-     * @throws \EE_Error
3860
-     */
3861
-    private function _construct_having_clause($having_params)
3862
-    {
3863
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3864
-        if ($SQL) {
3865
-            return " HAVING " . $SQL;
3866
-        } else {
3867
-            return '';
3868
-        }
3869
-    }
3870
-
3871
-
3872
-
3873
-    /**
3874
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3875
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3876
-     * EEM_Attendee.
3877
-     *
3878
-     * @param string $field_name
3879
-     * @param string $model_name
3880
-     * @return EE_Model_Field_Base
3881
-     * @throws EE_Error
3882
-     */
3883
-    protected function _get_field_on_model($field_name, $model_name)
3884
-    {
3885
-        $model_class = 'EEM_' . $model_name;
3886
-        $model_filepath = $model_class . ".model.php";
3887
-        if (is_readable($model_filepath)) {
3888
-            require_once($model_filepath);
3889
-            $model_instance = call_user_func($model_name . "::instance");
3890
-            /* @var $model_instance EEM_Base */
3891
-            return $model_instance->field_settings_for($field_name);
3892
-        } else {
3893
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3894
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3895
-        }
3896
-    }
3897
-
3898
-
3899
-
3900
-    /**
3901
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3902
-     * Event_Meta.meta_value = 'foo'))"
3903
-     *
3904
-     * @param array  $where_params see EEM_Base::get_all for documentation
3905
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3906
-     * @throws EE_Error
3907
-     * @return string of SQL
3908
-     */
3909
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3910
-    {
3911
-        $where_clauses = array();
3912
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3913
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3914
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3915
-                switch ($query_param) {
3916
-                    case 'not':
3917
-                    case 'NOT':
3918
-                        $where_clauses[] = "! ("
3919
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3920
-                                $glue)
3921
-                                           . ")";
3922
-                        break;
3923
-                    case 'and':
3924
-                    case 'AND':
3925
-                        $where_clauses[] = " ("
3926
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3927
-                                ' AND ')
3928
-                                           . ")";
3929
-                        break;
3930
-                    case 'or':
3931
-                    case 'OR':
3932
-                        $where_clauses[] = " ("
3933
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3934
-                                ' OR ')
3935
-                                           . ")";
3936
-                        break;
3937
-                }
3938
-            } else {
3939
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3940
-                //if it's not a normal field, maybe it's a custom selection?
3941
-                if (! $field_obj) {
3942
-                    if (isset($this->_custom_selections[$query_param][1])) {
3943
-                        $field_obj = $this->_custom_selections[$query_param][1];
3944
-                    } else {
3945
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3946
-                            "event_espresso"), $query_param));
3947
-                    }
3948
-                }
3949
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3950
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3951
-            }
3952
-        }
3953
-        return $where_clauses ? implode($glue, $where_clauses) : '';
3954
-    }
3955
-
3956
-
3957
-
3958
-    /**
3959
-     * Takes the input parameter and extract the table name (alias) and column name
3960
-     *
3961
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3962
-     * @throws EE_Error
3963
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3964
-     */
3965
-    private function _deduce_column_name_from_query_param($query_param)
3966
-    {
3967
-        $field = $this->_deduce_field_from_query_param($query_param);
3968
-        if ($field) {
3969
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3970
-                $query_param);
3971
-            return $table_alias_prefix . $field->get_qualified_column();
3972
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
3973
-            //maybe it's custom selection item?
3974
-            //if so, just use it as the "column name"
3975
-            return $query_param;
3976
-        } else {
3977
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
3978
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
3979
-        }
3980
-    }
3981
-
3982
-
3983
-
3984
-    /**
3985
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
3986
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
3987
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3988
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3989
-     *
3990
-     * @param string $condition_query_param_key
3991
-     * @return string
3992
-     */
3993
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
3994
-    {
3995
-        $pos_of_star = strpos($condition_query_param_key, '*');
3996
-        if ($pos_of_star === false) {
3997
-            return $condition_query_param_key;
3998
-        } else {
3999
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4000
-            return $condition_query_param_sans_star;
4001
-        }
4002
-    }
4003
-
4004
-
4005
-
4006
-    /**
4007
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4008
-     *
4009
-     * @param                            mixed      array | string    $op_and_value
4010
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4011
-     * @throws EE_Error
4012
-     * @return string
4013
-     */
4014
-    private function _construct_op_and_value($op_and_value, $field_obj)
4015
-    {
4016
-        if (is_array($op_and_value)) {
4017
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4018
-            if (! $operator) {
4019
-                $php_array_like_string = array();
4020
-                foreach ($op_and_value as $key => $value) {
4021
-                    $php_array_like_string[] = "$key=>$value";
4022
-                }
4023
-                throw new EE_Error(
4024
-                    sprintf(
4025
-                        __(
4026
-                            "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))",
4027
-                            "event_espresso"
4028
-                        ),
4029
-                        implode(",", $php_array_like_string)
4030
-                    )
4031
-                );
4032
-            }
4033
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4034
-        } else {
4035
-            $operator = '=';
4036
-            $value = $op_and_value;
4037
-        }
4038
-        //check to see if the value is actually another field
4039
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4040
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4041
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4042
-            //in this case, the value should be an array, or at least a comma-separated list
4043
-            //it will need to handle a little differently
4044
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4045
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4046
-            return $operator . SP . $cleaned_value;
4047
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4048
-            //the value should be an array with count of two.
4049
-            if (count($value) !== 2) {
4050
-                throw new EE_Error(
4051
-                    sprintf(
4052
-                        __(
4053
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4054
-                            'event_espresso'
4055
-                        ),
4056
-                        "BETWEEN"
4057
-                    )
4058
-                );
4059
-            }
4060
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4061
-            return $operator . SP . $cleaned_value;
4062
-        } elseif (in_array($operator, $this->_null_style_operators)) {
4063
-            if ($value !== null) {
4064
-                throw new EE_Error(
4065
-                    sprintf(
4066
-                        __(
4067
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4068
-                            "event_espresso"
4069
-                        ),
4070
-                        $value,
4071
-                        $operator
4072
-                    )
4073
-                );
4074
-            }
4075
-            return $operator;
4076
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
4077
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4078
-            //remove other junk. So just treat it as a string.
4079
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4080
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4081
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4082
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4083
-            throw new EE_Error(
4084
-                sprintf(
4085
-                    __(
4086
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4087
-                        'event_espresso'
4088
-                    ),
4089
-                    $operator,
4090
-                    $operator
4091
-                )
4092
-            );
4093
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4094
-            throw new EE_Error(
4095
-                sprintf(
4096
-                    __(
4097
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4098
-                        'event_espresso'
4099
-                    ),
4100
-                    $operator,
4101
-                    $operator
4102
-                )
4103
-            );
4104
-        } else {
4105
-            throw new EE_Error(
4106
-                sprintf(
4107
-                    __(
4108
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4109
-                        "event_espresso"
4110
-                    ),
4111
-                    http_build_query($op_and_value)
4112
-                )
4113
-            );
4114
-        }
4115
-    }
4116
-
4117
-
4118
-
4119
-    /**
4120
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4121
-     *
4122
-     * @param array                      $values
4123
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4124
-     *                                              '%s'
4125
-     * @return string
4126
-     * @throws \EE_Error
4127
-     */
4128
-    public function _construct_between_value($values, $field_obj)
4129
-    {
4130
-        $cleaned_values = array();
4131
-        foreach ($values as $value) {
4132
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4133
-        }
4134
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4135
-    }
4136
-
4137
-
4138
-
4139
-    /**
4140
-     * Takes an array or a comma-separated list of $values and cleans them
4141
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4142
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4143
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4144
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4145
-     *
4146
-     * @param mixed                      $values    array or comma-separated string
4147
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4148
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4149
-     * @throws \EE_Error
4150
-     */
4151
-    public function _construct_in_value($values, $field_obj)
4152
-    {
4153
-        //check if the value is a CSV list
4154
-        if (is_string($values)) {
4155
-            //in which case, turn it into an array
4156
-            $values = explode(",", $values);
4157
-        }
4158
-        $cleaned_values = array();
4159
-        foreach ($values as $value) {
4160
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4161
-        }
4162
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4163
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4164
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4165
-        if (empty($cleaned_values)) {
4166
-            $all_fields = $this->field_settings();
4167
-            $a_field = array_shift($all_fields);
4168
-            $main_table = $this->_get_main_table();
4169
-            $cleaned_values[] = "SELECT "
4170
-                                . $a_field->get_table_column()
4171
-                                . " FROM "
4172
-                                . $main_table->get_table_name()
4173
-                                . " WHERE FALSE";
4174
-        }
4175
-        return "(" . implode(",", $cleaned_values) . ")";
4176
-    }
4177
-
4178
-
4179
-
4180
-    /**
4181
-     * @param mixed                      $value
4182
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4183
-     * @throws EE_Error
4184
-     * @return false|null|string
4185
-     */
4186
-    private function _wpdb_prepare_using_field($value, $field_obj)
4187
-    {
4188
-        /** @type WPDB $wpdb */
4189
-        global $wpdb;
4190
-        if ($field_obj instanceof EE_Model_Field_Base) {
4191
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4192
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4193
-        } else {//$field_obj should really just be a data type
4194
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4195
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4196
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4197
-            }
4198
-            return $wpdb->prepare($field_obj, $value);
4199
-        }
4200
-    }
4201
-
4202
-
4203
-
4204
-    /**
4205
-     * Takes the input parameter and finds the model field that it indicates.
4206
-     *
4207
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4208
-     * @throws EE_Error
4209
-     * @return EE_Model_Field_Base
4210
-     */
4211
-    protected function _deduce_field_from_query_param($query_param_name)
4212
-    {
4213
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4214
-        //which will help us find the database table and column
4215
-        $query_param_parts = explode(".", $query_param_name);
4216
-        if (empty($query_param_parts)) {
4217
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4218
-                'event_espresso'), $query_param_name));
4219
-        }
4220
-        $number_of_parts = count($query_param_parts);
4221
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4222
-        if ($number_of_parts === 1) {
4223
-            $field_name = $last_query_param_part;
4224
-            $model_obj = $this;
4225
-        } else {// $number_of_parts >= 2
4226
-            //the last part is the column name, and there are only 2parts. therefore...
4227
-            $field_name = $last_query_param_part;
4228
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4229
-        }
4230
-        try {
4231
-            return $model_obj->field_settings_for($field_name);
4232
-        } catch (EE_Error $e) {
4233
-            return null;
4234
-        }
4235
-    }
4236
-
4237
-
4238
-
4239
-    /**
4240
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4241
-     * alias and column which corresponds to it
4242
-     *
4243
-     * @param string $field_name
4244
-     * @throws EE_Error
4245
-     * @return string
4246
-     */
4247
-    public function _get_qualified_column_for_field($field_name)
4248
-    {
4249
-        $all_fields = $this->field_settings();
4250
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4251
-        if ($field) {
4252
-            return $field->get_qualified_column();
4253
-        } else {
4254
-            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.",
4255
-                'event_espresso'), $field_name, get_class($this)));
4256
-        }
4257
-    }
4258
-
4259
-
4260
-
4261
-    /**
4262
-     * constructs the select use on special limit joins
4263
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4264
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4265
-     * (as that is typically where the limits would be set).
4266
-     *
4267
-     * @param  string       $table_alias The table the select is being built for
4268
-     * @param  mixed|string $limit       The limit for this select
4269
-     * @return string                The final select join element for the query.
4270
-     */
4271
-    public function _construct_limit_join_select($table_alias, $limit)
4272
-    {
4273
-        $SQL = '';
4274
-        foreach ($this->_tables as $table_obj) {
4275
-            if ($table_obj instanceof EE_Primary_Table) {
4276
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4277
-                    ? $table_obj->get_select_join_limit($limit)
4278
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4279
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4280
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4281
-                    ? $table_obj->get_select_join_limit_join($limit)
4282
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4283
-            }
4284
-        }
4285
-        return $SQL;
4286
-    }
4287
-
4288
-
4289
-
4290
-    /**
4291
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4292
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4293
-     *
4294
-     * @return string SQL
4295
-     * @throws \EE_Error
4296
-     */
4297
-    public function _construct_internal_join()
4298
-    {
4299
-        $SQL = $this->_get_main_table()->get_table_sql();
4300
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4301
-        return $SQL;
4302
-    }
4303
-
4304
-
4305
-
4306
-    /**
4307
-     * Constructs the SQL for joining all the tables on this model.
4308
-     * Normally $alias should be the primary table's alias, but in cases where
4309
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4310
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4311
-     * alias, this will construct SQL like:
4312
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4313
-     * With $alias being a secondary table's alias, this will construct SQL like:
4314
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4315
-     *
4316
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4317
-     * @return string
4318
-     */
4319
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4320
-    {
4321
-        $SQL = '';
4322
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4323
-        foreach ($this->_tables as $table_obj) {
4324
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4325
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4326
-                    //so we're joining to this table, meaning the table is already in
4327
-                    //the FROM statement, BUT the primary table isn't. So we want
4328
-                    //to add the inverse join sql
4329
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4330
-                } else {
4331
-                    //just add a regular JOIN to this table from the primary table
4332
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4333
-                }
4334
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4335
-        }
4336
-        return $SQL;
4337
-    }
4338
-
4339
-
4340
-
4341
-    /**
4342
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4343
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4344
-     * their data type (eg, '%s', '%d', etc)
4345
-     *
4346
-     * @return array
4347
-     */
4348
-    public function _get_data_types()
4349
-    {
4350
-        $data_types = array();
4351
-        foreach ($this->field_settings() as $field_obj) {
4352
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4353
-            /** @var $field_obj EE_Model_Field_Base */
4354
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4355
-        }
4356
-        return $data_types;
4357
-    }
4358
-
4359
-
4360
-
4361
-    /**
4362
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4363
-     *
4364
-     * @param string $model_name
4365
-     * @throws EE_Error
4366
-     * @return EEM_Base
4367
-     */
4368
-    public function get_related_model_obj($model_name)
4369
-    {
4370
-        $model_classname = "EEM_" . $model_name;
4371
-        if (! class_exists($model_classname)) {
4372
-            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",
4373
-                'event_espresso'), $model_name, $model_classname));
4374
-        }
4375
-        return call_user_func($model_classname . "::instance");
4376
-    }
4377
-
4378
-
4379
-
4380
-    /**
4381
-     * Returns the array of EE_ModelRelations for this model.
4382
-     *
4383
-     * @return EE_Model_Relation_Base[]
4384
-     */
4385
-    public function relation_settings()
4386
-    {
4387
-        return $this->_model_relations;
4388
-    }
4389
-
4390
-
4391
-
4392
-    /**
4393
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4394
-     * because without THOSE models, this model probably doesn't have much purpose.
4395
-     * (Eg, without an event, datetimes have little purpose.)
4396
-     *
4397
-     * @return EE_Belongs_To_Relation[]
4398
-     */
4399
-    public function belongs_to_relations()
4400
-    {
4401
-        $belongs_to_relations = array();
4402
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4403
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4404
-                $belongs_to_relations[$model_name] = $relation_obj;
4405
-            }
4406
-        }
4407
-        return $belongs_to_relations;
4408
-    }
4409
-
4410
-
4411
-
4412
-    /**
4413
-     * Returns the specified EE_Model_Relation, or throws an exception
4414
-     *
4415
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4416
-     * @throws EE_Error
4417
-     * @return EE_Model_Relation_Base
4418
-     */
4419
-    public function related_settings_for($relation_name)
4420
-    {
4421
-        $relatedModels = $this->relation_settings();
4422
-        if (! array_key_exists($relation_name, $relatedModels)) {
4423
-            throw new EE_Error(
4424
-                sprintf(
4425
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4426
-                        'event_espresso'),
4427
-                    $relation_name,
4428
-                    $this->_get_class_name(),
4429
-                    implode(', ', array_keys($relatedModels))
4430
-                )
4431
-            );
4432
-        }
4433
-        return $relatedModels[$relation_name];
4434
-    }
4435
-
4436
-
4437
-
4438
-    /**
4439
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4440
-     * fields
4441
-     *
4442
-     * @param string $fieldName
4443
-     * @throws EE_Error
4444
-     * @return EE_Model_Field_Base
4445
-     */
4446
-    public function field_settings_for($fieldName)
4447
-    {
4448
-        $fieldSettings = $this->field_settings(true);
4449
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4450
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4451
-                get_class($this)));
4452
-        }
4453
-        return $fieldSettings[$fieldName];
4454
-    }
4455
-
4456
-
4457
-
4458
-    /**
4459
-     * Checks if this field exists on this model
4460
-     *
4461
-     * @param string $fieldName a key in the model's _field_settings array
4462
-     * @return boolean
4463
-     */
4464
-    public function has_field($fieldName)
4465
-    {
4466
-        $fieldSettings = $this->field_settings(true);
4467
-        if (isset($fieldSettings[$fieldName])) {
4468
-            return true;
4469
-        } else {
4470
-            return false;
4471
-        }
4472
-    }
4473
-
4474
-
4475
-
4476
-    /**
4477
-     * Returns whether or not this model has a relation to the specified model
4478
-     *
4479
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4480
-     * @return boolean
4481
-     */
4482
-    public function has_relation($relation_name)
4483
-    {
4484
-        $relations = $this->relation_settings();
4485
-        if (isset($relations[$relation_name])) {
4486
-            return true;
4487
-        } else {
4488
-            return false;
4489
-        }
4490
-    }
4491
-
4492
-
4493
-
4494
-    /**
4495
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4496
-     * Eg, on EE_Answer that would be ANS_ID field object
4497
-     *
4498
-     * @param $field_obj
4499
-     * @return boolean
4500
-     */
4501
-    public function is_primary_key_field($field_obj)
4502
-    {
4503
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4504
-    }
4505
-
4506
-
4507
-
4508
-    /**
4509
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4510
-     * Eg, on EE_Answer that would be ANS_ID field object
4511
-     *
4512
-     * @return EE_Model_Field_Base
4513
-     * @throws EE_Error
4514
-     */
4515
-    public function get_primary_key_field()
4516
-    {
4517
-        if ($this->_primary_key_field === null) {
4518
-            foreach ($this->field_settings(true) as $field_obj) {
4519
-                if ($this->is_primary_key_field($field_obj)) {
4520
-                    $this->_primary_key_field = $field_obj;
4521
-                    break;
4522
-                }
4523
-            }
4524
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4525
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4526
-                    get_class($this)));
4527
-            }
4528
-        }
4529
-        return $this->_primary_key_field;
4530
-    }
4531
-
4532
-
4533
-
4534
-    /**
4535
-     * Returns whether or not not there is a primary key on this model.
4536
-     * Internally does some caching.
4537
-     *
4538
-     * @return boolean
4539
-     */
4540
-    public function has_primary_key_field()
4541
-    {
4542
-        if ($this->_has_primary_key_field === null) {
4543
-            try {
4544
-                $this->get_primary_key_field();
4545
-                $this->_has_primary_key_field = true;
4546
-            } catch (EE_Error $e) {
4547
-                $this->_has_primary_key_field = false;
4548
-            }
4549
-        }
4550
-        return $this->_has_primary_key_field;
4551
-    }
4552
-
4553
-
4554
-
4555
-    /**
4556
-     * Finds the first field of type $field_class_name.
4557
-     *
4558
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4559
-     *                                 EE_Foreign_Key_Field, etc
4560
-     * @return EE_Model_Field_Base or null if none is found
4561
-     */
4562
-    public function get_a_field_of_type($field_class_name)
4563
-    {
4564
-        foreach ($this->field_settings() as $field) {
4565
-            if ($field instanceof $field_class_name) {
4566
-                return $field;
4567
-            }
4568
-        }
4569
-        return null;
4570
-    }
4571
-
4572
-
4573
-
4574
-    /**
4575
-     * Gets a foreign key field pointing to model.
4576
-     *
4577
-     * @param string $model_name eg Event, Registration, not EEM_Event
4578
-     * @return EE_Foreign_Key_Field_Base
4579
-     * @throws EE_Error
4580
-     */
4581
-    public function get_foreign_key_to($model_name)
4582
-    {
4583
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4584
-            foreach ($this->field_settings() as $field) {
4585
-                if (
4586
-                    $field instanceof EE_Foreign_Key_Field_Base
4587
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4588
-                ) {
4589
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4590
-                    break;
4591
-                }
4592
-            }
4593
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4594
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4595
-                    'event_espresso'), $model_name, get_class($this)));
4596
-            }
4597
-        }
4598
-        return $this->_cache_foreign_key_to_fields[$model_name];
4599
-    }
4600
-
4601
-
4602
-
4603
-    /**
4604
-     * Gets the actual table for the table alias
4605
-     *
4606
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4607
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4608
-     *                            Either one works
4609
-     * @return EE_Table_Base
4610
-     */
4611
-    public function get_table_for_alias($table_alias)
4612
-    {
4613
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4614
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4615
-    }
4616
-
4617
-
4618
-
4619
-    /**
4620
-     * Returns a flat array of all field son this model, instead of organizing them
4621
-     * by table_alias as they are in the constructor.
4622
-     *
4623
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4624
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4625
-     */
4626
-    public function field_settings($include_db_only_fields = false)
4627
-    {
4628
-        if ($include_db_only_fields) {
4629
-            if ($this->_cached_fields === null) {
4630
-                $this->_cached_fields = array();
4631
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4632
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4633
-                        $this->_cached_fields[$field_name] = $field_obj;
4634
-                    }
4635
-                }
4636
-            }
4637
-            return $this->_cached_fields;
4638
-        } else {
4639
-            if ($this->_cached_fields_non_db_only === null) {
4640
-                $this->_cached_fields_non_db_only = array();
4641
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4642
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4643
-                        /** @var $field_obj EE_Model_Field_Base */
4644
-                        if (! $field_obj->is_db_only_field()) {
4645
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4646
-                        }
4647
-                    }
4648
-                }
4649
-            }
4650
-            return $this->_cached_fields_non_db_only;
4651
-        }
4652
-    }
4653
-
4654
-
4655
-
4656
-    /**
4657
-     *        cycle though array of attendees and create objects out of each item
4658
-     *
4659
-     * @access        private
4660
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4661
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4662
-     *                           numerically indexed)
4663
-     * @throws \EE_Error
4664
-     */
4665
-    protected function _create_objects($rows = array())
4666
-    {
4667
-        $array_of_objects = array();
4668
-        if (empty($rows)) {
4669
-            return array();
4670
-        }
4671
-        $count_if_model_has_no_primary_key = 0;
4672
-        $has_primary_key = $this->has_primary_key_field();
4673
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4674
-        foreach ((array)$rows as $row) {
4675
-            if (empty($row)) {
4676
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4677
-                return array();
4678
-            }
4679
-            //check if we've already set this object in the results array,
4680
-            //in which case there's no need to process it further (again)
4681
-            if ($has_primary_key) {
4682
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4683
-                    $row,
4684
-                    $primary_key_field->get_qualified_column(),
4685
-                    $primary_key_field->get_table_column()
4686
-                );
4687
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4688
-                    continue;
4689
-                }
4690
-            }
4691
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4692
-            if (! $classInstance) {
4693
-                throw new EE_Error(
4694
-                    sprintf(
4695
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4696
-                        $this->get_this_model_name(),
4697
-                        http_build_query($row)
4698
-                    )
4699
-                );
4700
-            }
4701
-            //set the timezone on the instantiated objects
4702
-            $classInstance->set_timezone($this->_timezone);
4703
-            //make sure if there is any timezone setting present that we set the timezone for the object
4704
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4705
-            $array_of_objects[$key] = $classInstance;
4706
-            //also, for all the relations of type BelongsTo, see if we can cache
4707
-            //those related models
4708
-            //(we could do this for other relations too, but if there are conditions
4709
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4710
-            //so it requires a little more thought than just caching them immediately...)
4711
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4712
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4713
-                    //check if this model's INFO is present. If so, cache it on the model
4714
-                    $other_model = $relation_obj->get_other_model();
4715
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4716
-                    //if we managed to make a model object from the results, cache it on the main model object
4717
-                    if ($other_model_obj_maybe) {
4718
-                        //set timezone on these other model objects if they are present
4719
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4720
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4721
-                    }
4722
-                }
4723
-            }
4724
-        }
4725
-        return $array_of_objects;
4726
-    }
4727
-
4728
-
4729
-
4730
-    /**
4731
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4732
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4733
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4734
-     * object (as set in the model_field!).
4735
-     *
4736
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4737
-     */
4738
-    public function create_default_object()
4739
-    {
4740
-        $this_model_fields_and_values = array();
4741
-        //setup the row using default values;
4742
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4743
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4744
-        }
4745
-        $className = $this->_get_class_name();
4746
-        $classInstance = EE_Registry::instance()
4747
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4748
-        return $classInstance;
4749
-    }
4750
-
4751
-
4752
-
4753
-    /**
4754
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4755
-     *                             or an stdClass where each property is the name of a column,
4756
-     * @return EE_Base_Class
4757
-     * @throws \EE_Error
4758
-     */
4759
-    public function instantiate_class_from_array_or_object($cols_n_values)
4760
-    {
4761
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4762
-            $cols_n_values = get_object_vars($cols_n_values);
4763
-        }
4764
-        $primary_key = null;
4765
-        //make sure the array only has keys that are fields/columns on this model
4766
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4767
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4768
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4769
-        }
4770
-        $className = $this->_get_class_name();
4771
-        //check we actually found results that we can use to build our model object
4772
-        //if not, return null
4773
-        if ($this->has_primary_key_field()) {
4774
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4775
-                return null;
4776
-            }
4777
-        } else if ($this->unique_indexes()) {
4778
-            $first_column = reset($this_model_fields_n_values);
4779
-            if (empty($first_column)) {
4780
-                return null;
4781
-            }
4782
-        }
4783
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4784
-        if ($primary_key) {
4785
-            $classInstance = $this->get_from_entity_map($primary_key);
4786
-            if (! $classInstance) {
4787
-                $classInstance = EE_Registry::instance()
4788
-                                            ->load_class($className,
4789
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4790
-                // add this new object to the entity map
4791
-                $classInstance = $this->add_to_entity_map($classInstance);
4792
-            }
4793
-        } else {
4794
-            $classInstance = EE_Registry::instance()
4795
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4796
-                                            true, false);
4797
-        }
4798
-        //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.
4799
-        $this->set_timezone($classInstance->get_timezone());
4800
-        return $classInstance;
4801
-    }
4802
-
4803
-
4804
-
4805
-    /**
4806
-     * Gets the model object from the  entity map if it exists
4807
-     *
4808
-     * @param int|string $id the ID of the model object
4809
-     * @return EE_Base_Class
4810
-     */
4811
-    public function get_from_entity_map($id)
4812
-    {
4813
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4814
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4815
-    }
4816
-
4817
-
4818
-
4819
-    /**
4820
-     * add_to_entity_map
4821
-     * Adds the object to the model's entity mappings
4822
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4823
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4824
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4825
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4826
-     *        then this method should be called immediately after the update query
4827
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4828
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4829
-     *
4830
-     * @param    EE_Base_Class $object
4831
-     * @throws EE_Error
4832
-     * @return \EE_Base_Class
4833
-     */
4834
-    public function add_to_entity_map(EE_Base_Class $object)
4835
-    {
4836
-        $className = $this->_get_class_name();
4837
-        if (! $object instanceof $className) {
4838
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4839
-                is_object($object) ? get_class($object) : $object, $className));
4840
-        }
4841
-        /** @var $object EE_Base_Class */
4842
-        if (! $object->ID()) {
4843
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4844
-                "event_espresso"), get_class($this)));
4845
-        }
4846
-        // double check it's not already there
4847
-        $classInstance = $this->get_from_entity_map($object->ID());
4848
-        if ($classInstance) {
4849
-            return $classInstance;
4850
-        } else {
4851
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4852
-            return $object;
4853
-        }
4854
-    }
4855
-
4856
-
4857
-
4858
-    /**
4859
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4860
-     * if no identifier is provided, then the entire entity map is emptied
4861
-     *
4862
-     * @param int|string $id the ID of the model object
4863
-     * @return boolean
4864
-     */
4865
-    public function clear_entity_map($id = null)
4866
-    {
4867
-        if (empty($id)) {
4868
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4869
-            return true;
4870
-        }
4871
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4872
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4873
-            return true;
4874
-        }
4875
-        return false;
4876
-    }
4877
-
4878
-
4879
-
4880
-    /**
4881
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4882
-     * Given an array where keys are column (or column alias) names and values,
4883
-     * returns an array of their corresponding field names and database values
4884
-     *
4885
-     * @param array $cols_n_values
4886
-     * @return array
4887
-     */
4888
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4889
-    {
4890
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4891
-    }
4892
-
4893
-
4894
-
4895
-    /**
4896
-     * _deduce_fields_n_values_from_cols_n_values
4897
-     * Given an array where keys are column (or column alias) names and values,
4898
-     * returns an array of their corresponding field names and database values
4899
-     *
4900
-     * @param string $cols_n_values
4901
-     * @return array
4902
-     */
4903
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4904
-    {
4905
-        $this_model_fields_n_values = array();
4906
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
4907
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4908
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4909
-            //there is a primary key on this table and its not set. Use defaults for all its columns
4910
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
4911
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4912
-                    if (! $field_obj->is_db_only_field()) {
4913
-                        //prepare field as if its coming from db
4914
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4915
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4916
-                    }
4917
-                }
4918
-            } else {
4919
-                //the table's rows existed. Use their values
4920
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4921
-                    if (! $field_obj->is_db_only_field()) {
4922
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4923
-                            $cols_n_values, $field_obj->get_qualified_column(),
4924
-                            $field_obj->get_table_column()
4925
-                        );
4926
-                    }
4927
-                }
4928
-            }
4929
-        }
4930
-        return $this_model_fields_n_values;
4931
-    }
4932
-
4933
-
4934
-
4935
-    /**
4936
-     * @param $cols_n_values
4937
-     * @param $qualified_column
4938
-     * @param $regular_column
4939
-     * @return null
4940
-     */
4941
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4942
-    {
4943
-        $value = null;
4944
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4945
-        //does the field on the model relate to this column retrieved from the db?
4946
-        //or is it a db-only field? (not relating to the model)
4947
-        if (isset($cols_n_values[$qualified_column])) {
4948
-            $value = $cols_n_values[$qualified_column];
4949
-        } elseif (isset($cols_n_values[$regular_column])) {
4950
-            $value = $cols_n_values[$regular_column];
4951
-        }
4952
-        return $value;
4953
-    }
4954
-
4955
-
4956
-
4957
-    /**
4958
-     * refresh_entity_map_from_db
4959
-     * Makes sure the model object in the entity map at $id assumes the values
4960
-     * of the database (opposite of EE_base_Class::save())
4961
-     *
4962
-     * @param int|string $id
4963
-     * @return EE_Base_Class
4964
-     * @throws \EE_Error
4965
-     */
4966
-    public function refresh_entity_map_from_db($id)
4967
-    {
4968
-        $obj_in_map = $this->get_from_entity_map($id);
4969
-        if ($obj_in_map) {
4970
-            $wpdb_results = $this->_get_all_wpdb_results(
4971
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
4972
-            );
4973
-            if ($wpdb_results && is_array($wpdb_results)) {
4974
-                $one_row = reset($wpdb_results);
4975
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
4976
-                    $obj_in_map->set_from_db($field_name, $db_value);
4977
-                }
4978
-                //clear the cache of related model objects
4979
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4980
-                    $obj_in_map->clear_cache($relation_name, null, true);
4981
-                }
4982
-            }
4983
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
4984
-            return $obj_in_map;
4985
-        } else {
4986
-            return $this->get_one_by_ID($id);
4987
-        }
4988
-    }
4989
-
4990
-
4991
-
4992
-    /**
4993
-     * refresh_entity_map_with
4994
-     * Leaves the entry in the entity map alone, but updates it to match the provided
4995
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4996
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4997
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4998
-     *
4999
-     * @param int|string    $id
5000
-     * @param EE_Base_Class $replacing_model_obj
5001
-     * @return \EE_Base_Class
5002
-     * @throws \EE_Error
5003
-     */
5004
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5005
-    {
5006
-        $obj_in_map = $this->get_from_entity_map($id);
5007
-        if ($obj_in_map) {
5008
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5009
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5010
-                    $obj_in_map->set($field_name, $value);
5011
-                }
5012
-                //make the model object in the entity map's cache match the $replacing_model_obj
5013
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5014
-                    $obj_in_map->clear_cache($relation_name, null, true);
5015
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5016
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5017
-                    }
5018
-                }
5019
-            }
5020
-            return $obj_in_map;
5021
-        } else {
5022
-            $this->add_to_entity_map($replacing_model_obj);
5023
-            return $replacing_model_obj;
5024
-        }
5025
-    }
5026
-
5027
-
5028
-
5029
-    /**
5030
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5031
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5032
-     * require_once($this->_getClassName().".class.php");
5033
-     *
5034
-     * @return string
5035
-     */
5036
-    private function _get_class_name()
5037
-    {
5038
-        return "EE_" . $this->get_this_model_name();
5039
-    }
5040
-
5041
-
5042
-
5043
-    /**
5044
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5045
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5046
-     * it would be 'Events'.
5047
-     *
5048
-     * @param int $quantity
5049
-     * @return string
5050
-     */
5051
-    public function item_name($quantity = 1)
5052
-    {
5053
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5054
-    }
5055
-
5056
-
5057
-
5058
-    /**
5059
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5060
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5061
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5062
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5063
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5064
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5065
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5066
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5067
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5068
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5069
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5070
-     *        return $previousReturnValue.$returnString;
5071
-     * }
5072
-     * require('EEM_Answer.model.php');
5073
-     * $answer=EEM_Answer::instance();
5074
-     * echo $answer->my_callback('monkeys',100);
5075
-     * //will output "you called my_callback! and passed args:monkeys,100"
5076
-     *
5077
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5078
-     * @param array  $args       array of original arguments passed to the function
5079
-     * @throws EE_Error
5080
-     * @return mixed whatever the plugin which calls add_filter decides
5081
-     */
5082
-    public function __call($methodName, $args)
5083
-    {
5084
-        $className = get_class($this);
5085
-        $tagName = "FHEE__{$className}__{$methodName}";
5086
-        if (! has_filter($tagName)) {
5087
-            throw new EE_Error(
5088
-                sprintf(
5089
-                    __('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 );',
5090
-                        'event_espresso'),
5091
-                    $methodName,
5092
-                    $className,
5093
-                    $tagName,
5094
-                    '<br />'
5095
-                )
5096
-            );
5097
-        }
5098
-        return apply_filters($tagName, null, $this, $args);
5099
-    }
5100
-
5101
-
5102
-
5103
-    /**
5104
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5105
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5106
-     *
5107
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5108
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5109
-     *                                                       the object's class name
5110
-     *                                                       or object's ID
5111
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5112
-     *                                                       exists in the database. If it does not, we add it
5113
-     * @throws EE_Error
5114
-     * @return EE_Base_Class
5115
-     */
5116
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5117
-    {
5118
-        $className = $this->_get_class_name();
5119
-        if ($base_class_obj_or_id instanceof $className) {
5120
-            $model_object = $base_class_obj_or_id;
5121
-        } else {
5122
-            $primary_key_field = $this->get_primary_key_field();
5123
-            if (
5124
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5125
-                && (
5126
-                    is_int($base_class_obj_or_id)
5127
-                    || is_string($base_class_obj_or_id)
5128
-                )
5129
-            ) {
5130
-                // assume it's an ID.
5131
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5132
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5133
-            } else if (
5134
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5135
-                && is_string($base_class_obj_or_id)
5136
-            ) {
5137
-                // assume its a string representation of the object
5138
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5139
-            } else {
5140
-                throw new EE_Error(
5141
-                    sprintf(
5142
-                        __(
5143
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5144
-                            'event_espresso'
5145
-                        ),
5146
-                        $base_class_obj_or_id,
5147
-                        $this->_get_class_name(),
5148
-                        print_r($base_class_obj_or_id, true)
5149
-                    )
5150
-                );
5151
-            }
5152
-        }
5153
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5154
-            $model_object->save();
5155
-        }
5156
-        return $model_object;
5157
-    }
5158
-
5159
-
5160
-
5161
-    /**
5162
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5163
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5164
-     * returns it ID.
5165
-     *
5166
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5167
-     * @return int|string depending on the type of this model object's ID
5168
-     * @throws EE_Error
5169
-     */
5170
-    public function ensure_is_ID($base_class_obj_or_id)
5171
-    {
5172
-        $className = $this->_get_class_name();
5173
-        if ($base_class_obj_or_id instanceof $className) {
5174
-            /** @var $base_class_obj_or_id EE_Base_Class */
5175
-            $id = $base_class_obj_or_id->ID();
5176
-        } elseif (is_int($base_class_obj_or_id)) {
5177
-            //assume it's an ID
5178
-            $id = $base_class_obj_or_id;
5179
-        } elseif (is_string($base_class_obj_or_id)) {
5180
-            //assume its a string representation of the object
5181
-            $id = $base_class_obj_or_id;
5182
-        } else {
5183
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5184
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5185
-                print_r($base_class_obj_or_id, true)));
5186
-        }
5187
-        return $id;
5188
-    }
5189
-
5190
-
5191
-
5192
-    /**
5193
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5194
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5195
-     * been sanitized and converted into the appropriate domain.
5196
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5197
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5198
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5199
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5200
-     * $EVT = EEM_Event::instance(); $old_setting =
5201
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5202
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5203
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5204
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5205
-     *
5206
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5207
-     * @return void
5208
-     */
5209
-    public function assume_values_already_prepared_by_model_object(
5210
-        $values_already_prepared = self::not_prepared_by_model_object
5211
-    ) {
5212
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5213
-    }
5214
-
5215
-
5216
-
5217
-    /**
5218
-     * Read comments for assume_values_already_prepared_by_model_object()
5219
-     *
5220
-     * @return int
5221
-     */
5222
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5223
-    {
5224
-        return $this->_values_already_prepared_by_model_object;
5225
-    }
5226
-
5227
-
5228
-
5229
-    /**
5230
-     * Gets all the indexes on this model
5231
-     *
5232
-     * @return EE_Index[]
5233
-     */
5234
-    public function indexes()
5235
-    {
5236
-        return $this->_indexes;
5237
-    }
5238
-
5239
-
5240
-
5241
-    /**
5242
-     * Gets all the Unique Indexes on this model
5243
-     *
5244
-     * @return EE_Unique_Index[]
5245
-     */
5246
-    public function unique_indexes()
5247
-    {
5248
-        $unique_indexes = array();
5249
-        foreach ($this->_indexes as $name => $index) {
5250
-            if ($index instanceof EE_Unique_Index) {
5251
-                $unique_indexes [$name] = $index;
5252
-            }
5253
-        }
5254
-        return $unique_indexes;
5255
-    }
5256
-
5257
-
5258
-
5259
-    /**
5260
-     * Gets all the fields which, when combined, make the primary key.
5261
-     * This is usually just an array with 1 element (the primary key), but in cases
5262
-     * where there is no primary key, it's a combination of fields as defined
5263
-     * on a primary index
5264
-     *
5265
-     * @return EE_Model_Field_Base[] indexed by the field's name
5266
-     * @throws \EE_Error
5267
-     */
5268
-    public function get_combined_primary_key_fields()
5269
-    {
5270
-        foreach ($this->indexes() as $index) {
5271
-            if ($index instanceof EE_Primary_Key_Index) {
5272
-                return $index->fields();
5273
-            }
5274
-        }
5275
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5276
-    }
5277
-
5278
-
5279
-
5280
-    /**
5281
-     * Used to build a primary key string (when the model has no primary key),
5282
-     * which can be used a unique string to identify this model object.
5283
-     *
5284
-     * @param array $cols_n_values keys are field names, values are their values
5285
-     * @return string
5286
-     * @throws \EE_Error
5287
-     */
5288
-    public function get_index_primary_key_string($cols_n_values)
5289
-    {
5290
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5291
-            $this->get_combined_primary_key_fields());
5292
-        return http_build_query($cols_n_values_for_primary_key_index);
5293
-    }
5294
-
5295
-
5296
-
5297
-    /**
5298
-     * Gets the field values from the primary key string
5299
-     *
5300
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5301
-     * @param string $index_primary_key_string
5302
-     * @return null|array
5303
-     * @throws \EE_Error
5304
-     */
5305
-    public function parse_index_primary_key_string($index_primary_key_string)
5306
-    {
5307
-        $key_fields = $this->get_combined_primary_key_fields();
5308
-        //check all of them are in the $id
5309
-        $key_vals_in_combined_pk = array();
5310
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5311
-        foreach ($key_fields as $key_field_name => $field_obj) {
5312
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5313
-                return null;
5314
-            }
5315
-        }
5316
-        return $key_vals_in_combined_pk;
5317
-    }
5318
-
5319
-
5320
-
5321
-    /**
5322
-     * verifies that an array of key-value pairs for model fields has a key
5323
-     * for each field comprising the primary key index
5324
-     *
5325
-     * @param array $key_vals
5326
-     * @return boolean
5327
-     * @throws \EE_Error
5328
-     */
5329
-    public function has_all_combined_primary_key_fields($key_vals)
5330
-    {
5331
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5332
-        foreach ($keys_it_should_have as $key) {
5333
-            if (! isset($key_vals[$key])) {
5334
-                return false;
5335
-            }
5336
-        }
5337
-        return true;
5338
-    }
5339
-
5340
-
5341
-
5342
-    /**
5343
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5344
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5345
-     *
5346
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5347
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5348
-     * @throws EE_Error
5349
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5350
-     *                                                              indexed)
5351
-     */
5352
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5353
-    {
5354
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5355
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5356
-        } elseif (is_array($model_object_or_attributes_array)) {
5357
-            $attributes_array = $model_object_or_attributes_array;
5358
-        } else {
5359
-            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",
5360
-                "event_espresso"), $model_object_or_attributes_array));
5361
-        }
5362
-        //even copies obviously won't have the same ID, so remove the primary key
5363
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5364
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5365
-            unset($attributes_array[$this->primary_key_name()]);
5366
-        }
5367
-        if (isset($query_params[0])) {
5368
-            $query_params[0] = array_merge($attributes_array, $query_params);
5369
-        } else {
5370
-            $query_params[0] = $attributes_array;
5371
-        }
5372
-        return $this->get_all($query_params);
5373
-    }
5374
-
5375
-
5376
-
5377
-    /**
5378
-     * Gets the first copy we find. See get_all_copies for more details
5379
-     *
5380
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5381
-     * @param array $query_params
5382
-     * @return EE_Base_Class
5383
-     * @throws \EE_Error
5384
-     */
5385
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5386
-    {
5387
-        if (! is_array($query_params)) {
5388
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5389
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5390
-                    gettype($query_params)), '4.6.0');
5391
-            $query_params = array();
5392
-        }
5393
-        $query_params['limit'] = 1;
5394
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5395
-        if (is_array($copies)) {
5396
-            return array_shift($copies);
5397
-        } else {
5398
-            return null;
5399
-        }
5400
-    }
5401
-
5402
-
5403
-
5404
-    /**
5405
-     * Updates the item with the specified id. Ignores default query parameters because
5406
-     * we have specified the ID, and its assumed we KNOW what we're doing
5407
-     *
5408
-     * @param array      $fields_n_values keys are field names, values are their new values
5409
-     * @param int|string $id              the value of the primary key to update
5410
-     * @return int number of rows updated
5411
-     * @throws \EE_Error
5412
-     */
5413
-    public function update_by_ID($fields_n_values, $id)
5414
-    {
5415
-        $query_params = array(
5416
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5417
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5418
-        );
5419
-        return $this->update($fields_n_values, $query_params);
5420
-    }
5421
-
5422
-
5423
-
5424
-    /**
5425
-     * Changes an operator which was supplied to the models into one usable in SQL
5426
-     *
5427
-     * @param string $operator_supplied
5428
-     * @return string an operator which can be used in SQL
5429
-     * @throws EE_Error
5430
-     */
5431
-    private function _prepare_operator_for_sql($operator_supplied)
5432
-    {
5433
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5434
-            : null;
5435
-        if ($sql_operator) {
5436
-            return $sql_operator;
5437
-        } else {
5438
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5439
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5440
-        }
5441
-    }
5442
-
5443
-
5444
-
5445
-    /**
5446
-     * Gets an array where keys are the primary keys and values are their 'names'
5447
-     * (as determined by the model object's name() function, which is often overridden)
5448
-     *
5449
-     * @param array $query_params like get_all's
5450
-     * @return string[]
5451
-     * @throws \EE_Error
5452
-     */
5453
-    public function get_all_names($query_params = array())
5454
-    {
5455
-        $objs = $this->get_all($query_params);
5456
-        $names = array();
5457
-        foreach ($objs as $obj) {
5458
-            $names[$obj->ID()] = $obj->name();
5459
-        }
5460
-        return $names;
5461
-    }
5462
-
5463
-
5464
-
5465
-    /**
5466
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5467
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5468
-     * this is duplicated effort and reduces efficiency) you would be better to use
5469
-     * array_keys() on $model_objects.
5470
-     *
5471
-     * @param \EE_Base_Class[] $model_objects
5472
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5473
-     *                                               in the returned array
5474
-     * @return array
5475
-     * @throws \EE_Error
5476
-     */
5477
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5478
-    {
5479
-        if (! $this->has_primary_key_field()) {
5480
-            if (WP_DEBUG) {
5481
-                EE_Error::add_error(
5482
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5483
-                    __FILE__,
5484
-                    __FUNCTION__,
5485
-                    __LINE__
5486
-                );
5487
-            }
5488
-        }
5489
-        $IDs = array();
5490
-        foreach ($model_objects as $model_object) {
5491
-            $id = $model_object->ID();
5492
-            if (! $id) {
5493
-                if ($filter_out_empty_ids) {
5494
-                    continue;
5495
-                }
5496
-                if (WP_DEBUG) {
5497
-                    EE_Error::add_error(
5498
-                        __(
5499
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5500
-                            'event_espresso'
5501
-                        ),
5502
-                        __FILE__,
5503
-                        __FUNCTION__,
5504
-                        __LINE__
5505
-                    );
5506
-                }
5507
-            }
5508
-            $IDs[] = $id;
5509
-        }
5510
-        return $IDs;
5511
-    }
5512
-
5513
-
5514
-
5515
-    /**
5516
-     * Returns the string used in capabilities relating to this model. If there
5517
-     * are no capabilities that relate to this model returns false
5518
-     *
5519
-     * @return string|false
5520
-     */
5521
-    public function cap_slug()
5522
-    {
5523
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5524
-    }
5525
-
5526
-
5527
-
5528
-    /**
5529
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5530
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5531
-     * only returns the cap restrictions array in that context (ie, the array
5532
-     * at that key)
5533
-     *
5534
-     * @param string $context
5535
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5536
-     * @throws \EE_Error
5537
-     */
5538
-    public function cap_restrictions($context = EEM_Base::caps_read)
5539
-    {
5540
-        EEM_Base::verify_is_valid_cap_context($context);
5541
-        //check if we ought to run the restriction generator first
5542
-        if (
5543
-            isset($this->_cap_restriction_generators[$context])
5544
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5545
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5546
-        ) {
5547
-            $this->_cap_restrictions[$context] = array_merge(
5548
-                $this->_cap_restrictions[$context],
5549
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5550
-            );
5551
-        }
5552
-        //and make sure we've finalized the construction of each restriction
5553
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5554
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5555
-                $where_conditions_obj->_finalize_construct($this);
5556
-            }
5557
-        }
5558
-        return $this->_cap_restrictions[$context];
5559
-    }
5560
-
5561
-
5562
-
5563
-    /**
5564
-     * Indicating whether or not this model thinks its a wp core model
5565
-     *
5566
-     * @return boolean
5567
-     */
5568
-    public function is_wp_core_model()
5569
-    {
5570
-        return $this->_wp_core_model;
5571
-    }
5572
-
5573
-
5574
-
5575
-    /**
5576
-     * Gets all the caps that are missing which impose a restriction on
5577
-     * queries made in this context
5578
-     *
5579
-     * @param string $context one of EEM_Base::caps_ constants
5580
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5581
-     * @throws \EE_Error
5582
-     */
5583
-    public function caps_missing($context = EEM_Base::caps_read)
5584
-    {
5585
-        $missing_caps = array();
5586
-        $cap_restrictions = $this->cap_restrictions($context);
5587
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5588
-            if (! EE_Capabilities::instance()
5589
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5590
-            ) {
5591
-                $missing_caps[$cap] = $restriction_if_no_cap;
5592
-            }
5593
-        }
5594
-        return $missing_caps;
5595
-    }
5596
-
5597
-
5598
-
5599
-    /**
5600
-     * Gets the mapping from capability contexts to action strings used in capability names
5601
-     *
5602
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5603
-     * one of 'read', 'edit', or 'delete'
5604
-     */
5605
-    public function cap_contexts_to_cap_action_map()
5606
-    {
5607
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5608
-            $this);
5609
-    }
5610
-
5611
-
5612
-
5613
-    /**
5614
-     * Gets the action string for the specified capability context
5615
-     *
5616
-     * @param string $context
5617
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5618
-     * @throws \EE_Error
5619
-     */
5620
-    public function cap_action_for_context($context)
5621
-    {
5622
-        $mapping = $this->cap_contexts_to_cap_action_map();
5623
-        if (isset($mapping[$context])) {
5624
-            return $mapping[$context];
5625
-        }
5626
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5627
-            return $action;
5628
-        }
5629
-        throw new EE_Error(
5630
-            sprintf(
5631
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5632
-                $context,
5633
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5634
-            )
5635
-        );
5636
-    }
5637
-
5638
-
5639
-
5640
-    /**
5641
-     * Returns all the capability contexts which are valid when querying models
5642
-     *
5643
-     * @return array
5644
-     */
5645
-    public static function valid_cap_contexts()
5646
-    {
5647
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5648
-            self::caps_read,
5649
-            self::caps_read_admin,
5650
-            self::caps_edit,
5651
-            self::caps_delete,
5652
-        ));
5653
-    }
5654
-
5655
-
5656
-
5657
-    /**
5658
-     * Returns all valid options for 'default_where_conditions'
5659
-     *
5660
-     * @return array
5661
-     */
5662
-    public static function valid_default_where_conditions()
5663
-    {
5664
-        return array(
5665
-            EEM_Base::default_where_conditions_all,
5666
-            EEM_Base::default_where_conditions_this_only,
5667
-            EEM_Base::default_where_conditions_others_only,
5668
-            EEM_Base::default_where_conditions_minimum_all,
5669
-            EEM_Base::default_where_conditions_minimum_others,
5670
-            EEM_Base::default_where_conditions_none
5671
-        );
5672
-    }
5673
-
5674
-    // public static function default_where_conditions_full
5675
-    /**
5676
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5677
-     *
5678
-     * @param string $context
5679
-     * @return bool
5680
-     * @throws \EE_Error
5681
-     */
5682
-    static public function verify_is_valid_cap_context($context)
5683
-    {
5684
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5685
-        if (in_array($context, $valid_cap_contexts)) {
5686
-            return true;
5687
-        } else {
5688
-            throw new EE_Error(
5689
-                sprintf(
5690
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5691
-                        'event_espresso'),
5692
-                    $context,
5693
-                    'EEM_Base',
5694
-                    implode(',', $valid_cap_contexts)
5695
-                )
5696
-            );
5697
-        }
5698
-    }
5699
-
5700
-
5701
-
5702
-    /**
5703
-     * Clears all the models field caches. This is only useful when a sub-class
5704
-     * might have added a field or something and these caches might be invalidated
5705
-     */
5706
-    protected function _invalidate_field_caches()
5707
-    {
5708
-        $this->_cache_foreign_key_to_fields = array();
5709
-        $this->_cached_fields = null;
5710
-        $this->_cached_fields_non_db_only = null;
5711
-    }
3569
+		}
3570
+		return $null_friendly_where_conditions;
3571
+	}
3572
+
3573
+
3574
+
3575
+	/**
3576
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3577
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3578
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3579
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3580
+	 *
3581
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3582
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3583
+	 */
3584
+	private function _get_default_where_conditions($model_relation_path = null)
3585
+	{
3586
+		if ($this->_ignore_where_strategy) {
3587
+			return array();
3588
+		}
3589
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3590
+	}
3591
+
3592
+
3593
+
3594
+	/**
3595
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3596
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3597
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3598
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3599
+	 * Similar to _get_default_where_conditions
3600
+	 *
3601
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3602
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3603
+	 */
3604
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3605
+	{
3606
+		if ($this->_ignore_where_strategy) {
3607
+			return array();
3608
+		}
3609
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3610
+	}
3611
+
3612
+
3613
+
3614
+	/**
3615
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3616
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3617
+	 *
3618
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3619
+	 * @return string
3620
+	 * @throws \EE_Error
3621
+	 */
3622
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3623
+	{
3624
+		$selects = $this->_get_columns_to_select_for_this_model();
3625
+		foreach (
3626
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3627
+			$name_of_other_model_included
3628
+		) {
3629
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3630
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3631
+			foreach ($other_model_selects as $key => $value) {
3632
+				$selects[] = $value;
3633
+			}
3634
+		}
3635
+		return implode(", ", $selects);
3636
+	}
3637
+
3638
+
3639
+
3640
+	/**
3641
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3642
+	 * So that's going to be the columns for all the fields on the model
3643
+	 *
3644
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3645
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3646
+	 */
3647
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3648
+	{
3649
+		$fields = $this->field_settings();
3650
+		$selects = array();
3651
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3652
+			$this->get_this_model_name());
3653
+		foreach ($fields as $field_obj) {
3654
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3655
+						 . $field_obj->get_table_alias()
3656
+						 . "."
3657
+						 . $field_obj->get_table_column()
3658
+						 . " AS '"
3659
+						 . $table_alias_with_model_relation_chain_prefix
3660
+						 . $field_obj->get_table_alias()
3661
+						 . "."
3662
+						 . $field_obj->get_table_column()
3663
+						 . "'";
3664
+		}
3665
+		//make sure we are also getting the PKs of each table
3666
+		$tables = $this->get_tables();
3667
+		if (count($tables) > 1) {
3668
+			foreach ($tables as $table_obj) {
3669
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3670
+									   . $table_obj->get_fully_qualified_pk_column();
3671
+				if (! in_array($qualified_pk_column, $selects)) {
3672
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3673
+				}
3674
+			}
3675
+		}
3676
+		return $selects;
3677
+	}
3678
+
3679
+
3680
+
3681
+	/**
3682
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3683
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3684
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3685
+	 * SQL for joining, and the data types
3686
+	 *
3687
+	 * @param null|string                 $original_query_param
3688
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3689
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3690
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3691
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3692
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3693
+	 *                                                          or 'Registration's
3694
+	 * @param string                      $original_query_param what it originally was (eg
3695
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3696
+	 *                                                          matches $query_param
3697
+	 * @throws EE_Error
3698
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3699
+	 */
3700
+	private function _extract_related_model_info_from_query_param(
3701
+		$query_param,
3702
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3703
+		$query_param_type,
3704
+		$original_query_param = null
3705
+	) {
3706
+		if ($original_query_param === null) {
3707
+			$original_query_param = $query_param;
3708
+		}
3709
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3710
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3711
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3712
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3713
+		//check to see if we have a field on this model
3714
+		$this_model_fields = $this->field_settings(true);
3715
+		if (array_key_exists($query_param, $this_model_fields)) {
3716
+			if ($allow_fields) {
3717
+				return;
3718
+			} else {
3719
+				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",
3720
+					"event_espresso"),
3721
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3722
+			}
3723
+		} //check if this is a special logic query param
3724
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3725
+			if ($allow_logic_query_params) {
3726
+				return;
3727
+			} else {
3728
+				throw new EE_Error(
3729
+					sprintf(
3730
+						__('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',
3731
+							'event_espresso'),
3732
+						implode('", "', $this->_logic_query_param_keys),
3733
+						$query_param,
3734
+						get_class($this),
3735
+						'<br />',
3736
+						"\t"
3737
+						. ' $passed_in_query_info = <pre>'
3738
+						. print_r($passed_in_query_info, true)
3739
+						. '</pre>'
3740
+						. "\n\t"
3741
+						. ' $query_param_type = '
3742
+						. $query_param_type
3743
+						. "\n\t"
3744
+						. ' $original_query_param = '
3745
+						. $original_query_param
3746
+					)
3747
+				);
3748
+			}
3749
+		} //check if it's a custom selection
3750
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3751
+			return;
3752
+		}
3753
+		//check if has a model name at the beginning
3754
+		//and
3755
+		//check if it's a field on a related model
3756
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3757
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3758
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3759
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3760
+				if ($query_param === '') {
3761
+					//nothing left to $query_param
3762
+					//we should actually end in a field name, not a model like this!
3763
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3764
+						"event_espresso"),
3765
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3766
+				} else {
3767
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3768
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3769
+						$passed_in_query_info, $query_param_type, $original_query_param);
3770
+					return;
3771
+				}
3772
+			} elseif ($query_param === $valid_related_model_name) {
3773
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3774
+				return;
3775
+			}
3776
+		}
3777
+		//ok so $query_param didn't start with a model name
3778
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3779
+		//it's wack, that's what it is
3780
+		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",
3781
+			"event_espresso"),
3782
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3783
+	}
3784
+
3785
+
3786
+
3787
+	/**
3788
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3789
+	 * and store it on $passed_in_query_info
3790
+	 *
3791
+	 * @param string                      $model_name
3792
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3793
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3794
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3795
+	 *                                                          and are adding a join to 'Payment' with the original
3796
+	 *                                                          query param key
3797
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3798
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3799
+	 *                                                          Payment wants to add default query params so that it
3800
+	 *                                                          will know what models to prepend onto its default query
3801
+	 *                                                          params or in case it wants to rename tables (in case
3802
+	 *                                                          there are multiple joins to the same table)
3803
+	 * @return void
3804
+	 * @throws \EE_Error
3805
+	 */
3806
+	private function _add_join_to_model(
3807
+		$model_name,
3808
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3809
+		$original_query_param
3810
+	) {
3811
+		$relation_obj = $this->related_settings_for($model_name);
3812
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3813
+		//check if the relation is HABTM, because then we're essentially doing two joins
3814
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3815
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3816
+			$join_model_obj = $relation_obj->get_join_model();
3817
+			//replace the model specified with the join model for this relation chain, whi
3818
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3819
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3820
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3821
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3822
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3823
+			$passed_in_query_info->merge($new_query_info);
3824
+		}
3825
+		//now just join to the other table pointed to by the relation object, and add its data types
3826
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3827
+			array($model_relation_chain => $model_name),
3828
+			$relation_obj->get_join_statement($model_relation_chain));
3829
+		$passed_in_query_info->merge($new_query_info);
3830
+	}
3831
+
3832
+
3833
+
3834
+	/**
3835
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3836
+	 *
3837
+	 * @param array $where_params like EEM_Base::get_all
3838
+	 * @return string of SQL
3839
+	 * @throws \EE_Error
3840
+	 */
3841
+	private function _construct_where_clause($where_params)
3842
+	{
3843
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3844
+		if ($SQL) {
3845
+			return " WHERE " . $SQL;
3846
+		} else {
3847
+			return '';
3848
+		}
3849
+	}
3850
+
3851
+
3852
+
3853
+	/**
3854
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3855
+	 * and should be passed HAVING parameters, not WHERE parameters
3856
+	 *
3857
+	 * @param array $having_params
3858
+	 * @return string
3859
+	 * @throws \EE_Error
3860
+	 */
3861
+	private function _construct_having_clause($having_params)
3862
+	{
3863
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3864
+		if ($SQL) {
3865
+			return " HAVING " . $SQL;
3866
+		} else {
3867
+			return '';
3868
+		}
3869
+	}
3870
+
3871
+
3872
+
3873
+	/**
3874
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3875
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3876
+	 * EEM_Attendee.
3877
+	 *
3878
+	 * @param string $field_name
3879
+	 * @param string $model_name
3880
+	 * @return EE_Model_Field_Base
3881
+	 * @throws EE_Error
3882
+	 */
3883
+	protected function _get_field_on_model($field_name, $model_name)
3884
+	{
3885
+		$model_class = 'EEM_' . $model_name;
3886
+		$model_filepath = $model_class . ".model.php";
3887
+		if (is_readable($model_filepath)) {
3888
+			require_once($model_filepath);
3889
+			$model_instance = call_user_func($model_name . "::instance");
3890
+			/* @var $model_instance EEM_Base */
3891
+			return $model_instance->field_settings_for($field_name);
3892
+		} else {
3893
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3894
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3895
+		}
3896
+	}
3897
+
3898
+
3899
+
3900
+	/**
3901
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3902
+	 * Event_Meta.meta_value = 'foo'))"
3903
+	 *
3904
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3905
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3906
+	 * @throws EE_Error
3907
+	 * @return string of SQL
3908
+	 */
3909
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3910
+	{
3911
+		$where_clauses = array();
3912
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3913
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3914
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3915
+				switch ($query_param) {
3916
+					case 'not':
3917
+					case 'NOT':
3918
+						$where_clauses[] = "! ("
3919
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3920
+								$glue)
3921
+										   . ")";
3922
+						break;
3923
+					case 'and':
3924
+					case 'AND':
3925
+						$where_clauses[] = " ("
3926
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3927
+								' AND ')
3928
+										   . ")";
3929
+						break;
3930
+					case 'or':
3931
+					case 'OR':
3932
+						$where_clauses[] = " ("
3933
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3934
+								' OR ')
3935
+										   . ")";
3936
+						break;
3937
+				}
3938
+			} else {
3939
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3940
+				//if it's not a normal field, maybe it's a custom selection?
3941
+				if (! $field_obj) {
3942
+					if (isset($this->_custom_selections[$query_param][1])) {
3943
+						$field_obj = $this->_custom_selections[$query_param][1];
3944
+					} else {
3945
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3946
+							"event_espresso"), $query_param));
3947
+					}
3948
+				}
3949
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3950
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3951
+			}
3952
+		}
3953
+		return $where_clauses ? implode($glue, $where_clauses) : '';
3954
+	}
3955
+
3956
+
3957
+
3958
+	/**
3959
+	 * Takes the input parameter and extract the table name (alias) and column name
3960
+	 *
3961
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3962
+	 * @throws EE_Error
3963
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3964
+	 */
3965
+	private function _deduce_column_name_from_query_param($query_param)
3966
+	{
3967
+		$field = $this->_deduce_field_from_query_param($query_param);
3968
+		if ($field) {
3969
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3970
+				$query_param);
3971
+			return $table_alias_prefix . $field->get_qualified_column();
3972
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
3973
+			//maybe it's custom selection item?
3974
+			//if so, just use it as the "column name"
3975
+			return $query_param;
3976
+		} else {
3977
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
3978
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
3979
+		}
3980
+	}
3981
+
3982
+
3983
+
3984
+	/**
3985
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
3986
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
3987
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3988
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3989
+	 *
3990
+	 * @param string $condition_query_param_key
3991
+	 * @return string
3992
+	 */
3993
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
3994
+	{
3995
+		$pos_of_star = strpos($condition_query_param_key, '*');
3996
+		if ($pos_of_star === false) {
3997
+			return $condition_query_param_key;
3998
+		} else {
3999
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4000
+			return $condition_query_param_sans_star;
4001
+		}
4002
+	}
4003
+
4004
+
4005
+
4006
+	/**
4007
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4008
+	 *
4009
+	 * @param                            mixed      array | string    $op_and_value
4010
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4011
+	 * @throws EE_Error
4012
+	 * @return string
4013
+	 */
4014
+	private function _construct_op_and_value($op_and_value, $field_obj)
4015
+	{
4016
+		if (is_array($op_and_value)) {
4017
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4018
+			if (! $operator) {
4019
+				$php_array_like_string = array();
4020
+				foreach ($op_and_value as $key => $value) {
4021
+					$php_array_like_string[] = "$key=>$value";
4022
+				}
4023
+				throw new EE_Error(
4024
+					sprintf(
4025
+						__(
4026
+							"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))",
4027
+							"event_espresso"
4028
+						),
4029
+						implode(",", $php_array_like_string)
4030
+					)
4031
+				);
4032
+			}
4033
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4034
+		} else {
4035
+			$operator = '=';
4036
+			$value = $op_and_value;
4037
+		}
4038
+		//check to see if the value is actually another field
4039
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4040
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4041
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4042
+			//in this case, the value should be an array, or at least a comma-separated list
4043
+			//it will need to handle a little differently
4044
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4045
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4046
+			return $operator . SP . $cleaned_value;
4047
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4048
+			//the value should be an array with count of two.
4049
+			if (count($value) !== 2) {
4050
+				throw new EE_Error(
4051
+					sprintf(
4052
+						__(
4053
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4054
+							'event_espresso'
4055
+						),
4056
+						"BETWEEN"
4057
+					)
4058
+				);
4059
+			}
4060
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4061
+			return $operator . SP . $cleaned_value;
4062
+		} elseif (in_array($operator, $this->_null_style_operators)) {
4063
+			if ($value !== null) {
4064
+				throw new EE_Error(
4065
+					sprintf(
4066
+						__(
4067
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4068
+							"event_espresso"
4069
+						),
4070
+						$value,
4071
+						$operator
4072
+					)
4073
+				);
4074
+			}
4075
+			return $operator;
4076
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
4077
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4078
+			//remove other junk. So just treat it as a string.
4079
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4080
+		} elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4081
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4082
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4083
+			throw new EE_Error(
4084
+				sprintf(
4085
+					__(
4086
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4087
+						'event_espresso'
4088
+					),
4089
+					$operator,
4090
+					$operator
4091
+				)
4092
+			);
4093
+		} elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4094
+			throw new EE_Error(
4095
+				sprintf(
4096
+					__(
4097
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4098
+						'event_espresso'
4099
+					),
4100
+					$operator,
4101
+					$operator
4102
+				)
4103
+			);
4104
+		} else {
4105
+			throw new EE_Error(
4106
+				sprintf(
4107
+					__(
4108
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4109
+						"event_espresso"
4110
+					),
4111
+					http_build_query($op_and_value)
4112
+				)
4113
+			);
4114
+		}
4115
+	}
4116
+
4117
+
4118
+
4119
+	/**
4120
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4121
+	 *
4122
+	 * @param array                      $values
4123
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4124
+	 *                                              '%s'
4125
+	 * @return string
4126
+	 * @throws \EE_Error
4127
+	 */
4128
+	public function _construct_between_value($values, $field_obj)
4129
+	{
4130
+		$cleaned_values = array();
4131
+		foreach ($values as $value) {
4132
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4133
+		}
4134
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4135
+	}
4136
+
4137
+
4138
+
4139
+	/**
4140
+	 * Takes an array or a comma-separated list of $values and cleans them
4141
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4142
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4143
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4144
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4145
+	 *
4146
+	 * @param mixed                      $values    array or comma-separated string
4147
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4148
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4149
+	 * @throws \EE_Error
4150
+	 */
4151
+	public function _construct_in_value($values, $field_obj)
4152
+	{
4153
+		//check if the value is a CSV list
4154
+		if (is_string($values)) {
4155
+			//in which case, turn it into an array
4156
+			$values = explode(",", $values);
4157
+		}
4158
+		$cleaned_values = array();
4159
+		foreach ($values as $value) {
4160
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4161
+		}
4162
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4163
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4164
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4165
+		if (empty($cleaned_values)) {
4166
+			$all_fields = $this->field_settings();
4167
+			$a_field = array_shift($all_fields);
4168
+			$main_table = $this->_get_main_table();
4169
+			$cleaned_values[] = "SELECT "
4170
+								. $a_field->get_table_column()
4171
+								. " FROM "
4172
+								. $main_table->get_table_name()
4173
+								. " WHERE FALSE";
4174
+		}
4175
+		return "(" . implode(",", $cleaned_values) . ")";
4176
+	}
4177
+
4178
+
4179
+
4180
+	/**
4181
+	 * @param mixed                      $value
4182
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4183
+	 * @throws EE_Error
4184
+	 * @return false|null|string
4185
+	 */
4186
+	private function _wpdb_prepare_using_field($value, $field_obj)
4187
+	{
4188
+		/** @type WPDB $wpdb */
4189
+		global $wpdb;
4190
+		if ($field_obj instanceof EE_Model_Field_Base) {
4191
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4192
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4193
+		} else {//$field_obj should really just be a data type
4194
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4195
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4196
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4197
+			}
4198
+			return $wpdb->prepare($field_obj, $value);
4199
+		}
4200
+	}
4201
+
4202
+
4203
+
4204
+	/**
4205
+	 * Takes the input parameter and finds the model field that it indicates.
4206
+	 *
4207
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4208
+	 * @throws EE_Error
4209
+	 * @return EE_Model_Field_Base
4210
+	 */
4211
+	protected function _deduce_field_from_query_param($query_param_name)
4212
+	{
4213
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4214
+		//which will help us find the database table and column
4215
+		$query_param_parts = explode(".", $query_param_name);
4216
+		if (empty($query_param_parts)) {
4217
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4218
+				'event_espresso'), $query_param_name));
4219
+		}
4220
+		$number_of_parts = count($query_param_parts);
4221
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4222
+		if ($number_of_parts === 1) {
4223
+			$field_name = $last_query_param_part;
4224
+			$model_obj = $this;
4225
+		} else {// $number_of_parts >= 2
4226
+			//the last part is the column name, and there are only 2parts. therefore...
4227
+			$field_name = $last_query_param_part;
4228
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4229
+		}
4230
+		try {
4231
+			return $model_obj->field_settings_for($field_name);
4232
+		} catch (EE_Error $e) {
4233
+			return null;
4234
+		}
4235
+	}
4236
+
4237
+
4238
+
4239
+	/**
4240
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4241
+	 * alias and column which corresponds to it
4242
+	 *
4243
+	 * @param string $field_name
4244
+	 * @throws EE_Error
4245
+	 * @return string
4246
+	 */
4247
+	public function _get_qualified_column_for_field($field_name)
4248
+	{
4249
+		$all_fields = $this->field_settings();
4250
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4251
+		if ($field) {
4252
+			return $field->get_qualified_column();
4253
+		} else {
4254
+			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.",
4255
+				'event_espresso'), $field_name, get_class($this)));
4256
+		}
4257
+	}
4258
+
4259
+
4260
+
4261
+	/**
4262
+	 * constructs the select use on special limit joins
4263
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4264
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4265
+	 * (as that is typically where the limits would be set).
4266
+	 *
4267
+	 * @param  string       $table_alias The table the select is being built for
4268
+	 * @param  mixed|string $limit       The limit for this select
4269
+	 * @return string                The final select join element for the query.
4270
+	 */
4271
+	public function _construct_limit_join_select($table_alias, $limit)
4272
+	{
4273
+		$SQL = '';
4274
+		foreach ($this->_tables as $table_obj) {
4275
+			if ($table_obj instanceof EE_Primary_Table) {
4276
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4277
+					? $table_obj->get_select_join_limit($limit)
4278
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4279
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4280
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4281
+					? $table_obj->get_select_join_limit_join($limit)
4282
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4283
+			}
4284
+		}
4285
+		return $SQL;
4286
+	}
4287
+
4288
+
4289
+
4290
+	/**
4291
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4292
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4293
+	 *
4294
+	 * @return string SQL
4295
+	 * @throws \EE_Error
4296
+	 */
4297
+	public function _construct_internal_join()
4298
+	{
4299
+		$SQL = $this->_get_main_table()->get_table_sql();
4300
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4301
+		return $SQL;
4302
+	}
4303
+
4304
+
4305
+
4306
+	/**
4307
+	 * Constructs the SQL for joining all the tables on this model.
4308
+	 * Normally $alias should be the primary table's alias, but in cases where
4309
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4310
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4311
+	 * alias, this will construct SQL like:
4312
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4313
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4314
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4315
+	 *
4316
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4317
+	 * @return string
4318
+	 */
4319
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4320
+	{
4321
+		$SQL = '';
4322
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4323
+		foreach ($this->_tables as $table_obj) {
4324
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4325
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4326
+					//so we're joining to this table, meaning the table is already in
4327
+					//the FROM statement, BUT the primary table isn't. So we want
4328
+					//to add the inverse join sql
4329
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4330
+				} else {
4331
+					//just add a regular JOIN to this table from the primary table
4332
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4333
+				}
4334
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4335
+		}
4336
+		return $SQL;
4337
+	}
4338
+
4339
+
4340
+
4341
+	/**
4342
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4343
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4344
+	 * their data type (eg, '%s', '%d', etc)
4345
+	 *
4346
+	 * @return array
4347
+	 */
4348
+	public function _get_data_types()
4349
+	{
4350
+		$data_types = array();
4351
+		foreach ($this->field_settings() as $field_obj) {
4352
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4353
+			/** @var $field_obj EE_Model_Field_Base */
4354
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4355
+		}
4356
+		return $data_types;
4357
+	}
4358
+
4359
+
4360
+
4361
+	/**
4362
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4363
+	 *
4364
+	 * @param string $model_name
4365
+	 * @throws EE_Error
4366
+	 * @return EEM_Base
4367
+	 */
4368
+	public function get_related_model_obj($model_name)
4369
+	{
4370
+		$model_classname = "EEM_" . $model_name;
4371
+		if (! class_exists($model_classname)) {
4372
+			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",
4373
+				'event_espresso'), $model_name, $model_classname));
4374
+		}
4375
+		return call_user_func($model_classname . "::instance");
4376
+	}
4377
+
4378
+
4379
+
4380
+	/**
4381
+	 * Returns the array of EE_ModelRelations for this model.
4382
+	 *
4383
+	 * @return EE_Model_Relation_Base[]
4384
+	 */
4385
+	public function relation_settings()
4386
+	{
4387
+		return $this->_model_relations;
4388
+	}
4389
+
4390
+
4391
+
4392
+	/**
4393
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4394
+	 * because without THOSE models, this model probably doesn't have much purpose.
4395
+	 * (Eg, without an event, datetimes have little purpose.)
4396
+	 *
4397
+	 * @return EE_Belongs_To_Relation[]
4398
+	 */
4399
+	public function belongs_to_relations()
4400
+	{
4401
+		$belongs_to_relations = array();
4402
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4403
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4404
+				$belongs_to_relations[$model_name] = $relation_obj;
4405
+			}
4406
+		}
4407
+		return $belongs_to_relations;
4408
+	}
4409
+
4410
+
4411
+
4412
+	/**
4413
+	 * Returns the specified EE_Model_Relation, or throws an exception
4414
+	 *
4415
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4416
+	 * @throws EE_Error
4417
+	 * @return EE_Model_Relation_Base
4418
+	 */
4419
+	public function related_settings_for($relation_name)
4420
+	{
4421
+		$relatedModels = $this->relation_settings();
4422
+		if (! array_key_exists($relation_name, $relatedModels)) {
4423
+			throw new EE_Error(
4424
+				sprintf(
4425
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4426
+						'event_espresso'),
4427
+					$relation_name,
4428
+					$this->_get_class_name(),
4429
+					implode(', ', array_keys($relatedModels))
4430
+				)
4431
+			);
4432
+		}
4433
+		return $relatedModels[$relation_name];
4434
+	}
4435
+
4436
+
4437
+
4438
+	/**
4439
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4440
+	 * fields
4441
+	 *
4442
+	 * @param string $fieldName
4443
+	 * @throws EE_Error
4444
+	 * @return EE_Model_Field_Base
4445
+	 */
4446
+	public function field_settings_for($fieldName)
4447
+	{
4448
+		$fieldSettings = $this->field_settings(true);
4449
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4450
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4451
+				get_class($this)));
4452
+		}
4453
+		return $fieldSettings[$fieldName];
4454
+	}
4455
+
4456
+
4457
+
4458
+	/**
4459
+	 * Checks if this field exists on this model
4460
+	 *
4461
+	 * @param string $fieldName a key in the model's _field_settings array
4462
+	 * @return boolean
4463
+	 */
4464
+	public function has_field($fieldName)
4465
+	{
4466
+		$fieldSettings = $this->field_settings(true);
4467
+		if (isset($fieldSettings[$fieldName])) {
4468
+			return true;
4469
+		} else {
4470
+			return false;
4471
+		}
4472
+	}
4473
+
4474
+
4475
+
4476
+	/**
4477
+	 * Returns whether or not this model has a relation to the specified model
4478
+	 *
4479
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4480
+	 * @return boolean
4481
+	 */
4482
+	public function has_relation($relation_name)
4483
+	{
4484
+		$relations = $this->relation_settings();
4485
+		if (isset($relations[$relation_name])) {
4486
+			return true;
4487
+		} else {
4488
+			return false;
4489
+		}
4490
+	}
4491
+
4492
+
4493
+
4494
+	/**
4495
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4496
+	 * Eg, on EE_Answer that would be ANS_ID field object
4497
+	 *
4498
+	 * @param $field_obj
4499
+	 * @return boolean
4500
+	 */
4501
+	public function is_primary_key_field($field_obj)
4502
+	{
4503
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4504
+	}
4505
+
4506
+
4507
+
4508
+	/**
4509
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4510
+	 * Eg, on EE_Answer that would be ANS_ID field object
4511
+	 *
4512
+	 * @return EE_Model_Field_Base
4513
+	 * @throws EE_Error
4514
+	 */
4515
+	public function get_primary_key_field()
4516
+	{
4517
+		if ($this->_primary_key_field === null) {
4518
+			foreach ($this->field_settings(true) as $field_obj) {
4519
+				if ($this->is_primary_key_field($field_obj)) {
4520
+					$this->_primary_key_field = $field_obj;
4521
+					break;
4522
+				}
4523
+			}
4524
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4525
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4526
+					get_class($this)));
4527
+			}
4528
+		}
4529
+		return $this->_primary_key_field;
4530
+	}
4531
+
4532
+
4533
+
4534
+	/**
4535
+	 * Returns whether or not not there is a primary key on this model.
4536
+	 * Internally does some caching.
4537
+	 *
4538
+	 * @return boolean
4539
+	 */
4540
+	public function has_primary_key_field()
4541
+	{
4542
+		if ($this->_has_primary_key_field === null) {
4543
+			try {
4544
+				$this->get_primary_key_field();
4545
+				$this->_has_primary_key_field = true;
4546
+			} catch (EE_Error $e) {
4547
+				$this->_has_primary_key_field = false;
4548
+			}
4549
+		}
4550
+		return $this->_has_primary_key_field;
4551
+	}
4552
+
4553
+
4554
+
4555
+	/**
4556
+	 * Finds the first field of type $field_class_name.
4557
+	 *
4558
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4559
+	 *                                 EE_Foreign_Key_Field, etc
4560
+	 * @return EE_Model_Field_Base or null if none is found
4561
+	 */
4562
+	public function get_a_field_of_type($field_class_name)
4563
+	{
4564
+		foreach ($this->field_settings() as $field) {
4565
+			if ($field instanceof $field_class_name) {
4566
+				return $field;
4567
+			}
4568
+		}
4569
+		return null;
4570
+	}
4571
+
4572
+
4573
+
4574
+	/**
4575
+	 * Gets a foreign key field pointing to model.
4576
+	 *
4577
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4578
+	 * @return EE_Foreign_Key_Field_Base
4579
+	 * @throws EE_Error
4580
+	 */
4581
+	public function get_foreign_key_to($model_name)
4582
+	{
4583
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4584
+			foreach ($this->field_settings() as $field) {
4585
+				if (
4586
+					$field instanceof EE_Foreign_Key_Field_Base
4587
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4588
+				) {
4589
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4590
+					break;
4591
+				}
4592
+			}
4593
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4594
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4595
+					'event_espresso'), $model_name, get_class($this)));
4596
+			}
4597
+		}
4598
+		return $this->_cache_foreign_key_to_fields[$model_name];
4599
+	}
4600
+
4601
+
4602
+
4603
+	/**
4604
+	 * Gets the actual table for the table alias
4605
+	 *
4606
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4607
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4608
+	 *                            Either one works
4609
+	 * @return EE_Table_Base
4610
+	 */
4611
+	public function get_table_for_alias($table_alias)
4612
+	{
4613
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4614
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4615
+	}
4616
+
4617
+
4618
+
4619
+	/**
4620
+	 * Returns a flat array of all field son this model, instead of organizing them
4621
+	 * by table_alias as they are in the constructor.
4622
+	 *
4623
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4624
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4625
+	 */
4626
+	public function field_settings($include_db_only_fields = false)
4627
+	{
4628
+		if ($include_db_only_fields) {
4629
+			if ($this->_cached_fields === null) {
4630
+				$this->_cached_fields = array();
4631
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4632
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4633
+						$this->_cached_fields[$field_name] = $field_obj;
4634
+					}
4635
+				}
4636
+			}
4637
+			return $this->_cached_fields;
4638
+		} else {
4639
+			if ($this->_cached_fields_non_db_only === null) {
4640
+				$this->_cached_fields_non_db_only = array();
4641
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4642
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4643
+						/** @var $field_obj EE_Model_Field_Base */
4644
+						if (! $field_obj->is_db_only_field()) {
4645
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4646
+						}
4647
+					}
4648
+				}
4649
+			}
4650
+			return $this->_cached_fields_non_db_only;
4651
+		}
4652
+	}
4653
+
4654
+
4655
+
4656
+	/**
4657
+	 *        cycle though array of attendees and create objects out of each item
4658
+	 *
4659
+	 * @access        private
4660
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4661
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4662
+	 *                           numerically indexed)
4663
+	 * @throws \EE_Error
4664
+	 */
4665
+	protected function _create_objects($rows = array())
4666
+	{
4667
+		$array_of_objects = array();
4668
+		if (empty($rows)) {
4669
+			return array();
4670
+		}
4671
+		$count_if_model_has_no_primary_key = 0;
4672
+		$has_primary_key = $this->has_primary_key_field();
4673
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4674
+		foreach ((array)$rows as $row) {
4675
+			if (empty($row)) {
4676
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4677
+				return array();
4678
+			}
4679
+			//check if we've already set this object in the results array,
4680
+			//in which case there's no need to process it further (again)
4681
+			if ($has_primary_key) {
4682
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4683
+					$row,
4684
+					$primary_key_field->get_qualified_column(),
4685
+					$primary_key_field->get_table_column()
4686
+				);
4687
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4688
+					continue;
4689
+				}
4690
+			}
4691
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4692
+			if (! $classInstance) {
4693
+				throw new EE_Error(
4694
+					sprintf(
4695
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4696
+						$this->get_this_model_name(),
4697
+						http_build_query($row)
4698
+					)
4699
+				);
4700
+			}
4701
+			//set the timezone on the instantiated objects
4702
+			$classInstance->set_timezone($this->_timezone);
4703
+			//make sure if there is any timezone setting present that we set the timezone for the object
4704
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4705
+			$array_of_objects[$key] = $classInstance;
4706
+			//also, for all the relations of type BelongsTo, see if we can cache
4707
+			//those related models
4708
+			//(we could do this for other relations too, but if there are conditions
4709
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4710
+			//so it requires a little more thought than just caching them immediately...)
4711
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4712
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4713
+					//check if this model's INFO is present. If so, cache it on the model
4714
+					$other_model = $relation_obj->get_other_model();
4715
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4716
+					//if we managed to make a model object from the results, cache it on the main model object
4717
+					if ($other_model_obj_maybe) {
4718
+						//set timezone on these other model objects if they are present
4719
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4720
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4721
+					}
4722
+				}
4723
+			}
4724
+		}
4725
+		return $array_of_objects;
4726
+	}
4727
+
4728
+
4729
+
4730
+	/**
4731
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4732
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4733
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4734
+	 * object (as set in the model_field!).
4735
+	 *
4736
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4737
+	 */
4738
+	public function create_default_object()
4739
+	{
4740
+		$this_model_fields_and_values = array();
4741
+		//setup the row using default values;
4742
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4743
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4744
+		}
4745
+		$className = $this->_get_class_name();
4746
+		$classInstance = EE_Registry::instance()
4747
+									->load_class($className, array($this_model_fields_and_values), false, false);
4748
+		return $classInstance;
4749
+	}
4750
+
4751
+
4752
+
4753
+	/**
4754
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4755
+	 *                             or an stdClass where each property is the name of a column,
4756
+	 * @return EE_Base_Class
4757
+	 * @throws \EE_Error
4758
+	 */
4759
+	public function instantiate_class_from_array_or_object($cols_n_values)
4760
+	{
4761
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4762
+			$cols_n_values = get_object_vars($cols_n_values);
4763
+		}
4764
+		$primary_key = null;
4765
+		//make sure the array only has keys that are fields/columns on this model
4766
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4767
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4768
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4769
+		}
4770
+		$className = $this->_get_class_name();
4771
+		//check we actually found results that we can use to build our model object
4772
+		//if not, return null
4773
+		if ($this->has_primary_key_field()) {
4774
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4775
+				return null;
4776
+			}
4777
+		} else if ($this->unique_indexes()) {
4778
+			$first_column = reset($this_model_fields_n_values);
4779
+			if (empty($first_column)) {
4780
+				return null;
4781
+			}
4782
+		}
4783
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4784
+		if ($primary_key) {
4785
+			$classInstance = $this->get_from_entity_map($primary_key);
4786
+			if (! $classInstance) {
4787
+				$classInstance = EE_Registry::instance()
4788
+											->load_class($className,
4789
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4790
+				// add this new object to the entity map
4791
+				$classInstance = $this->add_to_entity_map($classInstance);
4792
+			}
4793
+		} else {
4794
+			$classInstance = EE_Registry::instance()
4795
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4796
+											true, false);
4797
+		}
4798
+		//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.
4799
+		$this->set_timezone($classInstance->get_timezone());
4800
+		return $classInstance;
4801
+	}
4802
+
4803
+
4804
+
4805
+	/**
4806
+	 * Gets the model object from the  entity map if it exists
4807
+	 *
4808
+	 * @param int|string $id the ID of the model object
4809
+	 * @return EE_Base_Class
4810
+	 */
4811
+	public function get_from_entity_map($id)
4812
+	{
4813
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4814
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4815
+	}
4816
+
4817
+
4818
+
4819
+	/**
4820
+	 * add_to_entity_map
4821
+	 * Adds the object to the model's entity mappings
4822
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4823
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4824
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4825
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4826
+	 *        then this method should be called immediately after the update query
4827
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4828
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4829
+	 *
4830
+	 * @param    EE_Base_Class $object
4831
+	 * @throws EE_Error
4832
+	 * @return \EE_Base_Class
4833
+	 */
4834
+	public function add_to_entity_map(EE_Base_Class $object)
4835
+	{
4836
+		$className = $this->_get_class_name();
4837
+		if (! $object instanceof $className) {
4838
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4839
+				is_object($object) ? get_class($object) : $object, $className));
4840
+		}
4841
+		/** @var $object EE_Base_Class */
4842
+		if (! $object->ID()) {
4843
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4844
+				"event_espresso"), get_class($this)));
4845
+		}
4846
+		// double check it's not already there
4847
+		$classInstance = $this->get_from_entity_map($object->ID());
4848
+		if ($classInstance) {
4849
+			return $classInstance;
4850
+		} else {
4851
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4852
+			return $object;
4853
+		}
4854
+	}
4855
+
4856
+
4857
+
4858
+	/**
4859
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4860
+	 * if no identifier is provided, then the entire entity map is emptied
4861
+	 *
4862
+	 * @param int|string $id the ID of the model object
4863
+	 * @return boolean
4864
+	 */
4865
+	public function clear_entity_map($id = null)
4866
+	{
4867
+		if (empty($id)) {
4868
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4869
+			return true;
4870
+		}
4871
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4872
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4873
+			return true;
4874
+		}
4875
+		return false;
4876
+	}
4877
+
4878
+
4879
+
4880
+	/**
4881
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4882
+	 * Given an array where keys are column (or column alias) names and values,
4883
+	 * returns an array of their corresponding field names and database values
4884
+	 *
4885
+	 * @param array $cols_n_values
4886
+	 * @return array
4887
+	 */
4888
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4889
+	{
4890
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4891
+	}
4892
+
4893
+
4894
+
4895
+	/**
4896
+	 * _deduce_fields_n_values_from_cols_n_values
4897
+	 * Given an array where keys are column (or column alias) names and values,
4898
+	 * returns an array of their corresponding field names and database values
4899
+	 *
4900
+	 * @param string $cols_n_values
4901
+	 * @return array
4902
+	 */
4903
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4904
+	{
4905
+		$this_model_fields_n_values = array();
4906
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
4907
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4908
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4909
+			//there is a primary key on this table and its not set. Use defaults for all its columns
4910
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
4911
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4912
+					if (! $field_obj->is_db_only_field()) {
4913
+						//prepare field as if its coming from db
4914
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4915
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4916
+					}
4917
+				}
4918
+			} else {
4919
+				//the table's rows existed. Use their values
4920
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4921
+					if (! $field_obj->is_db_only_field()) {
4922
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4923
+							$cols_n_values, $field_obj->get_qualified_column(),
4924
+							$field_obj->get_table_column()
4925
+						);
4926
+					}
4927
+				}
4928
+			}
4929
+		}
4930
+		return $this_model_fields_n_values;
4931
+	}
4932
+
4933
+
4934
+
4935
+	/**
4936
+	 * @param $cols_n_values
4937
+	 * @param $qualified_column
4938
+	 * @param $regular_column
4939
+	 * @return null
4940
+	 */
4941
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4942
+	{
4943
+		$value = null;
4944
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4945
+		//does the field on the model relate to this column retrieved from the db?
4946
+		//or is it a db-only field? (not relating to the model)
4947
+		if (isset($cols_n_values[$qualified_column])) {
4948
+			$value = $cols_n_values[$qualified_column];
4949
+		} elseif (isset($cols_n_values[$regular_column])) {
4950
+			$value = $cols_n_values[$regular_column];
4951
+		}
4952
+		return $value;
4953
+	}
4954
+
4955
+
4956
+
4957
+	/**
4958
+	 * refresh_entity_map_from_db
4959
+	 * Makes sure the model object in the entity map at $id assumes the values
4960
+	 * of the database (opposite of EE_base_Class::save())
4961
+	 *
4962
+	 * @param int|string $id
4963
+	 * @return EE_Base_Class
4964
+	 * @throws \EE_Error
4965
+	 */
4966
+	public function refresh_entity_map_from_db($id)
4967
+	{
4968
+		$obj_in_map = $this->get_from_entity_map($id);
4969
+		if ($obj_in_map) {
4970
+			$wpdb_results = $this->_get_all_wpdb_results(
4971
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
4972
+			);
4973
+			if ($wpdb_results && is_array($wpdb_results)) {
4974
+				$one_row = reset($wpdb_results);
4975
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
4976
+					$obj_in_map->set_from_db($field_name, $db_value);
4977
+				}
4978
+				//clear the cache of related model objects
4979
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4980
+					$obj_in_map->clear_cache($relation_name, null, true);
4981
+				}
4982
+			}
4983
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
4984
+			return $obj_in_map;
4985
+		} else {
4986
+			return $this->get_one_by_ID($id);
4987
+		}
4988
+	}
4989
+
4990
+
4991
+
4992
+	/**
4993
+	 * refresh_entity_map_with
4994
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
4995
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4996
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4997
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4998
+	 *
4999
+	 * @param int|string    $id
5000
+	 * @param EE_Base_Class $replacing_model_obj
5001
+	 * @return \EE_Base_Class
5002
+	 * @throws \EE_Error
5003
+	 */
5004
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5005
+	{
5006
+		$obj_in_map = $this->get_from_entity_map($id);
5007
+		if ($obj_in_map) {
5008
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5009
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5010
+					$obj_in_map->set($field_name, $value);
5011
+				}
5012
+				//make the model object in the entity map's cache match the $replacing_model_obj
5013
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5014
+					$obj_in_map->clear_cache($relation_name, null, true);
5015
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5016
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5017
+					}
5018
+				}
5019
+			}
5020
+			return $obj_in_map;
5021
+		} else {
5022
+			$this->add_to_entity_map($replacing_model_obj);
5023
+			return $replacing_model_obj;
5024
+		}
5025
+	}
5026
+
5027
+
5028
+
5029
+	/**
5030
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5031
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5032
+	 * require_once($this->_getClassName().".class.php");
5033
+	 *
5034
+	 * @return string
5035
+	 */
5036
+	private function _get_class_name()
5037
+	{
5038
+		return "EE_" . $this->get_this_model_name();
5039
+	}
5040
+
5041
+
5042
+
5043
+	/**
5044
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5045
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5046
+	 * it would be 'Events'.
5047
+	 *
5048
+	 * @param int $quantity
5049
+	 * @return string
5050
+	 */
5051
+	public function item_name($quantity = 1)
5052
+	{
5053
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5054
+	}
5055
+
5056
+
5057
+
5058
+	/**
5059
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5060
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5061
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5062
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5063
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5064
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5065
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5066
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5067
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5068
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5069
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5070
+	 *        return $previousReturnValue.$returnString;
5071
+	 * }
5072
+	 * require('EEM_Answer.model.php');
5073
+	 * $answer=EEM_Answer::instance();
5074
+	 * echo $answer->my_callback('monkeys',100);
5075
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5076
+	 *
5077
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5078
+	 * @param array  $args       array of original arguments passed to the function
5079
+	 * @throws EE_Error
5080
+	 * @return mixed whatever the plugin which calls add_filter decides
5081
+	 */
5082
+	public function __call($methodName, $args)
5083
+	{
5084
+		$className = get_class($this);
5085
+		$tagName = "FHEE__{$className}__{$methodName}";
5086
+		if (! has_filter($tagName)) {
5087
+			throw new EE_Error(
5088
+				sprintf(
5089
+					__('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 );',
5090
+						'event_espresso'),
5091
+					$methodName,
5092
+					$className,
5093
+					$tagName,
5094
+					'<br />'
5095
+				)
5096
+			);
5097
+		}
5098
+		return apply_filters($tagName, null, $this, $args);
5099
+	}
5100
+
5101
+
5102
+
5103
+	/**
5104
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5105
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5106
+	 *
5107
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5108
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5109
+	 *                                                       the object's class name
5110
+	 *                                                       or object's ID
5111
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5112
+	 *                                                       exists in the database. If it does not, we add it
5113
+	 * @throws EE_Error
5114
+	 * @return EE_Base_Class
5115
+	 */
5116
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5117
+	{
5118
+		$className = $this->_get_class_name();
5119
+		if ($base_class_obj_or_id instanceof $className) {
5120
+			$model_object = $base_class_obj_or_id;
5121
+		} else {
5122
+			$primary_key_field = $this->get_primary_key_field();
5123
+			if (
5124
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5125
+				&& (
5126
+					is_int($base_class_obj_or_id)
5127
+					|| is_string($base_class_obj_or_id)
5128
+				)
5129
+			) {
5130
+				// assume it's an ID.
5131
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5132
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5133
+			} else if (
5134
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5135
+				&& is_string($base_class_obj_or_id)
5136
+			) {
5137
+				// assume its a string representation of the object
5138
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5139
+			} else {
5140
+				throw new EE_Error(
5141
+					sprintf(
5142
+						__(
5143
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5144
+							'event_espresso'
5145
+						),
5146
+						$base_class_obj_or_id,
5147
+						$this->_get_class_name(),
5148
+						print_r($base_class_obj_or_id, true)
5149
+					)
5150
+				);
5151
+			}
5152
+		}
5153
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5154
+			$model_object->save();
5155
+		}
5156
+		return $model_object;
5157
+	}
5158
+
5159
+
5160
+
5161
+	/**
5162
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5163
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5164
+	 * returns it ID.
5165
+	 *
5166
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5167
+	 * @return int|string depending on the type of this model object's ID
5168
+	 * @throws EE_Error
5169
+	 */
5170
+	public function ensure_is_ID($base_class_obj_or_id)
5171
+	{
5172
+		$className = $this->_get_class_name();
5173
+		if ($base_class_obj_or_id instanceof $className) {
5174
+			/** @var $base_class_obj_or_id EE_Base_Class */
5175
+			$id = $base_class_obj_or_id->ID();
5176
+		} elseif (is_int($base_class_obj_or_id)) {
5177
+			//assume it's an ID
5178
+			$id = $base_class_obj_or_id;
5179
+		} elseif (is_string($base_class_obj_or_id)) {
5180
+			//assume its a string representation of the object
5181
+			$id = $base_class_obj_or_id;
5182
+		} else {
5183
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5184
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5185
+				print_r($base_class_obj_or_id, true)));
5186
+		}
5187
+		return $id;
5188
+	}
5189
+
5190
+
5191
+
5192
+	/**
5193
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5194
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5195
+	 * been sanitized and converted into the appropriate domain.
5196
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5197
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5198
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5199
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5200
+	 * $EVT = EEM_Event::instance(); $old_setting =
5201
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5202
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5203
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5204
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5205
+	 *
5206
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5207
+	 * @return void
5208
+	 */
5209
+	public function assume_values_already_prepared_by_model_object(
5210
+		$values_already_prepared = self::not_prepared_by_model_object
5211
+	) {
5212
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5213
+	}
5214
+
5215
+
5216
+
5217
+	/**
5218
+	 * Read comments for assume_values_already_prepared_by_model_object()
5219
+	 *
5220
+	 * @return int
5221
+	 */
5222
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5223
+	{
5224
+		return $this->_values_already_prepared_by_model_object;
5225
+	}
5226
+
5227
+
5228
+
5229
+	/**
5230
+	 * Gets all the indexes on this model
5231
+	 *
5232
+	 * @return EE_Index[]
5233
+	 */
5234
+	public function indexes()
5235
+	{
5236
+		return $this->_indexes;
5237
+	}
5238
+
5239
+
5240
+
5241
+	/**
5242
+	 * Gets all the Unique Indexes on this model
5243
+	 *
5244
+	 * @return EE_Unique_Index[]
5245
+	 */
5246
+	public function unique_indexes()
5247
+	{
5248
+		$unique_indexes = array();
5249
+		foreach ($this->_indexes as $name => $index) {
5250
+			if ($index instanceof EE_Unique_Index) {
5251
+				$unique_indexes [$name] = $index;
5252
+			}
5253
+		}
5254
+		return $unique_indexes;
5255
+	}
5256
+
5257
+
5258
+
5259
+	/**
5260
+	 * Gets all the fields which, when combined, make the primary key.
5261
+	 * This is usually just an array with 1 element (the primary key), but in cases
5262
+	 * where there is no primary key, it's a combination of fields as defined
5263
+	 * on a primary index
5264
+	 *
5265
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5266
+	 * @throws \EE_Error
5267
+	 */
5268
+	public function get_combined_primary_key_fields()
5269
+	{
5270
+		foreach ($this->indexes() as $index) {
5271
+			if ($index instanceof EE_Primary_Key_Index) {
5272
+				return $index->fields();
5273
+			}
5274
+		}
5275
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5276
+	}
5277
+
5278
+
5279
+
5280
+	/**
5281
+	 * Used to build a primary key string (when the model has no primary key),
5282
+	 * which can be used a unique string to identify this model object.
5283
+	 *
5284
+	 * @param array $cols_n_values keys are field names, values are their values
5285
+	 * @return string
5286
+	 * @throws \EE_Error
5287
+	 */
5288
+	public function get_index_primary_key_string($cols_n_values)
5289
+	{
5290
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5291
+			$this->get_combined_primary_key_fields());
5292
+		return http_build_query($cols_n_values_for_primary_key_index);
5293
+	}
5294
+
5295
+
5296
+
5297
+	/**
5298
+	 * Gets the field values from the primary key string
5299
+	 *
5300
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5301
+	 * @param string $index_primary_key_string
5302
+	 * @return null|array
5303
+	 * @throws \EE_Error
5304
+	 */
5305
+	public function parse_index_primary_key_string($index_primary_key_string)
5306
+	{
5307
+		$key_fields = $this->get_combined_primary_key_fields();
5308
+		//check all of them are in the $id
5309
+		$key_vals_in_combined_pk = array();
5310
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5311
+		foreach ($key_fields as $key_field_name => $field_obj) {
5312
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5313
+				return null;
5314
+			}
5315
+		}
5316
+		return $key_vals_in_combined_pk;
5317
+	}
5318
+
5319
+
5320
+
5321
+	/**
5322
+	 * verifies that an array of key-value pairs for model fields has a key
5323
+	 * for each field comprising the primary key index
5324
+	 *
5325
+	 * @param array $key_vals
5326
+	 * @return boolean
5327
+	 * @throws \EE_Error
5328
+	 */
5329
+	public function has_all_combined_primary_key_fields($key_vals)
5330
+	{
5331
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5332
+		foreach ($keys_it_should_have as $key) {
5333
+			if (! isset($key_vals[$key])) {
5334
+				return false;
5335
+			}
5336
+		}
5337
+		return true;
5338
+	}
5339
+
5340
+
5341
+
5342
+	/**
5343
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5344
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5345
+	 *
5346
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5347
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5348
+	 * @throws EE_Error
5349
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5350
+	 *                                                              indexed)
5351
+	 */
5352
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5353
+	{
5354
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5355
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5356
+		} elseif (is_array($model_object_or_attributes_array)) {
5357
+			$attributes_array = $model_object_or_attributes_array;
5358
+		} else {
5359
+			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",
5360
+				"event_espresso"), $model_object_or_attributes_array));
5361
+		}
5362
+		//even copies obviously won't have the same ID, so remove the primary key
5363
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5364
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5365
+			unset($attributes_array[$this->primary_key_name()]);
5366
+		}
5367
+		if (isset($query_params[0])) {
5368
+			$query_params[0] = array_merge($attributes_array, $query_params);
5369
+		} else {
5370
+			$query_params[0] = $attributes_array;
5371
+		}
5372
+		return $this->get_all($query_params);
5373
+	}
5374
+
5375
+
5376
+
5377
+	/**
5378
+	 * Gets the first copy we find. See get_all_copies for more details
5379
+	 *
5380
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5381
+	 * @param array $query_params
5382
+	 * @return EE_Base_Class
5383
+	 * @throws \EE_Error
5384
+	 */
5385
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5386
+	{
5387
+		if (! is_array($query_params)) {
5388
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5389
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5390
+					gettype($query_params)), '4.6.0');
5391
+			$query_params = array();
5392
+		}
5393
+		$query_params['limit'] = 1;
5394
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5395
+		if (is_array($copies)) {
5396
+			return array_shift($copies);
5397
+		} else {
5398
+			return null;
5399
+		}
5400
+	}
5401
+
5402
+
5403
+
5404
+	/**
5405
+	 * Updates the item with the specified id. Ignores default query parameters because
5406
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5407
+	 *
5408
+	 * @param array      $fields_n_values keys are field names, values are their new values
5409
+	 * @param int|string $id              the value of the primary key to update
5410
+	 * @return int number of rows updated
5411
+	 * @throws \EE_Error
5412
+	 */
5413
+	public function update_by_ID($fields_n_values, $id)
5414
+	{
5415
+		$query_params = array(
5416
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5417
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5418
+		);
5419
+		return $this->update($fields_n_values, $query_params);
5420
+	}
5421
+
5422
+
5423
+
5424
+	/**
5425
+	 * Changes an operator which was supplied to the models into one usable in SQL
5426
+	 *
5427
+	 * @param string $operator_supplied
5428
+	 * @return string an operator which can be used in SQL
5429
+	 * @throws EE_Error
5430
+	 */
5431
+	private function _prepare_operator_for_sql($operator_supplied)
5432
+	{
5433
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5434
+			: null;
5435
+		if ($sql_operator) {
5436
+			return $sql_operator;
5437
+		} else {
5438
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5439
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5440
+		}
5441
+	}
5442
+
5443
+
5444
+
5445
+	/**
5446
+	 * Gets an array where keys are the primary keys and values are their 'names'
5447
+	 * (as determined by the model object's name() function, which is often overridden)
5448
+	 *
5449
+	 * @param array $query_params like get_all's
5450
+	 * @return string[]
5451
+	 * @throws \EE_Error
5452
+	 */
5453
+	public function get_all_names($query_params = array())
5454
+	{
5455
+		$objs = $this->get_all($query_params);
5456
+		$names = array();
5457
+		foreach ($objs as $obj) {
5458
+			$names[$obj->ID()] = $obj->name();
5459
+		}
5460
+		return $names;
5461
+	}
5462
+
5463
+
5464
+
5465
+	/**
5466
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5467
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5468
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5469
+	 * array_keys() on $model_objects.
5470
+	 *
5471
+	 * @param \EE_Base_Class[] $model_objects
5472
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5473
+	 *                                               in the returned array
5474
+	 * @return array
5475
+	 * @throws \EE_Error
5476
+	 */
5477
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5478
+	{
5479
+		if (! $this->has_primary_key_field()) {
5480
+			if (WP_DEBUG) {
5481
+				EE_Error::add_error(
5482
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5483
+					__FILE__,
5484
+					__FUNCTION__,
5485
+					__LINE__
5486
+				);
5487
+			}
5488
+		}
5489
+		$IDs = array();
5490
+		foreach ($model_objects as $model_object) {
5491
+			$id = $model_object->ID();
5492
+			if (! $id) {
5493
+				if ($filter_out_empty_ids) {
5494
+					continue;
5495
+				}
5496
+				if (WP_DEBUG) {
5497
+					EE_Error::add_error(
5498
+						__(
5499
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5500
+							'event_espresso'
5501
+						),
5502
+						__FILE__,
5503
+						__FUNCTION__,
5504
+						__LINE__
5505
+					);
5506
+				}
5507
+			}
5508
+			$IDs[] = $id;
5509
+		}
5510
+		return $IDs;
5511
+	}
5512
+
5513
+
5514
+
5515
+	/**
5516
+	 * Returns the string used in capabilities relating to this model. If there
5517
+	 * are no capabilities that relate to this model returns false
5518
+	 *
5519
+	 * @return string|false
5520
+	 */
5521
+	public function cap_slug()
5522
+	{
5523
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5524
+	}
5525
+
5526
+
5527
+
5528
+	/**
5529
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5530
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5531
+	 * only returns the cap restrictions array in that context (ie, the array
5532
+	 * at that key)
5533
+	 *
5534
+	 * @param string $context
5535
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5536
+	 * @throws \EE_Error
5537
+	 */
5538
+	public function cap_restrictions($context = EEM_Base::caps_read)
5539
+	{
5540
+		EEM_Base::verify_is_valid_cap_context($context);
5541
+		//check if we ought to run the restriction generator first
5542
+		if (
5543
+			isset($this->_cap_restriction_generators[$context])
5544
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5545
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5546
+		) {
5547
+			$this->_cap_restrictions[$context] = array_merge(
5548
+				$this->_cap_restrictions[$context],
5549
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5550
+			);
5551
+		}
5552
+		//and make sure we've finalized the construction of each restriction
5553
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5554
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5555
+				$where_conditions_obj->_finalize_construct($this);
5556
+			}
5557
+		}
5558
+		return $this->_cap_restrictions[$context];
5559
+	}
5560
+
5561
+
5562
+
5563
+	/**
5564
+	 * Indicating whether or not this model thinks its a wp core model
5565
+	 *
5566
+	 * @return boolean
5567
+	 */
5568
+	public function is_wp_core_model()
5569
+	{
5570
+		return $this->_wp_core_model;
5571
+	}
5572
+
5573
+
5574
+
5575
+	/**
5576
+	 * Gets all the caps that are missing which impose a restriction on
5577
+	 * queries made in this context
5578
+	 *
5579
+	 * @param string $context one of EEM_Base::caps_ constants
5580
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5581
+	 * @throws \EE_Error
5582
+	 */
5583
+	public function caps_missing($context = EEM_Base::caps_read)
5584
+	{
5585
+		$missing_caps = array();
5586
+		$cap_restrictions = $this->cap_restrictions($context);
5587
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5588
+			if (! EE_Capabilities::instance()
5589
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5590
+			) {
5591
+				$missing_caps[$cap] = $restriction_if_no_cap;
5592
+			}
5593
+		}
5594
+		return $missing_caps;
5595
+	}
5596
+
5597
+
5598
+
5599
+	/**
5600
+	 * Gets the mapping from capability contexts to action strings used in capability names
5601
+	 *
5602
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5603
+	 * one of 'read', 'edit', or 'delete'
5604
+	 */
5605
+	public function cap_contexts_to_cap_action_map()
5606
+	{
5607
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5608
+			$this);
5609
+	}
5610
+
5611
+
5612
+
5613
+	/**
5614
+	 * Gets the action string for the specified capability context
5615
+	 *
5616
+	 * @param string $context
5617
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5618
+	 * @throws \EE_Error
5619
+	 */
5620
+	public function cap_action_for_context($context)
5621
+	{
5622
+		$mapping = $this->cap_contexts_to_cap_action_map();
5623
+		if (isset($mapping[$context])) {
5624
+			return $mapping[$context];
5625
+		}
5626
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5627
+			return $action;
5628
+		}
5629
+		throw new EE_Error(
5630
+			sprintf(
5631
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5632
+				$context,
5633
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5634
+			)
5635
+		);
5636
+	}
5637
+
5638
+
5639
+
5640
+	/**
5641
+	 * Returns all the capability contexts which are valid when querying models
5642
+	 *
5643
+	 * @return array
5644
+	 */
5645
+	public static function valid_cap_contexts()
5646
+	{
5647
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5648
+			self::caps_read,
5649
+			self::caps_read_admin,
5650
+			self::caps_edit,
5651
+			self::caps_delete,
5652
+		));
5653
+	}
5654
+
5655
+
5656
+
5657
+	/**
5658
+	 * Returns all valid options for 'default_where_conditions'
5659
+	 *
5660
+	 * @return array
5661
+	 */
5662
+	public static function valid_default_where_conditions()
5663
+	{
5664
+		return array(
5665
+			EEM_Base::default_where_conditions_all,
5666
+			EEM_Base::default_where_conditions_this_only,
5667
+			EEM_Base::default_where_conditions_others_only,
5668
+			EEM_Base::default_where_conditions_minimum_all,
5669
+			EEM_Base::default_where_conditions_minimum_others,
5670
+			EEM_Base::default_where_conditions_none
5671
+		);
5672
+	}
5673
+
5674
+	// public static function default_where_conditions_full
5675
+	/**
5676
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5677
+	 *
5678
+	 * @param string $context
5679
+	 * @return bool
5680
+	 * @throws \EE_Error
5681
+	 */
5682
+	static public function verify_is_valid_cap_context($context)
5683
+	{
5684
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5685
+		if (in_array($context, $valid_cap_contexts)) {
5686
+			return true;
5687
+		} else {
5688
+			throw new EE_Error(
5689
+				sprintf(
5690
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5691
+						'event_espresso'),
5692
+					$context,
5693
+					'EEM_Base',
5694
+					implode(',', $valid_cap_contexts)
5695
+				)
5696
+			);
5697
+		}
5698
+	}
5699
+
5700
+
5701
+
5702
+	/**
5703
+	 * Clears all the models field caches. This is only useful when a sub-class
5704
+	 * might have added a field or something and these caches might be invalidated
5705
+	 */
5706
+	protected function _invalidate_field_caches()
5707
+	{
5708
+		$this->_cache_foreign_key_to_fields = array();
5709
+		$this->_cached_fields = null;
5710
+		$this->_cached_fields_non_db_only = null;
5711
+	}
5712 5712
 
5713 5713
 
5714 5714
 
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +215 added lines, -215 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('ABSPATH')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /*
5 5
   Plugin Name:		Event Espresso
@@ -40,239 +40,239 @@  discard block
 block discarded – undo
40 40
  * @since            4.0
41 41
  */
42 42
 if (function_exists('espresso_version')) {
43
-    /**
44
-     *    espresso_duplicate_plugin_error
45
-     *    displays if more than one version of EE is activated at the same time
46
-     */
47
-    function espresso_duplicate_plugin_error()
48
-    {
49
-        ?>
43
+	/**
44
+	 *    espresso_duplicate_plugin_error
45
+	 *    displays if more than one version of EE is activated at the same time
46
+	 */
47
+	function espresso_duplicate_plugin_error()
48
+	{
49
+		?>
50 50
         <div class="error">
51 51
             <p>
52 52
                 <?php echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                ); ?>
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+				); ?>
56 56
             </p>
57 57
         </div>
58 58
         <?php
59
-        espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-    }
59
+		espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+	}
61 61
 
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
-    if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
+	if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                            esc_html__(
79
-                                    'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                                    'event_espresso'
81
-                            ),
82
-                            EE_MIN_PHP_VER_REQUIRED,
83
-                            PHP_VERSION,
84
-                            '<br/>',
85
-                            '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+							esc_html__(
79
+									'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+									'event_espresso'
81
+							),
82
+							EE_MIN_PHP_VER_REQUIRED,
83
+							PHP_VERSION,
84
+							'<br/>',
85
+							'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        /**
97
-         * espresso_version
98
-         * Returns the plugin version
99
-         *
100
-         * @return string
101
-         */
102
-        function espresso_version()
103
-        {
104
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.23.rc.015');
105
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		/**
97
+		 * espresso_version
98
+		 * Returns the plugin version
99
+		 *
100
+		 * @return string
101
+		 */
102
+		function espresso_version()
103
+		{
104
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.23.rc.015');
105
+		}
106 106
 
107
-        // define versions
108
-        define('EVENT_ESPRESSO_VERSION', espresso_version());
109
-        define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
-        define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
-        define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
-        //used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
-        if ( ! defined('DS')) {
115
-            define('DS', '/');
116
-        }
117
-        if ( ! defined('PS')) {
118
-            define('PS', PATH_SEPARATOR);
119
-        }
120
-        if ( ! defined('SP')) {
121
-            define('SP', ' ');
122
-        }
123
-        if ( ! defined('EENL')) {
124
-            define('EENL', "\n");
125
-        }
126
-        define('EE_SUPPORT_EMAIL', '[email protected]');
127
-        // define the plugin directory and URL
128
-        define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
-        define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
-        define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
-        // main root folder paths
132
-        define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
-        define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
-        define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
-        define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
-        define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
-        define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
-        define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
-        define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
-        // core system paths
141
-        define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
-        define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
-        define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
-        define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
-        define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
-        define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
-        define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
-        define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
-        define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
-        define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
-        define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
-        define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
-        // gateways
154
-        define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
-        define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
-        // asset URL paths
157
-        define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
-        define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
-        define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
-        define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
-        define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
-        define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
-        // define upload paths
164
-        $uploads = wp_upload_dir();
165
-        // define the uploads directory and URL
166
-        define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
-        define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
-        // define the templates directory and URL
169
-        define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
-        define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
-        // define the gateway directory and URL
172
-        define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
-        define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
-        // languages folder/path
175
-        define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
-        define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
-        //check for dompdf fonts in uploads
178
-        if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
-            define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
-        }
181
-        //ajax constants
182
-        define(
183
-                'EE_FRONT_AJAX',
184
-                isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
-        );
186
-        define(
187
-                'EE_ADMIN_AJAX',
188
-                isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
-        );
190
-        //just a handy constant occasionally needed for finding values representing infinity in the DB
191
-        //you're better to use this than its straight value (currently -1) in case you ever
192
-        //want to change its default value! or find when -1 means infinity
193
-        define('EE_INF_IN_DB', -1);
194
-        define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
-        define('EE_DEBUG', false);
196
-        /**
197
-         *    espresso_plugin_activation
198
-         *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
199
-         */
200
-        function espresso_plugin_activation()
201
-        {
202
-            update_option('ee_espresso_activation', true);
203
-        }
107
+		// define versions
108
+		define('EVENT_ESPRESSO_VERSION', espresso_version());
109
+		define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
+		define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
+		define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
+		//used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
+		if ( ! defined('DS')) {
115
+			define('DS', '/');
116
+		}
117
+		if ( ! defined('PS')) {
118
+			define('PS', PATH_SEPARATOR);
119
+		}
120
+		if ( ! defined('SP')) {
121
+			define('SP', ' ');
122
+		}
123
+		if ( ! defined('EENL')) {
124
+			define('EENL', "\n");
125
+		}
126
+		define('EE_SUPPORT_EMAIL', '[email protected]');
127
+		// define the plugin directory and URL
128
+		define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
+		define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
+		define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
+		// main root folder paths
132
+		define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
+		define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
+		define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
+		define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
+		define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
+		define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
+		define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
+		define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
+		// core system paths
141
+		define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
+		define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
+		define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
+		define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
+		define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
+		define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
+		define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
+		define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
+		define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
+		define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
+		define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
+		define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
+		// gateways
154
+		define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
+		define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
+		// asset URL paths
157
+		define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
+		define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
+		define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
+		define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
+		define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
+		define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
+		// define upload paths
164
+		$uploads = wp_upload_dir();
165
+		// define the uploads directory and URL
166
+		define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
+		define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
+		// define the templates directory and URL
169
+		define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
+		define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
+		// define the gateway directory and URL
172
+		define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
+		define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
+		// languages folder/path
175
+		define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
+		define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
+		//check for dompdf fonts in uploads
178
+		if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
+			define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
+		}
181
+		//ajax constants
182
+		define(
183
+				'EE_FRONT_AJAX',
184
+				isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
+		);
186
+		define(
187
+				'EE_ADMIN_AJAX',
188
+				isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
+		);
190
+		//just a handy constant occasionally needed for finding values representing infinity in the DB
191
+		//you're better to use this than its straight value (currently -1) in case you ever
192
+		//want to change its default value! or find when -1 means infinity
193
+		define('EE_INF_IN_DB', -1);
194
+		define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
+		define('EE_DEBUG', false);
196
+		/**
197
+		 *    espresso_plugin_activation
198
+		 *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
199
+		 */
200
+		function espresso_plugin_activation()
201
+		{
202
+			update_option('ee_espresso_activation', true);
203
+		}
204 204
 
205
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
206
-        /**
207
-         *    espresso_load_error_handling
208
-         *    this function loads EE's class for handling exceptions and errors
209
-         */
210
-        function espresso_load_error_handling()
211
-        {
212
-            // load debugging tools
213
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
214
-                require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
215
-                EEH_Debug_Tools::instance();
216
-            }
217
-            // load error handling
218
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
219
-                require_once(EE_CORE . 'EE_Error.core.php');
220
-            } else {
221
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
222
-            }
223
-        }
205
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
206
+		/**
207
+		 *    espresso_load_error_handling
208
+		 *    this function loads EE's class for handling exceptions and errors
209
+		 */
210
+		function espresso_load_error_handling()
211
+		{
212
+			// load debugging tools
213
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
214
+				require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
215
+				EEH_Debug_Tools::instance();
216
+			}
217
+			// load error handling
218
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
219
+				require_once(EE_CORE . 'EE_Error.core.php');
220
+			} else {
221
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
222
+			}
223
+		}
224 224
 
225
-        /**
226
-         *    espresso_load_required
227
-         *    given a class name and path, this function will load that file or throw an exception
228
-         *
229
-         * @param    string $classname
230
-         * @param    string $full_path_to_file
231
-         * @throws    EE_Error
232
-         */
233
-        function espresso_load_required($classname, $full_path_to_file)
234
-        {
235
-            static $error_handling_loaded = false;
236
-            if ( ! $error_handling_loaded) {
237
-                espresso_load_error_handling();
238
-                $error_handling_loaded = true;
239
-            }
240
-            if (is_readable($full_path_to_file)) {
241
-                require_once($full_path_to_file);
242
-            } else {
243
-                throw new EE_Error (
244
-                        sprintf(
245
-                                esc_html__(
246
-                                        'The %s class file could not be located or is not readable due to file permissions.',
247
-                                        'event_espresso'
248
-                                ),
249
-                                $classname
250
-                        )
251
-                );
252
-            }
253
-        }
225
+		/**
226
+		 *    espresso_load_required
227
+		 *    given a class name and path, this function will load that file or throw an exception
228
+		 *
229
+		 * @param    string $classname
230
+		 * @param    string $full_path_to_file
231
+		 * @throws    EE_Error
232
+		 */
233
+		function espresso_load_required($classname, $full_path_to_file)
234
+		{
235
+			static $error_handling_loaded = false;
236
+			if ( ! $error_handling_loaded) {
237
+				espresso_load_error_handling();
238
+				$error_handling_loaded = true;
239
+			}
240
+			if (is_readable($full_path_to_file)) {
241
+				require_once($full_path_to_file);
242
+			} else {
243
+				throw new EE_Error (
244
+						sprintf(
245
+								esc_html__(
246
+										'The %s class file could not be located or is not readable due to file permissions.',
247
+										'event_espresso'
248
+								),
249
+								$classname
250
+						)
251
+				);
252
+			}
253
+		}
254 254
 
255
-        espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
256
-        espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
257
-        espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
258
-        new EE_Bootstrap();
259
-    }
255
+		espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
256
+		espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
257
+		espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
258
+		new EE_Bootstrap();
259
+	}
260 260
 }
261 261
 if ( ! function_exists('espresso_deactivate_plugin')) {
262
-    /**
263
-     *    deactivate_plugin
264
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
265
-     *
266
-     * @access public
267
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
268
-     * @return    void
269
-     */
270
-    function espresso_deactivate_plugin($plugin_basename = '')
271
-    {
272
-        if ( ! function_exists('deactivate_plugins')) {
273
-            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
274
-        }
275
-        unset($_GET['activate'], $_REQUEST['activate']);
276
-        deactivate_plugins($plugin_basename);
277
-    }
262
+	/**
263
+	 *    deactivate_plugin
264
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
265
+	 *
266
+	 * @access public
267
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
268
+	 * @return    void
269
+	 */
270
+	function espresso_deactivate_plugin($plugin_basename = '')
271
+	{
272
+		if ( ! function_exists('deactivate_plugins')) {
273
+			require_once(ABSPATH . 'wp-admin/includes/plugin.php');
274
+		}
275
+		unset($_GET['activate'], $_REQUEST['activate']);
276
+		deactivate_plugins($plugin_basename);
277
+	}
278 278
 }
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.