Completed
Branch BUG-10878-event-spaces-remaini... (2a7dd2)
by
unknown
33:43 queued 22:14
created
admin/extend/messages/espresso_events_Messages_Hooks_Extend.class.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -98,7 +98,7 @@
 block discarded – undo
98 98
      *
99 99
      * @param  EE_Event $event EE event object
100 100
      * @param  array    $data  The request data from the form
101
-     * @return bool success or fail
101
+     * @return integer success or fail
102 102
      * @throws EE_Error
103 103
      */
104 104
     public function attach_evt_message_templates($event, $data)
Please login to merge, or discard this patch.
Indentation   +267 added lines, -267 removed lines patch added patch discarded remove patch
@@ -14,276 +14,276 @@
 block discarded – undo
14 14
  */
15 15
 class espresso_events_Messages_Hooks_Extend extends espresso_events_Messages_Hooks
16 16
 {
17
-    /**
18
-     * espresso_events_Messages_Hooks_Extend constructor.
19
-     *
20
-     * @param \EE_Admin_Page $admin_page
21
-     */
22
-    public function __construct(EE_Admin_Page $admin_page)
23
-    {
24
-        /**
25
-         * Add cap restriction ... metaboxes should not show if user does not have the ability to edit_custom_messages
26
-         */
27
-        if (! EE_Registry::instance()->CAP->current_user_can(
28
-            'ee_edit_messages',
29
-            'messages_events_editor_metabox'
30
-        )) {
31
-            return;
32
-        }
33
-        add_filter(
34
-            'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
35
-            array($this, 'caf_updates'),
36
-            10
37
-        );
38
-        add_action(
39
-            'AHEE__Extend_Events_Admin_Page___duplicate_event__after',
40
-            array($this, 'duplicate_custom_message_settings'),
41
-            10,
42
-            2
43
-        );
44
-        parent::__construct($admin_page);
45
-    }
46
-
47
-
48
-    /**
49
-     * extending the properties set in espresso_events_Messages_Hooks
50
-     *
51
-     * @access protected
52
-     * @return void
53
-     */
54
-    protected function _extend_properties()
55
-    {
56
-        define('EE_MSGS_EXTEND_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'messages/assets/');
57
-        $this->_ajax_func = array(
58
-            'ee_msgs_create_new_custom' => 'create_new_custom',
59
-        );
60
-        $this->_metaboxes = array(
61
-            0 => array(
62
-                'page_route' => array('edit', 'create_new'),
63
-                'func'       => 'messages_metabox',
64
-                'label'      => esc_html__('Notifications', 'event_espresso'),
65
-                'priority'   => 'high',
66
-            ),
67
-        );
68
-
69
-        //see explanation for layout in EE_Admin_Hooks
70
-        $this->_scripts_styles = array(
71
-            'registers' => array(
72
-                'events_msg_admin'     => array(
73
-                    'url'     => EE_MSGS_EXTEND_ASSETS_URL . 'events_messages_admin.js',
74
-                    'depends' => array('ee-dialog', 'ee-parse-uri', 'ee-serialize-full-array'),
75
-                ),
76
-                'events_msg_admin_css' => array(
77
-                    'url'  => EE_MSGS_EXTEND_ASSETS_URL . 'ee_msg_events_admin.css',
78
-                    'type' => 'css',
79
-                ),
80
-            ),
81
-            'enqueues'  => array(
82
-                'events_msg_admin'     => array('edit', 'create_new'),
83
-                'events_msg_admin_css' => array('edit', 'create_new'),
84
-            ),
85
-        );
86
-    }
87
-
88
-
89
-    public function caf_updates($update_callbacks)
90
-    {
91
-        $update_callbacks[] = array($this, 'attach_evt_message_templates');
92
-        return $update_callbacks;
93
-    }
94
-
95
-
96
-    /**
97
-     * Handles attaching Message Templates to the Event on save.
98
-     *
99
-     * @param  EE_Event $event EE event object
100
-     * @param  array    $data  The request data from the form
101
-     * @return bool success or fail
102
-     * @throws EE_Error
103
-     */
104
-    public function attach_evt_message_templates($event, $data)
105
-    {
106
-        //first we remove all existing relations on the Event for message types.
107
-        $event->_remove_relations('Message_Template_Group');
108
-        //now let's just loop through the selected templates and add relations!
109
-        if (isset($data['event_message_templates_relation'])) {
110
-            foreach ($data['event_message_templates_relation'] as $grp_ID) {
111
-                $event->_add_relation_to($grp_ID, 'Message_Template_Group');
112
-            }
113
-        }
114
-        //now save
115
-        return $event->save();
116
-    }
117
-
118
-
119
-    /**
120
-     * @param $event
121
-     * @param $callback_args
122
-     * @return string
123
-     * @throws \EE_Error
124
-     */
125
-    public function messages_metabox($event, $callback_args)
126
-    {
127
-        //let's get the active messengers (b/c messenger objects have the active message templates)
128
-        //convert 'evt_id' to 'EVT_ID'
129
-        $this->_req_data['EVT_ID'] = isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null;
130
-        $this->_req_data['EVT_ID'] = isset($this->_req_data['post']) && empty($this->_req_data['EVT_ID'])
131
-            ? $this->_req_data['post']
132
-            : $this->_req_data['EVT_ID'];
133
-
134
-        $this->_req_data['EVT_ID'] = empty($this->_req_data['EVT_ID']) && isset($this->_req_data['evt_id'])
135
-            ? $this->_req_data['evt_id']
136
-            : $this->_req_data['EVT_ID'];
137
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
138
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
139
-        $active_messengers        = $message_resource_manager->active_messengers();
140
-        $tabs                     = array();
141
-
142
-        //empty messengers?
143
-        //Note message types will always have at least one available because every messenger has a default message type
144
-        // associated with it (payment) if no other message types are selected.
145
-        if (empty($active_messengers)) {
146
-            $msg_activate_url = EE_Admin_Page::add_query_args_and_nonce(
147
-                array('action' => 'settings'),
148
-                EE_MSG_ADMIN_URL
149
-            );
150
-            $error_msg        = sprintf(
151
-                esc_html__(
152
-                    'There are no active messengers. So no notifications will go out for %1$sany%2$s events.  You will want to %3$sActivate a Messenger%4$s.',
153
-                    'event_espresso'
154
-                ),
155
-                '<strong>',
156
-                '</strong>',
157
-                '<a href="' . $msg_activate_url . '">',
158
-                '</a>'
159
-            );
160
-            $error_content    = '<div class="error"><p>' . $error_msg . '</p></div>';
161
-            $internal_content = '<div id="messages-error"><p>' . $error_msg . '</p></div>';
162
-
163
-            echo $error_content;
164
-            echo $internal_content;
165
-            return '';
166
-        }
167
-
168
-        $event_id = isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null;
169
-        //get content for active messengers
170
-        foreach ($active_messengers as $name => $messenger) {
171
-            //first check if there are any active message types for this messenger.
172
-            $active_mts = $message_resource_manager->get_active_message_types_for_messenger($name);
173
-            if (empty($active_mts)) {
174
-                continue;
175
-            }
176
-
177
-            $tab_content = $messenger->get_messenger_admin_page_content(
178
-                'events',
179
-                'edit',
180
-                array('event' => $event_id)
181
-            );
182
-
183
-            if (! empty($tab_content)) {
184
-                $tabs[$name] = $tab_content;
185
-            }
186
-        }
187
-
188
-
189
-        //we want this to be tabbed content so let's use the EEH_Tabbed_Content::display helper.
190
-        $tabbed_content = EEH_Tabbed_Content::display($tabs);
191
-        if ($tabbed_content instanceof WP_Error) {
192
-            $tabbed_content = $tabbed_content->get_error_message();
193
-        }
194
-
195
-        $notices = '
17
+	/**
18
+	 * espresso_events_Messages_Hooks_Extend constructor.
19
+	 *
20
+	 * @param \EE_Admin_Page $admin_page
21
+	 */
22
+	public function __construct(EE_Admin_Page $admin_page)
23
+	{
24
+		/**
25
+		 * Add cap restriction ... metaboxes should not show if user does not have the ability to edit_custom_messages
26
+		 */
27
+		if (! EE_Registry::instance()->CAP->current_user_can(
28
+			'ee_edit_messages',
29
+			'messages_events_editor_metabox'
30
+		)) {
31
+			return;
32
+		}
33
+		add_filter(
34
+			'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
35
+			array($this, 'caf_updates'),
36
+			10
37
+		);
38
+		add_action(
39
+			'AHEE__Extend_Events_Admin_Page___duplicate_event__after',
40
+			array($this, 'duplicate_custom_message_settings'),
41
+			10,
42
+			2
43
+		);
44
+		parent::__construct($admin_page);
45
+	}
46
+
47
+
48
+	/**
49
+	 * extending the properties set in espresso_events_Messages_Hooks
50
+	 *
51
+	 * @access protected
52
+	 * @return void
53
+	 */
54
+	protected function _extend_properties()
55
+	{
56
+		define('EE_MSGS_EXTEND_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'messages/assets/');
57
+		$this->_ajax_func = array(
58
+			'ee_msgs_create_new_custom' => 'create_new_custom',
59
+		);
60
+		$this->_metaboxes = array(
61
+			0 => array(
62
+				'page_route' => array('edit', 'create_new'),
63
+				'func'       => 'messages_metabox',
64
+				'label'      => esc_html__('Notifications', 'event_espresso'),
65
+				'priority'   => 'high',
66
+			),
67
+		);
68
+
69
+		//see explanation for layout in EE_Admin_Hooks
70
+		$this->_scripts_styles = array(
71
+			'registers' => array(
72
+				'events_msg_admin'     => array(
73
+					'url'     => EE_MSGS_EXTEND_ASSETS_URL . 'events_messages_admin.js',
74
+					'depends' => array('ee-dialog', 'ee-parse-uri', 'ee-serialize-full-array'),
75
+				),
76
+				'events_msg_admin_css' => array(
77
+					'url'  => EE_MSGS_EXTEND_ASSETS_URL . 'ee_msg_events_admin.css',
78
+					'type' => 'css',
79
+				),
80
+			),
81
+			'enqueues'  => array(
82
+				'events_msg_admin'     => array('edit', 'create_new'),
83
+				'events_msg_admin_css' => array('edit', 'create_new'),
84
+			),
85
+		);
86
+	}
87
+
88
+
89
+	public function caf_updates($update_callbacks)
90
+	{
91
+		$update_callbacks[] = array($this, 'attach_evt_message_templates');
92
+		return $update_callbacks;
93
+	}
94
+
95
+
96
+	/**
97
+	 * Handles attaching Message Templates to the Event on save.
98
+	 *
99
+	 * @param  EE_Event $event EE event object
100
+	 * @param  array    $data  The request data from the form
101
+	 * @return bool success or fail
102
+	 * @throws EE_Error
103
+	 */
104
+	public function attach_evt_message_templates($event, $data)
105
+	{
106
+		//first we remove all existing relations on the Event for message types.
107
+		$event->_remove_relations('Message_Template_Group');
108
+		//now let's just loop through the selected templates and add relations!
109
+		if (isset($data['event_message_templates_relation'])) {
110
+			foreach ($data['event_message_templates_relation'] as $grp_ID) {
111
+				$event->_add_relation_to($grp_ID, 'Message_Template_Group');
112
+			}
113
+		}
114
+		//now save
115
+		return $event->save();
116
+	}
117
+
118
+
119
+	/**
120
+	 * @param $event
121
+	 * @param $callback_args
122
+	 * @return string
123
+	 * @throws \EE_Error
124
+	 */
125
+	public function messages_metabox($event, $callback_args)
126
+	{
127
+		//let's get the active messengers (b/c messenger objects have the active message templates)
128
+		//convert 'evt_id' to 'EVT_ID'
129
+		$this->_req_data['EVT_ID'] = isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null;
130
+		$this->_req_data['EVT_ID'] = isset($this->_req_data['post']) && empty($this->_req_data['EVT_ID'])
131
+			? $this->_req_data['post']
132
+			: $this->_req_data['EVT_ID'];
133
+
134
+		$this->_req_data['EVT_ID'] = empty($this->_req_data['EVT_ID']) && isset($this->_req_data['evt_id'])
135
+			? $this->_req_data['evt_id']
136
+			: $this->_req_data['EVT_ID'];
137
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
138
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
139
+		$active_messengers        = $message_resource_manager->active_messengers();
140
+		$tabs                     = array();
141
+
142
+		//empty messengers?
143
+		//Note message types will always have at least one available because every messenger has a default message type
144
+		// associated with it (payment) if no other message types are selected.
145
+		if (empty($active_messengers)) {
146
+			$msg_activate_url = EE_Admin_Page::add_query_args_and_nonce(
147
+				array('action' => 'settings'),
148
+				EE_MSG_ADMIN_URL
149
+			);
150
+			$error_msg        = sprintf(
151
+				esc_html__(
152
+					'There are no active messengers. So no notifications will go out for %1$sany%2$s events.  You will want to %3$sActivate a Messenger%4$s.',
153
+					'event_espresso'
154
+				),
155
+				'<strong>',
156
+				'</strong>',
157
+				'<a href="' . $msg_activate_url . '">',
158
+				'</a>'
159
+			);
160
+			$error_content    = '<div class="error"><p>' . $error_msg . '</p></div>';
161
+			$internal_content = '<div id="messages-error"><p>' . $error_msg . '</p></div>';
162
+
163
+			echo $error_content;
164
+			echo $internal_content;
165
+			return '';
166
+		}
167
+
168
+		$event_id = isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null;
169
+		//get content for active messengers
170
+		foreach ($active_messengers as $name => $messenger) {
171
+			//first check if there are any active message types for this messenger.
172
+			$active_mts = $message_resource_manager->get_active_message_types_for_messenger($name);
173
+			if (empty($active_mts)) {
174
+				continue;
175
+			}
176
+
177
+			$tab_content = $messenger->get_messenger_admin_page_content(
178
+				'events',
179
+				'edit',
180
+				array('event' => $event_id)
181
+			);
182
+
183
+			if (! empty($tab_content)) {
184
+				$tabs[$name] = $tab_content;
185
+			}
186
+		}
187
+
188
+
189
+		//we want this to be tabbed content so let's use the EEH_Tabbed_Content::display helper.
190
+		$tabbed_content = EEH_Tabbed_Content::display($tabs);
191
+		if ($tabbed_content instanceof WP_Error) {
192
+			$tabbed_content = $tabbed_content->get_error_message();
193
+		}
194
+
195
+		$notices = '
196 196
 	<div id="espresso-ajax-loading" class="ajax-loader-grey">
197 197
 		<span class="ee-spinner ee-spin"></span><span class="hidden">'
198
-        . esc_html__('loading...', 'event_espresso')
199
-        . '</span>
198
+		. esc_html__('loading...', 'event_espresso')
199
+		. '</span>
200 200
 	</div>
201 201
 	<div class="ee-notices"></div>';
202 202
 
203
-        if (defined('DOING_AJAX')) {
204
-            return $tabbed_content;
205
-        }
206
-
207
-        do_action('AHEE__espresso_events_Messages_Hooks_Extend__messages_metabox__before_content');
208
-        echo $notices . '<div class="messages-tabs-content">' . $tabbed_content . '</div>';
209
-        do_action('AHEE__espresso_events_Messages_Hooks_Extend__messages_metabox__after_content');
210
-    }
211
-
212
-
213
-    /**
214
-     * Ajax callback for ee_msgs_create_new_custom ajax request.
215
-     * Takes incoming GRP_ID and name and description values from ajax request
216
-     * to create a new custom template based off of the incoming GRP_ID.
217
-     *
218
-     * @access public
219
-     * @return string either an html string will be returned or a success message
220
-     * @throws EE_Error
221
-     */
222
-    public function create_new_custom()
223
-    {
224
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_edit_messages', 'create_new_custom_ajax')) {
225
-            wp_die(__('You don\'t have privileges to do this action', 'event_espresso'));
226
-        }
227
-
228
-        //let's clean up the _POST global a bit for downstream usage of name and description.
229
-        $_POST['templateName']        = ! empty($this->_req_data['custom_template_args']['MTP_name'])
230
-            ? $this->_req_data['custom_template_args']['MTP_name']
231
-            : '';
232
-        $_POST['templateDescription'] = ! empty($this->_req_data['custom_template_args']['MTP_description'])
233
-            ? $this->_req_data['custom_template_args']['MTP_description']
234
-            : '';
235
-
236
-
237
-        // set EE_Admin_Page object (see method details in EE_Admin_Hooks parent
238
-        $this->_set_page_object();
239
-
240
-        // is this a template switch if so EE_Admin_Page child needs this object
241
-        $this->_page_object->set_hook_object($this);
242
-
243
-        $this->_page_object->add_message_template(
244
-            $this->_req_data['messageType'],
245
-            $this->_req_data['messenger'],
246
-            $this->_req_data['group_ID']
247
-        );
248
-    }
249
-
250
-
251
-    public function create_new_admin_footer()
252
-    {
253
-        $this->edit_admin_footer();
254
-    }
255
-
256
-
257
-    /**
258
-     * This is the dynamic method for this class
259
-     * that will end up hooking into the 'admin_footer' hook on the 'edit_event' route in the events page.
260
-     *
261
-     * @return string
262
-     * @throws DomainException
263
-     */
264
-    public function edit_admin_footer()
265
-    {
266
-        EEH_Template::display_template(
267
-            EE_CORE_CAF_ADMIN_EXTEND . 'messages/templates/create_custom_template_form.template.php'
268
-        );
269
-    }
270
-
271
-
272
-    /**
273
-     * Callback for AHEE__Extend_Events_Admin_Page___duplicate_event__after hook used to ensure new events duplicate
274
-     * the assigned custom message templates.
275
-     *
276
-     * @param EE_Event $new_event
277
-     * @param EE_Event $original_event
278
-     * @throws EE_Error
279
-     */
280
-    public function duplicate_custom_message_settings(EE_Event $new_event, EE_Event $original_event)
281
-    {
282
-        $message_template_groups = $original_event->get_many_related('Message_Template_Group');
283
-        foreach ($message_template_groups as $message_template_group) {
284
-            $new_event->_add_relation_to($message_template_group, 'Message_Template_Group');
285
-        }
286
-        //save new event
287
-        $new_event->save();
288
-    }
203
+		if (defined('DOING_AJAX')) {
204
+			return $tabbed_content;
205
+		}
206
+
207
+		do_action('AHEE__espresso_events_Messages_Hooks_Extend__messages_metabox__before_content');
208
+		echo $notices . '<div class="messages-tabs-content">' . $tabbed_content . '</div>';
209
+		do_action('AHEE__espresso_events_Messages_Hooks_Extend__messages_metabox__after_content');
210
+	}
211
+
212
+
213
+	/**
214
+	 * Ajax callback for ee_msgs_create_new_custom ajax request.
215
+	 * Takes incoming GRP_ID and name and description values from ajax request
216
+	 * to create a new custom template based off of the incoming GRP_ID.
217
+	 *
218
+	 * @access public
219
+	 * @return string either an html string will be returned or a success message
220
+	 * @throws EE_Error
221
+	 */
222
+	public function create_new_custom()
223
+	{
224
+		if (! EE_Registry::instance()->CAP->current_user_can('ee_edit_messages', 'create_new_custom_ajax')) {
225
+			wp_die(__('You don\'t have privileges to do this action', 'event_espresso'));
226
+		}
227
+
228
+		//let's clean up the _POST global a bit for downstream usage of name and description.
229
+		$_POST['templateName']        = ! empty($this->_req_data['custom_template_args']['MTP_name'])
230
+			? $this->_req_data['custom_template_args']['MTP_name']
231
+			: '';
232
+		$_POST['templateDescription'] = ! empty($this->_req_data['custom_template_args']['MTP_description'])
233
+			? $this->_req_data['custom_template_args']['MTP_description']
234
+			: '';
235
+
236
+
237
+		// set EE_Admin_Page object (see method details in EE_Admin_Hooks parent
238
+		$this->_set_page_object();
239
+
240
+		// is this a template switch if so EE_Admin_Page child needs this object
241
+		$this->_page_object->set_hook_object($this);
242
+
243
+		$this->_page_object->add_message_template(
244
+			$this->_req_data['messageType'],
245
+			$this->_req_data['messenger'],
246
+			$this->_req_data['group_ID']
247
+		);
248
+	}
249
+
250
+
251
+	public function create_new_admin_footer()
252
+	{
253
+		$this->edit_admin_footer();
254
+	}
255
+
256
+
257
+	/**
258
+	 * This is the dynamic method for this class
259
+	 * that will end up hooking into the 'admin_footer' hook on the 'edit_event' route in the events page.
260
+	 *
261
+	 * @return string
262
+	 * @throws DomainException
263
+	 */
264
+	public function edit_admin_footer()
265
+	{
266
+		EEH_Template::display_template(
267
+			EE_CORE_CAF_ADMIN_EXTEND . 'messages/templates/create_custom_template_form.template.php'
268
+		);
269
+	}
270
+
271
+
272
+	/**
273
+	 * Callback for AHEE__Extend_Events_Admin_Page___duplicate_event__after hook used to ensure new events duplicate
274
+	 * the assigned custom message templates.
275
+	 *
276
+	 * @param EE_Event $new_event
277
+	 * @param EE_Event $original_event
278
+	 * @throws EE_Error
279
+	 */
280
+	public function duplicate_custom_message_settings(EE_Event $new_event, EE_Event $original_event)
281
+	{
282
+		$message_template_groups = $original_event->get_many_related('Message_Template_Group');
283
+		foreach ($message_template_groups as $message_template_group) {
284
+			$new_event->_add_relation_to($message_template_group, 'Message_Template_Group');
285
+		}
286
+		//save new event
287
+		$new_event->save();
288
+	}
289 289
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
         /**
25 25
          * Add cap restriction ... metaboxes should not show if user does not have the ability to edit_custom_messages
26 26
          */
27
-        if (! EE_Registry::instance()->CAP->current_user_can(
27
+        if ( ! EE_Registry::instance()->CAP->current_user_can(
28 28
             'ee_edit_messages',
29 29
             'messages_events_editor_metabox'
30 30
         )) {
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
      */
54 54
     protected function _extend_properties()
55 55
     {
56
-        define('EE_MSGS_EXTEND_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'messages/assets/');
56
+        define('EE_MSGS_EXTEND_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL.'messages/assets/');
57 57
         $this->_ajax_func = array(
58 58
             'ee_msgs_create_new_custom' => 'create_new_custom',
59 59
         );
@@ -70,11 +70,11 @@  discard block
 block discarded – undo
70 70
         $this->_scripts_styles = array(
71 71
             'registers' => array(
72 72
                 'events_msg_admin'     => array(
73
-                    'url'     => EE_MSGS_EXTEND_ASSETS_URL . 'events_messages_admin.js',
73
+                    'url'     => EE_MSGS_EXTEND_ASSETS_URL.'events_messages_admin.js',
74 74
                     'depends' => array('ee-dialog', 'ee-parse-uri', 'ee-serialize-full-array'),
75 75
                 ),
76 76
                 'events_msg_admin_css' => array(
77
-                    'url'  => EE_MSGS_EXTEND_ASSETS_URL . 'ee_msg_events_admin.css',
77
+                    'url'  => EE_MSGS_EXTEND_ASSETS_URL.'ee_msg_events_admin.css',
78 78
                     'type' => 'css',
79 79
                 ),
80 80
             ),
@@ -147,18 +147,18 @@  discard block
 block discarded – undo
147 147
                 array('action' => 'settings'),
148 148
                 EE_MSG_ADMIN_URL
149 149
             );
150
-            $error_msg        = sprintf(
150
+            $error_msg = sprintf(
151 151
                 esc_html__(
152 152
                     'There are no active messengers. So no notifications will go out for %1$sany%2$s events.  You will want to %3$sActivate a Messenger%4$s.',
153 153
                     'event_espresso'
154 154
                 ),
155 155
                 '<strong>',
156 156
                 '</strong>',
157
-                '<a href="' . $msg_activate_url . '">',
157
+                '<a href="'.$msg_activate_url.'">',
158 158
                 '</a>'
159 159
             );
160
-            $error_content    = '<div class="error"><p>' . $error_msg . '</p></div>';
161
-            $internal_content = '<div id="messages-error"><p>' . $error_msg . '</p></div>';
160
+            $error_content    = '<div class="error"><p>'.$error_msg.'</p></div>';
161
+            $internal_content = '<div id="messages-error"><p>'.$error_msg.'</p></div>';
162 162
 
163 163
             echo $error_content;
164 164
             echo $internal_content;
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
                 array('event' => $event_id)
181 181
             );
182 182
 
183
-            if (! empty($tab_content)) {
183
+            if ( ! empty($tab_content)) {
184 184
                 $tabs[$name] = $tab_content;
185 185
             }
186 186
         }
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
         }
206 206
 
207 207
         do_action('AHEE__espresso_events_Messages_Hooks_Extend__messages_metabox__before_content');
208
-        echo $notices . '<div class="messages-tabs-content">' . $tabbed_content . '</div>';
208
+        echo $notices.'<div class="messages-tabs-content">'.$tabbed_content.'</div>';
209 209
         do_action('AHEE__espresso_events_Messages_Hooks_Extend__messages_metabox__after_content');
210 210
     }
211 211
 
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
      */
222 222
     public function create_new_custom()
223 223
     {
224
-        if (! EE_Registry::instance()->CAP->current_user_can('ee_edit_messages', 'create_new_custom_ajax')) {
224
+        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_edit_messages', 'create_new_custom_ajax')) {
225 225
             wp_die(__('You don\'t have privileges to do this action', 'event_espresso'));
226 226
         }
227 227
 
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
     public function edit_admin_footer()
265 265
     {
266 266
         EEH_Template::display_template(
267
-            EE_CORE_CAF_ADMIN_EXTEND . 'messages/templates/create_custom_template_form.template.php'
267
+            EE_CORE_CAF_ADMIN_EXTEND.'messages/templates/create_custom_template_form.template.php'
268 268
         );
269 269
     }
270 270
 
Please login to merge, or discard this patch.
core/libraries/rest_api/Model_Data_Translator.php 2 patches
Indentation   +521 added lines, -521 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 namespace EventEspresso\core\libraries\rest_api;
3 3
 
4 4
 if (! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 
8 8
 
@@ -26,525 +26,525 @@  discard block
 block discarded – undo
26 26
 class Model_Data_Translator
27 27
 {
28 28
 
29
-    /**
30
-     * We used to use -1 for infinity in the rest api, but that's ambiguous for
31
-     * fields that COULD contain -1; so we use null
32
-     */
33
-    const ee_inf_in_rest = null;
34
-
35
-
36
-
37
-    /**
38
-     * Prepares a possible array of input values from JSON for use by the models
39
-     *
40
-     * @param \EE_Model_Field_Base $field_obj
41
-     * @param mixed                $original_value_maybe_array
42
-     * @param string               $requested_version
43
-     * @param string               $timezone_string treat values as being in this timezone
44
-     * @return mixed
45
-     * @throws \DomainException
46
-     */
47
-    public static function prepare_field_values_from_json(
48
-        $field_obj,
49
-        $original_value_maybe_array,
50
-        $requested_version,
51
-        $timezone_string = 'UTC'
52
-    ) {
53
-        if (is_array($original_value_maybe_array)) {
54
-            $new_value_maybe_array = array();
55
-            foreach ($original_value_maybe_array as $array_key => $array_item) {
56
-                $new_value_maybe_array[$array_key] = Model_Data_Translator::prepare_field_value_from_json(
57
-                    $field_obj,
58
-                    $array_item,
59
-                    $requested_version,
60
-                    $timezone_string
61
-                );
62
-            }
63
-        } else {
64
-            $new_value_maybe_array = Model_Data_Translator::prepare_field_value_from_json(
65
-                $field_obj,
66
-                $original_value_maybe_array,
67
-                $requested_version,
68
-                $timezone_string
69
-            );
70
-        }
71
-        return $new_value_maybe_array;
72
-    }
73
-
74
-
75
-
76
-    /**
77
-     * Prepares an array of field values FOR use in JSON/REST API
78
-     *
79
-     * @param \EE_Model_Field_Base $field_obj
80
-     * @param mixed                $original_value_maybe_array
81
-     * @param string               $request_version (eg 4.8.36)
82
-     * @return array
83
-     */
84
-    public static function prepare_field_values_for_json($field_obj, $original_value_maybe_array, $request_version)
85
-    {
86
-        if (is_array($original_value_maybe_array)) {
87
-            $new_value_maybe_array = array();
88
-            foreach ($original_value_maybe_array as $array_key => $array_item) {
89
-                $new_value_maybe_array[$array_key] = Model_Data_Translator::prepare_field_value_for_json(
90
-                    $field_obj,
91
-                    $array_item,
92
-                    $request_version
93
-                );
94
-            }
95
-        } else {
96
-            $new_value_maybe_array = Model_Data_Translator::prepare_field_value_for_json(
97
-                $field_obj,
98
-                $original_value_maybe_array,
99
-                $request_version
100
-            );
101
-        }
102
-        return $new_value_maybe_array;
103
-    }
104
-
105
-
106
-
107
-    /**
108
-     * Prepares incoming data from the json or $_REQUEST parameters for the models'
109
-     * "$query_params".
110
-     *
111
-     * @param \EE_Model_Field_Base $field_obj
112
-     * @param mixed                $original_value
113
-     * @param string               $requested_version
114
-     * @param string               $timezone_string treat values as being in this timezone
115
-     * @return mixed
116
-     * @throws \DomainException
117
-     */
118
-    public static function prepare_field_value_from_json(
119
-        $field_obj,
120
-        $original_value,
121
-        $requested_version,
122
-        $timezone_string = 'UTC' // UTC
123
-    )
124
-    {
125
-        $timezone_string = $timezone_string !== '' ? $timezone_string : get_option('timezone_string', '');
126
-        $new_value = null;
127
-        if ($field_obj instanceof \EE_Infinite_Integer_Field
128
-            && in_array($original_value, array(null, ''), true)
129
-        ) {
130
-            $new_value = EE_INF;
131
-        } elseif ($field_obj instanceof \EE_Datetime_Field) {
132
-            list($offset_sign, $offset_secs) = Model_Data_Translator::parse_timezone_offset(
133
-                $field_obj->get_timezone_offset(
134
-                    new \DateTimeZone($timezone_string)
135
-                )
136
-            );
137
-            $offset_string =
138
-                str_pad(
139
-                    floor($offset_secs / HOUR_IN_SECONDS),
140
-                    2,
141
-                    '0',
142
-                    STR_PAD_LEFT
143
-                )
144
-                . ':'
145
-                . str_pad(
146
-                    ($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
147
-                    2,
148
-                    '0',
149
-                    STR_PAD_LEFT
150
-                );
151
-            $new_value = rest_parse_date($original_value . $offset_sign . $offset_string);
152
-        } else {
153
-            $new_value = $original_value;
154
-        }
155
-        return $new_value;
156
-    }
157
-
158
-
159
-
160
-    /**
161
-     * determines what's going on with them timezone strings
162
-     *
163
-     * @param int $timezone_offset
164
-     * @return array
165
-     */
166
-    private static function parse_timezone_offset($timezone_offset)
167
-    {
168
-        $first_char = substr((string)$timezone_offset, 0, 1);
169
-        if ($first_char === '+' || $first_char === '-') {
170
-            $offset_sign = $first_char;
171
-            $offset_secs = substr((string)$timezone_offset, 1);
172
-        } else {
173
-            $offset_sign = '+';
174
-            $offset_secs = $timezone_offset;
175
-        }
176
-        return array($offset_sign, $offset_secs);
177
-    }
178
-
179
-
180
-
181
-    /**
182
-     * Prepares a field's value for display in the API.
183
-     * The $original_value should be in the model object's domain of values, see the explanation at the top of EEM_Base.
184
-     * However, for backward compatibility, we also attempt to handle $original_values from the
185
-     * model client-code domain, and from the database domain.
186
-     * E.g., when working with EE_Datetime_Fields, $original_value should be a DateTime or DbSafeDateTime
187
-     * (model object domain). However, for backward compatibility, we also accept a unix timestamp
188
-     * (old model object domain), MySQL datetime string (database domain) or string formatted according to the
189
-     * WP Datetime format (model client-code domain)
190
-     *
191
-     * @param \EE_Model_Field_Base $field_obj
192
-     * @param mixed                $original_value
193
-     * @param string               $requested_version
194
-     * @return mixed
195
-     */
196
-    public static function prepare_field_value_for_json($field_obj, $original_value, $requested_version)
197
-    {
198
-        if ($original_value === EE_INF) {
199
-            $new_value = Model_Data_Translator::ee_inf_in_rest;
200
-        } elseif ($field_obj instanceof \EE_Datetime_Field) {
201
-            if (is_string($original_value)) {
202
-                //did they submit a string of a unix timestamp?
203
-                if (is_numeric($original_value)) {
204
-                    $datetime_obj = new \DateTime();
205
-                    $datetime_obj->setTimestamp((int)$original_value);
206
-                } else {
207
-                    //first, check if its a MySQL timestamp in GMT
208
-                    $datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
209
-                }
210
-                if (! $datetime_obj instanceof \DateTime) {
211
-                    //so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
212
-                    $datetime_obj = $field_obj->prepare_for_set($original_value);
213
-                }
214
-                $original_value = $datetime_obj;
215
-            }
216
-            if ($original_value instanceof \DateTime) {
217
-                $new_value = $original_value->format('Y-m-d H:i:s');
218
-            } elseif (is_int($original_value)) {
219
-                $new_value = date('Y-m-d H:i:s', $original_value);
220
-            } elseif($original_value === null || $original_value === '') {
221
-                $new_value = null;
222
-            } else {
223
-                //so it's not a datetime object, unix timestamp (as string or int),
224
-                //MySQL timestamp, or even a string in the field object's format. So no idea what it is
225
-                throw new \EE_Error(
226
-                    sprintf(
227
-                        esc_html__(
228
-                            // @codingStandardsIgnoreStart
229
-                            'The value "%1$s" for the field "%2$s" on model "%3$s" could not be understood. It should be a PHP DateTime, unix timestamp, MySQL date, or string in the format "%4$s".',
230
-                            // @codingStandardsIgnoreEnd
231
-                            'event_espressso'
232
-                        ),
233
-                        $original_value,
234
-                        $field_obj->get_name(),
235
-                        $field_obj->get_model_name(),
236
-                        $field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
237
-                    )
238
-                );
239
-            }
240
-            $new_value = mysql_to_rfc3339($new_value);
241
-        } else {
242
-            $new_value = $original_value;
243
-        }
244
-        return apply_filters(
245
-            'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
246
-            $new_value,
247
-            $field_obj,
248
-            $original_value,
249
-            $requested_version
250
-        );
251
-    }
252
-
253
-
254
-
255
-    /**
256
-     * Prepares condition-query-parameters (like what's in where and having) from
257
-     * the format expected in the API to use in the models
258
-     *
259
-     * @param array     $inputted_query_params_of_this_type
260
-     * @param \EEM_Base $model
261
-     * @param string    $requested_version
262
-     * @return array
263
-     * @throws \DomainException
264
-     * @throws \EE_Error
265
-     */
266
-    public static function prepare_conditions_query_params_for_models(
267
-        $inputted_query_params_of_this_type,
268
-        \EEM_Base $model,
269
-        $requested_version
270
-    ) {
271
-        $query_param_for_models = array();
272
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
273
-            $query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($query_param_key);
274
-            $field = Model_Data_Translator::deduce_field_from_query_param(
275
-                $query_param_sans_stars,
276
-                $model
277
-            );
278
-            //double-check is it a *_gmt field?
279
-            if (! $field instanceof \EE_Model_Field_Base
280
-                && Model_Data_Translator::is_gmt_date_field_name($query_param_sans_stars)
281
-            ) {
282
-                //yep, take off '_gmt', and find the field
283
-                $query_param_key = Model_Data_Translator::remove_gmt_from_field_name($query_param_sans_stars);
284
-                $field = Model_Data_Translator::deduce_field_from_query_param(
285
-                    $query_param_key,
286
-                    $model
287
-                );
288
-                $timezone = 'UTC';
289
-            } else {
290
-                //so it's not a GMT field. Set the timezone on the model to the default
291
-                $timezone = \EEH_DTT_Helper::get_valid_timezone_string();
292
-            }
293
-            if ($field instanceof \EE_Model_Field_Base) {
294
-                //did they specify an operator?
295
-                if (is_array($query_param_value)) {
296
-                    $op = $query_param_value[0];
297
-                    $translated_value = array($op);
298
-                    if (isset($query_param_value[1])) {
299
-                        $value = $query_param_value[1];
300
-                        $translated_value[1] = Model_Data_Translator::prepare_field_values_from_json($field, $value,
301
-                            $requested_version, $timezone);
302
-                    }
303
-                } else {
304
-                    $translated_value = Model_Data_Translator::prepare_field_value_from_json($field, $query_param_value,
305
-                        $requested_version, $timezone);
306
-                }
307
-                $query_param_for_models[$query_param_key] = $translated_value;
308
-            } else {
309
-                //so it's not for a field, assume it's a logic query param key
310
-                $query_param_for_models[$query_param_key] = Model_Data_Translator::prepare_conditions_query_params_for_models($query_param_value,
311
-                    $model, $requested_version);
312
-            }
313
-        }
314
-        return $query_param_for_models;
315
-    }
316
-
317
-
318
-
319
-    /**
320
-     * Mostly checks if the last 4 characters are "_gmt", indicating its a
321
-     * gmt date field name
322
-     *
323
-     * @param string $field_name
324
-     * @return boolean
325
-     */
326
-    public static function is_gmt_date_field_name($field_name)
327
-    {
328
-        return substr(
329
-                   Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name),
330
-                   -4,
331
-                   4
332
-               ) === '_gmt';
333
-    }
334
-
335
-
336
-
337
-    /**
338
-     * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
339
-     *
340
-     * @param string $field_name
341
-     * @return string
342
-     */
343
-    public static function remove_gmt_from_field_name($field_name)
344
-    {
345
-        if (! Model_Data_Translator::is_gmt_date_field_name($field_name)) {
346
-            return $field_name;
347
-        }
348
-        $query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name);
349
-        $query_param_sans_gmt_and_sans_stars = substr(
350
-            $query_param_sans_stars,
351
-            0,
352
-            strrpos(
353
-                $field_name,
354
-                '_gmt'
355
-            )
356
-        );
357
-        return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
358
-    }
359
-
360
-
361
-
362
-    /**
363
-     * Takes a field name from the REST API and prepares it for the model querying
364
-     *
365
-     * @param string $field_name
366
-     * @return string
367
-     */
368
-    public static function prepare_field_name_from_json($field_name)
369
-    {
370
-        if (Model_Data_Translator::is_gmt_date_field_name($field_name)) {
371
-            return Model_Data_Translator::remove_gmt_from_field_name($field_name);
372
-        }
373
-        return $field_name;
374
-    }
375
-
376
-
377
-
378
-    /**
379
-     * Takes array of field names from REST API and prepares for models
380
-     *
381
-     * @param array $field_names
382
-     * @return array of field names (possibly include model prefixes)
383
-     */
384
-    public static function prepare_field_names_from_json(array $field_names)
385
-    {
386
-        $new_array = array();
387
-        foreach ($field_names as $key => $field_name) {
388
-            $new_array[$key] = Model_Data_Translator::prepare_field_name_from_json($field_name);
389
-        }
390
-        return $new_array;
391
-    }
392
-
393
-
394
-
395
-    /**
396
-     * Takes array where array keys are field names (possibly with model path prefixes)
397
-     * from the REST API and prepares them for model querying
398
-     *
399
-     * @param array $field_names_as_keys
400
-     * @return array
401
-     */
402
-    public static function prepare_field_names_in_array_keys_from_json(array $field_names_as_keys)
403
-    {
404
-        $new_array = array();
405
-        foreach ($field_names_as_keys as $field_name => $value) {
406
-            $new_array[Model_Data_Translator::prepare_field_name_from_json($field_name)] = $value;
407
-        }
408
-        return $new_array;
409
-    }
410
-
411
-
412
-
413
-    /**
414
-     * Prepares an array of model query params for use in the REST API
415
-     *
416
-     * @param array     $model_query_params
417
-     * @param \EEM_Base $model
418
-     * @param string    $requested_version eg "4.8.36". If null is provided, defaults to the latest release of the EE4
419
-     *                                     REST API
420
-     * @return array which can be passed into the EE4 REST API when querying a model resource
421
-     * @throws \EE_Error
422
-     */
423
-    public static function prepare_query_params_for_rest_api(
424
-        array $model_query_params,
425
-        \EEM_Base $model,
426
-        $requested_version = null
427
-    ) {
428
-        if ($requested_version === null) {
429
-            $requested_version = \EED_Core_Rest_Api::latest_rest_api_version();
430
-        }
431
-        $rest_query_params = $model_query_params;
432
-        if (isset($model_query_params[0])) {
433
-            $rest_query_params['where'] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api(
434
-                $model_query_params[0],
435
-                $model,
436
-                $requested_version
437
-            );
438
-            unset($rest_query_params[0]);
439
-        }
440
-        if (isset($model_query_params['having'])) {
441
-            $rest_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api(
442
-                $model_query_params['having'],
443
-                $model,
444
-                $requested_version
445
-            );
446
-        }
447
-        return apply_filters('FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
448
-            $rest_query_params, $model_query_params, $model, $requested_version);
449
-    }
450
-
451
-
452
-
453
-    /**
454
-     * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
455
-     *
456
-     * @param array     $inputted_query_params_of_this_type eg like the "where" or "having" conditions query params
457
-     *                                                      passed into EEM_Base::get_all()
458
-     * @param \EEM_Base $model
459
-     * @param string    $requested_version                  eg "4.8.36"
460
-     * @return array ready for use in the rest api query params
461
-     * @throws \EE_Error
462
-     */
463
-    public static function prepare_conditions_query_params_for_rest_api(
464
-        $inputted_query_params_of_this_type,
465
-        \EEM_Base $model,
466
-        $requested_version
467
-    ) {
468
-        $query_param_for_models = array();
469
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
470
-            $field = Model_Data_Translator::deduce_field_from_query_param(
471
-                Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($query_param_key),
472
-                $model
473
-            );
474
-            if ($field instanceof \EE_Model_Field_Base) {
475
-                //did they specify an operator?
476
-                if (is_array($query_param_value)) {
477
-                    $op = $query_param_value[0];
478
-                    $translated_value = array($op);
479
-                    if (isset($query_param_value[1])) {
480
-                        $value = $query_param_value[1];
481
-                        $translated_value[1] = Model_Data_Translator::prepare_field_values_for_json($field, $value,
482
-                            $requested_version);
483
-                    }
484
-                } else {
485
-                    $translated_value = Model_Data_Translator::prepare_field_value_for_json($field, $query_param_value,
486
-                        $requested_version);
487
-                }
488
-                $query_param_for_models[$query_param_key] = $translated_value;
489
-            } else {
490
-                //so it's not for a field, assume it's a logic query param key
491
-                $query_param_for_models[$query_param_key] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api($query_param_value,
492
-                    $model, $requested_version);
493
-            }
494
-        }
495
-        return $query_param_for_models;
496
-    }
497
-
498
-
499
-
500
-    /**
501
-     * @param $condition_query_param_key
502
-     * @return string
503
-     */
504
-    public static function remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
505
-    {
506
-        $pos_of_star = strpos($condition_query_param_key, '*');
507
-        if ($pos_of_star === false) {
508
-            return $condition_query_param_key;
509
-        } else {
510
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
511
-            return $condition_query_param_sans_star;
512
-        }
513
-    }
514
-
515
-
516
-
517
-    /**
518
-     * Takes the input parameter and finds the model field that it indicates.
519
-     *
520
-     * @param string    $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
521
-     * @param \EEM_Base $model
522
-     * @return \EE_Model_Field_Base
523
-     * @throws \EE_Error
524
-     */
525
-    public static function deduce_field_from_query_param($query_param_name, \EEM_Base $model)
526
-    {
527
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
528
-        //which will help us find the database table and column
529
-        $query_param_parts = explode('.', $query_param_name);
530
-        if (empty($query_param_parts)) {
531
-            throw new \EE_Error(sprintf(__('_extract_column_name is empty when trying to extract column and table name from %s',
532
-                'event_espresso'), $query_param_name));
533
-        }
534
-        $number_of_parts = count($query_param_parts);
535
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
536
-        if ($number_of_parts === 1) {
537
-            $field_name = $last_query_param_part;
538
-        } else {// $number_of_parts >= 2
539
-            //the last part is the column name, and there are only 2parts. therefore...
540
-            $field_name = $last_query_param_part;
541
-            $model = \EE_Registry::instance()->load_model($query_param_parts[$number_of_parts - 2]);
542
-        }
543
-        try {
544
-            return $model->field_settings_for($field_name);
545
-        } catch (\EE_Error $e) {
546
-            return null;
547
-        }
548
-    }
29
+	/**
30
+	 * We used to use -1 for infinity in the rest api, but that's ambiguous for
31
+	 * fields that COULD contain -1; so we use null
32
+	 */
33
+	const ee_inf_in_rest = null;
34
+
35
+
36
+
37
+	/**
38
+	 * Prepares a possible array of input values from JSON for use by the models
39
+	 *
40
+	 * @param \EE_Model_Field_Base $field_obj
41
+	 * @param mixed                $original_value_maybe_array
42
+	 * @param string               $requested_version
43
+	 * @param string               $timezone_string treat values as being in this timezone
44
+	 * @return mixed
45
+	 * @throws \DomainException
46
+	 */
47
+	public static function prepare_field_values_from_json(
48
+		$field_obj,
49
+		$original_value_maybe_array,
50
+		$requested_version,
51
+		$timezone_string = 'UTC'
52
+	) {
53
+		if (is_array($original_value_maybe_array)) {
54
+			$new_value_maybe_array = array();
55
+			foreach ($original_value_maybe_array as $array_key => $array_item) {
56
+				$new_value_maybe_array[$array_key] = Model_Data_Translator::prepare_field_value_from_json(
57
+					$field_obj,
58
+					$array_item,
59
+					$requested_version,
60
+					$timezone_string
61
+				);
62
+			}
63
+		} else {
64
+			$new_value_maybe_array = Model_Data_Translator::prepare_field_value_from_json(
65
+				$field_obj,
66
+				$original_value_maybe_array,
67
+				$requested_version,
68
+				$timezone_string
69
+			);
70
+		}
71
+		return $new_value_maybe_array;
72
+	}
73
+
74
+
75
+
76
+	/**
77
+	 * Prepares an array of field values FOR use in JSON/REST API
78
+	 *
79
+	 * @param \EE_Model_Field_Base $field_obj
80
+	 * @param mixed                $original_value_maybe_array
81
+	 * @param string               $request_version (eg 4.8.36)
82
+	 * @return array
83
+	 */
84
+	public static function prepare_field_values_for_json($field_obj, $original_value_maybe_array, $request_version)
85
+	{
86
+		if (is_array($original_value_maybe_array)) {
87
+			$new_value_maybe_array = array();
88
+			foreach ($original_value_maybe_array as $array_key => $array_item) {
89
+				$new_value_maybe_array[$array_key] = Model_Data_Translator::prepare_field_value_for_json(
90
+					$field_obj,
91
+					$array_item,
92
+					$request_version
93
+				);
94
+			}
95
+		} else {
96
+			$new_value_maybe_array = Model_Data_Translator::prepare_field_value_for_json(
97
+				$field_obj,
98
+				$original_value_maybe_array,
99
+				$request_version
100
+			);
101
+		}
102
+		return $new_value_maybe_array;
103
+	}
104
+
105
+
106
+
107
+	/**
108
+	 * Prepares incoming data from the json or $_REQUEST parameters for the models'
109
+	 * "$query_params".
110
+	 *
111
+	 * @param \EE_Model_Field_Base $field_obj
112
+	 * @param mixed                $original_value
113
+	 * @param string               $requested_version
114
+	 * @param string               $timezone_string treat values as being in this timezone
115
+	 * @return mixed
116
+	 * @throws \DomainException
117
+	 */
118
+	public static function prepare_field_value_from_json(
119
+		$field_obj,
120
+		$original_value,
121
+		$requested_version,
122
+		$timezone_string = 'UTC' // UTC
123
+	)
124
+	{
125
+		$timezone_string = $timezone_string !== '' ? $timezone_string : get_option('timezone_string', '');
126
+		$new_value = null;
127
+		if ($field_obj instanceof \EE_Infinite_Integer_Field
128
+			&& in_array($original_value, array(null, ''), true)
129
+		) {
130
+			$new_value = EE_INF;
131
+		} elseif ($field_obj instanceof \EE_Datetime_Field) {
132
+			list($offset_sign, $offset_secs) = Model_Data_Translator::parse_timezone_offset(
133
+				$field_obj->get_timezone_offset(
134
+					new \DateTimeZone($timezone_string)
135
+				)
136
+			);
137
+			$offset_string =
138
+				str_pad(
139
+					floor($offset_secs / HOUR_IN_SECONDS),
140
+					2,
141
+					'0',
142
+					STR_PAD_LEFT
143
+				)
144
+				. ':'
145
+				. str_pad(
146
+					($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
147
+					2,
148
+					'0',
149
+					STR_PAD_LEFT
150
+				);
151
+			$new_value = rest_parse_date($original_value . $offset_sign . $offset_string);
152
+		} else {
153
+			$new_value = $original_value;
154
+		}
155
+		return $new_value;
156
+	}
157
+
158
+
159
+
160
+	/**
161
+	 * determines what's going on with them timezone strings
162
+	 *
163
+	 * @param int $timezone_offset
164
+	 * @return array
165
+	 */
166
+	private static function parse_timezone_offset($timezone_offset)
167
+	{
168
+		$first_char = substr((string)$timezone_offset, 0, 1);
169
+		if ($first_char === '+' || $first_char === '-') {
170
+			$offset_sign = $first_char;
171
+			$offset_secs = substr((string)$timezone_offset, 1);
172
+		} else {
173
+			$offset_sign = '+';
174
+			$offset_secs = $timezone_offset;
175
+		}
176
+		return array($offset_sign, $offset_secs);
177
+	}
178
+
179
+
180
+
181
+	/**
182
+	 * Prepares a field's value for display in the API.
183
+	 * The $original_value should be in the model object's domain of values, see the explanation at the top of EEM_Base.
184
+	 * However, for backward compatibility, we also attempt to handle $original_values from the
185
+	 * model client-code domain, and from the database domain.
186
+	 * E.g., when working with EE_Datetime_Fields, $original_value should be a DateTime or DbSafeDateTime
187
+	 * (model object domain). However, for backward compatibility, we also accept a unix timestamp
188
+	 * (old model object domain), MySQL datetime string (database domain) or string formatted according to the
189
+	 * WP Datetime format (model client-code domain)
190
+	 *
191
+	 * @param \EE_Model_Field_Base $field_obj
192
+	 * @param mixed                $original_value
193
+	 * @param string               $requested_version
194
+	 * @return mixed
195
+	 */
196
+	public static function prepare_field_value_for_json($field_obj, $original_value, $requested_version)
197
+	{
198
+		if ($original_value === EE_INF) {
199
+			$new_value = Model_Data_Translator::ee_inf_in_rest;
200
+		} elseif ($field_obj instanceof \EE_Datetime_Field) {
201
+			if (is_string($original_value)) {
202
+				//did they submit a string of a unix timestamp?
203
+				if (is_numeric($original_value)) {
204
+					$datetime_obj = new \DateTime();
205
+					$datetime_obj->setTimestamp((int)$original_value);
206
+				} else {
207
+					//first, check if its a MySQL timestamp in GMT
208
+					$datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
209
+				}
210
+				if (! $datetime_obj instanceof \DateTime) {
211
+					//so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
212
+					$datetime_obj = $field_obj->prepare_for_set($original_value);
213
+				}
214
+				$original_value = $datetime_obj;
215
+			}
216
+			if ($original_value instanceof \DateTime) {
217
+				$new_value = $original_value->format('Y-m-d H:i:s');
218
+			} elseif (is_int($original_value)) {
219
+				$new_value = date('Y-m-d H:i:s', $original_value);
220
+			} elseif($original_value === null || $original_value === '') {
221
+				$new_value = null;
222
+			} else {
223
+				//so it's not a datetime object, unix timestamp (as string or int),
224
+				//MySQL timestamp, or even a string in the field object's format. So no idea what it is
225
+				throw new \EE_Error(
226
+					sprintf(
227
+						esc_html__(
228
+							// @codingStandardsIgnoreStart
229
+							'The value "%1$s" for the field "%2$s" on model "%3$s" could not be understood. It should be a PHP DateTime, unix timestamp, MySQL date, or string in the format "%4$s".',
230
+							// @codingStandardsIgnoreEnd
231
+							'event_espressso'
232
+						),
233
+						$original_value,
234
+						$field_obj->get_name(),
235
+						$field_obj->get_model_name(),
236
+						$field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
237
+					)
238
+				);
239
+			}
240
+			$new_value = mysql_to_rfc3339($new_value);
241
+		} else {
242
+			$new_value = $original_value;
243
+		}
244
+		return apply_filters(
245
+			'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
246
+			$new_value,
247
+			$field_obj,
248
+			$original_value,
249
+			$requested_version
250
+		);
251
+	}
252
+
253
+
254
+
255
+	/**
256
+	 * Prepares condition-query-parameters (like what's in where and having) from
257
+	 * the format expected in the API to use in the models
258
+	 *
259
+	 * @param array     $inputted_query_params_of_this_type
260
+	 * @param \EEM_Base $model
261
+	 * @param string    $requested_version
262
+	 * @return array
263
+	 * @throws \DomainException
264
+	 * @throws \EE_Error
265
+	 */
266
+	public static function prepare_conditions_query_params_for_models(
267
+		$inputted_query_params_of_this_type,
268
+		\EEM_Base $model,
269
+		$requested_version
270
+	) {
271
+		$query_param_for_models = array();
272
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
273
+			$query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($query_param_key);
274
+			$field = Model_Data_Translator::deduce_field_from_query_param(
275
+				$query_param_sans_stars,
276
+				$model
277
+			);
278
+			//double-check is it a *_gmt field?
279
+			if (! $field instanceof \EE_Model_Field_Base
280
+				&& Model_Data_Translator::is_gmt_date_field_name($query_param_sans_stars)
281
+			) {
282
+				//yep, take off '_gmt', and find the field
283
+				$query_param_key = Model_Data_Translator::remove_gmt_from_field_name($query_param_sans_stars);
284
+				$field = Model_Data_Translator::deduce_field_from_query_param(
285
+					$query_param_key,
286
+					$model
287
+				);
288
+				$timezone = 'UTC';
289
+			} else {
290
+				//so it's not a GMT field. Set the timezone on the model to the default
291
+				$timezone = \EEH_DTT_Helper::get_valid_timezone_string();
292
+			}
293
+			if ($field instanceof \EE_Model_Field_Base) {
294
+				//did they specify an operator?
295
+				if (is_array($query_param_value)) {
296
+					$op = $query_param_value[0];
297
+					$translated_value = array($op);
298
+					if (isset($query_param_value[1])) {
299
+						$value = $query_param_value[1];
300
+						$translated_value[1] = Model_Data_Translator::prepare_field_values_from_json($field, $value,
301
+							$requested_version, $timezone);
302
+					}
303
+				} else {
304
+					$translated_value = Model_Data_Translator::prepare_field_value_from_json($field, $query_param_value,
305
+						$requested_version, $timezone);
306
+				}
307
+				$query_param_for_models[$query_param_key] = $translated_value;
308
+			} else {
309
+				//so it's not for a field, assume it's a logic query param key
310
+				$query_param_for_models[$query_param_key] = Model_Data_Translator::prepare_conditions_query_params_for_models($query_param_value,
311
+					$model, $requested_version);
312
+			}
313
+		}
314
+		return $query_param_for_models;
315
+	}
316
+
317
+
318
+
319
+	/**
320
+	 * Mostly checks if the last 4 characters are "_gmt", indicating its a
321
+	 * gmt date field name
322
+	 *
323
+	 * @param string $field_name
324
+	 * @return boolean
325
+	 */
326
+	public static function is_gmt_date_field_name($field_name)
327
+	{
328
+		return substr(
329
+				   Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name),
330
+				   -4,
331
+				   4
332
+			   ) === '_gmt';
333
+	}
334
+
335
+
336
+
337
+	/**
338
+	 * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
339
+	 *
340
+	 * @param string $field_name
341
+	 * @return string
342
+	 */
343
+	public static function remove_gmt_from_field_name($field_name)
344
+	{
345
+		if (! Model_Data_Translator::is_gmt_date_field_name($field_name)) {
346
+			return $field_name;
347
+		}
348
+		$query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name);
349
+		$query_param_sans_gmt_and_sans_stars = substr(
350
+			$query_param_sans_stars,
351
+			0,
352
+			strrpos(
353
+				$field_name,
354
+				'_gmt'
355
+			)
356
+		);
357
+		return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
358
+	}
359
+
360
+
361
+
362
+	/**
363
+	 * Takes a field name from the REST API and prepares it for the model querying
364
+	 *
365
+	 * @param string $field_name
366
+	 * @return string
367
+	 */
368
+	public static function prepare_field_name_from_json($field_name)
369
+	{
370
+		if (Model_Data_Translator::is_gmt_date_field_name($field_name)) {
371
+			return Model_Data_Translator::remove_gmt_from_field_name($field_name);
372
+		}
373
+		return $field_name;
374
+	}
375
+
376
+
377
+
378
+	/**
379
+	 * Takes array of field names from REST API and prepares for models
380
+	 *
381
+	 * @param array $field_names
382
+	 * @return array of field names (possibly include model prefixes)
383
+	 */
384
+	public static function prepare_field_names_from_json(array $field_names)
385
+	{
386
+		$new_array = array();
387
+		foreach ($field_names as $key => $field_name) {
388
+			$new_array[$key] = Model_Data_Translator::prepare_field_name_from_json($field_name);
389
+		}
390
+		return $new_array;
391
+	}
392
+
393
+
394
+
395
+	/**
396
+	 * Takes array where array keys are field names (possibly with model path prefixes)
397
+	 * from the REST API and prepares them for model querying
398
+	 *
399
+	 * @param array $field_names_as_keys
400
+	 * @return array
401
+	 */
402
+	public static function prepare_field_names_in_array_keys_from_json(array $field_names_as_keys)
403
+	{
404
+		$new_array = array();
405
+		foreach ($field_names_as_keys as $field_name => $value) {
406
+			$new_array[Model_Data_Translator::prepare_field_name_from_json($field_name)] = $value;
407
+		}
408
+		return $new_array;
409
+	}
410
+
411
+
412
+
413
+	/**
414
+	 * Prepares an array of model query params for use in the REST API
415
+	 *
416
+	 * @param array     $model_query_params
417
+	 * @param \EEM_Base $model
418
+	 * @param string    $requested_version eg "4.8.36". If null is provided, defaults to the latest release of the EE4
419
+	 *                                     REST API
420
+	 * @return array which can be passed into the EE4 REST API when querying a model resource
421
+	 * @throws \EE_Error
422
+	 */
423
+	public static function prepare_query_params_for_rest_api(
424
+		array $model_query_params,
425
+		\EEM_Base $model,
426
+		$requested_version = null
427
+	) {
428
+		if ($requested_version === null) {
429
+			$requested_version = \EED_Core_Rest_Api::latest_rest_api_version();
430
+		}
431
+		$rest_query_params = $model_query_params;
432
+		if (isset($model_query_params[0])) {
433
+			$rest_query_params['where'] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api(
434
+				$model_query_params[0],
435
+				$model,
436
+				$requested_version
437
+			);
438
+			unset($rest_query_params[0]);
439
+		}
440
+		if (isset($model_query_params['having'])) {
441
+			$rest_query_params['having'] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api(
442
+				$model_query_params['having'],
443
+				$model,
444
+				$requested_version
445
+			);
446
+		}
447
+		return apply_filters('FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
448
+			$rest_query_params, $model_query_params, $model, $requested_version);
449
+	}
450
+
451
+
452
+
453
+	/**
454
+	 * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
455
+	 *
456
+	 * @param array     $inputted_query_params_of_this_type eg like the "where" or "having" conditions query params
457
+	 *                                                      passed into EEM_Base::get_all()
458
+	 * @param \EEM_Base $model
459
+	 * @param string    $requested_version                  eg "4.8.36"
460
+	 * @return array ready for use in the rest api query params
461
+	 * @throws \EE_Error
462
+	 */
463
+	public static function prepare_conditions_query_params_for_rest_api(
464
+		$inputted_query_params_of_this_type,
465
+		\EEM_Base $model,
466
+		$requested_version
467
+	) {
468
+		$query_param_for_models = array();
469
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
470
+			$field = Model_Data_Translator::deduce_field_from_query_param(
471
+				Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($query_param_key),
472
+				$model
473
+			);
474
+			if ($field instanceof \EE_Model_Field_Base) {
475
+				//did they specify an operator?
476
+				if (is_array($query_param_value)) {
477
+					$op = $query_param_value[0];
478
+					$translated_value = array($op);
479
+					if (isset($query_param_value[1])) {
480
+						$value = $query_param_value[1];
481
+						$translated_value[1] = Model_Data_Translator::prepare_field_values_for_json($field, $value,
482
+							$requested_version);
483
+					}
484
+				} else {
485
+					$translated_value = Model_Data_Translator::prepare_field_value_for_json($field, $query_param_value,
486
+						$requested_version);
487
+				}
488
+				$query_param_for_models[$query_param_key] = $translated_value;
489
+			} else {
490
+				//so it's not for a field, assume it's a logic query param key
491
+				$query_param_for_models[$query_param_key] = Model_Data_Translator::prepare_conditions_query_params_for_rest_api($query_param_value,
492
+					$model, $requested_version);
493
+			}
494
+		}
495
+		return $query_param_for_models;
496
+	}
497
+
498
+
499
+
500
+	/**
501
+	 * @param $condition_query_param_key
502
+	 * @return string
503
+	 */
504
+	public static function remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
505
+	{
506
+		$pos_of_star = strpos($condition_query_param_key, '*');
507
+		if ($pos_of_star === false) {
508
+			return $condition_query_param_key;
509
+		} else {
510
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
511
+			return $condition_query_param_sans_star;
512
+		}
513
+	}
514
+
515
+
516
+
517
+	/**
518
+	 * Takes the input parameter and finds the model field that it indicates.
519
+	 *
520
+	 * @param string    $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
521
+	 * @param \EEM_Base $model
522
+	 * @return \EE_Model_Field_Base
523
+	 * @throws \EE_Error
524
+	 */
525
+	public static function deduce_field_from_query_param($query_param_name, \EEM_Base $model)
526
+	{
527
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
528
+		//which will help us find the database table and column
529
+		$query_param_parts = explode('.', $query_param_name);
530
+		if (empty($query_param_parts)) {
531
+			throw new \EE_Error(sprintf(__('_extract_column_name is empty when trying to extract column and table name from %s',
532
+				'event_espresso'), $query_param_name));
533
+		}
534
+		$number_of_parts = count($query_param_parts);
535
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
536
+		if ($number_of_parts === 1) {
537
+			$field_name = $last_query_param_part;
538
+		} else {// $number_of_parts >= 2
539
+			//the last part is the column name, and there are only 2parts. therefore...
540
+			$field_name = $last_query_param_part;
541
+			$model = \EE_Registry::instance()->load_model($query_param_parts[$number_of_parts - 2]);
542
+		}
543
+		try {
544
+			return $model->field_settings_for($field_name);
545
+		} catch (\EE_Error $e) {
546
+			return null;
547
+		}
548
+	}
549 549
 
550 550
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 namespace EventEspresso\core\libraries\rest_api;
3 3
 
4
-if (! defined('EVENT_ESPRESSO_VERSION')) {
4
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5 5
     exit('No direct script access allowed');
6 6
 }
7 7
 
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
                     '0',
149 149
                     STR_PAD_LEFT
150 150
                 );
151
-            $new_value = rest_parse_date($original_value . $offset_sign . $offset_string);
151
+            $new_value = rest_parse_date($original_value.$offset_sign.$offset_string);
152 152
         } else {
153 153
             $new_value = $original_value;
154 154
         }
@@ -165,10 +165,10 @@  discard block
 block discarded – undo
165 165
      */
166 166
     private static function parse_timezone_offset($timezone_offset)
167 167
     {
168
-        $first_char = substr((string)$timezone_offset, 0, 1);
168
+        $first_char = substr((string) $timezone_offset, 0, 1);
169 169
         if ($first_char === '+' || $first_char === '-') {
170 170
             $offset_sign = $first_char;
171
-            $offset_secs = substr((string)$timezone_offset, 1);
171
+            $offset_secs = substr((string) $timezone_offset, 1);
172 172
         } else {
173 173
             $offset_sign = '+';
174 174
             $offset_secs = $timezone_offset;
@@ -202,12 +202,12 @@  discard block
 block discarded – undo
202 202
                 //did they submit a string of a unix timestamp?
203 203
                 if (is_numeric($original_value)) {
204 204
                     $datetime_obj = new \DateTime();
205
-                    $datetime_obj->setTimestamp((int)$original_value);
205
+                    $datetime_obj->setTimestamp((int) $original_value);
206 206
                 } else {
207 207
                     //first, check if its a MySQL timestamp in GMT
208 208
                     $datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
209 209
                 }
210
-                if (! $datetime_obj instanceof \DateTime) {
210
+                if ( ! $datetime_obj instanceof \DateTime) {
211 211
                     //so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
212 212
                     $datetime_obj = $field_obj->prepare_for_set($original_value);
213 213
                 }
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
                 $new_value = $original_value->format('Y-m-d H:i:s');
218 218
             } elseif (is_int($original_value)) {
219 219
                 $new_value = date('Y-m-d H:i:s', $original_value);
220
-            } elseif($original_value === null || $original_value === '') {
220
+            } elseif ($original_value === null || $original_value === '') {
221 221
                 $new_value = null;
222 222
             } else {
223 223
                 //so it's not a datetime object, unix timestamp (as string or int),
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
                         $original_value,
234 234
                         $field_obj->get_name(),
235 235
                         $field_obj->get_model_name(),
236
-                        $field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
236
+                        $field_obj->get_time_format().' '.$field_obj->get_time_format()
237 237
                     )
238 238
                 );
239 239
             }
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
                 $model
277 277
             );
278 278
             //double-check is it a *_gmt field?
279
-            if (! $field instanceof \EE_Model_Field_Base
279
+            if ( ! $field instanceof \EE_Model_Field_Base
280 280
                 && Model_Data_Translator::is_gmt_date_field_name($query_param_sans_stars)
281 281
             ) {
282 282
                 //yep, take off '_gmt', and find the field
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
      */
343 343
     public static function remove_gmt_from_field_name($field_name)
344 344
     {
345
-        if (! Model_Data_Translator::is_gmt_date_field_name($field_name)) {
345
+        if ( ! Model_Data_Translator::is_gmt_date_field_name($field_name)) {
346 346
             return $field_name;
347 347
         }
348 348
         $query_param_sans_stars = Model_Data_Translator::remove_stars_and_anything_after_from_condition_query_param_key($field_name);
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Indentation   +2669 added lines, -2669 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 do_action('AHEE_log', __FILE__, ' FILE LOADED', '');
5 5
 
@@ -25,2674 +25,2674 @@  discard block
 block discarded – undo
25 25
 abstract class EE_Base_Class
26 26
 {
27 27
 
28
-    /**
29
-     * This is an array of the original properties and values provided during construction
30
-     * of this model object. (keys are model field names, values are their values).
31
-     * This list is important to remember so that when we are merging data from the db, we know
32
-     * which values to override and which to not override.
33
-     *
34
-     * @var array
35
-     */
36
-    protected $_props_n_values_provided_in_constructor;
37
-
38
-    /**
39
-     * Timezone
40
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
-     * access to it.
44
-     *
45
-     * @var string
46
-     */
47
-    protected $_timezone;
48
-
49
-
50
-
51
-    /**
52
-     * date format
53
-     * pattern or format for displaying dates
54
-     *
55
-     * @var string $_dt_frmt
56
-     */
57
-    protected $_dt_frmt;
58
-
59
-
60
-
61
-    /**
62
-     * time format
63
-     * pattern or format for displaying time
64
-     *
65
-     * @var string $_tm_frmt
66
-     */
67
-    protected $_tm_frmt;
68
-
69
-
70
-
71
-    /**
72
-     * This property is for holding a cached array of object properties indexed by property name as the key.
73
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
74
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
-     *
77
-     * @var array
78
-     */
79
-    protected $_cached_properties = array();
80
-
81
-    /**
82
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
83
-     * single
84
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
-     * all others have an array)
87
-     *
88
-     * @var array
89
-     */
90
-    protected $_model_relations = array();
91
-
92
-    /**
93
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
-     *
96
-     * @var array
97
-     */
98
-    protected $_fields = array();
99
-
100
-    /**
101
-     * @var boolean indicating whether or not this model object is intended to ever be saved
102
-     * For example, we might create model objects intended to only be used for the duration
103
-     * of this request and to be thrown away, and if they were accidentally saved
104
-     * it would be a bug.
105
-     */
106
-    protected $_allow_persist = true;
107
-
108
-    /**
109
-     * @var boolean indicating whether or not this model object's properties have changed since construction
110
-     */
111
-    protected $_has_changes = false;
112
-
113
-
114
-
115
-    /**
116
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
117
-     * play nice
118
-     *
119
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
120
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
121
-     *                                                         TXN_amount, QST_name, etc) and values are their values
122
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
123
-     *                                                         corresponding db model or not.
124
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
125
-     *                                                         be in when instantiating a EE_Base_Class object.
126
-     * @param array   $date_formats                            An array of date formats to set on construct where first
127
-     *                                                         value is the date_format and second value is the time
128
-     *                                                         format.
129
-     * @throws EE_Error
130
-     */
131
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
132
-    {
133
-        $className = get_class($this);
134
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
135
-        $model = $this->get_model();
136
-        $model_fields = $model->field_settings(false);
137
-        // ensure $fieldValues is an array
138
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
139
-        // EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
140
-        // verify client code has not passed any invalid field names
141
-        foreach ($fieldValues as $field_name => $field_value) {
142
-            if ( ! isset($model_fields[$field_name])) {
143
-                throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
144
-                    "event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
145
-            }
146
-        }
147
-        // EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
148
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
149
-        if ( ! empty($date_formats) && is_array($date_formats)) {
150
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
151
-        } else {
152
-            //set default formats for date and time
153
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
154
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
155
-        }
156
-        //if db model is instantiating
157
-        if ($bydb) {
158
-            //client code has indicated these field values are from the database
159
-            foreach ($model_fields as $fieldName => $field) {
160
-                $this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
161
-            }
162
-        } else {
163
-            //we're constructing a brand
164
-            //new instance of the model object. Generally, this means we'll need to do more field validation
165
-            foreach ($model_fields as $fieldName => $field) {
166
-                $this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
167
-            }
168
-        }
169
-        //remember what values were passed to this constructor
170
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
171
-        //remember in entity mapper
172
-        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
173
-            $model->add_to_entity_map($this);
174
-        }
175
-        //setup all the relations
176
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
177
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
178
-                $this->_model_relations[$relation_name] = null;
179
-            } else {
180
-                $this->_model_relations[$relation_name] = array();
181
-            }
182
-        }
183
-        /**
184
-         * Action done at the end of each model object construction
185
-         *
186
-         * @param EE_Base_Class $this the model object just created
187
-         */
188
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
189
-    }
190
-
191
-
192
-
193
-    /**
194
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
195
-     *
196
-     * @return boolean
197
-     */
198
-    public function allow_persist()
199
-    {
200
-        return $this->_allow_persist;
201
-    }
202
-
203
-
204
-
205
-    /**
206
-     * Sets whether or not this model object should be allowed to be saved to the DB.
207
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
208
-     * you got new information that somehow made you change your mind.
209
-     *
210
-     * @param boolean $allow_persist
211
-     * @return boolean
212
-     */
213
-    public function set_allow_persist($allow_persist)
214
-    {
215
-        return $this->_allow_persist = $allow_persist;
216
-    }
217
-
218
-
219
-
220
-    /**
221
-     * Gets the field's original value when this object was constructed during this request.
222
-     * This can be helpful when determining if a model object has changed or not
223
-     *
224
-     * @param string $field_name
225
-     * @return mixed|null
226
-     * @throws \EE_Error
227
-     */
228
-    public function get_original($field_name)
229
-    {
230
-        if (isset($this->_props_n_values_provided_in_constructor[$field_name])
231
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
232
-        ) {
233
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
234
-        } else {
235
-            return null;
236
-        }
237
-    }
238
-
239
-
240
-
241
-    /**
242
-     * @param EE_Base_Class $obj
243
-     * @return string
244
-     */
245
-    public function get_class($obj)
246
-    {
247
-        return get_class($obj);
248
-    }
249
-
250
-
251
-
252
-    /**
253
-     * Overrides parent because parent expects old models.
254
-     * This also doesn't do any validation, and won't work for serialized arrays
255
-     *
256
-     * @param    string $field_name
257
-     * @param    mixed  $field_value
258
-     * @param bool      $use_default
259
-     * @throws \EE_Error
260
-     */
261
-    public function set($field_name, $field_value, $use_default = false)
262
-    {
263
-        // if not using default and nothing has changed, and object has already been setup (has ID),
264
-        // then don't do anything
265
-        if (
266
-            ! $use_default
267
-            && $this->_fields[$field_name] === $field_value
268
-            && $this->ID()
269
-        ) {
270
-            return;
271
-        }
272
-        $this->_has_changes = true;
273
-        $field_obj = $this->get_model()->field_settings_for($field_name);
274
-        if ($field_obj instanceof EE_Model_Field_Base) {
275
-            //			if ( method_exists( $field_obj, 'set_timezone' )) {
276
-            if ($field_obj instanceof EE_Datetime_Field) {
277
-                $field_obj->set_timezone($this->_timezone);
278
-                $field_obj->set_date_format($this->_dt_frmt);
279
-                $field_obj->set_time_format($this->_tm_frmt);
280
-            }
281
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
282
-            //should the value be null?
283
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
284
-                $this->_fields[$field_name] = $field_obj->get_default_value();
285
-                /**
286
-                 * To save having to refactor all the models, if a default value is used for a
287
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
288
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
289
-                 * object.
290
-                 *
291
-                 * @since 4.6.10+
292
-                 */
293
-                if (
294
-                    $field_obj instanceof EE_Datetime_Field
295
-                    && $this->_fields[$field_name] !== null
296
-                    && ! $this->_fields[$field_name] instanceof DateTime
297
-                ) {
298
-                    empty($this->_fields[$field_name])
299
-                        ? $this->set($field_name, time())
300
-                        : $this->set($field_name, $this->_fields[$field_name]);
301
-                }
302
-            } else {
303
-                $this->_fields[$field_name] = $holder_of_value;
304
-            }
305
-            //if we're not in the constructor...
306
-            //now check if what we set was a primary key
307
-            if (
308
-                //note: props_n_values_provided_in_constructor is only set at the END of the constructor
309
-                $this->_props_n_values_provided_in_constructor
310
-                && $field_value
311
-                && $field_name === self::_get_primary_key_name(get_class($this))
312
-            ) {
313
-                //if so, we want all this object's fields to be filled either with
314
-                //what we've explicitly set on this model
315
-                //or what we have in the db
316
-                // echo "setting primary key!";
317
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
318
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
319
-                foreach ($fields_on_model as $field_obj) {
320
-                    if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
321
-                         && $field_obj->get_name() !== $field_name
322
-                    ) {
323
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
324
-                    }
325
-                }
326
-                //oh this model object has an ID? well make sure its in the entity mapper
327
-                $this->get_model()->add_to_entity_map($this);
328
-            }
329
-            //let's unset any cache for this field_name from the $_cached_properties property.
330
-            $this->_clear_cached_property($field_name);
331
-        } else {
332
-            throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
333
-                "event_espresso"), $field_name));
334
-        }
335
-    }
336
-
337
-
338
-
339
-    /**
340
-     * This sets the field value on the db column if it exists for the given $column_name or
341
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
342
-     *
343
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
344
-     * @param string $field_name  Must be the exact column name.
345
-     * @param mixed  $field_value The value to set.
346
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
347
-     * @throws \EE_Error
348
-     */
349
-    public function set_field_or_extra_meta($field_name, $field_value)
350
-    {
351
-        if ($this->get_model()->has_field($field_name)) {
352
-            $this->set($field_name, $field_value);
353
-            return true;
354
-        } else {
355
-            //ensure this object is saved first so that extra meta can be properly related.
356
-            $this->save();
357
-            return $this->update_extra_meta($field_name, $field_value);
358
-        }
359
-    }
360
-
361
-
362
-
363
-    /**
364
-     * This retrieves the value of the db column set on this class or if that's not present
365
-     * it will attempt to retrieve from extra_meta if found.
366
-     * Example Usage:
367
-     * Via EE_Message child class:
368
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
369
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
370
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
371
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
372
-     * value for those extra fields dynamically via the EE_message object.
373
-     *
374
-     * @param  string $field_name expecting the fully qualified field name.
375
-     * @return mixed|null  value for the field if found.  null if not found.
376
-     * @throws \EE_Error
377
-     */
378
-    public function get_field_or_extra_meta($field_name)
379
-    {
380
-        if ($this->get_model()->has_field($field_name)) {
381
-            $column_value = $this->get($field_name);
382
-        } else {
383
-            //This isn't a column in the main table, let's see if it is in the extra meta.
384
-            $column_value = $this->get_extra_meta($field_name, true, null);
385
-        }
386
-        return $column_value;
387
-    }
388
-
389
-
390
-
391
-    /**
392
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
393
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
394
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
395
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
396
-     *
397
-     * @access public
398
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
399
-     * @return void
400
-     * @throws \EE_Error
401
-     */
402
-    public function set_timezone($timezone = '')
403
-    {
404
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
405
-        //make sure we clear all cached properties because they won't be relevant now
406
-        $this->_clear_cached_properties();
407
-        //make sure we update field settings and the date for all EE_Datetime_Fields
408
-        $model_fields = $this->get_model()->field_settings(false);
409
-        foreach ($model_fields as $field_name => $field_obj) {
410
-            if ($field_obj instanceof EE_Datetime_Field) {
411
-                $field_obj->set_timezone($this->_timezone);
412
-                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
413
-                    $this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
414
-                }
415
-            }
416
-        }
417
-    }
418
-
419
-
420
-
421
-    /**
422
-     * This just returns whatever is set for the current timezone.
423
-     *
424
-     * @access public
425
-     * @return string timezone string
426
-     */
427
-    public function get_timezone()
428
-    {
429
-        return $this->_timezone;
430
-    }
431
-
432
-
433
-
434
-    /**
435
-     * This sets the internal date format to what is sent in to be used as the new default for the class
436
-     * internally instead of wp set date format options
437
-     *
438
-     * @since 4.6
439
-     * @param string $format should be a format recognizable by PHP date() functions.
440
-     */
441
-    public function set_date_format($format)
442
-    {
443
-        $this->_dt_frmt = $format;
444
-        //clear cached_properties because they won't be relevant now.
445
-        $this->_clear_cached_properties();
446
-    }
447
-
448
-
449
-
450
-    /**
451
-     * This sets the internal time format string to what is sent in to be used as the new default for the
452
-     * class internally instead of wp set time format options.
453
-     *
454
-     * @since 4.6
455
-     * @param string $format should be a format recognizable by PHP date() functions.
456
-     */
457
-    public function set_time_format($format)
458
-    {
459
-        $this->_tm_frmt = $format;
460
-        //clear cached_properties because they won't be relevant now.
461
-        $this->_clear_cached_properties();
462
-    }
463
-
464
-
465
-
466
-    /**
467
-     * This returns the current internal set format for the date and time formats.
468
-     *
469
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
470
-     *                             where the first value is the date format and the second value is the time format.
471
-     * @return mixed string|array
472
-     */
473
-    public function get_format($full = true)
474
-    {
475
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
476
-    }
477
-
478
-
479
-
480
-    /**
481
-     * cache
482
-     * stores the passed model object on the current model object.
483
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
484
-     *
485
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
486
-     *                                       'Registration' associated with this model object
487
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
488
-     *                                       that could be a payment or a registration)
489
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
490
-     *                                       items which will be stored in an array on this object
491
-     * @throws EE_Error
492
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
493
-     *                  related thing, no array)
494
-     */
495
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
496
-    {
497
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
498
-        if ( ! $object_to_cache instanceof EE_Base_Class) {
499
-            return false;
500
-        }
501
-        // also get "how" the object is related, or throw an error
502
-        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
503
-            throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
504
-                $relationName, get_class($this)));
505
-        }
506
-        // how many things are related ?
507
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
508
-            // if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
509
-            // so for these model objects just set it to be cached
510
-            $this->_model_relations[$relationName] = $object_to_cache;
511
-            $return = true;
512
-        } else {
513
-            // otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
514
-            // eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
515
-            if ( ! is_array($this->_model_relations[$relationName])) {
516
-                // if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
517
-                $this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
518
-                    ? array($this->_model_relations[$relationName]) : array();
519
-            }
520
-            // first check for a cache_id which is normally empty
521
-            if ( ! empty($cache_id)) {
522
-                // if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
523
-                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
524
-                $return = $cache_id;
525
-            } elseif ($object_to_cache->ID()) {
526
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
527
-                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
528
-                $return = $object_to_cache->ID();
529
-            } else {
530
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
531
-                $this->_model_relations[$relationName][] = $object_to_cache;
532
-                // move the internal pointer to the end of the array
533
-                end($this->_model_relations[$relationName]);
534
-                // and grab the key so that we can return it
535
-                $return = key($this->_model_relations[$relationName]);
536
-            }
537
-        }
538
-        return $return;
539
-    }
540
-
541
-
542
-
543
-    /**
544
-     * For adding an item to the cached_properties property.
545
-     *
546
-     * @access protected
547
-     * @param string      $fieldname the property item the corresponding value is for.
548
-     * @param mixed       $value     The value we are caching.
549
-     * @param string|null $cache_type
550
-     * @return void
551
-     * @throws \EE_Error
552
-     */
553
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
554
-    {
555
-        //first make sure this property exists
556
-        $this->get_model()->field_settings_for($fieldname);
557
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
558
-        $this->_cached_properties[$fieldname][$cache_type] = $value;
559
-    }
560
-
561
-
562
-
563
-    /**
564
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
565
-     * This also SETS the cache if we return the actual property!
566
-     *
567
-     * @param string $fieldname        the name of the property we're trying to retrieve
568
-     * @param bool   $pretty
569
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
570
-     *                                 (in cases where the same property may be used for different outputs
571
-     *                                 - i.e. datetime, money etc.)
572
-     *                                 It can also accept certain pre-defined "schema" strings
573
-     *                                 to define how to output the property.
574
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
575
-     * @return mixed                   whatever the value for the property is we're retrieving
576
-     * @throws \EE_Error
577
-     */
578
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
579
-    {
580
-        //verify the field exists
581
-        $this->get_model()->field_settings_for($fieldname);
582
-        $cache_type = $pretty ? 'pretty' : 'standard';
583
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
584
-        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
585
-            return $this->_cached_properties[$fieldname][$cache_type];
586
-        }
587
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
588
-        if ($field_obj instanceof EE_Model_Field_Base) {
589
-            // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
590
-            if ($field_obj instanceof EE_Datetime_Field) {
591
-                $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
592
-            }
593
-            if ( ! isset($this->_fields[$fieldname])) {
594
-                $this->_fields[$fieldname] = null;
595
-            }
596
-            $value = $pretty
597
-                ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
598
-                : $field_obj->prepare_for_get($this->_fields[$fieldname]);
599
-            $this->_set_cached_property($fieldname, $value, $cache_type);
600
-            return $value;
601
-        }
602
-        return null;
603
-    }
604
-
605
-
606
-
607
-    /**
608
-     * set timezone, formats, and output for EE_Datetime_Field objects
609
-     *
610
-     * @param \EE_Datetime_Field $datetime_field
611
-     * @param bool               $pretty
612
-     * @param null $date_or_time
613
-     * @return void
614
-     * @throws \EE_Error
615
-     */
616
-    protected function _prepare_datetime_field(
617
-        EE_Datetime_Field $datetime_field,
618
-        $pretty = false,
619
-        $date_or_time = null
620
-    ) {
621
-        $datetime_field->set_timezone($this->_timezone);
622
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
623
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
624
-        //set the output returned
625
-        switch ($date_or_time) {
626
-            case 'D' :
627
-                $datetime_field->set_date_time_output('date');
628
-                break;
629
-            case 'T' :
630
-                $datetime_field->set_date_time_output('time');
631
-                break;
632
-            default :
633
-                $datetime_field->set_date_time_output();
634
-        }
635
-    }
636
-
637
-
638
-
639
-    /**
640
-     * This just takes care of clearing out the cached_properties
641
-     *
642
-     * @return void
643
-     */
644
-    protected function _clear_cached_properties()
645
-    {
646
-        $this->_cached_properties = array();
647
-    }
648
-
649
-
650
-
651
-    /**
652
-     * This just clears out ONE property if it exists in the cache
653
-     *
654
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
655
-     * @return void
656
-     */
657
-    protected function _clear_cached_property($property_name)
658
-    {
659
-        if (isset($this->_cached_properties[$property_name])) {
660
-            unset($this->_cached_properties[$property_name]);
661
-        }
662
-    }
663
-
664
-
665
-
666
-    /**
667
-     * Ensures that this related thing is a model object.
668
-     *
669
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
670
-     * @param string $model_name   name of the related thing, eg 'Attendee',
671
-     * @return EE_Base_Class
672
-     * @throws \EE_Error
673
-     */
674
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
675
-    {
676
-        $other_model_instance = self::_get_model_instance_with_name(
677
-            self::_get_model_classname($model_name),
678
-            $this->_timezone
679
-        );
680
-        return $other_model_instance->ensure_is_obj($object_or_id);
681
-    }
682
-
683
-
684
-
685
-    /**
686
-     * Forgets the cached model of the given relation Name. So the next time we request it,
687
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
688
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
689
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
690
-     *
691
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
692
-     *                                                     Eg 'Registration'
693
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
694
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
695
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
696
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
697
-     *                                                     this is HasMany or HABTM.
698
-     * @throws EE_Error
699
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
700
-     *                       relation from all
701
-     */
702
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
703
-    {
704
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
705
-        $index_in_cache = '';
706
-        if ( ! $relationship_to_model) {
707
-            throw new EE_Error(
708
-                sprintf(
709
-                    __("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
710
-                    $relationName,
711
-                    get_class($this)
712
-                )
713
-            );
714
-        }
715
-        if ($clear_all) {
716
-            $obj_removed = true;
717
-            $this->_model_relations[$relationName] = null;
718
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
719
-            $obj_removed = $this->_model_relations[$relationName];
720
-            $this->_model_relations[$relationName] = null;
721
-        } else {
722
-            if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
723
-                && $object_to_remove_or_index_into_array->ID()
724
-            ) {
725
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
726
-                if (is_array($this->_model_relations[$relationName])
727
-                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
728
-                ) {
729
-                    $index_found_at = null;
730
-                    //find this object in the array even though it has a different key
731
-                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
732
-                        if (
733
-                            $obj instanceof EE_Base_Class
734
-                            && (
735
-                                $obj == $object_to_remove_or_index_into_array
736
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
737
-                            )
738
-                        ) {
739
-                            $index_found_at = $index;
740
-                            break;
741
-                        }
742
-                    }
743
-                    if ($index_found_at) {
744
-                        $index_in_cache = $index_found_at;
745
-                    } else {
746
-                        //it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
747
-                        //if it wasn't in it to begin with. So we're done
748
-                        return $object_to_remove_or_index_into_array;
749
-                    }
750
-                }
751
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
752
-                //so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
753
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
754
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
755
-                        $index_in_cache = $index;
756
-                    }
757
-                }
758
-            } else {
759
-                $index_in_cache = $object_to_remove_or_index_into_array;
760
-            }
761
-            //supposedly we've found it. But it could just be that the client code
762
-            //provided a bad index/object
763
-            if (
764
-            isset(
765
-                $this->_model_relations[$relationName],
766
-                $this->_model_relations[$relationName][$index_in_cache]
767
-            )
768
-            ) {
769
-                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
770
-                unset($this->_model_relations[$relationName][$index_in_cache]);
771
-            } else {
772
-                //that thing was never cached anyways.
773
-                $obj_removed = null;
774
-            }
775
-        }
776
-        return $obj_removed;
777
-    }
778
-
779
-
780
-
781
-    /**
782
-     * update_cache_after_object_save
783
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
784
-     * obtained after being saved to the db
785
-     *
786
-     * @param string         $relationName       - the type of object that is cached
787
-     * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
788
-     * @param string         $current_cache_id   - the ID that was used when originally caching the object
789
-     * @return boolean TRUE on success, FALSE on fail
790
-     * @throws \EE_Error
791
-     */
792
-    public function update_cache_after_object_save(
793
-        $relationName,
794
-        EE_Base_Class $newly_saved_object,
795
-        $current_cache_id = ''
796
-    ) {
797
-        // verify that incoming object is of the correct type
798
-        $obj_class = 'EE_' . $relationName;
799
-        if ($newly_saved_object instanceof $obj_class) {
800
-            /* @type EE_Base_Class $newly_saved_object */
801
-            // now get the type of relation
802
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
803
-            // if this is a 1:1 relationship
804
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
805
-                // then just replace the cached object with the newly saved object
806
-                $this->_model_relations[$relationName] = $newly_saved_object;
807
-                return true;
808
-                // or if it's some kind of sordid feral polyamorous relationship...
809
-            } elseif (is_array($this->_model_relations[$relationName])
810
-                      && isset($this->_model_relations[$relationName][$current_cache_id])
811
-            ) {
812
-                // then remove the current cached item
813
-                unset($this->_model_relations[$relationName][$current_cache_id]);
814
-                // and cache the newly saved object using it's new ID
815
-                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
816
-                return true;
817
-            }
818
-        }
819
-        return false;
820
-    }
821
-
822
-
823
-
824
-    /**
825
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
826
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
827
-     *
828
-     * @param string $relationName
829
-     * @return EE_Base_Class
830
-     */
831
-    public function get_one_from_cache($relationName)
832
-    {
833
-        $cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
834
-            : null;
835
-        if (is_array($cached_array_or_object)) {
836
-            return array_shift($cached_array_or_object);
837
-        } else {
838
-            return $cached_array_or_object;
839
-        }
840
-    }
841
-
842
-
843
-
844
-    /**
845
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
846
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
847
-     *
848
-     * @param string $relationName
849
-     * @throws \EE_Error
850
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
851
-     */
852
-    public function get_all_from_cache($relationName)
853
-    {
854
-        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
855
-        // if the result is not an array, but exists, make it an array
856
-        $objects = is_array($objects) ? $objects : array($objects);
857
-        //bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
858
-        //basically, if this model object was stored in the session, and these cached model objects
859
-        //already have IDs, let's make sure they're in their model's entity mapper
860
-        //otherwise we will have duplicates next time we call
861
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
862
-        $model = EE_Registry::instance()->load_model($relationName);
863
-        foreach ($objects as $model_object) {
864
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
865
-                //ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
866
-                if ($model_object->ID()) {
867
-                    $model->add_to_entity_map($model_object);
868
-                }
869
-            } else {
870
-                throw new EE_Error(
871
-                    sprintf(
872
-                        __(
873
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
874
-                            'event_espresso'
875
-                        ),
876
-                        $relationName,
877
-                        gettype($model_object)
878
-                    )
879
-                );
880
-            }
881
-        }
882
-        return $objects;
883
-    }
884
-
885
-
886
-
887
-    /**
888
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
889
-     * matching the given query conditions.
890
-     *
891
-     * @param null  $field_to_order_by  What field is being used as the reference point.
892
-     * @param int   $limit              How many objects to return.
893
-     * @param array $query_params       Any additional conditions on the query.
894
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
895
-     *                                  you can indicate just the columns you want returned
896
-     * @return array|EE_Base_Class[]
897
-     * @throws \EE_Error
898
-     */
899
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
900
-    {
901
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
902
-            ? $this->get_model()->get_primary_key_field()->get_name()
903
-            : $field_to_order_by;
904
-        $current_value = ! empty($field) ? $this->get($field) : null;
905
-        if (empty($field) || empty($current_value)) {
906
-            return array();
907
-        }
908
-        return $this->get_model()->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
909
-    }
910
-
911
-
912
-
913
-    /**
914
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
915
-     * matching the given query conditions.
916
-     *
917
-     * @param null  $field_to_order_by  What field is being used as the reference point.
918
-     * @param int   $limit              How many objects to return.
919
-     * @param array $query_params       Any additional conditions on the query.
920
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
921
-     *                                  you can indicate just the columns you want returned
922
-     * @return array|EE_Base_Class[]
923
-     * @throws \EE_Error
924
-     */
925
-    public function previous_x(
926
-        $field_to_order_by = null,
927
-        $limit = 1,
928
-        $query_params = array(),
929
-        $columns_to_select = null
930
-    ) {
931
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
932
-            ? $this->get_model()->get_primary_key_field()->get_name()
933
-            : $field_to_order_by;
934
-        $current_value = ! empty($field) ? $this->get($field) : null;
935
-        if (empty($field) || empty($current_value)) {
936
-            return array();
937
-        }
938
-        return $this->get_model()->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
939
-    }
940
-
941
-
942
-
943
-    /**
944
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
945
-     * matching the given query conditions.
946
-     *
947
-     * @param null  $field_to_order_by  What field is being used as the reference point.
948
-     * @param array $query_params       Any additional conditions on the query.
949
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
950
-     *                                  you can indicate just the columns you want returned
951
-     * @return array|EE_Base_Class
952
-     * @throws \EE_Error
953
-     */
954
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
955
-    {
956
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
957
-            ? $this->get_model()->get_primary_key_field()->get_name()
958
-            : $field_to_order_by;
959
-        $current_value = ! empty($field) ? $this->get($field) : null;
960
-        if (empty($field) || empty($current_value)) {
961
-            return array();
962
-        }
963
-        return $this->get_model()->next($current_value, $field, $query_params, $columns_to_select);
964
-    }
965
-
966
-
967
-
968
-    /**
969
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
970
-     * matching the given query conditions.
971
-     *
972
-     * @param null  $field_to_order_by  What field is being used as the reference point.
973
-     * @param array $query_params       Any additional conditions on the query.
974
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
975
-     *                                  you can indicate just the column you want returned
976
-     * @return array|EE_Base_Class
977
-     * @throws \EE_Error
978
-     */
979
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
980
-    {
981
-        $field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
982
-            ? $this->get_model()->get_primary_key_field()->get_name()
983
-            : $field_to_order_by;
984
-        $current_value = ! empty($field) ? $this->get($field) : null;
985
-        if (empty($field) || empty($current_value)) {
986
-            return array();
987
-        }
988
-        return $this->get_model()->previous($current_value, $field, $query_params, $columns_to_select);
989
-    }
990
-
991
-
992
-
993
-    /**
994
-     * Overrides parent because parent expects old models.
995
-     * This also doesn't do any validation, and won't work for serialized arrays
996
-     *
997
-     * @param string $field_name
998
-     * @param mixed  $field_value_from_db
999
-     * @throws \EE_Error
1000
-     */
1001
-    public function set_from_db($field_name, $field_value_from_db)
1002
-    {
1003
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1004
-        if ($field_obj instanceof EE_Model_Field_Base) {
1005
-            //you would think the DB has no NULLs for non-null label fields right? wrong!
1006
-            //eg, a CPT model object could have an entry in the posts table, but no
1007
-            //entry in the meta table. Meaning that all its columns in the meta table
1008
-            //are null! yikes! so when we find one like that, use defaults for its meta columns
1009
-            if ($field_value_from_db === null) {
1010
-                if ($field_obj->is_nullable()) {
1011
-                    //if the field allows nulls, then let it be null
1012
-                    $field_value = null;
1013
-                } else {
1014
-                    $field_value = $field_obj->get_default_value();
1015
-                }
1016
-            } else {
1017
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1018
-            }
1019
-            $this->_fields[$field_name] = $field_value;
1020
-            $this->_clear_cached_property($field_name);
1021
-        }
1022
-    }
1023
-
1024
-
1025
-
1026
-    /**
1027
-     * verifies that the specified field is of the correct type
1028
-     *
1029
-     * @param string $field_name
1030
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1031
-     *                                (in cases where the same property may be used for different outputs
1032
-     *                                - i.e. datetime, money etc.)
1033
-     * @return mixed
1034
-     * @throws \EE_Error
1035
-     */
1036
-    public function get($field_name, $extra_cache_ref = null)
1037
-    {
1038
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1039
-    }
1040
-
1041
-
1042
-
1043
-    /**
1044
-     * This method simply returns the RAW unprocessed value for the given property in this class
1045
-     *
1046
-     * @param  string $field_name A valid fieldname
1047
-     * @return mixed              Whatever the raw value stored on the property is.
1048
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1049
-     */
1050
-    public function get_raw($field_name)
1051
-    {
1052
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1053
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1054
-            ? $this->_fields[$field_name]->format('U')
1055
-            : $this->_fields[$field_name];
1056
-    }
1057
-
1058
-
1059
-
1060
-    /**
1061
-     * This is used to return the internal DateTime object used for a field that is a
1062
-     * EE_Datetime_Field.
1063
-     *
1064
-     * @param string $field_name               The field name retrieving the DateTime object.
1065
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1066
-     * @throws \EE_Error
1067
-     *                                         an error is set and false returned.  If the field IS an
1068
-     *                                         EE_Datetime_Field and but the field value is null, then
1069
-     *                                         just null is returned (because that indicates that likely
1070
-     *                                         this field is nullable).
1071
-     */
1072
-    public function get_DateTime_object($field_name)
1073
-    {
1074
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1075
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1076
-            EE_Error::add_error(
1077
-                sprintf(
1078
-                    __(
1079
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1080
-                        'event_espresso'
1081
-                    ),
1082
-                    $field_name
1083
-                ),
1084
-                __FILE__,
1085
-                __FUNCTION__,
1086
-                __LINE__
1087
-            );
1088
-            return false;
1089
-        }
1090
-        return $this->_fields[$field_name];
1091
-    }
1092
-
1093
-
1094
-
1095
-    /**
1096
-     * To be used in template to immediately echo out the value, and format it for output.
1097
-     * Eg, should call stripslashes and whatnot before echoing
1098
-     *
1099
-     * @param string $field_name      the name of the field as it appears in the DB
1100
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1101
-     *                                (in cases where the same property may be used for different outputs
1102
-     *                                - i.e. datetime, money etc.)
1103
-     * @return void
1104
-     * @throws \EE_Error
1105
-     */
1106
-    public function e($field_name, $extra_cache_ref = null)
1107
-    {
1108
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1109
-    }
1110
-
1111
-
1112
-
1113
-    /**
1114
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1115
-     * can be easily used as the value of form input.
1116
-     *
1117
-     * @param string $field_name
1118
-     * @return void
1119
-     * @throws \EE_Error
1120
-     */
1121
-    public function f($field_name)
1122
-    {
1123
-        $this->e($field_name, 'form_input');
1124
-    }
1125
-
1126
-
1127
-
1128
-    /**
1129
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1130
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1131
-     * to see what options are available.
1132
-     * @param string $field_name
1133
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1134
-     *                                (in cases where the same property may be used for different outputs
1135
-     *                                - i.e. datetime, money etc.)
1136
-     * @return mixed
1137
-     * @throws \EE_Error
1138
-     */
1139
-    public function get_pretty($field_name, $extra_cache_ref = null)
1140
-    {
1141
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1142
-    }
1143
-
1144
-
1145
-
1146
-    /**
1147
-     * This simply returns the datetime for the given field name
1148
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1149
-     * (and the equivalent e_date, e_time, e_datetime).
1150
-     *
1151
-     * @access   protected
1152
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1153
-     * @param string   $dt_frmt      valid datetime format used for date
1154
-     *                               (if '' then we just use the default on the field,
1155
-     *                               if NULL we use the last-used format)
1156
-     * @param string   $tm_frmt      Same as above except this is for time format
1157
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1158
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1159
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1160
-     *                               if field is not a valid dtt field, or void if echoing
1161
-     * @throws \EE_Error
1162
-     */
1163
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1164
-    {
1165
-        // clear cached property
1166
-        $this->_clear_cached_property($field_name);
1167
-        //reset format properties because they are used in get()
1168
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1169
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1170
-        if ($echo) {
1171
-            $this->e($field_name, $date_or_time);
1172
-            return '';
1173
-        }
1174
-        return $this->get($field_name, $date_or_time);
1175
-    }
1176
-
1177
-
1178
-
1179
-    /**
1180
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1181
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1182
-     * other echoes the pretty value for dtt)
1183
-     *
1184
-     * @param  string $field_name name of model object datetime field holding the value
1185
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1186
-     * @return string            datetime value formatted
1187
-     * @throws \EE_Error
1188
-     */
1189
-    public function get_date($field_name, $format = '')
1190
-    {
1191
-        return $this->_get_datetime($field_name, $format, null, 'D');
1192
-    }
1193
-
1194
-
1195
-
1196
-    /**
1197
-     * @param      $field_name
1198
-     * @param string $format
1199
-     * @throws \EE_Error
1200
-     */
1201
-    public function e_date($field_name, $format = '')
1202
-    {
1203
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1204
-    }
1205
-
1206
-
1207
-
1208
-    /**
1209
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1210
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1211
-     * other echoes the pretty value for dtt)
1212
-     *
1213
-     * @param  string $field_name name of model object datetime field holding the value
1214
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1215
-     * @return string             datetime value formatted
1216
-     * @throws \EE_Error
1217
-     */
1218
-    public function get_time($field_name, $format = '')
1219
-    {
1220
-        return $this->_get_datetime($field_name, null, $format, 'T');
1221
-    }
1222
-
1223
-
1224
-
1225
-    /**
1226
-     * @param      $field_name
1227
-     * @param string $format
1228
-     * @throws \EE_Error
1229
-     */
1230
-    public function e_time($field_name, $format = '')
1231
-    {
1232
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1233
-    }
1234
-
1235
-
1236
-
1237
-    /**
1238
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1239
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1240
-     * other echoes the pretty value for dtt)
1241
-     *
1242
-     * @param  string $field_name name of model object datetime field holding the value
1243
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1244
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1245
-     * @return string             datetime value formatted
1246
-     * @throws \EE_Error
1247
-     */
1248
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1249
-    {
1250
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1251
-    }
1252
-
1253
-
1254
-
1255
-    /**
1256
-     * @param string $field_name
1257
-     * @param string $dt_frmt
1258
-     * @param string $tm_frmt
1259
-     * @throws \EE_Error
1260
-     */
1261
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1262
-    {
1263
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1264
-    }
1265
-
1266
-
1267
-
1268
-    /**
1269
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1270
-     *
1271
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1272
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1273
-     *                           on the object will be used.
1274
-     * @return string Date and time string in set locale or false if no field exists for the given
1275
-     * @throws \EE_Error
1276
-     *                           field name.
1277
-     */
1278
-    public function get_i18n_datetime($field_name, $format = '')
1279
-    {
1280
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1281
-        return date_i18n(
1282
-            $format,
1283
-            EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1284
-        );
1285
-    }
1286
-
1287
-
1288
-
1289
-    /**
1290
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1291
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1292
-     * thrown.
1293
-     *
1294
-     * @param  string $field_name The field name being checked
1295
-     * @throws EE_Error
1296
-     * @return EE_Datetime_Field
1297
-     */
1298
-    protected function _get_dtt_field_settings($field_name)
1299
-    {
1300
-        $field = $this->get_model()->field_settings_for($field_name);
1301
-        //check if field is dtt
1302
-        if ($field instanceof EE_Datetime_Field) {
1303
-            return $field;
1304
-        } else {
1305
-            throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1306
-                'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1307
-        }
1308
-    }
1309
-
1310
-
1311
-
1312
-
1313
-    /**
1314
-     * NOTE ABOUT BELOW:
1315
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1316
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1317
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1318
-     * method and make sure you send the entire datetime value for setting.
1319
-     */
1320
-    /**
1321
-     * sets the time on a datetime property
1322
-     *
1323
-     * @access protected
1324
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1325
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1326
-     * @throws \EE_Error
1327
-     */
1328
-    protected function _set_time_for($time, $fieldname)
1329
-    {
1330
-        $this->_set_date_time('T', $time, $fieldname);
1331
-    }
1332
-
1333
-
1334
-
1335
-    /**
1336
-     * sets the date on a datetime property
1337
-     *
1338
-     * @access protected
1339
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1340
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1341
-     * @throws \EE_Error
1342
-     */
1343
-    protected function _set_date_for($date, $fieldname)
1344
-    {
1345
-        $this->_set_date_time('D', $date, $fieldname);
1346
-    }
1347
-
1348
-
1349
-
1350
-    /**
1351
-     * This takes care of setting a date or time independently on a given model object property. This method also
1352
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1353
-     *
1354
-     * @access protected
1355
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1356
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1357
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1358
-     *                                        EE_Datetime_Field property)
1359
-     * @throws \EE_Error
1360
-     */
1361
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1362
-    {
1363
-        $field = $this->_get_dtt_field_settings($fieldname);
1364
-        $field->set_timezone($this->_timezone);
1365
-        $field->set_date_format($this->_dt_frmt);
1366
-        $field->set_time_format($this->_tm_frmt);
1367
-        switch ($what) {
1368
-            case 'T' :
1369
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1370
-                    $datetime_value,
1371
-                    $this->_fields[$fieldname]
1372
-                );
1373
-                break;
1374
-            case 'D' :
1375
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1376
-                    $datetime_value,
1377
-                    $this->_fields[$fieldname]
1378
-                );
1379
-                break;
1380
-            case 'B' :
1381
-                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1382
-                break;
1383
-        }
1384
-        $this->_clear_cached_property($fieldname);
1385
-    }
1386
-
1387
-
1388
-
1389
-    /**
1390
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1391
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1392
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1393
-     * that could lead to some unexpected results!
1394
-     *
1395
-     * @access public
1396
-     * @param string               $field_name This is the name of the field on the object that contains the date/time
1397
-     *                                         value being returned.
1398
-     * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1399
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1400
-     * @param string               $prepend    You can include something to prepend on the timestamp
1401
-     * @param string               $append     You can include something to append on the timestamp
1402
-     * @throws EE_Error
1403
-     * @return string timestamp
1404
-     */
1405
-    public function display_in_my_timezone(
1406
-        $field_name,
1407
-        $callback = 'get_datetime',
1408
-        $args = null,
1409
-        $prepend = '',
1410
-        $append = ''
1411
-    ) {
1412
-        $timezone = EEH_DTT_Helper::get_timezone();
1413
-        if ($timezone === $this->_timezone) {
1414
-            return '';
1415
-        }
1416
-        $original_timezone = $this->_timezone;
1417
-        $this->set_timezone($timezone);
1418
-        $fn = (array)$field_name;
1419
-        $args = array_merge($fn, (array)$args);
1420
-        if ( ! method_exists($this, $callback)) {
1421
-            throw new EE_Error(
1422
-                sprintf(
1423
-                    __(
1424
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1425
-                        'event_espresso'
1426
-                    ),
1427
-                    $callback
1428
-                )
1429
-            );
1430
-        }
1431
-        $args = (array)$args;
1432
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1433
-        $this->set_timezone($original_timezone);
1434
-        return $return;
1435
-    }
1436
-
1437
-
1438
-
1439
-    /**
1440
-     * Deletes this model object.
1441
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1442
-     * override
1443
-     * `EE_Base_Class::_delete` NOT this class.
1444
-     *
1445
-     * @return boolean | int
1446
-     * @throws \EE_Error
1447
-     */
1448
-    public function delete()
1449
-    {
1450
-        /**
1451
-         * Called just before the `EE_Base_Class::_delete` method call.
1452
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1453
-         * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1454
-         * soft deletes (trash) the object and does not permanently delete it.
1455
-         *
1456
-         * @param EE_Base_Class $model_object about to be 'deleted'
1457
-         */
1458
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1459
-        $result = $this->_delete();
1460
-        /**
1461
-         * Called just after the `EE_Base_Class::_delete` method call.
1462
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1463
-         * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1464
-         * soft deletes (trash) the object and does not permanently delete it.
1465
-         *
1466
-         * @param EE_Base_Class $model_object that was just 'deleted'
1467
-         * @param boolean       $result
1468
-         */
1469
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1470
-        return $result;
1471
-    }
1472
-
1473
-
1474
-
1475
-    /**
1476
-     * Calls the specific delete method for the instantiated class.
1477
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1478
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1479
-     * `EE_Base_Class::delete`
1480
-     *
1481
-     * @return bool|int
1482
-     * @throws \EE_Error
1483
-     */
1484
-    protected function _delete()
1485
-    {
1486
-        return $this->delete_permanently();
1487
-    }
1488
-
1489
-
1490
-
1491
-    /**
1492
-     * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1493
-     * error)
1494
-     *
1495
-     * @return bool | int
1496
-     * @throws \EE_Error
1497
-     */
1498
-    public function delete_permanently()
1499
-    {
1500
-        /**
1501
-         * Called just before HARD deleting a model object
1502
-         *
1503
-         * @param EE_Base_Class $model_object about to be 'deleted'
1504
-         */
1505
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1506
-        $model = $this->get_model();
1507
-        $result = $model->delete_permanently_by_ID($this->ID());
1508
-        $this->refresh_cache_of_related_objects();
1509
-        /**
1510
-         * Called just after HARD deleting a model object
1511
-         *
1512
-         * @param EE_Base_Class $model_object that was just 'deleted'
1513
-         * @param boolean       $result
1514
-         */
1515
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1516
-        return $result;
1517
-    }
1518
-
1519
-
1520
-
1521
-    /**
1522
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1523
-     * related model objects
1524
-     *
1525
-     * @throws \EE_Error
1526
-     */
1527
-    public function refresh_cache_of_related_objects()
1528
-    {
1529
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1530
-            if ( ! empty($this->_model_relations[$relation_name])) {
1531
-                $related_objects = $this->_model_relations[$relation_name];
1532
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1533
-                    //this relation only stores a single model object, not an array
1534
-                    //but let's make it consistent
1535
-                    $related_objects = array($related_objects);
1536
-                }
1537
-                foreach ($related_objects as $related_object) {
1538
-                    //only refresh their cache if they're in memory
1539
-                    if ($related_object instanceof EE_Base_Class) {
1540
-                        $related_object->clear_cache($this->get_model()->get_this_model_name(), $this);
1541
-                    }
1542
-                }
1543
-            }
1544
-        }
1545
-    }
1546
-
1547
-
1548
-
1549
-    /**
1550
-     *        Saves this object to the database. An array may be supplied to set some values on this
1551
-     * object just before saving.
1552
-     *
1553
-     * @access public
1554
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1555
-     *                                 if provided during the save() method (often client code will change the fields'
1556
-     *                                 values before calling save)
1557
-     * @throws \EE_Error
1558
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1559
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1560
-     */
1561
-    public function save($set_cols_n_values = array())
1562
-    {
1563
-        /**
1564
-         * Filters the fields we're about to save on the model object
1565
-         *
1566
-         * @param array         $set_cols_n_values
1567
-         * @param EE_Base_Class $model_object
1568
-         */
1569
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1570
-            $this);
1571
-        //set attributes as provided in $set_cols_n_values
1572
-        foreach ($set_cols_n_values as $column => $value) {
1573
-            $this->set($column, $value);
1574
-        }
1575
-        // no changes ? then don't do anything
1576
-        if (! $this->_has_changes && $this->ID() && $this->get_model()->get_primary_key_field()->is_auto_increment()) {
1577
-            return 0;
1578
-        }
1579
-        /**
1580
-         * Saving a model object.
1581
-         * Before we perform a save, this action is fired.
1582
-         *
1583
-         * @param EE_Base_Class $model_object the model object about to be saved.
1584
-         */
1585
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1586
-        if ( ! $this->allow_persist()) {
1587
-            return 0;
1588
-        }
1589
-        //now get current attribute values
1590
-        $save_cols_n_values = $this->_fields;
1591
-        //if the object already has an ID, update it. Otherwise, insert it
1592
-        //also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1593
-        $old_assumption_concerning_value_preparation = $this->get_model()
1594
-                                                            ->get_assumption_concerning_values_already_prepared_by_model_object();
1595
-        $this->get_model()->assume_values_already_prepared_by_model_object(true);
1596
-        //does this model have an autoincrement PK?
1597
-        if ($this->get_model()->has_primary_key_field()) {
1598
-            if ($this->get_model()->get_primary_key_field()->is_auto_increment()) {
1599
-                //ok check if it's set, if so: update; if not, insert
1600
-                if ( ! empty($save_cols_n_values[self::_get_primary_key_name(get_class($this))])) {
1601
-                    $results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1602
-                } else {
1603
-                    unset($save_cols_n_values[self::_get_primary_key_name(get_class($this))]);
1604
-                    $results = $this->get_model()->insert($save_cols_n_values);
1605
-                    if ($results) {
1606
-                        //if successful, set the primary key
1607
-                        //but don't use the normal SET method, because it will check if
1608
-                        //an item with the same ID exists in the mapper & db, then
1609
-                        //will find it in the db (because we just added it) and THAT object
1610
-                        //will get added to the mapper before we can add this one!
1611
-                        //but if we just avoid using the SET method, all that headache can be avoided
1612
-                        $pk_field_name = self::_get_primary_key_name(get_class($this));
1613
-                        $this->_fields[$pk_field_name] = $results;
1614
-                        $this->_clear_cached_property($pk_field_name);
1615
-                        $this->get_model()->add_to_entity_map($this);
1616
-                        $this->_update_cached_related_model_objs_fks();
1617
-                    }
1618
-                }
1619
-            } else {//PK is NOT auto-increment
1620
-                //so check if one like it already exists in the db
1621
-                if ($this->get_model()->exists_by_ID($this->ID())) {
1622
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1623
-                        throw new EE_Error(
1624
-                            sprintf(
1625
-                                __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1626
-                                    'event_espresso'),
1627
-                                get_class($this),
1628
-                                get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1629
-                                get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1630
-                                '<br />'
1631
-                            )
1632
-                        );
1633
-                    }
1634
-                    $results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1635
-                } else {
1636
-                    $results = $this->get_model()->insert($save_cols_n_values);
1637
-                    $this->_update_cached_related_model_objs_fks();
1638
-                }
1639
-            }
1640
-        } else {//there is NO primary key
1641
-            $already_in_db = false;
1642
-            foreach ($this->get_model()->unique_indexes() as $index) {
1643
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1644
-                if ($this->get_model()->exists(array($uniqueness_where_params))) {
1645
-                    $already_in_db = true;
1646
-                }
1647
-            }
1648
-            if ($already_in_db) {
1649
-                $combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1650
-                    $this->get_model()->get_combined_primary_key_fields());
1651
-                $results = $this->get_model()->update($save_cols_n_values, $combined_pk_fields_n_values);
1652
-            } else {
1653
-                $results = $this->get_model()->insert($save_cols_n_values);
1654
-            }
1655
-        }
1656
-        //restore the old assumption about values being prepared by the model object
1657
-        $this->get_model()
1658
-             ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1659
-        /**
1660
-         * After saving the model object this action is called
1661
-         *
1662
-         * @param EE_Base_Class $model_object which was just saved
1663
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1664
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1665
-         */
1666
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1667
-        $this->_has_changes = false;
1668
-        return $results;
1669
-    }
1670
-
1671
-
1672
-
1673
-    /**
1674
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1675
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1676
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1677
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1678
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1679
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1680
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1681
-     *
1682
-     * @return void
1683
-     * @throws \EE_Error
1684
-     */
1685
-    protected function _update_cached_related_model_objs_fks()
1686
-    {
1687
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1688
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1689
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1690
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1691
-                        $this->get_model()->get_this_model_name()
1692
-                    );
1693
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1694
-                    if ($related_model_obj_in_cache->ID()) {
1695
-                        $related_model_obj_in_cache->save();
1696
-                    }
1697
-                }
1698
-            }
1699
-        }
1700
-    }
1701
-
1702
-
1703
-
1704
-    /**
1705
-     * Saves this model object and its NEW cached relations to the database.
1706
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1707
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1708
-     * because otherwise, there's a potential for infinite looping of saving
1709
-     * Saves the cached related model objects, and ensures the relation between them
1710
-     * and this object and properly setup
1711
-     *
1712
-     * @return int ID of new model object on save; 0 on failure+
1713
-     * @throws \EE_Error
1714
-     */
1715
-    public function save_new_cached_related_model_objs()
1716
-    {
1717
-        //make sure this has been saved
1718
-        if ( ! $this->ID()) {
1719
-            $id = $this->save();
1720
-        } else {
1721
-            $id = $this->ID();
1722
-        }
1723
-        //now save all the NEW cached model objects  (ie they don't exist in the DB)
1724
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1725
-            if ($this->_model_relations[$relationName]) {
1726
-                //is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1727
-                //or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1728
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1729
-                    //add a relation to that relation type (which saves the appropriate thing in the process)
1730
-                    //but ONLY if it DOES NOT exist in the DB
1731
-                    /* @var $related_model_obj EE_Base_Class */
1732
-                    $related_model_obj = $this->_model_relations[$relationName];
1733
-                    //					if( ! $related_model_obj->ID()){
1734
-                    $this->_add_relation_to($related_model_obj, $relationName);
1735
-                    $related_model_obj->save_new_cached_related_model_objs();
1736
-                    //					}
1737
-                } else {
1738
-                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1739
-                        //add a relation to that relation type (which saves the appropriate thing in the process)
1740
-                        //but ONLY if it DOES NOT exist in the DB
1741
-                        //						if( ! $related_model_obj->ID()){
1742
-                        $this->_add_relation_to($related_model_obj, $relationName);
1743
-                        $related_model_obj->save_new_cached_related_model_objs();
1744
-                        //						}
1745
-                    }
1746
-                }
1747
-            }
1748
-        }
1749
-        return $id;
1750
-    }
1751
-
1752
-
1753
-
1754
-    /**
1755
-     * for getting a model while instantiated.
1756
-     *
1757
-     * @return \EEM_Base | \EEM_CPT_Base
1758
-     */
1759
-    public function get_model()
1760
-    {
1761
-        $modelName = self::_get_model_classname(get_class($this));
1762
-        return self::_get_model_instance_with_name($modelName, $this->_timezone);
1763
-    }
1764
-
1765
-
1766
-
1767
-    /**
1768
-     * @param $props_n_values
1769
-     * @param $classname
1770
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1771
-     * @throws \EE_Error
1772
-     */
1773
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1774
-    {
1775
-        //TODO: will not work for Term_Relationships because they have no PK!
1776
-        $primary_id_ref = self::_get_primary_key_name($classname);
1777
-        if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1778
-            $id = $props_n_values[$primary_id_ref];
1779
-            return self::_get_model($classname)->get_from_entity_map($id);
1780
-        }
1781
-        return false;
1782
-    }
1783
-
1784
-
1785
-
1786
-    /**
1787
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1788
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1789
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1790
-     * we return false.
1791
-     *
1792
-     * @param  array  $props_n_values   incoming array of properties and their values
1793
-     * @param  string $classname        the classname of the child class
1794
-     * @param null    $timezone
1795
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
1796
-     *                                  date_format and the second value is the time format
1797
-     * @return mixed (EE_Base_Class|bool)
1798
-     * @throws \EE_Error
1799
-     */
1800
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1801
-    {
1802
-        $existing = null;
1803
-        if (self::_get_model($classname)->has_primary_key_field()) {
1804
-            $primary_id_ref = self::_get_primary_key_name($classname);
1805
-            if (array_key_exists($primary_id_ref, $props_n_values)
1806
-                && ! empty($props_n_values[$primary_id_ref])
1807
-            ) {
1808
-                $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1809
-                    $props_n_values[$primary_id_ref]
1810
-                );
1811
-            }
1812
-        } elseif (self::_get_model($classname, $timezone)->has_all_combined_primary_key_fields($props_n_values)) {
1813
-            //no primary key on this model, but there's still a matching item in the DB
1814
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1815
-                self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1816
-            );
1817
-        }
1818
-        if ($existing) {
1819
-            //set date formats if present before setting values
1820
-            if ( ! empty($date_formats) && is_array($date_formats)) {
1821
-                $existing->set_date_format($date_formats[0]);
1822
-                $existing->set_time_format($date_formats[1]);
1823
-            } else {
1824
-                //set default formats for date and time
1825
-                $existing->set_date_format(get_option('date_format'));
1826
-                $existing->set_time_format(get_option('time_format'));
1827
-            }
1828
-            foreach ($props_n_values as $property => $field_value) {
1829
-                $existing->set($property, $field_value);
1830
-            }
1831
-            return $existing;
1832
-        } else {
1833
-            return false;
1834
-        }
1835
-    }
1836
-
1837
-
1838
-
1839
-    /**
1840
-     * Gets the EEM_*_Model for this class
1841
-     *
1842
-     * @access public now, as this is more convenient
1843
-     * @param      $classname
1844
-     * @param null $timezone
1845
-     * @throws EE_Error
1846
-     * @return EEM_Base
1847
-     */
1848
-    protected static function _get_model($classname, $timezone = null)
1849
-    {
1850
-        //find model for this class
1851
-        if ( ! $classname) {
1852
-            throw new EE_Error(
1853
-                sprintf(
1854
-                    __(
1855
-                        "What were you thinking calling _get_model(%s)?? You need to specify the class name",
1856
-                        "event_espresso"
1857
-                    ),
1858
-                    $classname
1859
-                )
1860
-            );
1861
-        }
1862
-        $modelName = self::_get_model_classname($classname);
1863
-        return self::_get_model_instance_with_name($modelName, $timezone);
1864
-    }
1865
-
1866
-
1867
-
1868
-    /**
1869
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1870
-     *
1871
-     * @param string $model_classname
1872
-     * @param null   $timezone
1873
-     * @return EEM_Base
1874
-     */
1875
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1876
-    {
1877
-        $model_classname = str_replace('EEM_', '', $model_classname);
1878
-        $model = EE_Registry::instance()->load_model($model_classname);
1879
-        $model->set_timezone($timezone);
1880
-        return $model;
1881
-    }
1882
-
1883
-
1884
-
1885
-    /**
1886
-     * If a model name is provided (eg Registration), gets the model classname for that model.
1887
-     * Also works if a model class's classname is provided (eg EE_Registration).
1888
-     *
1889
-     * @param null $model_name
1890
-     * @return string like EEM_Attendee
1891
-     */
1892
-    private static function _get_model_classname($model_name = null)
1893
-    {
1894
-        if (strpos($model_name, "EE_") === 0) {
1895
-            $model_classname = str_replace("EE_", "EEM_", $model_name);
1896
-        } else {
1897
-            $model_classname = "EEM_" . $model_name;
1898
-        }
1899
-        return $model_classname;
1900
-    }
1901
-
1902
-
1903
-
1904
-    /**
1905
-     * returns the name of the primary key attribute
1906
-     *
1907
-     * @param null $classname
1908
-     * @throws EE_Error
1909
-     * @return string
1910
-     */
1911
-    protected static function _get_primary_key_name($classname = null)
1912
-    {
1913
-        if ( ! $classname) {
1914
-            throw new EE_Error(
1915
-                sprintf(
1916
-                    __("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1917
-                    $classname
1918
-                )
1919
-            );
1920
-        }
1921
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
1922
-    }
1923
-
1924
-
1925
-
1926
-    /**
1927
-     * Gets the value of the primary key.
1928
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
1929
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
1930
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
1931
-     *
1932
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
1933
-     * @throws \EE_Error
1934
-     */
1935
-    public function ID()
1936
-    {
1937
-        //now that we know the name of the variable, use a variable variable to get its value and return its
1938
-        if ($this->get_model()->has_primary_key_field()) {
1939
-            return $this->_fields[self::_get_primary_key_name(get_class($this))];
1940
-        } else {
1941
-            return $this->get_model()->get_index_primary_key_string($this->_fields);
1942
-        }
1943
-    }
1944
-
1945
-
1946
-
1947
-    /**
1948
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
1949
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
1950
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
1951
-     *
1952
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
1953
-     * @param string $relationName                     eg 'Events','Question',etc.
1954
-     *                                                 an attendee to a group, you also want to specify which role they
1955
-     *                                                 will have in that group. So you would use this parameter to
1956
-     *                                                 specify array('role-column-name'=>'role-id')
1957
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
1958
-     *                                                 allow you to further constrict the relation to being added.
1959
-     *                                                 However, keep in mind that the columns (keys) given must match a
1960
-     *                                                 column on the JOIN table and currently only the HABTM models
1961
-     *                                                 accept these additional conditions.  Also remember that if an
1962
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
1963
-     *                                                 NEW row is created in the join table.
1964
-     * @param null   $cache_id
1965
-     * @throws EE_Error
1966
-     * @return EE_Base_Class the object the relation was added to
1967
-     */
1968
-    public function _add_relation_to(
1969
-        $otherObjectModelObjectOrID,
1970
-        $relationName,
1971
-        $extra_join_model_fields_n_values = array(),
1972
-        $cache_id = null
1973
-    ) {
1974
-        //if this thing exists in the DB, save the relation to the DB
1975
-        if ($this->ID()) {
1976
-            $otherObject = $this->get_model()
1977
-                                ->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
1978
-                                    $extra_join_model_fields_n_values);
1979
-            //clear cache so future get_many_related and get_first_related() return new results.
1980
-            $this->clear_cache($relationName, $otherObject, true);
1981
-            if ($otherObject instanceof EE_Base_Class) {
1982
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1983
-            }
1984
-        } else {
1985
-            //this thing doesn't exist in the DB,  so just cache it
1986
-            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
1987
-                throw new EE_Error(sprintf(
1988
-                    __('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
1989
-                        'event_espresso'),
1990
-                    $otherObjectModelObjectOrID,
1991
-                    get_class($this)
1992
-                ));
1993
-            } else {
1994
-                $otherObject = $otherObjectModelObjectOrID;
1995
-            }
1996
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
1997
-        }
1998
-        if ($otherObject instanceof EE_Base_Class) {
1999
-            //fix the reciprocal relation too
2000
-            if ($otherObject->ID()) {
2001
-                //its saved so assumed relations exist in the DB, so we can just
2002
-                //clear the cache so future queries use the updated info in the DB
2003
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), null, true);
2004
-            } else {
2005
-                //it's not saved, so it caches relations like this
2006
-                $otherObject->cache($this->get_model()->get_this_model_name(), $this);
2007
-            }
2008
-        }
2009
-        return $otherObject;
2010
-    }
2011
-
2012
-
2013
-
2014
-    /**
2015
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2016
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2017
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2018
-     * from the cache
2019
-     *
2020
-     * @param mixed  $otherObjectModelObjectOrID
2021
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2022
-     *                to the DB yet
2023
-     * @param string $relationName
2024
-     * @param array  $where_query
2025
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2026
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2027
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2028
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2029
-     *                created in the join table.
2030
-     * @return EE_Base_Class the relation was removed from
2031
-     * @throws \EE_Error
2032
-     */
2033
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2034
-    {
2035
-        if ($this->ID()) {
2036
-            //if this exists in the DB, save the relation change to the DB too
2037
-            $otherObject = $this->get_model()
2038
-                                ->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2039
-                                    $where_query);
2040
-            $this->clear_cache($relationName, $otherObject);
2041
-        } else {
2042
-            //this doesn't exist in the DB, just remove it from the cache
2043
-            $otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2044
-        }
2045
-        if ($otherObject instanceof EE_Base_Class) {
2046
-            $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2047
-        }
2048
-        return $otherObject;
2049
-    }
2050
-
2051
-
2052
-
2053
-    /**
2054
-     * Removes ALL the related things for the $relationName.
2055
-     *
2056
-     * @param string $relationName
2057
-     * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2058
-     * @return EE_Base_Class
2059
-     * @throws \EE_Error
2060
-     */
2061
-    public function _remove_relations($relationName, $where_query_params = array())
2062
-    {
2063
-        if ($this->ID()) {
2064
-            //if this exists in the DB, save the relation change to the DB too
2065
-            $otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2066
-            $this->clear_cache($relationName, null, true);
2067
-        } else {
2068
-            //this doesn't exist in the DB, just remove it from the cache
2069
-            $otherObjects = $this->clear_cache($relationName, null, true);
2070
-        }
2071
-        if (is_array($otherObjects)) {
2072
-            foreach ($otherObjects as $otherObject) {
2073
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2074
-            }
2075
-        }
2076
-        return $otherObjects;
2077
-    }
2078
-
2079
-
2080
-
2081
-    /**
2082
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2083
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2084
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2085
-     * because we want to get even deleted items etc.
2086
-     *
2087
-     * @param string $relationName key in the model's _model_relations array
2088
-     * @param array  $query_params like EEM_Base::get_all
2089
-     * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2090
-     * @throws \EE_Error
2091
-     *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2092
-     *                             you want IDs
2093
-     */
2094
-    public function get_many_related($relationName, $query_params = array())
2095
-    {
2096
-        if ($this->ID()) {
2097
-            //this exists in the DB, so get the related things from either the cache or the DB
2098
-            //if there are query parameters, forget about caching the related model objects.
2099
-            if ($query_params) {
2100
-                $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2101
-            } else {
2102
-                //did we already cache the result of this query?
2103
-                $cached_results = $this->get_all_from_cache($relationName);
2104
-                if ( ! $cached_results) {
2105
-                    $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2106
-                    //if no query parameters were passed, then we got all the related model objects
2107
-                    //for that relation. We can cache them then.
2108
-                    foreach ($related_model_objects as $related_model_object) {
2109
-                        $this->cache($relationName, $related_model_object);
2110
-                    }
2111
-                } else {
2112
-                    $related_model_objects = $cached_results;
2113
-                }
2114
-            }
2115
-        } else {
2116
-            //this doesn't exist in the DB, so just get the related things from the cache
2117
-            $related_model_objects = $this->get_all_from_cache($relationName);
2118
-        }
2119
-        return $related_model_objects;
2120
-    }
2121
-
2122
-
2123
-
2124
-    /**
2125
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2126
-     * unless otherwise specified in the $query_params
2127
-     *
2128
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2129
-     * @param array  $query_params   like EEM_Base::get_all's
2130
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2131
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2132
-     *                               that by the setting $distinct to TRUE;
2133
-     * @return int
2134
-     */
2135
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2136
-    {
2137
-        return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2138
-    }
2139
-
2140
-
2141
-
2142
-    /**
2143
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2144
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2145
-     *
2146
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2147
-     * @param array  $query_params  like EEM_Base::get_all's
2148
-     * @param string $field_to_sum  name of field to count by.
2149
-     *                              By default, uses primary key (which doesn't make much sense, so you should probably
2150
-     *                              change it)
2151
-     * @return int
2152
-     */
2153
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2154
-    {
2155
-        return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2156
-    }
2157
-
2158
-
2159
-
2160
-    /**
2161
-     * Gets the first (ie, one) related model object of the specified type.
2162
-     *
2163
-     * @param string $relationName key in the model's _model_relations array
2164
-     * @param array  $query_params like EEM_Base::get_all
2165
-     * @return EE_Base_Class (not an array, a single object)
2166
-     * @throws \EE_Error
2167
-     */
2168
-    public function get_first_related($relationName, $query_params = array())
2169
-    {
2170
-        if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2171
-            //if they've provided some query parameters, don't bother trying to cache the result
2172
-            //also make sure we're not caching the result of get_first_related
2173
-            //on a relation which should have an array of objects (because the cache might have an array of objects)
2174
-            if ($query_params
2175
-                || ! $this->get_model()->related_settings_for($relationName)
2176
-                     instanceof
2177
-                     EE_Belongs_To_Relation
2178
-            ) {
2179
-                $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2180
-            } else {
2181
-                //first, check if we've already cached the result of this query
2182
-                $cached_result = $this->get_one_from_cache($relationName);
2183
-                if ( ! $cached_result) {
2184
-                    $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2185
-                    $this->cache($relationName, $related_model_object);
2186
-                } else {
2187
-                    $related_model_object = $cached_result;
2188
-                }
2189
-            }
2190
-        } else {
2191
-            $related_model_object = null;
2192
-            //this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2193
-            if ($this->get_model()->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2194
-                $related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2195
-            }
2196
-            //this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2197
-            if ( ! $related_model_object) {
2198
-                $related_model_object = $this->get_one_from_cache($relationName);
2199
-            }
2200
-        }
2201
-        return $related_model_object;
2202
-    }
2203
-
2204
-
2205
-
2206
-    /**
2207
-     * Does a delete on all related objects of type $relationName and removes
2208
-     * the current model object's relation to them. If they can't be deleted (because
2209
-     * of blocking related model objects) does nothing. If the related model objects are
2210
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2211
-     * If this model object doesn't exist yet in the DB, just removes its related things
2212
-     *
2213
-     * @param string $relationName
2214
-     * @param array  $query_params like EEM_Base::get_all's
2215
-     * @return int how many deleted
2216
-     * @throws \EE_Error
2217
-     */
2218
-    public function delete_related($relationName, $query_params = array())
2219
-    {
2220
-        if ($this->ID()) {
2221
-            $count = $this->get_model()->delete_related($this, $relationName, $query_params);
2222
-        } else {
2223
-            $count = count($this->get_all_from_cache($relationName));
2224
-            $this->clear_cache($relationName, null, true);
2225
-        }
2226
-        return $count;
2227
-    }
2228
-
2229
-
2230
-
2231
-    /**
2232
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2233
-     * the current model object's relation to them. If they can't be deleted (because
2234
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2235
-     * If the related thing isn't a soft-deletable model object, this function is identical
2236
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2237
-     *
2238
-     * @param string $relationName
2239
-     * @param array  $query_params like EEM_Base::get_all's
2240
-     * @return int how many deleted (including those soft deleted)
2241
-     * @throws \EE_Error
2242
-     */
2243
-    public function delete_related_permanently($relationName, $query_params = array())
2244
-    {
2245
-        if ($this->ID()) {
2246
-            $count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2247
-        } else {
2248
-            $count = count($this->get_all_from_cache($relationName));
2249
-        }
2250
-        $this->clear_cache($relationName, null, true);
2251
-        return $count;
2252
-    }
2253
-
2254
-
2255
-
2256
-    /**
2257
-     * is_set
2258
-     * Just a simple utility function children can use for checking if property exists
2259
-     *
2260
-     * @access  public
2261
-     * @param  string $field_name property to check
2262
-     * @return bool                              TRUE if existing,FALSE if not.
2263
-     */
2264
-    public function is_set($field_name)
2265
-    {
2266
-        return isset($this->_fields[$field_name]);
2267
-    }
2268
-
2269
-
2270
-
2271
-    /**
2272
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2273
-     * EE_Error exception if they don't
2274
-     *
2275
-     * @param  mixed (string|array) $properties properties to check
2276
-     * @throws EE_Error
2277
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2278
-     */
2279
-    protected function _property_exists($properties)
2280
-    {
2281
-        foreach ((array)$properties as $property_name) {
2282
-            //first make sure this property exists
2283
-            if ( ! $this->_fields[$property_name]) {
2284
-                throw new EE_Error(
2285
-                    sprintf(
2286
-                        __(
2287
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2288
-                            'event_espresso'
2289
-                        ),
2290
-                        $property_name
2291
-                    )
2292
-                );
2293
-            }
2294
-        }
2295
-        return true;
2296
-    }
2297
-
2298
-
2299
-
2300
-    /**
2301
-     * This simply returns an array of model fields for this object
2302
-     *
2303
-     * @return array
2304
-     * @throws \EE_Error
2305
-     */
2306
-    public function model_field_array()
2307
-    {
2308
-        $fields = $this->get_model()->field_settings(false);
2309
-        $properties = array();
2310
-        //remove prepended underscore
2311
-        foreach ($fields as $field_name => $settings) {
2312
-            $properties[$field_name] = $this->get($field_name);
2313
-        }
2314
-        return $properties;
2315
-    }
2316
-
2317
-
2318
-
2319
-    /**
2320
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2321
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2322
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2323
-     * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2324
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2325
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2326
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
2327
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
2328
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2329
-     * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2330
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2331
-     *        return $previousReturnValue.$returnString;
2332
-     * }
2333
-     * require('EE_Answer.class.php');
2334
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2335
-     * echo $answer->my_callback('monkeys',100);
2336
-     * //will output "you called my_callback! and passed args:monkeys,100"
2337
-     *
2338
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2339
-     * @param array  $args       array of original arguments passed to the function
2340
-     * @throws EE_Error
2341
-     * @return mixed whatever the plugin which calls add_filter decides
2342
-     */
2343
-    public function __call($methodName, $args)
2344
-    {
2345
-        $className = get_class($this);
2346
-        $tagName = "FHEE__{$className}__{$methodName}";
2347
-        if ( ! has_filter($tagName)) {
2348
-            throw new EE_Error(
2349
-                sprintf(
2350
-                    __(
2351
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2352
-                        "event_espresso"
2353
-                    ),
2354
-                    $methodName,
2355
-                    $className,
2356
-                    $tagName
2357
-                )
2358
-            );
2359
-        }
2360
-        return apply_filters($tagName, null, $this, $args);
2361
-    }
2362
-
2363
-
2364
-
2365
-    /**
2366
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2367
-     * A $previous_value can be specified in case there are many meta rows with the same key
2368
-     *
2369
-     * @param string $meta_key
2370
-     * @param mixed  $meta_value
2371
-     * @param mixed  $previous_value
2372
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2373
-     * @throws \EE_Error
2374
-     * NOTE: if the values haven't changed, returns 0
2375
-     */
2376
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2377
-    {
2378
-        $query_params = array(
2379
-            array(
2380
-                'EXM_key'  => $meta_key,
2381
-                'OBJ_ID'   => $this->ID(),
2382
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2383
-            ),
2384
-        );
2385
-        if ($previous_value !== null) {
2386
-            $query_params[0]['EXM_value'] = $meta_value;
2387
-        }
2388
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2389
-        if ( ! $existing_rows_like_that) {
2390
-            return $this->add_extra_meta($meta_key, $meta_value);
2391
-        }
2392
-        foreach ($existing_rows_like_that as $existing_row) {
2393
-            $existing_row->save(array('EXM_value' => $meta_value));
2394
-        }
2395
-        return count($existing_rows_like_that);
2396
-    }
2397
-
2398
-
2399
-
2400
-    /**
2401
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2402
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2403
-     * extra meta row was entered, false if not
2404
-     *
2405
-     * @param string  $meta_key
2406
-     * @param string  $meta_value
2407
-     * @param boolean $unique
2408
-     * @return boolean
2409
-     * @throws \EE_Error
2410
-     */
2411
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2412
-    {
2413
-        if ($unique) {
2414
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2415
-                array(
2416
-                    array(
2417
-                        'EXM_key'  => $meta_key,
2418
-                        'OBJ_ID'   => $this->ID(),
2419
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2420
-                    ),
2421
-                )
2422
-            );
2423
-            if ($existing_extra_meta) {
2424
-                return false;
2425
-            }
2426
-        }
2427
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2428
-            array(
2429
-                'EXM_key'   => $meta_key,
2430
-                'EXM_value' => $meta_value,
2431
-                'OBJ_ID'    => $this->ID(),
2432
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2433
-            )
2434
-        );
2435
-        $new_extra_meta->save();
2436
-        return true;
2437
-    }
2438
-
2439
-
2440
-
2441
-    /**
2442
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2443
-     * is specified, only deletes extra meta records with that value.
2444
-     *
2445
-     * @param string $meta_key
2446
-     * @param string $meta_value
2447
-     * @return int number of extra meta rows deleted
2448
-     * @throws \EE_Error
2449
-     */
2450
-    public function delete_extra_meta($meta_key, $meta_value = null)
2451
-    {
2452
-        $query_params = array(
2453
-            array(
2454
-                'EXM_key'  => $meta_key,
2455
-                'OBJ_ID'   => $this->ID(),
2456
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2457
-            ),
2458
-        );
2459
-        if ($meta_value !== null) {
2460
-            $query_params[0]['EXM_value'] = $meta_value;
2461
-        }
2462
-        return EEM_Extra_Meta::instance()->delete($query_params);
2463
-    }
2464
-
2465
-
2466
-
2467
-    /**
2468
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2469
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2470
-     * You can specify $default is case you haven't found the extra meta
2471
-     *
2472
-     * @param string  $meta_key
2473
-     * @param boolean $single
2474
-     * @param mixed   $default if we don't find anything, what should we return?
2475
-     * @return mixed single value if $single; array if ! $single
2476
-     * @throws \EE_Error
2477
-     */
2478
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2479
-    {
2480
-        if ($single) {
2481
-            $result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2482
-            if ($result instanceof EE_Extra_Meta) {
2483
-                return $result->value();
2484
-            } else {
2485
-                return $default;
2486
-            }
2487
-        } else {
2488
-            $results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2489
-            if ($results) {
2490
-                $values = array();
2491
-                foreach ($results as $result) {
2492
-                    if ($result instanceof EE_Extra_Meta) {
2493
-                        $values[$result->ID()] = $result->value();
2494
-                    }
2495
-                }
2496
-                return $values;
2497
-            } else {
2498
-                return $default;
2499
-            }
2500
-        }
2501
-    }
2502
-
2503
-
2504
-
2505
-    /**
2506
-     * Returns a simple array of all the extra meta associated with this model object.
2507
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2508
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2509
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2510
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2511
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2512
-     * finally the extra meta's value as each sub-value. (eg
2513
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2514
-     *
2515
-     * @param boolean $one_of_each_key
2516
-     * @return array
2517
-     * @throws \EE_Error
2518
-     */
2519
-    public function all_extra_meta_array($one_of_each_key = true)
2520
-    {
2521
-        $return_array = array();
2522
-        if ($one_of_each_key) {
2523
-            $extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2524
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2525
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2526
-                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2527
-                }
2528
-            }
2529
-        } else {
2530
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2531
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2532
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2533
-                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2534
-                        $return_array[$extra_meta_obj->key()] = array();
2535
-                    }
2536
-                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2537
-                }
2538
-            }
2539
-        }
2540
-        return $return_array;
2541
-    }
2542
-
2543
-
2544
-
2545
-    /**
2546
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2547
-     *
2548
-     * @return string
2549
-     * @throws \EE_Error
2550
-     */
2551
-    public function name()
2552
-    {
2553
-        //find a field that's not a text field
2554
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2555
-        if ($field_we_can_use) {
2556
-            return $this->get($field_we_can_use->get_name());
2557
-        } else {
2558
-            $first_few_properties = $this->model_field_array();
2559
-            $first_few_properties = array_slice($first_few_properties, 0, 3);
2560
-            $name_parts = array();
2561
-            foreach ($first_few_properties as $name => $value) {
2562
-                $name_parts[] = "$name:$value";
2563
-            }
2564
-            return implode(",", $name_parts);
2565
-        }
2566
-    }
2567
-
2568
-
2569
-
2570
-    /**
2571
-     * in_entity_map
2572
-     * Checks if this model object has been proven to already be in the entity map
2573
-     *
2574
-     * @return boolean
2575
-     * @throws \EE_Error
2576
-     */
2577
-    public function in_entity_map()
2578
-    {
2579
-        if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2580
-            //well, if we looked, did we find it in the entity map?
2581
-            return true;
2582
-        } else {
2583
-            return false;
2584
-        }
2585
-    }
2586
-
2587
-
2588
-
2589
-    /**
2590
-     * refresh_from_db
2591
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
2592
-     *
2593
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2594
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2595
-     */
2596
-    public function refresh_from_db()
2597
-    {
2598
-        if ($this->ID() && $this->in_entity_map()) {
2599
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
2600
-        } else {
2601
-            //if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2602
-            //if it has an ID but it's not in the map, and you're asking me to refresh it
2603
-            //that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2604
-            //absolutely nothing in it for this ID
2605
-            if (WP_DEBUG) {
2606
-                throw new EE_Error(
2607
-                    sprintf(
2608
-                        __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2609
-                            'event_espresso'),
2610
-                        $this->ID(),
2611
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2612
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2613
-                    )
2614
-                );
2615
-            }
2616
-        }
2617
-    }
2618
-
2619
-
2620
-
2621
-    /**
2622
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2623
-     * (probably a bad assumption they have made, oh well)
2624
-     *
2625
-     * @return string
2626
-     */
2627
-    public function __toString()
2628
-    {
2629
-        try {
2630
-            return sprintf('%s (%s)', $this->name(), $this->ID());
2631
-        } catch (Exception $e) {
2632
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2633
-            return '';
2634
-        }
2635
-    }
2636
-
2637
-
2638
-
2639
-    /**
2640
-     * Clear related model objects if they're already in the DB, because otherwise when we
2641
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
2642
-     * This means if we have made changes to those related model objects, and want to unserialize
2643
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
2644
-     * Instead, those related model objects should be directly serialized and stored.
2645
-     * Eg, the following won't work:
2646
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2647
-     * $att = $reg->attendee();
2648
-     * $att->set( 'ATT_fname', 'Dirk' );
2649
-     * update_option( 'my_option', serialize( $reg ) );
2650
-     * //END REQUEST
2651
-     * //START NEXT REQUEST
2652
-     * $reg = get_option( 'my_option' );
2653
-     * $reg->attendee()->save();
2654
-     * And would need to be replace with:
2655
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2656
-     * $att = $reg->attendee();
2657
-     * $att->set( 'ATT_fname', 'Dirk' );
2658
-     * update_option( 'my_option', serialize( $reg ) );
2659
-     * //END REQUEST
2660
-     * //START NEXT REQUEST
2661
-     * $att = get_option( 'my_option' );
2662
-     * $att->save();
2663
-     *
2664
-     * @return array
2665
-     * @throws \EE_Error
2666
-     */
2667
-    public function __sleep()
2668
-    {
2669
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2670
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
2671
-                $classname = 'EE_' . $this->get_model()->get_this_model_name();
2672
-                if (
2673
-                    $this->get_one_from_cache($relation_name) instanceof $classname
2674
-                    && $this->get_one_from_cache($relation_name)->ID()
2675
-                ) {
2676
-                    $this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2677
-                }
2678
-            }
2679
-        }
2680
-        $this->_props_n_values_provided_in_constructor = array();
2681
-        return array_keys(get_object_vars($this));
2682
-    }
2683
-
2684
-
2685
-
2686
-    /**
2687
-     * restore _props_n_values_provided_in_constructor
2688
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2689
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
2690
-     * At best, you would only be able to detect if state change has occurred during THIS request.
2691
-     */
2692
-    public function __wakeup()
2693
-    {
2694
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
2695
-    }
28
+	/**
29
+	 * This is an array of the original properties and values provided during construction
30
+	 * of this model object. (keys are model field names, values are their values).
31
+	 * This list is important to remember so that when we are merging data from the db, we know
32
+	 * which values to override and which to not override.
33
+	 *
34
+	 * @var array
35
+	 */
36
+	protected $_props_n_values_provided_in_constructor;
37
+
38
+	/**
39
+	 * Timezone
40
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
+	 * access to it.
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $_timezone;
48
+
49
+
50
+
51
+	/**
52
+	 * date format
53
+	 * pattern or format for displaying dates
54
+	 *
55
+	 * @var string $_dt_frmt
56
+	 */
57
+	protected $_dt_frmt;
58
+
59
+
60
+
61
+	/**
62
+	 * time format
63
+	 * pattern or format for displaying time
64
+	 *
65
+	 * @var string $_tm_frmt
66
+	 */
67
+	protected $_tm_frmt;
68
+
69
+
70
+
71
+	/**
72
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
73
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
74
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
+	 *
77
+	 * @var array
78
+	 */
79
+	protected $_cached_properties = array();
80
+
81
+	/**
82
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
83
+	 * single
84
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
+	 * all others have an array)
87
+	 *
88
+	 * @var array
89
+	 */
90
+	protected $_model_relations = array();
91
+
92
+	/**
93
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
+	 *
96
+	 * @var array
97
+	 */
98
+	protected $_fields = array();
99
+
100
+	/**
101
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
102
+	 * For example, we might create model objects intended to only be used for the duration
103
+	 * of this request and to be thrown away, and if they were accidentally saved
104
+	 * it would be a bug.
105
+	 */
106
+	protected $_allow_persist = true;
107
+
108
+	/**
109
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
110
+	 */
111
+	protected $_has_changes = false;
112
+
113
+
114
+
115
+	/**
116
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
117
+	 * play nice
118
+	 *
119
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
120
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
121
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
122
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
123
+	 *                                                         corresponding db model or not.
124
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
125
+	 *                                                         be in when instantiating a EE_Base_Class object.
126
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
127
+	 *                                                         value is the date_format and second value is the time
128
+	 *                                                         format.
129
+	 * @throws EE_Error
130
+	 */
131
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
132
+	{
133
+		$className = get_class($this);
134
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
135
+		$model = $this->get_model();
136
+		$model_fields = $model->field_settings(false);
137
+		// ensure $fieldValues is an array
138
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
139
+		// EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
140
+		// verify client code has not passed any invalid field names
141
+		foreach ($fieldValues as $field_name => $field_value) {
142
+			if ( ! isset($model_fields[$field_name])) {
143
+				throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
144
+					"event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
145
+			}
146
+		}
147
+		// EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
148
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
149
+		if ( ! empty($date_formats) && is_array($date_formats)) {
150
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
151
+		} else {
152
+			//set default formats for date and time
153
+			$this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
154
+			$this->_tm_frmt = (string)get_option('time_format', 'g:i a');
155
+		}
156
+		//if db model is instantiating
157
+		if ($bydb) {
158
+			//client code has indicated these field values are from the database
159
+			foreach ($model_fields as $fieldName => $field) {
160
+				$this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
161
+			}
162
+		} else {
163
+			//we're constructing a brand
164
+			//new instance of the model object. Generally, this means we'll need to do more field validation
165
+			foreach ($model_fields as $fieldName => $field) {
166
+				$this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
167
+			}
168
+		}
169
+		//remember what values were passed to this constructor
170
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
171
+		//remember in entity mapper
172
+		if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
173
+			$model->add_to_entity_map($this);
174
+		}
175
+		//setup all the relations
176
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
177
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
178
+				$this->_model_relations[$relation_name] = null;
179
+			} else {
180
+				$this->_model_relations[$relation_name] = array();
181
+			}
182
+		}
183
+		/**
184
+		 * Action done at the end of each model object construction
185
+		 *
186
+		 * @param EE_Base_Class $this the model object just created
187
+		 */
188
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
189
+	}
190
+
191
+
192
+
193
+	/**
194
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
195
+	 *
196
+	 * @return boolean
197
+	 */
198
+	public function allow_persist()
199
+	{
200
+		return $this->_allow_persist;
201
+	}
202
+
203
+
204
+
205
+	/**
206
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
207
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
208
+	 * you got new information that somehow made you change your mind.
209
+	 *
210
+	 * @param boolean $allow_persist
211
+	 * @return boolean
212
+	 */
213
+	public function set_allow_persist($allow_persist)
214
+	{
215
+		return $this->_allow_persist = $allow_persist;
216
+	}
217
+
218
+
219
+
220
+	/**
221
+	 * Gets the field's original value when this object was constructed during this request.
222
+	 * This can be helpful when determining if a model object has changed or not
223
+	 *
224
+	 * @param string $field_name
225
+	 * @return mixed|null
226
+	 * @throws \EE_Error
227
+	 */
228
+	public function get_original($field_name)
229
+	{
230
+		if (isset($this->_props_n_values_provided_in_constructor[$field_name])
231
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
232
+		) {
233
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
234
+		} else {
235
+			return null;
236
+		}
237
+	}
238
+
239
+
240
+
241
+	/**
242
+	 * @param EE_Base_Class $obj
243
+	 * @return string
244
+	 */
245
+	public function get_class($obj)
246
+	{
247
+		return get_class($obj);
248
+	}
249
+
250
+
251
+
252
+	/**
253
+	 * Overrides parent because parent expects old models.
254
+	 * This also doesn't do any validation, and won't work for serialized arrays
255
+	 *
256
+	 * @param    string $field_name
257
+	 * @param    mixed  $field_value
258
+	 * @param bool      $use_default
259
+	 * @throws \EE_Error
260
+	 */
261
+	public function set($field_name, $field_value, $use_default = false)
262
+	{
263
+		// if not using default and nothing has changed, and object has already been setup (has ID),
264
+		// then don't do anything
265
+		if (
266
+			! $use_default
267
+			&& $this->_fields[$field_name] === $field_value
268
+			&& $this->ID()
269
+		) {
270
+			return;
271
+		}
272
+		$this->_has_changes = true;
273
+		$field_obj = $this->get_model()->field_settings_for($field_name);
274
+		if ($field_obj instanceof EE_Model_Field_Base) {
275
+			//			if ( method_exists( $field_obj, 'set_timezone' )) {
276
+			if ($field_obj instanceof EE_Datetime_Field) {
277
+				$field_obj->set_timezone($this->_timezone);
278
+				$field_obj->set_date_format($this->_dt_frmt);
279
+				$field_obj->set_time_format($this->_tm_frmt);
280
+			}
281
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
282
+			//should the value be null?
283
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
284
+				$this->_fields[$field_name] = $field_obj->get_default_value();
285
+				/**
286
+				 * To save having to refactor all the models, if a default value is used for a
287
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
288
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
289
+				 * object.
290
+				 *
291
+				 * @since 4.6.10+
292
+				 */
293
+				if (
294
+					$field_obj instanceof EE_Datetime_Field
295
+					&& $this->_fields[$field_name] !== null
296
+					&& ! $this->_fields[$field_name] instanceof DateTime
297
+				) {
298
+					empty($this->_fields[$field_name])
299
+						? $this->set($field_name, time())
300
+						: $this->set($field_name, $this->_fields[$field_name]);
301
+				}
302
+			} else {
303
+				$this->_fields[$field_name] = $holder_of_value;
304
+			}
305
+			//if we're not in the constructor...
306
+			//now check if what we set was a primary key
307
+			if (
308
+				//note: props_n_values_provided_in_constructor is only set at the END of the constructor
309
+				$this->_props_n_values_provided_in_constructor
310
+				&& $field_value
311
+				&& $field_name === self::_get_primary_key_name(get_class($this))
312
+			) {
313
+				//if so, we want all this object's fields to be filled either with
314
+				//what we've explicitly set on this model
315
+				//or what we have in the db
316
+				// echo "setting primary key!";
317
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
318
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
319
+				foreach ($fields_on_model as $field_obj) {
320
+					if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
321
+						 && $field_obj->get_name() !== $field_name
322
+					) {
323
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
324
+					}
325
+				}
326
+				//oh this model object has an ID? well make sure its in the entity mapper
327
+				$this->get_model()->add_to_entity_map($this);
328
+			}
329
+			//let's unset any cache for this field_name from the $_cached_properties property.
330
+			$this->_clear_cached_property($field_name);
331
+		} else {
332
+			throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
333
+				"event_espresso"), $field_name));
334
+		}
335
+	}
336
+
337
+
338
+
339
+	/**
340
+	 * This sets the field value on the db column if it exists for the given $column_name or
341
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
342
+	 *
343
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
344
+	 * @param string $field_name  Must be the exact column name.
345
+	 * @param mixed  $field_value The value to set.
346
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
347
+	 * @throws \EE_Error
348
+	 */
349
+	public function set_field_or_extra_meta($field_name, $field_value)
350
+	{
351
+		if ($this->get_model()->has_field($field_name)) {
352
+			$this->set($field_name, $field_value);
353
+			return true;
354
+		} else {
355
+			//ensure this object is saved first so that extra meta can be properly related.
356
+			$this->save();
357
+			return $this->update_extra_meta($field_name, $field_value);
358
+		}
359
+	}
360
+
361
+
362
+
363
+	/**
364
+	 * This retrieves the value of the db column set on this class or if that's not present
365
+	 * it will attempt to retrieve from extra_meta if found.
366
+	 * Example Usage:
367
+	 * Via EE_Message child class:
368
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
369
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
370
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
371
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
372
+	 * value for those extra fields dynamically via the EE_message object.
373
+	 *
374
+	 * @param  string $field_name expecting the fully qualified field name.
375
+	 * @return mixed|null  value for the field if found.  null if not found.
376
+	 * @throws \EE_Error
377
+	 */
378
+	public function get_field_or_extra_meta($field_name)
379
+	{
380
+		if ($this->get_model()->has_field($field_name)) {
381
+			$column_value = $this->get($field_name);
382
+		} else {
383
+			//This isn't a column in the main table, let's see if it is in the extra meta.
384
+			$column_value = $this->get_extra_meta($field_name, true, null);
385
+		}
386
+		return $column_value;
387
+	}
388
+
389
+
390
+
391
+	/**
392
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
393
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
394
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
395
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
396
+	 *
397
+	 * @access public
398
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
399
+	 * @return void
400
+	 * @throws \EE_Error
401
+	 */
402
+	public function set_timezone($timezone = '')
403
+	{
404
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
405
+		//make sure we clear all cached properties because they won't be relevant now
406
+		$this->_clear_cached_properties();
407
+		//make sure we update field settings and the date for all EE_Datetime_Fields
408
+		$model_fields = $this->get_model()->field_settings(false);
409
+		foreach ($model_fields as $field_name => $field_obj) {
410
+			if ($field_obj instanceof EE_Datetime_Field) {
411
+				$field_obj->set_timezone($this->_timezone);
412
+				if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
413
+					$this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
414
+				}
415
+			}
416
+		}
417
+	}
418
+
419
+
420
+
421
+	/**
422
+	 * This just returns whatever is set for the current timezone.
423
+	 *
424
+	 * @access public
425
+	 * @return string timezone string
426
+	 */
427
+	public function get_timezone()
428
+	{
429
+		return $this->_timezone;
430
+	}
431
+
432
+
433
+
434
+	/**
435
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
436
+	 * internally instead of wp set date format options
437
+	 *
438
+	 * @since 4.6
439
+	 * @param string $format should be a format recognizable by PHP date() functions.
440
+	 */
441
+	public function set_date_format($format)
442
+	{
443
+		$this->_dt_frmt = $format;
444
+		//clear cached_properties because they won't be relevant now.
445
+		$this->_clear_cached_properties();
446
+	}
447
+
448
+
449
+
450
+	/**
451
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
452
+	 * class internally instead of wp set time format options.
453
+	 *
454
+	 * @since 4.6
455
+	 * @param string $format should be a format recognizable by PHP date() functions.
456
+	 */
457
+	public function set_time_format($format)
458
+	{
459
+		$this->_tm_frmt = $format;
460
+		//clear cached_properties because they won't be relevant now.
461
+		$this->_clear_cached_properties();
462
+	}
463
+
464
+
465
+
466
+	/**
467
+	 * This returns the current internal set format for the date and time formats.
468
+	 *
469
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
470
+	 *                             where the first value is the date format and the second value is the time format.
471
+	 * @return mixed string|array
472
+	 */
473
+	public function get_format($full = true)
474
+	{
475
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
476
+	}
477
+
478
+
479
+
480
+	/**
481
+	 * cache
482
+	 * stores the passed model object on the current model object.
483
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
484
+	 *
485
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
486
+	 *                                       'Registration' associated with this model object
487
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
488
+	 *                                       that could be a payment or a registration)
489
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
490
+	 *                                       items which will be stored in an array on this object
491
+	 * @throws EE_Error
492
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
493
+	 *                  related thing, no array)
494
+	 */
495
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
496
+	{
497
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
498
+		if ( ! $object_to_cache instanceof EE_Base_Class) {
499
+			return false;
500
+		}
501
+		// also get "how" the object is related, or throw an error
502
+		if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
503
+			throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
504
+				$relationName, get_class($this)));
505
+		}
506
+		// how many things are related ?
507
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
508
+			// if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
509
+			// so for these model objects just set it to be cached
510
+			$this->_model_relations[$relationName] = $object_to_cache;
511
+			$return = true;
512
+		} else {
513
+			// otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
514
+			// eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
515
+			if ( ! is_array($this->_model_relations[$relationName])) {
516
+				// if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
517
+				$this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
518
+					? array($this->_model_relations[$relationName]) : array();
519
+			}
520
+			// first check for a cache_id which is normally empty
521
+			if ( ! empty($cache_id)) {
522
+				// if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
523
+				$this->_model_relations[$relationName][$cache_id] = $object_to_cache;
524
+				$return = $cache_id;
525
+			} elseif ($object_to_cache->ID()) {
526
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
527
+				$this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
528
+				$return = $object_to_cache->ID();
529
+			} else {
530
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
531
+				$this->_model_relations[$relationName][] = $object_to_cache;
532
+				// move the internal pointer to the end of the array
533
+				end($this->_model_relations[$relationName]);
534
+				// and grab the key so that we can return it
535
+				$return = key($this->_model_relations[$relationName]);
536
+			}
537
+		}
538
+		return $return;
539
+	}
540
+
541
+
542
+
543
+	/**
544
+	 * For adding an item to the cached_properties property.
545
+	 *
546
+	 * @access protected
547
+	 * @param string      $fieldname the property item the corresponding value is for.
548
+	 * @param mixed       $value     The value we are caching.
549
+	 * @param string|null $cache_type
550
+	 * @return void
551
+	 * @throws \EE_Error
552
+	 */
553
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
554
+	{
555
+		//first make sure this property exists
556
+		$this->get_model()->field_settings_for($fieldname);
557
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
558
+		$this->_cached_properties[$fieldname][$cache_type] = $value;
559
+	}
560
+
561
+
562
+
563
+	/**
564
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
565
+	 * This also SETS the cache if we return the actual property!
566
+	 *
567
+	 * @param string $fieldname        the name of the property we're trying to retrieve
568
+	 * @param bool   $pretty
569
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
570
+	 *                                 (in cases where the same property may be used for different outputs
571
+	 *                                 - i.e. datetime, money etc.)
572
+	 *                                 It can also accept certain pre-defined "schema" strings
573
+	 *                                 to define how to output the property.
574
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
575
+	 * @return mixed                   whatever the value for the property is we're retrieving
576
+	 * @throws \EE_Error
577
+	 */
578
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
579
+	{
580
+		//verify the field exists
581
+		$this->get_model()->field_settings_for($fieldname);
582
+		$cache_type = $pretty ? 'pretty' : 'standard';
583
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
584
+		if (isset($this->_cached_properties[$fieldname][$cache_type])) {
585
+			return $this->_cached_properties[$fieldname][$cache_type];
586
+		}
587
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
588
+		if ($field_obj instanceof EE_Model_Field_Base) {
589
+			// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
590
+			if ($field_obj instanceof EE_Datetime_Field) {
591
+				$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
592
+			}
593
+			if ( ! isset($this->_fields[$fieldname])) {
594
+				$this->_fields[$fieldname] = null;
595
+			}
596
+			$value = $pretty
597
+				? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
598
+				: $field_obj->prepare_for_get($this->_fields[$fieldname]);
599
+			$this->_set_cached_property($fieldname, $value, $cache_type);
600
+			return $value;
601
+		}
602
+		return null;
603
+	}
604
+
605
+
606
+
607
+	/**
608
+	 * set timezone, formats, and output for EE_Datetime_Field objects
609
+	 *
610
+	 * @param \EE_Datetime_Field $datetime_field
611
+	 * @param bool               $pretty
612
+	 * @param null $date_or_time
613
+	 * @return void
614
+	 * @throws \EE_Error
615
+	 */
616
+	protected function _prepare_datetime_field(
617
+		EE_Datetime_Field $datetime_field,
618
+		$pretty = false,
619
+		$date_or_time = null
620
+	) {
621
+		$datetime_field->set_timezone($this->_timezone);
622
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
623
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
624
+		//set the output returned
625
+		switch ($date_or_time) {
626
+			case 'D' :
627
+				$datetime_field->set_date_time_output('date');
628
+				break;
629
+			case 'T' :
630
+				$datetime_field->set_date_time_output('time');
631
+				break;
632
+			default :
633
+				$datetime_field->set_date_time_output();
634
+		}
635
+	}
636
+
637
+
638
+
639
+	/**
640
+	 * This just takes care of clearing out the cached_properties
641
+	 *
642
+	 * @return void
643
+	 */
644
+	protected function _clear_cached_properties()
645
+	{
646
+		$this->_cached_properties = array();
647
+	}
648
+
649
+
650
+
651
+	/**
652
+	 * This just clears out ONE property if it exists in the cache
653
+	 *
654
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
655
+	 * @return void
656
+	 */
657
+	protected function _clear_cached_property($property_name)
658
+	{
659
+		if (isset($this->_cached_properties[$property_name])) {
660
+			unset($this->_cached_properties[$property_name]);
661
+		}
662
+	}
663
+
664
+
665
+
666
+	/**
667
+	 * Ensures that this related thing is a model object.
668
+	 *
669
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
670
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
671
+	 * @return EE_Base_Class
672
+	 * @throws \EE_Error
673
+	 */
674
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
675
+	{
676
+		$other_model_instance = self::_get_model_instance_with_name(
677
+			self::_get_model_classname($model_name),
678
+			$this->_timezone
679
+		);
680
+		return $other_model_instance->ensure_is_obj($object_or_id);
681
+	}
682
+
683
+
684
+
685
+	/**
686
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
687
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
688
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
689
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
690
+	 *
691
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
692
+	 *                                                     Eg 'Registration'
693
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
694
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
695
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
696
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
697
+	 *                                                     this is HasMany or HABTM.
698
+	 * @throws EE_Error
699
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
700
+	 *                       relation from all
701
+	 */
702
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
703
+	{
704
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
705
+		$index_in_cache = '';
706
+		if ( ! $relationship_to_model) {
707
+			throw new EE_Error(
708
+				sprintf(
709
+					__("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
710
+					$relationName,
711
+					get_class($this)
712
+				)
713
+			);
714
+		}
715
+		if ($clear_all) {
716
+			$obj_removed = true;
717
+			$this->_model_relations[$relationName] = null;
718
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
719
+			$obj_removed = $this->_model_relations[$relationName];
720
+			$this->_model_relations[$relationName] = null;
721
+		} else {
722
+			if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
723
+				&& $object_to_remove_or_index_into_array->ID()
724
+			) {
725
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
726
+				if (is_array($this->_model_relations[$relationName])
727
+					&& ! isset($this->_model_relations[$relationName][$index_in_cache])
728
+				) {
729
+					$index_found_at = null;
730
+					//find this object in the array even though it has a different key
731
+					foreach ($this->_model_relations[$relationName] as $index => $obj) {
732
+						if (
733
+							$obj instanceof EE_Base_Class
734
+							&& (
735
+								$obj == $object_to_remove_or_index_into_array
736
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
737
+							)
738
+						) {
739
+							$index_found_at = $index;
740
+							break;
741
+						}
742
+					}
743
+					if ($index_found_at) {
744
+						$index_in_cache = $index_found_at;
745
+					} else {
746
+						//it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
747
+						//if it wasn't in it to begin with. So we're done
748
+						return $object_to_remove_or_index_into_array;
749
+					}
750
+				}
751
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
752
+				//so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
753
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
754
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
755
+						$index_in_cache = $index;
756
+					}
757
+				}
758
+			} else {
759
+				$index_in_cache = $object_to_remove_or_index_into_array;
760
+			}
761
+			//supposedly we've found it. But it could just be that the client code
762
+			//provided a bad index/object
763
+			if (
764
+			isset(
765
+				$this->_model_relations[$relationName],
766
+				$this->_model_relations[$relationName][$index_in_cache]
767
+			)
768
+			) {
769
+				$obj_removed = $this->_model_relations[$relationName][$index_in_cache];
770
+				unset($this->_model_relations[$relationName][$index_in_cache]);
771
+			} else {
772
+				//that thing was never cached anyways.
773
+				$obj_removed = null;
774
+			}
775
+		}
776
+		return $obj_removed;
777
+	}
778
+
779
+
780
+
781
+	/**
782
+	 * update_cache_after_object_save
783
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
784
+	 * obtained after being saved to the db
785
+	 *
786
+	 * @param string         $relationName       - the type of object that is cached
787
+	 * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
788
+	 * @param string         $current_cache_id   - the ID that was used when originally caching the object
789
+	 * @return boolean TRUE on success, FALSE on fail
790
+	 * @throws \EE_Error
791
+	 */
792
+	public function update_cache_after_object_save(
793
+		$relationName,
794
+		EE_Base_Class $newly_saved_object,
795
+		$current_cache_id = ''
796
+	) {
797
+		// verify that incoming object is of the correct type
798
+		$obj_class = 'EE_' . $relationName;
799
+		if ($newly_saved_object instanceof $obj_class) {
800
+			/* @type EE_Base_Class $newly_saved_object */
801
+			// now get the type of relation
802
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
803
+			// if this is a 1:1 relationship
804
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
805
+				// then just replace the cached object with the newly saved object
806
+				$this->_model_relations[$relationName] = $newly_saved_object;
807
+				return true;
808
+				// or if it's some kind of sordid feral polyamorous relationship...
809
+			} elseif (is_array($this->_model_relations[$relationName])
810
+					  && isset($this->_model_relations[$relationName][$current_cache_id])
811
+			) {
812
+				// then remove the current cached item
813
+				unset($this->_model_relations[$relationName][$current_cache_id]);
814
+				// and cache the newly saved object using it's new ID
815
+				$this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
816
+				return true;
817
+			}
818
+		}
819
+		return false;
820
+	}
821
+
822
+
823
+
824
+	/**
825
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
826
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
827
+	 *
828
+	 * @param string $relationName
829
+	 * @return EE_Base_Class
830
+	 */
831
+	public function get_one_from_cache($relationName)
832
+	{
833
+		$cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
834
+			: null;
835
+		if (is_array($cached_array_or_object)) {
836
+			return array_shift($cached_array_or_object);
837
+		} else {
838
+			return $cached_array_or_object;
839
+		}
840
+	}
841
+
842
+
843
+
844
+	/**
845
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
846
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
847
+	 *
848
+	 * @param string $relationName
849
+	 * @throws \EE_Error
850
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
851
+	 */
852
+	public function get_all_from_cache($relationName)
853
+	{
854
+		$objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
855
+		// if the result is not an array, but exists, make it an array
856
+		$objects = is_array($objects) ? $objects : array($objects);
857
+		//bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
858
+		//basically, if this model object was stored in the session, and these cached model objects
859
+		//already have IDs, let's make sure they're in their model's entity mapper
860
+		//otherwise we will have duplicates next time we call
861
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
862
+		$model = EE_Registry::instance()->load_model($relationName);
863
+		foreach ($objects as $model_object) {
864
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
865
+				//ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
866
+				if ($model_object->ID()) {
867
+					$model->add_to_entity_map($model_object);
868
+				}
869
+			} else {
870
+				throw new EE_Error(
871
+					sprintf(
872
+						__(
873
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
874
+							'event_espresso'
875
+						),
876
+						$relationName,
877
+						gettype($model_object)
878
+					)
879
+				);
880
+			}
881
+		}
882
+		return $objects;
883
+	}
884
+
885
+
886
+
887
+	/**
888
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
889
+	 * matching the given query conditions.
890
+	 *
891
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
892
+	 * @param int   $limit              How many objects to return.
893
+	 * @param array $query_params       Any additional conditions on the query.
894
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
895
+	 *                                  you can indicate just the columns you want returned
896
+	 * @return array|EE_Base_Class[]
897
+	 * @throws \EE_Error
898
+	 */
899
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
900
+	{
901
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
902
+			? $this->get_model()->get_primary_key_field()->get_name()
903
+			: $field_to_order_by;
904
+		$current_value = ! empty($field) ? $this->get($field) : null;
905
+		if (empty($field) || empty($current_value)) {
906
+			return array();
907
+		}
908
+		return $this->get_model()->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
909
+	}
910
+
911
+
912
+
913
+	/**
914
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
915
+	 * matching the given query conditions.
916
+	 *
917
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
918
+	 * @param int   $limit              How many objects to return.
919
+	 * @param array $query_params       Any additional conditions on the query.
920
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
921
+	 *                                  you can indicate just the columns you want returned
922
+	 * @return array|EE_Base_Class[]
923
+	 * @throws \EE_Error
924
+	 */
925
+	public function previous_x(
926
+		$field_to_order_by = null,
927
+		$limit = 1,
928
+		$query_params = array(),
929
+		$columns_to_select = null
930
+	) {
931
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
932
+			? $this->get_model()->get_primary_key_field()->get_name()
933
+			: $field_to_order_by;
934
+		$current_value = ! empty($field) ? $this->get($field) : null;
935
+		if (empty($field) || empty($current_value)) {
936
+			return array();
937
+		}
938
+		return $this->get_model()->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
939
+	}
940
+
941
+
942
+
943
+	/**
944
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
945
+	 * matching the given query conditions.
946
+	 *
947
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
948
+	 * @param array $query_params       Any additional conditions on the query.
949
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
950
+	 *                                  you can indicate just the columns you want returned
951
+	 * @return array|EE_Base_Class
952
+	 * @throws \EE_Error
953
+	 */
954
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
955
+	{
956
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
957
+			? $this->get_model()->get_primary_key_field()->get_name()
958
+			: $field_to_order_by;
959
+		$current_value = ! empty($field) ? $this->get($field) : null;
960
+		if (empty($field) || empty($current_value)) {
961
+			return array();
962
+		}
963
+		return $this->get_model()->next($current_value, $field, $query_params, $columns_to_select);
964
+	}
965
+
966
+
967
+
968
+	/**
969
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
970
+	 * matching the given query conditions.
971
+	 *
972
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
973
+	 * @param array $query_params       Any additional conditions on the query.
974
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
975
+	 *                                  you can indicate just the column you want returned
976
+	 * @return array|EE_Base_Class
977
+	 * @throws \EE_Error
978
+	 */
979
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
980
+	{
981
+		$field = empty($field_to_order_by) && $this->get_model()->has_primary_key_field()
982
+			? $this->get_model()->get_primary_key_field()->get_name()
983
+			: $field_to_order_by;
984
+		$current_value = ! empty($field) ? $this->get($field) : null;
985
+		if (empty($field) || empty($current_value)) {
986
+			return array();
987
+		}
988
+		return $this->get_model()->previous($current_value, $field, $query_params, $columns_to_select);
989
+	}
990
+
991
+
992
+
993
+	/**
994
+	 * Overrides parent because parent expects old models.
995
+	 * This also doesn't do any validation, and won't work for serialized arrays
996
+	 *
997
+	 * @param string $field_name
998
+	 * @param mixed  $field_value_from_db
999
+	 * @throws \EE_Error
1000
+	 */
1001
+	public function set_from_db($field_name, $field_value_from_db)
1002
+	{
1003
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1004
+		if ($field_obj instanceof EE_Model_Field_Base) {
1005
+			//you would think the DB has no NULLs for non-null label fields right? wrong!
1006
+			//eg, a CPT model object could have an entry in the posts table, but no
1007
+			//entry in the meta table. Meaning that all its columns in the meta table
1008
+			//are null! yikes! so when we find one like that, use defaults for its meta columns
1009
+			if ($field_value_from_db === null) {
1010
+				if ($field_obj->is_nullable()) {
1011
+					//if the field allows nulls, then let it be null
1012
+					$field_value = null;
1013
+				} else {
1014
+					$field_value = $field_obj->get_default_value();
1015
+				}
1016
+			} else {
1017
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1018
+			}
1019
+			$this->_fields[$field_name] = $field_value;
1020
+			$this->_clear_cached_property($field_name);
1021
+		}
1022
+	}
1023
+
1024
+
1025
+
1026
+	/**
1027
+	 * verifies that the specified field is of the correct type
1028
+	 *
1029
+	 * @param string $field_name
1030
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1031
+	 *                                (in cases where the same property may be used for different outputs
1032
+	 *                                - i.e. datetime, money etc.)
1033
+	 * @return mixed
1034
+	 * @throws \EE_Error
1035
+	 */
1036
+	public function get($field_name, $extra_cache_ref = null)
1037
+	{
1038
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1039
+	}
1040
+
1041
+
1042
+
1043
+	/**
1044
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1045
+	 *
1046
+	 * @param  string $field_name A valid fieldname
1047
+	 * @return mixed              Whatever the raw value stored on the property is.
1048
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1049
+	 */
1050
+	public function get_raw($field_name)
1051
+	{
1052
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1053
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1054
+			? $this->_fields[$field_name]->format('U')
1055
+			: $this->_fields[$field_name];
1056
+	}
1057
+
1058
+
1059
+
1060
+	/**
1061
+	 * This is used to return the internal DateTime object used for a field that is a
1062
+	 * EE_Datetime_Field.
1063
+	 *
1064
+	 * @param string $field_name               The field name retrieving the DateTime object.
1065
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1066
+	 * @throws \EE_Error
1067
+	 *                                         an error is set and false returned.  If the field IS an
1068
+	 *                                         EE_Datetime_Field and but the field value is null, then
1069
+	 *                                         just null is returned (because that indicates that likely
1070
+	 *                                         this field is nullable).
1071
+	 */
1072
+	public function get_DateTime_object($field_name)
1073
+	{
1074
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1075
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1076
+			EE_Error::add_error(
1077
+				sprintf(
1078
+					__(
1079
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1080
+						'event_espresso'
1081
+					),
1082
+					$field_name
1083
+				),
1084
+				__FILE__,
1085
+				__FUNCTION__,
1086
+				__LINE__
1087
+			);
1088
+			return false;
1089
+		}
1090
+		return $this->_fields[$field_name];
1091
+	}
1092
+
1093
+
1094
+
1095
+	/**
1096
+	 * To be used in template to immediately echo out the value, and format it for output.
1097
+	 * Eg, should call stripslashes and whatnot before echoing
1098
+	 *
1099
+	 * @param string $field_name      the name of the field as it appears in the DB
1100
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1101
+	 *                                (in cases where the same property may be used for different outputs
1102
+	 *                                - i.e. datetime, money etc.)
1103
+	 * @return void
1104
+	 * @throws \EE_Error
1105
+	 */
1106
+	public function e($field_name, $extra_cache_ref = null)
1107
+	{
1108
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1109
+	}
1110
+
1111
+
1112
+
1113
+	/**
1114
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1115
+	 * can be easily used as the value of form input.
1116
+	 *
1117
+	 * @param string $field_name
1118
+	 * @return void
1119
+	 * @throws \EE_Error
1120
+	 */
1121
+	public function f($field_name)
1122
+	{
1123
+		$this->e($field_name, 'form_input');
1124
+	}
1125
+
1126
+
1127
+
1128
+	/**
1129
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1130
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1131
+	 * to see what options are available.
1132
+	 * @param string $field_name
1133
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1134
+	 *                                (in cases where the same property may be used for different outputs
1135
+	 *                                - i.e. datetime, money etc.)
1136
+	 * @return mixed
1137
+	 * @throws \EE_Error
1138
+	 */
1139
+	public function get_pretty($field_name, $extra_cache_ref = null)
1140
+	{
1141
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1142
+	}
1143
+
1144
+
1145
+
1146
+	/**
1147
+	 * This simply returns the datetime for the given field name
1148
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1149
+	 * (and the equivalent e_date, e_time, e_datetime).
1150
+	 *
1151
+	 * @access   protected
1152
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1153
+	 * @param string   $dt_frmt      valid datetime format used for date
1154
+	 *                               (if '' then we just use the default on the field,
1155
+	 *                               if NULL we use the last-used format)
1156
+	 * @param string   $tm_frmt      Same as above except this is for time format
1157
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1158
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1159
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1160
+	 *                               if field is not a valid dtt field, or void if echoing
1161
+	 * @throws \EE_Error
1162
+	 */
1163
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1164
+	{
1165
+		// clear cached property
1166
+		$this->_clear_cached_property($field_name);
1167
+		//reset format properties because they are used in get()
1168
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1169
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1170
+		if ($echo) {
1171
+			$this->e($field_name, $date_or_time);
1172
+			return '';
1173
+		}
1174
+		return $this->get($field_name, $date_or_time);
1175
+	}
1176
+
1177
+
1178
+
1179
+	/**
1180
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1181
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1182
+	 * other echoes the pretty value for dtt)
1183
+	 *
1184
+	 * @param  string $field_name name of model object datetime field holding the value
1185
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1186
+	 * @return string            datetime value formatted
1187
+	 * @throws \EE_Error
1188
+	 */
1189
+	public function get_date($field_name, $format = '')
1190
+	{
1191
+		return $this->_get_datetime($field_name, $format, null, 'D');
1192
+	}
1193
+
1194
+
1195
+
1196
+	/**
1197
+	 * @param      $field_name
1198
+	 * @param string $format
1199
+	 * @throws \EE_Error
1200
+	 */
1201
+	public function e_date($field_name, $format = '')
1202
+	{
1203
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1204
+	}
1205
+
1206
+
1207
+
1208
+	/**
1209
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1210
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1211
+	 * other echoes the pretty value for dtt)
1212
+	 *
1213
+	 * @param  string $field_name name of model object datetime field holding the value
1214
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1215
+	 * @return string             datetime value formatted
1216
+	 * @throws \EE_Error
1217
+	 */
1218
+	public function get_time($field_name, $format = '')
1219
+	{
1220
+		return $this->_get_datetime($field_name, null, $format, 'T');
1221
+	}
1222
+
1223
+
1224
+
1225
+	/**
1226
+	 * @param      $field_name
1227
+	 * @param string $format
1228
+	 * @throws \EE_Error
1229
+	 */
1230
+	public function e_time($field_name, $format = '')
1231
+	{
1232
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1233
+	}
1234
+
1235
+
1236
+
1237
+	/**
1238
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1239
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1240
+	 * other echoes the pretty value for dtt)
1241
+	 *
1242
+	 * @param  string $field_name name of model object datetime field holding the value
1243
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1244
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1245
+	 * @return string             datetime value formatted
1246
+	 * @throws \EE_Error
1247
+	 */
1248
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1249
+	{
1250
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1251
+	}
1252
+
1253
+
1254
+
1255
+	/**
1256
+	 * @param string $field_name
1257
+	 * @param string $dt_frmt
1258
+	 * @param string $tm_frmt
1259
+	 * @throws \EE_Error
1260
+	 */
1261
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1262
+	{
1263
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1264
+	}
1265
+
1266
+
1267
+
1268
+	/**
1269
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1270
+	 *
1271
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1272
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1273
+	 *                           on the object will be used.
1274
+	 * @return string Date and time string in set locale or false if no field exists for the given
1275
+	 * @throws \EE_Error
1276
+	 *                           field name.
1277
+	 */
1278
+	public function get_i18n_datetime($field_name, $format = '')
1279
+	{
1280
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1281
+		return date_i18n(
1282
+			$format,
1283
+			EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1284
+		);
1285
+	}
1286
+
1287
+
1288
+
1289
+	/**
1290
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1291
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1292
+	 * thrown.
1293
+	 *
1294
+	 * @param  string $field_name The field name being checked
1295
+	 * @throws EE_Error
1296
+	 * @return EE_Datetime_Field
1297
+	 */
1298
+	protected function _get_dtt_field_settings($field_name)
1299
+	{
1300
+		$field = $this->get_model()->field_settings_for($field_name);
1301
+		//check if field is dtt
1302
+		if ($field instanceof EE_Datetime_Field) {
1303
+			return $field;
1304
+		} else {
1305
+			throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1306
+				'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1307
+		}
1308
+	}
1309
+
1310
+
1311
+
1312
+
1313
+	/**
1314
+	 * NOTE ABOUT BELOW:
1315
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1316
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1317
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1318
+	 * method and make sure you send the entire datetime value for setting.
1319
+	 */
1320
+	/**
1321
+	 * sets the time on a datetime property
1322
+	 *
1323
+	 * @access protected
1324
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1325
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1326
+	 * @throws \EE_Error
1327
+	 */
1328
+	protected function _set_time_for($time, $fieldname)
1329
+	{
1330
+		$this->_set_date_time('T', $time, $fieldname);
1331
+	}
1332
+
1333
+
1334
+
1335
+	/**
1336
+	 * sets the date on a datetime property
1337
+	 *
1338
+	 * @access protected
1339
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1340
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1341
+	 * @throws \EE_Error
1342
+	 */
1343
+	protected function _set_date_for($date, $fieldname)
1344
+	{
1345
+		$this->_set_date_time('D', $date, $fieldname);
1346
+	}
1347
+
1348
+
1349
+
1350
+	/**
1351
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1352
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1353
+	 *
1354
+	 * @access protected
1355
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1356
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1357
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1358
+	 *                                        EE_Datetime_Field property)
1359
+	 * @throws \EE_Error
1360
+	 */
1361
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1362
+	{
1363
+		$field = $this->_get_dtt_field_settings($fieldname);
1364
+		$field->set_timezone($this->_timezone);
1365
+		$field->set_date_format($this->_dt_frmt);
1366
+		$field->set_time_format($this->_tm_frmt);
1367
+		switch ($what) {
1368
+			case 'T' :
1369
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1370
+					$datetime_value,
1371
+					$this->_fields[$fieldname]
1372
+				);
1373
+				break;
1374
+			case 'D' :
1375
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1376
+					$datetime_value,
1377
+					$this->_fields[$fieldname]
1378
+				);
1379
+				break;
1380
+			case 'B' :
1381
+				$this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1382
+				break;
1383
+		}
1384
+		$this->_clear_cached_property($fieldname);
1385
+	}
1386
+
1387
+
1388
+
1389
+	/**
1390
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1391
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1392
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1393
+	 * that could lead to some unexpected results!
1394
+	 *
1395
+	 * @access public
1396
+	 * @param string               $field_name This is the name of the field on the object that contains the date/time
1397
+	 *                                         value being returned.
1398
+	 * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1399
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1400
+	 * @param string               $prepend    You can include something to prepend on the timestamp
1401
+	 * @param string               $append     You can include something to append on the timestamp
1402
+	 * @throws EE_Error
1403
+	 * @return string timestamp
1404
+	 */
1405
+	public function display_in_my_timezone(
1406
+		$field_name,
1407
+		$callback = 'get_datetime',
1408
+		$args = null,
1409
+		$prepend = '',
1410
+		$append = ''
1411
+	) {
1412
+		$timezone = EEH_DTT_Helper::get_timezone();
1413
+		if ($timezone === $this->_timezone) {
1414
+			return '';
1415
+		}
1416
+		$original_timezone = $this->_timezone;
1417
+		$this->set_timezone($timezone);
1418
+		$fn = (array)$field_name;
1419
+		$args = array_merge($fn, (array)$args);
1420
+		if ( ! method_exists($this, $callback)) {
1421
+			throw new EE_Error(
1422
+				sprintf(
1423
+					__(
1424
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1425
+						'event_espresso'
1426
+					),
1427
+					$callback
1428
+				)
1429
+			);
1430
+		}
1431
+		$args = (array)$args;
1432
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1433
+		$this->set_timezone($original_timezone);
1434
+		return $return;
1435
+	}
1436
+
1437
+
1438
+
1439
+	/**
1440
+	 * Deletes this model object.
1441
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1442
+	 * override
1443
+	 * `EE_Base_Class::_delete` NOT this class.
1444
+	 *
1445
+	 * @return boolean | int
1446
+	 * @throws \EE_Error
1447
+	 */
1448
+	public function delete()
1449
+	{
1450
+		/**
1451
+		 * Called just before the `EE_Base_Class::_delete` method call.
1452
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1453
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1454
+		 * soft deletes (trash) the object and does not permanently delete it.
1455
+		 *
1456
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1457
+		 */
1458
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1459
+		$result = $this->_delete();
1460
+		/**
1461
+		 * Called just after the `EE_Base_Class::_delete` method call.
1462
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1463
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1464
+		 * soft deletes (trash) the object and does not permanently delete it.
1465
+		 *
1466
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1467
+		 * @param boolean       $result
1468
+		 */
1469
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1470
+		return $result;
1471
+	}
1472
+
1473
+
1474
+
1475
+	/**
1476
+	 * Calls the specific delete method for the instantiated class.
1477
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1478
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1479
+	 * `EE_Base_Class::delete`
1480
+	 *
1481
+	 * @return bool|int
1482
+	 * @throws \EE_Error
1483
+	 */
1484
+	protected function _delete()
1485
+	{
1486
+		return $this->delete_permanently();
1487
+	}
1488
+
1489
+
1490
+
1491
+	/**
1492
+	 * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1493
+	 * error)
1494
+	 *
1495
+	 * @return bool | int
1496
+	 * @throws \EE_Error
1497
+	 */
1498
+	public function delete_permanently()
1499
+	{
1500
+		/**
1501
+		 * Called just before HARD deleting a model object
1502
+		 *
1503
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1504
+		 */
1505
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1506
+		$model = $this->get_model();
1507
+		$result = $model->delete_permanently_by_ID($this->ID());
1508
+		$this->refresh_cache_of_related_objects();
1509
+		/**
1510
+		 * Called just after HARD deleting a model object
1511
+		 *
1512
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1513
+		 * @param boolean       $result
1514
+		 */
1515
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1516
+		return $result;
1517
+	}
1518
+
1519
+
1520
+
1521
+	/**
1522
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1523
+	 * related model objects
1524
+	 *
1525
+	 * @throws \EE_Error
1526
+	 */
1527
+	public function refresh_cache_of_related_objects()
1528
+	{
1529
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1530
+			if ( ! empty($this->_model_relations[$relation_name])) {
1531
+				$related_objects = $this->_model_relations[$relation_name];
1532
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1533
+					//this relation only stores a single model object, not an array
1534
+					//but let's make it consistent
1535
+					$related_objects = array($related_objects);
1536
+				}
1537
+				foreach ($related_objects as $related_object) {
1538
+					//only refresh their cache if they're in memory
1539
+					if ($related_object instanceof EE_Base_Class) {
1540
+						$related_object->clear_cache($this->get_model()->get_this_model_name(), $this);
1541
+					}
1542
+				}
1543
+			}
1544
+		}
1545
+	}
1546
+
1547
+
1548
+
1549
+	/**
1550
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1551
+	 * object just before saving.
1552
+	 *
1553
+	 * @access public
1554
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1555
+	 *                                 if provided during the save() method (often client code will change the fields'
1556
+	 *                                 values before calling save)
1557
+	 * @throws \EE_Error
1558
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1559
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1560
+	 */
1561
+	public function save($set_cols_n_values = array())
1562
+	{
1563
+		/**
1564
+		 * Filters the fields we're about to save on the model object
1565
+		 *
1566
+		 * @param array         $set_cols_n_values
1567
+		 * @param EE_Base_Class $model_object
1568
+		 */
1569
+		$set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1570
+			$this);
1571
+		//set attributes as provided in $set_cols_n_values
1572
+		foreach ($set_cols_n_values as $column => $value) {
1573
+			$this->set($column, $value);
1574
+		}
1575
+		// no changes ? then don't do anything
1576
+		if (! $this->_has_changes && $this->ID() && $this->get_model()->get_primary_key_field()->is_auto_increment()) {
1577
+			return 0;
1578
+		}
1579
+		/**
1580
+		 * Saving a model object.
1581
+		 * Before we perform a save, this action is fired.
1582
+		 *
1583
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1584
+		 */
1585
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1586
+		if ( ! $this->allow_persist()) {
1587
+			return 0;
1588
+		}
1589
+		//now get current attribute values
1590
+		$save_cols_n_values = $this->_fields;
1591
+		//if the object already has an ID, update it. Otherwise, insert it
1592
+		//also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1593
+		$old_assumption_concerning_value_preparation = $this->get_model()
1594
+															->get_assumption_concerning_values_already_prepared_by_model_object();
1595
+		$this->get_model()->assume_values_already_prepared_by_model_object(true);
1596
+		//does this model have an autoincrement PK?
1597
+		if ($this->get_model()->has_primary_key_field()) {
1598
+			if ($this->get_model()->get_primary_key_field()->is_auto_increment()) {
1599
+				//ok check if it's set, if so: update; if not, insert
1600
+				if ( ! empty($save_cols_n_values[self::_get_primary_key_name(get_class($this))])) {
1601
+					$results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1602
+				} else {
1603
+					unset($save_cols_n_values[self::_get_primary_key_name(get_class($this))]);
1604
+					$results = $this->get_model()->insert($save_cols_n_values);
1605
+					if ($results) {
1606
+						//if successful, set the primary key
1607
+						//but don't use the normal SET method, because it will check if
1608
+						//an item with the same ID exists in the mapper & db, then
1609
+						//will find it in the db (because we just added it) and THAT object
1610
+						//will get added to the mapper before we can add this one!
1611
+						//but if we just avoid using the SET method, all that headache can be avoided
1612
+						$pk_field_name = self::_get_primary_key_name(get_class($this));
1613
+						$this->_fields[$pk_field_name] = $results;
1614
+						$this->_clear_cached_property($pk_field_name);
1615
+						$this->get_model()->add_to_entity_map($this);
1616
+						$this->_update_cached_related_model_objs_fks();
1617
+					}
1618
+				}
1619
+			} else {//PK is NOT auto-increment
1620
+				//so check if one like it already exists in the db
1621
+				if ($this->get_model()->exists_by_ID($this->ID())) {
1622
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1623
+						throw new EE_Error(
1624
+							sprintf(
1625
+								__('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1626
+									'event_espresso'),
1627
+								get_class($this),
1628
+								get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1629
+								get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1630
+								'<br />'
1631
+							)
1632
+						);
1633
+					}
1634
+					$results = $this->get_model()->update_by_ID($save_cols_n_values, $this->ID());
1635
+				} else {
1636
+					$results = $this->get_model()->insert($save_cols_n_values);
1637
+					$this->_update_cached_related_model_objs_fks();
1638
+				}
1639
+			}
1640
+		} else {//there is NO primary key
1641
+			$already_in_db = false;
1642
+			foreach ($this->get_model()->unique_indexes() as $index) {
1643
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1644
+				if ($this->get_model()->exists(array($uniqueness_where_params))) {
1645
+					$already_in_db = true;
1646
+				}
1647
+			}
1648
+			if ($already_in_db) {
1649
+				$combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1650
+					$this->get_model()->get_combined_primary_key_fields());
1651
+				$results = $this->get_model()->update($save_cols_n_values, $combined_pk_fields_n_values);
1652
+			} else {
1653
+				$results = $this->get_model()->insert($save_cols_n_values);
1654
+			}
1655
+		}
1656
+		//restore the old assumption about values being prepared by the model object
1657
+		$this->get_model()
1658
+			 ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1659
+		/**
1660
+		 * After saving the model object this action is called
1661
+		 *
1662
+		 * @param EE_Base_Class $model_object which was just saved
1663
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1664
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1665
+		 */
1666
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1667
+		$this->_has_changes = false;
1668
+		return $results;
1669
+	}
1670
+
1671
+
1672
+
1673
+	/**
1674
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1675
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1676
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1677
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1678
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1679
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1680
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1681
+	 *
1682
+	 * @return void
1683
+	 * @throws \EE_Error
1684
+	 */
1685
+	protected function _update_cached_related_model_objs_fks()
1686
+	{
1687
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
1688
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1689
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1690
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1691
+						$this->get_model()->get_this_model_name()
1692
+					);
1693
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1694
+					if ($related_model_obj_in_cache->ID()) {
1695
+						$related_model_obj_in_cache->save();
1696
+					}
1697
+				}
1698
+			}
1699
+		}
1700
+	}
1701
+
1702
+
1703
+
1704
+	/**
1705
+	 * Saves this model object and its NEW cached relations to the database.
1706
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1707
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1708
+	 * because otherwise, there's a potential for infinite looping of saving
1709
+	 * Saves the cached related model objects, and ensures the relation between them
1710
+	 * and this object and properly setup
1711
+	 *
1712
+	 * @return int ID of new model object on save; 0 on failure+
1713
+	 * @throws \EE_Error
1714
+	 */
1715
+	public function save_new_cached_related_model_objs()
1716
+	{
1717
+		//make sure this has been saved
1718
+		if ( ! $this->ID()) {
1719
+			$id = $this->save();
1720
+		} else {
1721
+			$id = $this->ID();
1722
+		}
1723
+		//now save all the NEW cached model objects  (ie they don't exist in the DB)
1724
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1725
+			if ($this->_model_relations[$relationName]) {
1726
+				//is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1727
+				//or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1728
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1729
+					//add a relation to that relation type (which saves the appropriate thing in the process)
1730
+					//but ONLY if it DOES NOT exist in the DB
1731
+					/* @var $related_model_obj EE_Base_Class */
1732
+					$related_model_obj = $this->_model_relations[$relationName];
1733
+					//					if( ! $related_model_obj->ID()){
1734
+					$this->_add_relation_to($related_model_obj, $relationName);
1735
+					$related_model_obj->save_new_cached_related_model_objs();
1736
+					//					}
1737
+				} else {
1738
+					foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1739
+						//add a relation to that relation type (which saves the appropriate thing in the process)
1740
+						//but ONLY if it DOES NOT exist in the DB
1741
+						//						if( ! $related_model_obj->ID()){
1742
+						$this->_add_relation_to($related_model_obj, $relationName);
1743
+						$related_model_obj->save_new_cached_related_model_objs();
1744
+						//						}
1745
+					}
1746
+				}
1747
+			}
1748
+		}
1749
+		return $id;
1750
+	}
1751
+
1752
+
1753
+
1754
+	/**
1755
+	 * for getting a model while instantiated.
1756
+	 *
1757
+	 * @return \EEM_Base | \EEM_CPT_Base
1758
+	 */
1759
+	public function get_model()
1760
+	{
1761
+		$modelName = self::_get_model_classname(get_class($this));
1762
+		return self::_get_model_instance_with_name($modelName, $this->_timezone);
1763
+	}
1764
+
1765
+
1766
+
1767
+	/**
1768
+	 * @param $props_n_values
1769
+	 * @param $classname
1770
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1771
+	 * @throws \EE_Error
1772
+	 */
1773
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1774
+	{
1775
+		//TODO: will not work for Term_Relationships because they have no PK!
1776
+		$primary_id_ref = self::_get_primary_key_name($classname);
1777
+		if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1778
+			$id = $props_n_values[$primary_id_ref];
1779
+			return self::_get_model($classname)->get_from_entity_map($id);
1780
+		}
1781
+		return false;
1782
+	}
1783
+
1784
+
1785
+
1786
+	/**
1787
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1788
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1789
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1790
+	 * we return false.
1791
+	 *
1792
+	 * @param  array  $props_n_values   incoming array of properties and their values
1793
+	 * @param  string $classname        the classname of the child class
1794
+	 * @param null    $timezone
1795
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
1796
+	 *                                  date_format and the second value is the time format
1797
+	 * @return mixed (EE_Base_Class|bool)
1798
+	 * @throws \EE_Error
1799
+	 */
1800
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1801
+	{
1802
+		$existing = null;
1803
+		if (self::_get_model($classname)->has_primary_key_field()) {
1804
+			$primary_id_ref = self::_get_primary_key_name($classname);
1805
+			if (array_key_exists($primary_id_ref, $props_n_values)
1806
+				&& ! empty($props_n_values[$primary_id_ref])
1807
+			) {
1808
+				$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1809
+					$props_n_values[$primary_id_ref]
1810
+				);
1811
+			}
1812
+		} elseif (self::_get_model($classname, $timezone)->has_all_combined_primary_key_fields($props_n_values)) {
1813
+			//no primary key on this model, but there's still a matching item in the DB
1814
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1815
+				self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1816
+			);
1817
+		}
1818
+		if ($existing) {
1819
+			//set date formats if present before setting values
1820
+			if ( ! empty($date_formats) && is_array($date_formats)) {
1821
+				$existing->set_date_format($date_formats[0]);
1822
+				$existing->set_time_format($date_formats[1]);
1823
+			} else {
1824
+				//set default formats for date and time
1825
+				$existing->set_date_format(get_option('date_format'));
1826
+				$existing->set_time_format(get_option('time_format'));
1827
+			}
1828
+			foreach ($props_n_values as $property => $field_value) {
1829
+				$existing->set($property, $field_value);
1830
+			}
1831
+			return $existing;
1832
+		} else {
1833
+			return false;
1834
+		}
1835
+	}
1836
+
1837
+
1838
+
1839
+	/**
1840
+	 * Gets the EEM_*_Model for this class
1841
+	 *
1842
+	 * @access public now, as this is more convenient
1843
+	 * @param      $classname
1844
+	 * @param null $timezone
1845
+	 * @throws EE_Error
1846
+	 * @return EEM_Base
1847
+	 */
1848
+	protected static function _get_model($classname, $timezone = null)
1849
+	{
1850
+		//find model for this class
1851
+		if ( ! $classname) {
1852
+			throw new EE_Error(
1853
+				sprintf(
1854
+					__(
1855
+						"What were you thinking calling _get_model(%s)?? You need to specify the class name",
1856
+						"event_espresso"
1857
+					),
1858
+					$classname
1859
+				)
1860
+			);
1861
+		}
1862
+		$modelName = self::_get_model_classname($classname);
1863
+		return self::_get_model_instance_with_name($modelName, $timezone);
1864
+	}
1865
+
1866
+
1867
+
1868
+	/**
1869
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1870
+	 *
1871
+	 * @param string $model_classname
1872
+	 * @param null   $timezone
1873
+	 * @return EEM_Base
1874
+	 */
1875
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1876
+	{
1877
+		$model_classname = str_replace('EEM_', '', $model_classname);
1878
+		$model = EE_Registry::instance()->load_model($model_classname);
1879
+		$model->set_timezone($timezone);
1880
+		return $model;
1881
+	}
1882
+
1883
+
1884
+
1885
+	/**
1886
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
1887
+	 * Also works if a model class's classname is provided (eg EE_Registration).
1888
+	 *
1889
+	 * @param null $model_name
1890
+	 * @return string like EEM_Attendee
1891
+	 */
1892
+	private static function _get_model_classname($model_name = null)
1893
+	{
1894
+		if (strpos($model_name, "EE_") === 0) {
1895
+			$model_classname = str_replace("EE_", "EEM_", $model_name);
1896
+		} else {
1897
+			$model_classname = "EEM_" . $model_name;
1898
+		}
1899
+		return $model_classname;
1900
+	}
1901
+
1902
+
1903
+
1904
+	/**
1905
+	 * returns the name of the primary key attribute
1906
+	 *
1907
+	 * @param null $classname
1908
+	 * @throws EE_Error
1909
+	 * @return string
1910
+	 */
1911
+	protected static function _get_primary_key_name($classname = null)
1912
+	{
1913
+		if ( ! $classname) {
1914
+			throw new EE_Error(
1915
+				sprintf(
1916
+					__("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
1917
+					$classname
1918
+				)
1919
+			);
1920
+		}
1921
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
1922
+	}
1923
+
1924
+
1925
+
1926
+	/**
1927
+	 * Gets the value of the primary key.
1928
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
1929
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
1930
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
1931
+	 *
1932
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
1933
+	 * @throws \EE_Error
1934
+	 */
1935
+	public function ID()
1936
+	{
1937
+		//now that we know the name of the variable, use a variable variable to get its value and return its
1938
+		if ($this->get_model()->has_primary_key_field()) {
1939
+			return $this->_fields[self::_get_primary_key_name(get_class($this))];
1940
+		} else {
1941
+			return $this->get_model()->get_index_primary_key_string($this->_fields);
1942
+		}
1943
+	}
1944
+
1945
+
1946
+
1947
+	/**
1948
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
1949
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
1950
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
1951
+	 *
1952
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
1953
+	 * @param string $relationName                     eg 'Events','Question',etc.
1954
+	 *                                                 an attendee to a group, you also want to specify which role they
1955
+	 *                                                 will have in that group. So you would use this parameter to
1956
+	 *                                                 specify array('role-column-name'=>'role-id')
1957
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
1958
+	 *                                                 allow you to further constrict the relation to being added.
1959
+	 *                                                 However, keep in mind that the columns (keys) given must match a
1960
+	 *                                                 column on the JOIN table and currently only the HABTM models
1961
+	 *                                                 accept these additional conditions.  Also remember that if an
1962
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
1963
+	 *                                                 NEW row is created in the join table.
1964
+	 * @param null   $cache_id
1965
+	 * @throws EE_Error
1966
+	 * @return EE_Base_Class the object the relation was added to
1967
+	 */
1968
+	public function _add_relation_to(
1969
+		$otherObjectModelObjectOrID,
1970
+		$relationName,
1971
+		$extra_join_model_fields_n_values = array(),
1972
+		$cache_id = null
1973
+	) {
1974
+		//if this thing exists in the DB, save the relation to the DB
1975
+		if ($this->ID()) {
1976
+			$otherObject = $this->get_model()
1977
+								->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
1978
+									$extra_join_model_fields_n_values);
1979
+			//clear cache so future get_many_related and get_first_related() return new results.
1980
+			$this->clear_cache($relationName, $otherObject, true);
1981
+			if ($otherObject instanceof EE_Base_Class) {
1982
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
1983
+			}
1984
+		} else {
1985
+			//this thing doesn't exist in the DB,  so just cache it
1986
+			if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
1987
+				throw new EE_Error(sprintf(
1988
+					__('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
1989
+						'event_espresso'),
1990
+					$otherObjectModelObjectOrID,
1991
+					get_class($this)
1992
+				));
1993
+			} else {
1994
+				$otherObject = $otherObjectModelObjectOrID;
1995
+			}
1996
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
1997
+		}
1998
+		if ($otherObject instanceof EE_Base_Class) {
1999
+			//fix the reciprocal relation too
2000
+			if ($otherObject->ID()) {
2001
+				//its saved so assumed relations exist in the DB, so we can just
2002
+				//clear the cache so future queries use the updated info in the DB
2003
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), null, true);
2004
+			} else {
2005
+				//it's not saved, so it caches relations like this
2006
+				$otherObject->cache($this->get_model()->get_this_model_name(), $this);
2007
+			}
2008
+		}
2009
+		return $otherObject;
2010
+	}
2011
+
2012
+
2013
+
2014
+	/**
2015
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2016
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2017
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2018
+	 * from the cache
2019
+	 *
2020
+	 * @param mixed  $otherObjectModelObjectOrID
2021
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2022
+	 *                to the DB yet
2023
+	 * @param string $relationName
2024
+	 * @param array  $where_query
2025
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2026
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2027
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2028
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2029
+	 *                created in the join table.
2030
+	 * @return EE_Base_Class the relation was removed from
2031
+	 * @throws \EE_Error
2032
+	 */
2033
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2034
+	{
2035
+		if ($this->ID()) {
2036
+			//if this exists in the DB, save the relation change to the DB too
2037
+			$otherObject = $this->get_model()
2038
+								->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2039
+									$where_query);
2040
+			$this->clear_cache($relationName, $otherObject);
2041
+		} else {
2042
+			//this doesn't exist in the DB, just remove it from the cache
2043
+			$otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2044
+		}
2045
+		if ($otherObject instanceof EE_Base_Class) {
2046
+			$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2047
+		}
2048
+		return $otherObject;
2049
+	}
2050
+
2051
+
2052
+
2053
+	/**
2054
+	 * Removes ALL the related things for the $relationName.
2055
+	 *
2056
+	 * @param string $relationName
2057
+	 * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2058
+	 * @return EE_Base_Class
2059
+	 * @throws \EE_Error
2060
+	 */
2061
+	public function _remove_relations($relationName, $where_query_params = array())
2062
+	{
2063
+		if ($this->ID()) {
2064
+			//if this exists in the DB, save the relation change to the DB too
2065
+			$otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2066
+			$this->clear_cache($relationName, null, true);
2067
+		} else {
2068
+			//this doesn't exist in the DB, just remove it from the cache
2069
+			$otherObjects = $this->clear_cache($relationName, null, true);
2070
+		}
2071
+		if (is_array($otherObjects)) {
2072
+			foreach ($otherObjects as $otherObject) {
2073
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2074
+			}
2075
+		}
2076
+		return $otherObjects;
2077
+	}
2078
+
2079
+
2080
+
2081
+	/**
2082
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2083
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2084
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2085
+	 * because we want to get even deleted items etc.
2086
+	 *
2087
+	 * @param string $relationName key in the model's _model_relations array
2088
+	 * @param array  $query_params like EEM_Base::get_all
2089
+	 * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2090
+	 * @throws \EE_Error
2091
+	 *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2092
+	 *                             you want IDs
2093
+	 */
2094
+	public function get_many_related($relationName, $query_params = array())
2095
+	{
2096
+		if ($this->ID()) {
2097
+			//this exists in the DB, so get the related things from either the cache or the DB
2098
+			//if there are query parameters, forget about caching the related model objects.
2099
+			if ($query_params) {
2100
+				$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2101
+			} else {
2102
+				//did we already cache the result of this query?
2103
+				$cached_results = $this->get_all_from_cache($relationName);
2104
+				if ( ! $cached_results) {
2105
+					$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2106
+					//if no query parameters were passed, then we got all the related model objects
2107
+					//for that relation. We can cache them then.
2108
+					foreach ($related_model_objects as $related_model_object) {
2109
+						$this->cache($relationName, $related_model_object);
2110
+					}
2111
+				} else {
2112
+					$related_model_objects = $cached_results;
2113
+				}
2114
+			}
2115
+		} else {
2116
+			//this doesn't exist in the DB, so just get the related things from the cache
2117
+			$related_model_objects = $this->get_all_from_cache($relationName);
2118
+		}
2119
+		return $related_model_objects;
2120
+	}
2121
+
2122
+
2123
+
2124
+	/**
2125
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2126
+	 * unless otherwise specified in the $query_params
2127
+	 *
2128
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2129
+	 * @param array  $query_params   like EEM_Base::get_all's
2130
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2131
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2132
+	 *                               that by the setting $distinct to TRUE;
2133
+	 * @return int
2134
+	 */
2135
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2136
+	{
2137
+		return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2138
+	}
2139
+
2140
+
2141
+
2142
+	/**
2143
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2144
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2145
+	 *
2146
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2147
+	 * @param array  $query_params  like EEM_Base::get_all's
2148
+	 * @param string $field_to_sum  name of field to count by.
2149
+	 *                              By default, uses primary key (which doesn't make much sense, so you should probably
2150
+	 *                              change it)
2151
+	 * @return int
2152
+	 */
2153
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2154
+	{
2155
+		return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2156
+	}
2157
+
2158
+
2159
+
2160
+	/**
2161
+	 * Gets the first (ie, one) related model object of the specified type.
2162
+	 *
2163
+	 * @param string $relationName key in the model's _model_relations array
2164
+	 * @param array  $query_params like EEM_Base::get_all
2165
+	 * @return EE_Base_Class (not an array, a single object)
2166
+	 * @throws \EE_Error
2167
+	 */
2168
+	public function get_first_related($relationName, $query_params = array())
2169
+	{
2170
+		if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2171
+			//if they've provided some query parameters, don't bother trying to cache the result
2172
+			//also make sure we're not caching the result of get_first_related
2173
+			//on a relation which should have an array of objects (because the cache might have an array of objects)
2174
+			if ($query_params
2175
+				|| ! $this->get_model()->related_settings_for($relationName)
2176
+					 instanceof
2177
+					 EE_Belongs_To_Relation
2178
+			) {
2179
+				$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2180
+			} else {
2181
+				//first, check if we've already cached the result of this query
2182
+				$cached_result = $this->get_one_from_cache($relationName);
2183
+				if ( ! $cached_result) {
2184
+					$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2185
+					$this->cache($relationName, $related_model_object);
2186
+				} else {
2187
+					$related_model_object = $cached_result;
2188
+				}
2189
+			}
2190
+		} else {
2191
+			$related_model_object = null;
2192
+			//this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2193
+			if ($this->get_model()->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2194
+				$related_model_object = $this->get_model()->get_first_related($this, $relationName, $query_params);
2195
+			}
2196
+			//this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2197
+			if ( ! $related_model_object) {
2198
+				$related_model_object = $this->get_one_from_cache($relationName);
2199
+			}
2200
+		}
2201
+		return $related_model_object;
2202
+	}
2203
+
2204
+
2205
+
2206
+	/**
2207
+	 * Does a delete on all related objects of type $relationName and removes
2208
+	 * the current model object's relation to them. If they can't be deleted (because
2209
+	 * of blocking related model objects) does nothing. If the related model objects are
2210
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2211
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2212
+	 *
2213
+	 * @param string $relationName
2214
+	 * @param array  $query_params like EEM_Base::get_all's
2215
+	 * @return int how many deleted
2216
+	 * @throws \EE_Error
2217
+	 */
2218
+	public function delete_related($relationName, $query_params = array())
2219
+	{
2220
+		if ($this->ID()) {
2221
+			$count = $this->get_model()->delete_related($this, $relationName, $query_params);
2222
+		} else {
2223
+			$count = count($this->get_all_from_cache($relationName));
2224
+			$this->clear_cache($relationName, null, true);
2225
+		}
2226
+		return $count;
2227
+	}
2228
+
2229
+
2230
+
2231
+	/**
2232
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2233
+	 * the current model object's relation to them. If they can't be deleted (because
2234
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2235
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2236
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2237
+	 *
2238
+	 * @param string $relationName
2239
+	 * @param array  $query_params like EEM_Base::get_all's
2240
+	 * @return int how many deleted (including those soft deleted)
2241
+	 * @throws \EE_Error
2242
+	 */
2243
+	public function delete_related_permanently($relationName, $query_params = array())
2244
+	{
2245
+		if ($this->ID()) {
2246
+			$count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2247
+		} else {
2248
+			$count = count($this->get_all_from_cache($relationName));
2249
+		}
2250
+		$this->clear_cache($relationName, null, true);
2251
+		return $count;
2252
+	}
2253
+
2254
+
2255
+
2256
+	/**
2257
+	 * is_set
2258
+	 * Just a simple utility function children can use for checking if property exists
2259
+	 *
2260
+	 * @access  public
2261
+	 * @param  string $field_name property to check
2262
+	 * @return bool                              TRUE if existing,FALSE if not.
2263
+	 */
2264
+	public function is_set($field_name)
2265
+	{
2266
+		return isset($this->_fields[$field_name]);
2267
+	}
2268
+
2269
+
2270
+
2271
+	/**
2272
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2273
+	 * EE_Error exception if they don't
2274
+	 *
2275
+	 * @param  mixed (string|array) $properties properties to check
2276
+	 * @throws EE_Error
2277
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2278
+	 */
2279
+	protected function _property_exists($properties)
2280
+	{
2281
+		foreach ((array)$properties as $property_name) {
2282
+			//first make sure this property exists
2283
+			if ( ! $this->_fields[$property_name]) {
2284
+				throw new EE_Error(
2285
+					sprintf(
2286
+						__(
2287
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2288
+							'event_espresso'
2289
+						),
2290
+						$property_name
2291
+					)
2292
+				);
2293
+			}
2294
+		}
2295
+		return true;
2296
+	}
2297
+
2298
+
2299
+
2300
+	/**
2301
+	 * This simply returns an array of model fields for this object
2302
+	 *
2303
+	 * @return array
2304
+	 * @throws \EE_Error
2305
+	 */
2306
+	public function model_field_array()
2307
+	{
2308
+		$fields = $this->get_model()->field_settings(false);
2309
+		$properties = array();
2310
+		//remove prepended underscore
2311
+		foreach ($fields as $field_name => $settings) {
2312
+			$properties[$field_name] = $this->get($field_name);
2313
+		}
2314
+		return $properties;
2315
+	}
2316
+
2317
+
2318
+
2319
+	/**
2320
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2321
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2322
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2323
+	 * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2324
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2325
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2326
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
2327
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
2328
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2329
+	 * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2330
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2331
+	 *        return $previousReturnValue.$returnString;
2332
+	 * }
2333
+	 * require('EE_Answer.class.php');
2334
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2335
+	 * echo $answer->my_callback('monkeys',100);
2336
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2337
+	 *
2338
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2339
+	 * @param array  $args       array of original arguments passed to the function
2340
+	 * @throws EE_Error
2341
+	 * @return mixed whatever the plugin which calls add_filter decides
2342
+	 */
2343
+	public function __call($methodName, $args)
2344
+	{
2345
+		$className = get_class($this);
2346
+		$tagName = "FHEE__{$className}__{$methodName}";
2347
+		if ( ! has_filter($tagName)) {
2348
+			throw new EE_Error(
2349
+				sprintf(
2350
+					__(
2351
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2352
+						"event_espresso"
2353
+					),
2354
+					$methodName,
2355
+					$className,
2356
+					$tagName
2357
+				)
2358
+			);
2359
+		}
2360
+		return apply_filters($tagName, null, $this, $args);
2361
+	}
2362
+
2363
+
2364
+
2365
+	/**
2366
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2367
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2368
+	 *
2369
+	 * @param string $meta_key
2370
+	 * @param mixed  $meta_value
2371
+	 * @param mixed  $previous_value
2372
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2373
+	 * @throws \EE_Error
2374
+	 * NOTE: if the values haven't changed, returns 0
2375
+	 */
2376
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2377
+	{
2378
+		$query_params = array(
2379
+			array(
2380
+				'EXM_key'  => $meta_key,
2381
+				'OBJ_ID'   => $this->ID(),
2382
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2383
+			),
2384
+		);
2385
+		if ($previous_value !== null) {
2386
+			$query_params[0]['EXM_value'] = $meta_value;
2387
+		}
2388
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2389
+		if ( ! $existing_rows_like_that) {
2390
+			return $this->add_extra_meta($meta_key, $meta_value);
2391
+		}
2392
+		foreach ($existing_rows_like_that as $existing_row) {
2393
+			$existing_row->save(array('EXM_value' => $meta_value));
2394
+		}
2395
+		return count($existing_rows_like_that);
2396
+	}
2397
+
2398
+
2399
+
2400
+	/**
2401
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2402
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2403
+	 * extra meta row was entered, false if not
2404
+	 *
2405
+	 * @param string  $meta_key
2406
+	 * @param string  $meta_value
2407
+	 * @param boolean $unique
2408
+	 * @return boolean
2409
+	 * @throws \EE_Error
2410
+	 */
2411
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2412
+	{
2413
+		if ($unique) {
2414
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2415
+				array(
2416
+					array(
2417
+						'EXM_key'  => $meta_key,
2418
+						'OBJ_ID'   => $this->ID(),
2419
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2420
+					),
2421
+				)
2422
+			);
2423
+			if ($existing_extra_meta) {
2424
+				return false;
2425
+			}
2426
+		}
2427
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2428
+			array(
2429
+				'EXM_key'   => $meta_key,
2430
+				'EXM_value' => $meta_value,
2431
+				'OBJ_ID'    => $this->ID(),
2432
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2433
+			)
2434
+		);
2435
+		$new_extra_meta->save();
2436
+		return true;
2437
+	}
2438
+
2439
+
2440
+
2441
+	/**
2442
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2443
+	 * is specified, only deletes extra meta records with that value.
2444
+	 *
2445
+	 * @param string $meta_key
2446
+	 * @param string $meta_value
2447
+	 * @return int number of extra meta rows deleted
2448
+	 * @throws \EE_Error
2449
+	 */
2450
+	public function delete_extra_meta($meta_key, $meta_value = null)
2451
+	{
2452
+		$query_params = array(
2453
+			array(
2454
+				'EXM_key'  => $meta_key,
2455
+				'OBJ_ID'   => $this->ID(),
2456
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2457
+			),
2458
+		);
2459
+		if ($meta_value !== null) {
2460
+			$query_params[0]['EXM_value'] = $meta_value;
2461
+		}
2462
+		return EEM_Extra_Meta::instance()->delete($query_params);
2463
+	}
2464
+
2465
+
2466
+
2467
+	/**
2468
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2469
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2470
+	 * You can specify $default is case you haven't found the extra meta
2471
+	 *
2472
+	 * @param string  $meta_key
2473
+	 * @param boolean $single
2474
+	 * @param mixed   $default if we don't find anything, what should we return?
2475
+	 * @return mixed single value if $single; array if ! $single
2476
+	 * @throws \EE_Error
2477
+	 */
2478
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2479
+	{
2480
+		if ($single) {
2481
+			$result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2482
+			if ($result instanceof EE_Extra_Meta) {
2483
+				return $result->value();
2484
+			} else {
2485
+				return $default;
2486
+			}
2487
+		} else {
2488
+			$results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2489
+			if ($results) {
2490
+				$values = array();
2491
+				foreach ($results as $result) {
2492
+					if ($result instanceof EE_Extra_Meta) {
2493
+						$values[$result->ID()] = $result->value();
2494
+					}
2495
+				}
2496
+				return $values;
2497
+			} else {
2498
+				return $default;
2499
+			}
2500
+		}
2501
+	}
2502
+
2503
+
2504
+
2505
+	/**
2506
+	 * Returns a simple array of all the extra meta associated with this model object.
2507
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2508
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2509
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2510
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2511
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2512
+	 * finally the extra meta's value as each sub-value. (eg
2513
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2514
+	 *
2515
+	 * @param boolean $one_of_each_key
2516
+	 * @return array
2517
+	 * @throws \EE_Error
2518
+	 */
2519
+	public function all_extra_meta_array($one_of_each_key = true)
2520
+	{
2521
+		$return_array = array();
2522
+		if ($one_of_each_key) {
2523
+			$extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2524
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2525
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2526
+					$return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2527
+				}
2528
+			}
2529
+		} else {
2530
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2531
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2532
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2533
+					if ( ! isset($return_array[$extra_meta_obj->key()])) {
2534
+						$return_array[$extra_meta_obj->key()] = array();
2535
+					}
2536
+					$return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2537
+				}
2538
+			}
2539
+		}
2540
+		return $return_array;
2541
+	}
2542
+
2543
+
2544
+
2545
+	/**
2546
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2547
+	 *
2548
+	 * @return string
2549
+	 * @throws \EE_Error
2550
+	 */
2551
+	public function name()
2552
+	{
2553
+		//find a field that's not a text field
2554
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2555
+		if ($field_we_can_use) {
2556
+			return $this->get($field_we_can_use->get_name());
2557
+		} else {
2558
+			$first_few_properties = $this->model_field_array();
2559
+			$first_few_properties = array_slice($first_few_properties, 0, 3);
2560
+			$name_parts = array();
2561
+			foreach ($first_few_properties as $name => $value) {
2562
+				$name_parts[] = "$name:$value";
2563
+			}
2564
+			return implode(",", $name_parts);
2565
+		}
2566
+	}
2567
+
2568
+
2569
+
2570
+	/**
2571
+	 * in_entity_map
2572
+	 * Checks if this model object has been proven to already be in the entity map
2573
+	 *
2574
+	 * @return boolean
2575
+	 * @throws \EE_Error
2576
+	 */
2577
+	public function in_entity_map()
2578
+	{
2579
+		if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2580
+			//well, if we looked, did we find it in the entity map?
2581
+			return true;
2582
+		} else {
2583
+			return false;
2584
+		}
2585
+	}
2586
+
2587
+
2588
+
2589
+	/**
2590
+	 * refresh_from_db
2591
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
2592
+	 *
2593
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2594
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2595
+	 */
2596
+	public function refresh_from_db()
2597
+	{
2598
+		if ($this->ID() && $this->in_entity_map()) {
2599
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
2600
+		} else {
2601
+			//if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2602
+			//if it has an ID but it's not in the map, and you're asking me to refresh it
2603
+			//that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2604
+			//absolutely nothing in it for this ID
2605
+			if (WP_DEBUG) {
2606
+				throw new EE_Error(
2607
+					sprintf(
2608
+						__('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2609
+							'event_espresso'),
2610
+						$this->ID(),
2611
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2612
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2613
+					)
2614
+				);
2615
+			}
2616
+		}
2617
+	}
2618
+
2619
+
2620
+
2621
+	/**
2622
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2623
+	 * (probably a bad assumption they have made, oh well)
2624
+	 *
2625
+	 * @return string
2626
+	 */
2627
+	public function __toString()
2628
+	{
2629
+		try {
2630
+			return sprintf('%s (%s)', $this->name(), $this->ID());
2631
+		} catch (Exception $e) {
2632
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2633
+			return '';
2634
+		}
2635
+	}
2636
+
2637
+
2638
+
2639
+	/**
2640
+	 * Clear related model objects if they're already in the DB, because otherwise when we
2641
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
2642
+	 * This means if we have made changes to those related model objects, and want to unserialize
2643
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
2644
+	 * Instead, those related model objects should be directly serialized and stored.
2645
+	 * Eg, the following won't work:
2646
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2647
+	 * $att = $reg->attendee();
2648
+	 * $att->set( 'ATT_fname', 'Dirk' );
2649
+	 * update_option( 'my_option', serialize( $reg ) );
2650
+	 * //END REQUEST
2651
+	 * //START NEXT REQUEST
2652
+	 * $reg = get_option( 'my_option' );
2653
+	 * $reg->attendee()->save();
2654
+	 * And would need to be replace with:
2655
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2656
+	 * $att = $reg->attendee();
2657
+	 * $att->set( 'ATT_fname', 'Dirk' );
2658
+	 * update_option( 'my_option', serialize( $reg ) );
2659
+	 * //END REQUEST
2660
+	 * //START NEXT REQUEST
2661
+	 * $att = get_option( 'my_option' );
2662
+	 * $att->save();
2663
+	 *
2664
+	 * @return array
2665
+	 * @throws \EE_Error
2666
+	 */
2667
+	public function __sleep()
2668
+	{
2669
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2670
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
2671
+				$classname = 'EE_' . $this->get_model()->get_this_model_name();
2672
+				if (
2673
+					$this->get_one_from_cache($relation_name) instanceof $classname
2674
+					&& $this->get_one_from_cache($relation_name)->ID()
2675
+				) {
2676
+					$this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2677
+				}
2678
+			}
2679
+		}
2680
+		$this->_props_n_values_provided_in_constructor = array();
2681
+		return array_keys(get_object_vars($this));
2682
+	}
2683
+
2684
+
2685
+
2686
+	/**
2687
+	 * restore _props_n_values_provided_in_constructor
2688
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2689
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
2690
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
2691
+	 */
2692
+	public function __wakeup()
2693
+	{
2694
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
2695
+	}
2696 2696
 
2697 2697
 
2698 2698
 
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -150,8 +150,8 @@  discard block
 block discarded – undo
150 150
             list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
151 151
         } else {
152 152
             //set default formats for date and time
153
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
154
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
153
+            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
154
+            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
155 155
         }
156 156
         //if db model is instantiating
157 157
         if ($bydb) {
@@ -472,7 +472,7 @@  discard block
 block discarded – undo
472 472
      */
473 473
     public function get_format($full = true)
474 474
     {
475
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
475
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
476 476
     }
477 477
 
478 478
 
@@ -580,7 +580,7 @@  discard block
 block discarded – undo
580 580
         //verify the field exists
581 581
         $this->get_model()->field_settings_for($fieldname);
582 582
         $cache_type = $pretty ? 'pretty' : 'standard';
583
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
583
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
584 584
         if (isset($this->_cached_properties[$fieldname][$cache_type])) {
585 585
             return $this->_cached_properties[$fieldname][$cache_type];
586 586
         }
@@ -795,7 +795,7 @@  discard block
 block discarded – undo
795 795
         $current_cache_id = ''
796 796
     ) {
797 797
         // verify that incoming object is of the correct type
798
-        $obj_class = 'EE_' . $relationName;
798
+        $obj_class = 'EE_'.$relationName;
799 799
         if ($newly_saved_object instanceof $obj_class) {
800 800
             /* @type EE_Base_Class $newly_saved_object */
801 801
             // now get the type of relation
@@ -1277,7 +1277,7 @@  discard block
 block discarded – undo
1277 1277
      */
1278 1278
     public function get_i18n_datetime($field_name, $format = '')
1279 1279
     {
1280
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1280
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1281 1281
         return date_i18n(
1282 1282
             $format,
1283 1283
             EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
@@ -1415,8 +1415,8 @@  discard block
 block discarded – undo
1415 1415
         }
1416 1416
         $original_timezone = $this->_timezone;
1417 1417
         $this->set_timezone($timezone);
1418
-        $fn = (array)$field_name;
1419
-        $args = array_merge($fn, (array)$args);
1418
+        $fn = (array) $field_name;
1419
+        $args = array_merge($fn, (array) $args);
1420 1420
         if ( ! method_exists($this, $callback)) {
1421 1421
             throw new EE_Error(
1422 1422
                 sprintf(
@@ -1428,8 +1428,8 @@  discard block
 block discarded – undo
1428 1428
                 )
1429 1429
             );
1430 1430
         }
1431
-        $args = (array)$args;
1432
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1431
+        $args = (array) $args;
1432
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1433 1433
         $this->set_timezone($original_timezone);
1434 1434
         return $return;
1435 1435
     }
@@ -1566,14 +1566,14 @@  discard block
 block discarded – undo
1566 1566
          * @param array         $set_cols_n_values
1567 1567
          * @param EE_Base_Class $model_object
1568 1568
          */
1569
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1569
+        $set_cols_n_values = (array) apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1570 1570
             $this);
1571 1571
         //set attributes as provided in $set_cols_n_values
1572 1572
         foreach ($set_cols_n_values as $column => $value) {
1573 1573
             $this->set($column, $value);
1574 1574
         }
1575 1575
         // no changes ? then don't do anything
1576
-        if (! $this->_has_changes && $this->ID() && $this->get_model()->get_primary_key_field()->is_auto_increment()) {
1576
+        if ( ! $this->_has_changes && $this->ID() && $this->get_model()->get_primary_key_field()->is_auto_increment()) {
1577 1577
             return 0;
1578 1578
         }
1579 1579
         /**
@@ -1625,8 +1625,8 @@  discard block
 block discarded – undo
1625 1625
                                 __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1626 1626
                                     'event_espresso'),
1627 1627
                                 get_class($this),
1628
-                                get_class($this->get_model()) . '::instance()->add_to_entity_map()',
1629
-                                get_class($this->get_model()) . '::instance()->get_one_by_ID()',
1628
+                                get_class($this->get_model()).'::instance()->add_to_entity_map()',
1629
+                                get_class($this->get_model()).'::instance()->get_one_by_ID()',
1630 1630
                                 '<br />'
1631 1631
                             )
1632 1632
                         );
@@ -1894,7 +1894,7 @@  discard block
 block discarded – undo
1894 1894
         if (strpos($model_name, "EE_") === 0) {
1895 1895
             $model_classname = str_replace("EE_", "EEM_", $model_name);
1896 1896
         } else {
1897
-            $model_classname = "EEM_" . $model_name;
1897
+            $model_classname = "EEM_".$model_name;
1898 1898
         }
1899 1899
         return $model_classname;
1900 1900
     }
@@ -2278,7 +2278,7 @@  discard block
 block discarded – undo
2278 2278
      */
2279 2279
     protected function _property_exists($properties)
2280 2280
     {
2281
-        foreach ((array)$properties as $property_name) {
2281
+        foreach ((array) $properties as $property_name) {
2282 2282
             //first make sure this property exists
2283 2283
             if ( ! $this->_fields[$property_name]) {
2284 2284
                 throw new EE_Error(
@@ -2608,8 +2608,8 @@  discard block
 block discarded – undo
2608 2608
                         __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2609 2609
                             'event_espresso'),
2610 2610
                         $this->ID(),
2611
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2612
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2611
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
2612
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
2613 2613
                     )
2614 2614
                 );
2615 2615
             }
@@ -2668,7 +2668,7 @@  discard block
 block discarded – undo
2668 2668
     {
2669 2669
         foreach ($this->get_model()->relation_settings() as $relation_name => $relation_obj) {
2670 2670
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
2671
-                $classname = 'EE_' . $this->get_model()->get_this_model_name();
2671
+                $classname = 'EE_'.$this->get_model()->get_this_model_name();
2672 2672
                 if (
2673 2673
                     $this->get_one_from_cache($relation_name) instanceof $classname
2674 2674
                     && $this->get_one_from_cache($relation_name)->ID()
Please login to merge, or discard this patch.
core/domain/services/event/EventSpacesCalculator.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -164,7 +164,7 @@
 block discarded – undo
164 164
 
165 165
 
166 166
     /**
167
-     * @param $ticket
167
+     * @param \EE_Base_Class $ticket
168 168
      * @throws DomainException
169 169
      * @throws EE_Error
170 170
      * @throws UnexpectedEntityException
Please login to merge, or discard this patch.
Indentation   +495 added lines, -495 removed lines patch added patch discarded remove patch
@@ -27,501 +27,501 @@
 block discarded – undo
27 27
 class EventSpacesCalculator
28 28
 {
29 29
 
30
-    /**
31
-     * @var EE_Event $event
32
-     */
33
-    private $event;
34
-
35
-    /**
36
-     * @var array $datetime_query_params
37
-     */
38
-    private $datetime_query_params;
39
-
40
-    /**
41
-     * @var EE_Ticket[] $active_tickets
42
-     */
43
-    private $active_tickets = array();
44
-
45
-    /**
46
-     * @var EE_Datetime[] $datetimes
47
-     */
48
-    private $datetimes = array();
49
-
50
-    /**
51
-     * Array of Ticket IDs grouped by Datetime
52
-     *
53
-     * @var array $datetimes
54
-     */
55
-    private $datetime_tickets = array();
56
-
57
-    /**
58
-     * Max spaces for each Datetime (reg limit - previous sold)
59
-     *
60
-     * @var array $datetime_spaces
61
-     */
62
-    private $datetime_spaces = array();
63
-
64
-    /**
65
-     * Array of Datetime IDs grouped by Ticket
66
-     *
67
-     * @var array $ticket_datetimes
68
-     */
69
-    private $ticket_datetimes = array();
70
-
71
-    /**
72
-     * maximum ticket quantities for each ticket (adjusted for reg limit)
73
-     *
74
-     * @var array $ticket_quantities
75
-     */
76
-    private $ticket_quantities = array();
77
-
78
-    /**
79
-     * total quantity of sold and reserved for each ticket
80
-     *
81
-     * @var array $tickets_sold
82
-     */
83
-    private $tickets_sold = array();
84
-
85
-    /**
86
-     * total spaces available across all datetimes
87
-     *
88
-     * @var array $total_spaces
89
-     */
90
-    private $total_spaces = array();
91
-
92
-    /**
93
-     * @var boolean $debug
94
-     */
95
-    private $debug = false;
96
-
97
-
98
-
99
-    /**
100
-     * EventSpacesCalculator constructor.
101
-     *
102
-     * @param EE_Event $event
103
-     * @param array    $datetime_query_params
104
-     * @throws EE_Error
105
-     */
106
-    public function __construct(EE_Event $event, array $datetime_query_params = array())
107
-    {
108
-        $this->event = $event;
109
-        $this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
110
-    }
111
-
112
-
113
-
114
-    /**
115
-     * @return EE_Ticket[]
116
-     * @throws EE_Error
117
-     */
118
-    public function getActiveTickets()
119
-    {
120
-        if(empty($this->active_tickets)) {
121
-            $this->active_tickets = $this->event->tickets(
122
-                array(
123
-                    array(
124
-                        'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
125
-                        'TKT_deleted'  => false,
126
-                    ),
127
-                    'order_by' => array('TKT_qty' => 'ASC')
128
-                )
129
-            );
130
-        }
131
-        return $this->active_tickets;
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     * @param EE_Ticket[] $active_tickets
138
-     * @throws EE_Error
139
-     * @throws DomainException
140
-     * @throws UnexpectedEntityException
141
-     */
142
-    public function setActiveTickets(array $active_tickets = array())
143
-    {
144
-        if (! empty($active_tickets)){
145
-            foreach ($active_tickets as $active_ticket) {
146
-                $this->validateTicket($active_ticket);
147
-            }
148
-            // sort incoming array by ticket quantity (asc)
149
-            usort(
150
-                $active_tickets,
151
-                function (EE_Ticket $a, EE_Ticket $b) {
152
-                    if ($a->qty() === $b->qty()) {
153
-                        return 0;
154
-                    }
155
-                    return ($a->qty() < $b->qty())
156
-                        ? -1
157
-                        : 1;
158
-                }
159
-            );
160
-        }
161
-        $this->active_tickets = $active_tickets;
162
-    }
163
-
164
-
165
-
166
-    /**
167
-     * @param $ticket
168
-     * @throws DomainException
169
-     * @throws EE_Error
170
-     * @throws UnexpectedEntityException
171
-     */
172
-    private function validateTicket($ticket)
173
-    {
174
-        if (! $ticket instanceof EE_Ticket) {
175
-            throw new DomainException(
176
-                esc_html__(
177
-                    'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
178
-                    'event_espresso'
179
-                )
180
-            );
181
-        }
182
-        if ($ticket->get_event_ID() !== $this->event->ID()) {
183
-            throw new DomainException(
184
-                sprintf(
185
-                    esc_html__(
186
-                        'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
187
-                        'event_espresso'
188
-                    ),
189
-                    $ticket->get_event_ID(),
190
-                    $this->event->ID()
191
-                )
192
-            );
193
-        }
194
-    }
195
-
196
-
197
-
198
-    /**
199
-     * @return EE_Datetime[]
200
-     */
201
-    public function getDatetimes()
202
-    {
203
-        return $this->datetimes;
204
-    }
205
-
206
-
207
-
208
-    /**
209
-     * @param EE_Datetime $datetime
210
-     * @throws EE_Error
211
-     * @throws DomainException
212
-     */
213
-    public function setDatetime(EE_Datetime $datetime)
214
-    {
215
-        if ($datetime->event()->ID() !== $this->event->ID()) {
216
-            throw new DomainException(
217
-                sprintf(
218
-                    esc_html__(
219
-                        'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
220
-                        'event_espresso'
221
-                    ),
222
-                    $datetime->event()->ID(),
223
-                    $this->event->ID()
224
-                )
225
-            );
226
-        }
227
-        $this->datetimes[$datetime->ID()] = $datetime;
228
-    }
229
-
230
-
231
-
232
-    /**
233
-     * calculate spaces remaining based on "saleable" tickets
234
-     *
235
-     * @return float|int
236
-     * @throws EE_Error
237
-     * @throws DomainException
238
-     * @throws UnexpectedEntityException
239
-     */
240
-    public function spacesRemaining()
241
-    {
242
-        $this->initialize();
243
-        return $this->calculate();
244
-    }
245
-
246
-
247
-
248
-    /**
249
-     * calculates total available spaces for an event with no regard for sold tickets
250
-     *
251
-     * @return int|float
252
-     * @throws EE_Error
253
-     * @throws DomainException
254
-     * @throws UnexpectedEntityException
255
-     */
256
-    public function totalSpacesAvailable()
257
-    {
258
-        $this->initialize();
259
-        return $this->calculate(false);
260
-    }
261
-
262
-
263
-
264
-    /**
265
-     * Loops through the active tickets for the event
266
-     * and builds a series of data arrays that will be used for calculating
267
-     * the total maximum available spaces, as well as the spaces remaining.
268
-     * Because ticket quantities affect datetime spaces and vice versa,
269
-     * we need to be constantly updating these data arrays as things change,
270
-     * which is the entire reason for their existence.
271
-     *
272
-     * @throws EE_Error
273
-     * @throws DomainException
274
-     * @throws UnexpectedEntityException
275
-     */
276
-    private function initialize()
277
-    {
278
-        if ($this->debug) {
279
-            echo "\n\n" . __LINE__ . ') ' . strtoupper(__METHOD__) . '()';
280
-        }
281
-        $this->datetime_tickets = array();
282
-        $this->datetime_spaces = array();
283
-        $this->ticket_datetimes = array();
284
-        $this->ticket_quantities = array();
285
-        $this->tickets_sold = array();
286
-        $this->total_spaces = array();
287
-        $active_tickets = $this->getActiveTickets();
288
-        if (! empty($active_tickets)) {
289
-            foreach ($active_tickets as $ticket) {
290
-                $this->validateTicket($ticket);
291
-                // we need to index our data arrays using strings for the purpose of sorting,
292
-                // but we also need them to be unique, so  we'll just prepend a letter T to the ID
293
-                $ticket_identifier = "T{$ticket->ID()}";
294
-                // to start, we'll just consider the raw qty to be the maximum availability for this ticket
295
-                $max_tickets = $ticket->qty();
296
-                // but we'll adjust that after looping over each datetime for the ticket and checking reg limits
297
-                $ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
298
-                foreach ($ticket_datetimes as $datetime) {
299
-                    // save all datetimes
300
-                    $this->setDatetime($datetime);
301
-                    $datetime_identifier = "D{$datetime->ID()}";
302
-                    $reg_limit = $datetime->reg_limit();
303
-                    // ticket quantity can not exceed datetime reg limit
304
-                    $max_tickets = min($max_tickets, $reg_limit);
305
-                    // as described earlier, because we need to be able to constantly adjust numbers for things,
306
-                    // we are going to move all of our data into the following arrays:
307
-                    // datetime spaces initially represents the reg limit for each datetime,
308
-                    // but this will get adjusted as tickets are accounted for
309
-                    $this->datetime_spaces[$datetime_identifier] = $reg_limit;
310
-                    // just an array of ticket IDs grouped by datetime
311
-                    $this->datetime_tickets[$datetime_identifier][] = $ticket_identifier;
312
-                    // and an array of datetime IDs grouped by ticket
313
-                    $this->ticket_datetimes[$ticket_identifier][] = $datetime_identifier;
314
-                }
315
-                // total quantity of sold and reserved for each ticket
316
-                $this->tickets_sold[$ticket_identifier] = $ticket->sold() + $ticket->reserved();
317
-                // and the maximum ticket quantities for each ticket (adjusted for reg limit)
318
-                $this->ticket_quantities[$ticket_identifier] = $max_tickets;
319
-            }
320
-        }
321
-        // sort datetime spaces by reg limit, but maintain our string indexes
322
-        asort($this->datetime_spaces, SORT_NUMERIC);
323
-        // datetime tickets need to be sorted in the SAME order as the above array...
324
-        // so we'll just use array_merge() to take the structure of datetime_spaces
325
-        // but overwrite all of the data with that from datetime_tickets
326
-        $this->datetime_tickets = array_merge(
327
-            $this->datetime_spaces,
328
-            $this->datetime_tickets
329
-        );
330
-        if ($this->debug) {
331
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
332
-            \EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
333
-            \EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
334
-        }
335
-    }
336
-
337
-
338
-
339
-    /**
340
-     * performs calculations on initialized data
341
-     *
342
-     * @param bool $consider_sold
343
-     * @return int|float
344
-     */
345
-    private function calculate($consider_sold = true)
346
-    {
347
-        if ($this->debug) {
348
-            echo "\n\n" . __LINE__ . ') ' . strtoupper(__METHOD__) . '()';
349
-        }
350
-        foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
351
-            $this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
352
-        }
353
-        // total spaces available is just the sum of the spaces available for each datetime
354
-        $spaces_remaining = array_sum($this->total_spaces);
355
-        if($consider_sold) {
356
-            // less the sum of all tickets sold for these datetimes
357
-            $spaces_remaining -= array_sum($this->tickets_sold);
358
-        }
359
-        if ($this->debug) {
360
-            \EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
361
-            \EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
362
-            \EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
363
-        }
364
-        return $spaces_remaining;
365
-    }
366
-
367
-
368
-
369
-    /**
370
-     * @param string $datetime_identifier
371
-     * @param array  $tickets
372
-     */
373
-    private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
374
-    {
375
-        // make sure a reg limit is set for the datetime
376
-        $reg_limit = isset($this->datetime_spaces[$datetime_identifier])
377
-            ? $this->datetime_spaces[$datetime_identifier]
378
-            : 0;
379
-        // and bail if it is not
380
-        if (! $reg_limit) {
381
-            if ($this->debug) {
382
-                echo "\n . {$datetime_identifier} AT CAPACITY";
383
-            }
384
-            return;
385
-        }
386
-        if ($this->debug) {
387
-            echo "\n\n{$datetime_identifier}";
388
-            echo "\n . " . 'REG LIMIT: ' . $reg_limit;
389
-        }
390
-        // set default number of available spaces
391
-        $available_spaces = 0;
392
-        $this->total_spaces[$datetime_identifier] = 0;
393
-        foreach ($tickets as $ticket_identifier) {
394
-            $available_spaces = $this->calculateAvailableSpacesForTicket(
395
-                $datetime_identifier,
396
-                $reg_limit,
397
-                $ticket_identifier,
398
-                $available_spaces
399
-            );
400
-        }
401
-        // spaces can't be negative
402
-        $available_spaces = max($available_spaces, 0);
403
-        if ($available_spaces) {
404
-            // track any non-zero values
405
-            $this->total_spaces[$datetime_identifier] += $available_spaces;
406
-            if ($this->debug) {
407
-                echo "\n . spaces: {$available_spaces}";
408
-            }
409
-        } else {
410
-            if ($this->debug) {
411
-                echo "\n . NO TICKETS AVAILABLE FOR DATETIME";
412
-            }
413
-        }
414
-        if ($this->debug) {
415
-            \EEH_Debug_Tools::printr($this->total_spaces[$datetime_identifier], '$spaces_remaining', __FILE__, __LINE__);
416
-            \EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
417
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
418
-        }
419
-    }
420
-
421
-
422
-
423
-    /**
424
-     * @param string $datetime_identifier
425
-     * @param int    $reg_limit
426
-     * @param string $ticket_identifier
427
-     * @param int    $available_spaces
428
-     * @return int
429
-     */
430
-    private function calculateAvailableSpacesForTicket($datetime_identifier, $reg_limit,$ticket_identifier, $available_spaces)
431
-    {
432
-        if ($this->debug) {
433
-            echo "\n . {$ticket_identifier}";
434
-        }
435
-        // make sure ticket quantity is set
436
-        $ticket_quantity = isset($this->ticket_quantities[$ticket_identifier])
437
-            ? $this->ticket_quantities[$ticket_identifier]
438
-            : 0;
439
-        if ($ticket_quantity) {
440
-            if ($this->debug) {
441
-                echo "\n . . available_spaces ({$available_spaces}) <= reg_limit ({$reg_limit}) = ";
442
-                echo ($available_spaces <= $reg_limit)
443
-                    ? 'true'
444
-                    : 'false';
445
-            }
446
-            // if the datetime is NOT at full capacity yet
447
-            if ($available_spaces <= $reg_limit) {
448
-                // then the maximum ticket quantity we can allocate is the lowest value of either:
449
-                //  the number of remaining spaces for the datetime, which is the limit - spaces already taken
450
-                //  or the maximum ticket quantity
451
-                $ticket_quantity = min(($reg_limit - $available_spaces), $ticket_quantity);
452
-                // adjust the available quantity in our tracking array
453
-                $this->ticket_quantities[$ticket_identifier] -= $ticket_quantity;
454
-                // and increment spaces allocated for this datetime
455
-                $available_spaces += $ticket_quantity;
456
-                if ($this->debug) {
457
-                    echo "\n . . ticket quantity: {$ticket_quantity} ({$ticket_identifier})";
458
-                    echo "\n . . . allocate {$ticket_quantity} tickets ({$ticket_identifier})";
459
-                    if ($available_spaces >= $reg_limit) {
460
-                        echo "\n . {$datetime_identifier} AT CAPACITY";
461
-                    }
462
-                }
463
-                // now adjust all other datetimes that allow access to this ticket
464
-                $this->adjustDatetimes(
465
-                    $datetime_identifier,
466
-                    $available_spaces,
467
-                    $reg_limit,
468
-                    $ticket_identifier,
469
-                    $ticket_quantity
470
-                );
471
-            }
472
-        }
473
-        return $available_spaces;
474
-    }
475
-
476
-
477
-
478
-    /**
479
-     * subtracts ticket amounts from all datetime reg limits
480
-     * that allow access to the ticket specified,
481
-     * because that ticket could be used
482
-     * to attend any of the datetimes it has access to
483
-     *
484
-     * @param string $datetime_identifier
485
-     * @param int    $available_spaces
486
-     * @param int    $reg_limit
487
-     * @param string $ticket_identifier
488
-     * @param int    $ticket_quantity
489
-     */
490
-    private function adjustDatetimes($datetime_identifier, $available_spaces, $reg_limit, $ticket_identifier, $ticket_quantity)
491
-    {
492
-        foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
493
-            // if the supplied ticket has access to this datetime
494
-            if (in_array($ticket_identifier, $datetime_tickets, true)) {
495
-                // and datetime has spaces available
496
-                if (isset($this->datetime_spaces[$datetime_ID])) {
497
-                    // then decrement the available spaces for the datetime
498
-                    $this->datetime_spaces[$datetime_ID] -= $ticket_quantity;
499
-                    // but don't let quantities go below zero
500
-                    $this->datetime_spaces[$datetime_ID] = max(
501
-                        $this->datetime_spaces[$datetime_ID],
502
-                        0
503
-                    );
504
-                    if ($this->debug) {
505
-                        echo "\n . . . " . $datetime_ID . " capacity reduced by {$ticket_quantity}";
506
-                        echo " because it allows access to {$ticket_identifier}";
507
-                    }
508
-                }
509
-                // if this datetime is at full capacity
510
-                if ($datetime_ID === $datetime_identifier && $available_spaces >= $reg_limit) {
511
-                    // then all of it's tickets are now unavailable
512
-                    foreach ($datetime_tickets as $datetime_ticket) {
513
-                        // so  set any tracked available quantities to zero
514
-                        if (isset($this->ticket_quantities[$datetime_ticket])) {
515
-                            $this->ticket_quantities[$datetime_ticket] = 0;
516
-                        }
517
-                        if ($this->debug) {
518
-                            echo "\n . . . " . $datetime_ticket . ' unavailable: ';
519
-                        }
520
-                    }
521
-                }
522
-            }
523
-        }
524
-    }
30
+	/**
31
+	 * @var EE_Event $event
32
+	 */
33
+	private $event;
34
+
35
+	/**
36
+	 * @var array $datetime_query_params
37
+	 */
38
+	private $datetime_query_params;
39
+
40
+	/**
41
+	 * @var EE_Ticket[] $active_tickets
42
+	 */
43
+	private $active_tickets = array();
44
+
45
+	/**
46
+	 * @var EE_Datetime[] $datetimes
47
+	 */
48
+	private $datetimes = array();
49
+
50
+	/**
51
+	 * Array of Ticket IDs grouped by Datetime
52
+	 *
53
+	 * @var array $datetimes
54
+	 */
55
+	private $datetime_tickets = array();
56
+
57
+	/**
58
+	 * Max spaces for each Datetime (reg limit - previous sold)
59
+	 *
60
+	 * @var array $datetime_spaces
61
+	 */
62
+	private $datetime_spaces = array();
63
+
64
+	/**
65
+	 * Array of Datetime IDs grouped by Ticket
66
+	 *
67
+	 * @var array $ticket_datetimes
68
+	 */
69
+	private $ticket_datetimes = array();
70
+
71
+	/**
72
+	 * maximum ticket quantities for each ticket (adjusted for reg limit)
73
+	 *
74
+	 * @var array $ticket_quantities
75
+	 */
76
+	private $ticket_quantities = array();
77
+
78
+	/**
79
+	 * total quantity of sold and reserved for each ticket
80
+	 *
81
+	 * @var array $tickets_sold
82
+	 */
83
+	private $tickets_sold = array();
84
+
85
+	/**
86
+	 * total spaces available across all datetimes
87
+	 *
88
+	 * @var array $total_spaces
89
+	 */
90
+	private $total_spaces = array();
91
+
92
+	/**
93
+	 * @var boolean $debug
94
+	 */
95
+	private $debug = false;
96
+
97
+
98
+
99
+	/**
100
+	 * EventSpacesCalculator constructor.
101
+	 *
102
+	 * @param EE_Event $event
103
+	 * @param array    $datetime_query_params
104
+	 * @throws EE_Error
105
+	 */
106
+	public function __construct(EE_Event $event, array $datetime_query_params = array())
107
+	{
108
+		$this->event = $event;
109
+		$this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
110
+	}
111
+
112
+
113
+
114
+	/**
115
+	 * @return EE_Ticket[]
116
+	 * @throws EE_Error
117
+	 */
118
+	public function getActiveTickets()
119
+	{
120
+		if(empty($this->active_tickets)) {
121
+			$this->active_tickets = $this->event->tickets(
122
+				array(
123
+					array(
124
+						'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
125
+						'TKT_deleted'  => false,
126
+					),
127
+					'order_by' => array('TKT_qty' => 'ASC')
128
+				)
129
+			);
130
+		}
131
+		return $this->active_tickets;
132
+	}
133
+
134
+
135
+
136
+	/**
137
+	 * @param EE_Ticket[] $active_tickets
138
+	 * @throws EE_Error
139
+	 * @throws DomainException
140
+	 * @throws UnexpectedEntityException
141
+	 */
142
+	public function setActiveTickets(array $active_tickets = array())
143
+	{
144
+		if (! empty($active_tickets)){
145
+			foreach ($active_tickets as $active_ticket) {
146
+				$this->validateTicket($active_ticket);
147
+			}
148
+			// sort incoming array by ticket quantity (asc)
149
+			usort(
150
+				$active_tickets,
151
+				function (EE_Ticket $a, EE_Ticket $b) {
152
+					if ($a->qty() === $b->qty()) {
153
+						return 0;
154
+					}
155
+					return ($a->qty() < $b->qty())
156
+						? -1
157
+						: 1;
158
+				}
159
+			);
160
+		}
161
+		$this->active_tickets = $active_tickets;
162
+	}
163
+
164
+
165
+
166
+	/**
167
+	 * @param $ticket
168
+	 * @throws DomainException
169
+	 * @throws EE_Error
170
+	 * @throws UnexpectedEntityException
171
+	 */
172
+	private function validateTicket($ticket)
173
+	{
174
+		if (! $ticket instanceof EE_Ticket) {
175
+			throw new DomainException(
176
+				esc_html__(
177
+					'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
178
+					'event_espresso'
179
+				)
180
+			);
181
+		}
182
+		if ($ticket->get_event_ID() !== $this->event->ID()) {
183
+			throw new DomainException(
184
+				sprintf(
185
+					esc_html__(
186
+						'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
187
+						'event_espresso'
188
+					),
189
+					$ticket->get_event_ID(),
190
+					$this->event->ID()
191
+				)
192
+			);
193
+		}
194
+	}
195
+
196
+
197
+
198
+	/**
199
+	 * @return EE_Datetime[]
200
+	 */
201
+	public function getDatetimes()
202
+	{
203
+		return $this->datetimes;
204
+	}
205
+
206
+
207
+
208
+	/**
209
+	 * @param EE_Datetime $datetime
210
+	 * @throws EE_Error
211
+	 * @throws DomainException
212
+	 */
213
+	public function setDatetime(EE_Datetime $datetime)
214
+	{
215
+		if ($datetime->event()->ID() !== $this->event->ID()) {
216
+			throw new DomainException(
217
+				sprintf(
218
+					esc_html__(
219
+						'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
220
+						'event_espresso'
221
+					),
222
+					$datetime->event()->ID(),
223
+					$this->event->ID()
224
+				)
225
+			);
226
+		}
227
+		$this->datetimes[$datetime->ID()] = $datetime;
228
+	}
229
+
230
+
231
+
232
+	/**
233
+	 * calculate spaces remaining based on "saleable" tickets
234
+	 *
235
+	 * @return float|int
236
+	 * @throws EE_Error
237
+	 * @throws DomainException
238
+	 * @throws UnexpectedEntityException
239
+	 */
240
+	public function spacesRemaining()
241
+	{
242
+		$this->initialize();
243
+		return $this->calculate();
244
+	}
245
+
246
+
247
+
248
+	/**
249
+	 * calculates total available spaces for an event with no regard for sold tickets
250
+	 *
251
+	 * @return int|float
252
+	 * @throws EE_Error
253
+	 * @throws DomainException
254
+	 * @throws UnexpectedEntityException
255
+	 */
256
+	public function totalSpacesAvailable()
257
+	{
258
+		$this->initialize();
259
+		return $this->calculate(false);
260
+	}
261
+
262
+
263
+
264
+	/**
265
+	 * Loops through the active tickets for the event
266
+	 * and builds a series of data arrays that will be used for calculating
267
+	 * the total maximum available spaces, as well as the spaces remaining.
268
+	 * Because ticket quantities affect datetime spaces and vice versa,
269
+	 * we need to be constantly updating these data arrays as things change,
270
+	 * which is the entire reason for their existence.
271
+	 *
272
+	 * @throws EE_Error
273
+	 * @throws DomainException
274
+	 * @throws UnexpectedEntityException
275
+	 */
276
+	private function initialize()
277
+	{
278
+		if ($this->debug) {
279
+			echo "\n\n" . __LINE__ . ') ' . strtoupper(__METHOD__) . '()';
280
+		}
281
+		$this->datetime_tickets = array();
282
+		$this->datetime_spaces = array();
283
+		$this->ticket_datetimes = array();
284
+		$this->ticket_quantities = array();
285
+		$this->tickets_sold = array();
286
+		$this->total_spaces = array();
287
+		$active_tickets = $this->getActiveTickets();
288
+		if (! empty($active_tickets)) {
289
+			foreach ($active_tickets as $ticket) {
290
+				$this->validateTicket($ticket);
291
+				// we need to index our data arrays using strings for the purpose of sorting,
292
+				// but we also need them to be unique, so  we'll just prepend a letter T to the ID
293
+				$ticket_identifier = "T{$ticket->ID()}";
294
+				// to start, we'll just consider the raw qty to be the maximum availability for this ticket
295
+				$max_tickets = $ticket->qty();
296
+				// but we'll adjust that after looping over each datetime for the ticket and checking reg limits
297
+				$ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
298
+				foreach ($ticket_datetimes as $datetime) {
299
+					// save all datetimes
300
+					$this->setDatetime($datetime);
301
+					$datetime_identifier = "D{$datetime->ID()}";
302
+					$reg_limit = $datetime->reg_limit();
303
+					// ticket quantity can not exceed datetime reg limit
304
+					$max_tickets = min($max_tickets, $reg_limit);
305
+					// as described earlier, because we need to be able to constantly adjust numbers for things,
306
+					// we are going to move all of our data into the following arrays:
307
+					// datetime spaces initially represents the reg limit for each datetime,
308
+					// but this will get adjusted as tickets are accounted for
309
+					$this->datetime_spaces[$datetime_identifier] = $reg_limit;
310
+					// just an array of ticket IDs grouped by datetime
311
+					$this->datetime_tickets[$datetime_identifier][] = $ticket_identifier;
312
+					// and an array of datetime IDs grouped by ticket
313
+					$this->ticket_datetimes[$ticket_identifier][] = $datetime_identifier;
314
+				}
315
+				// total quantity of sold and reserved for each ticket
316
+				$this->tickets_sold[$ticket_identifier] = $ticket->sold() + $ticket->reserved();
317
+				// and the maximum ticket quantities for each ticket (adjusted for reg limit)
318
+				$this->ticket_quantities[$ticket_identifier] = $max_tickets;
319
+			}
320
+		}
321
+		// sort datetime spaces by reg limit, but maintain our string indexes
322
+		asort($this->datetime_spaces, SORT_NUMERIC);
323
+		// datetime tickets need to be sorted in the SAME order as the above array...
324
+		// so we'll just use array_merge() to take the structure of datetime_spaces
325
+		// but overwrite all of the data with that from datetime_tickets
326
+		$this->datetime_tickets = array_merge(
327
+			$this->datetime_spaces,
328
+			$this->datetime_tickets
329
+		);
330
+		if ($this->debug) {
331
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
332
+			\EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
333
+			\EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
334
+		}
335
+	}
336
+
337
+
338
+
339
+	/**
340
+	 * performs calculations on initialized data
341
+	 *
342
+	 * @param bool $consider_sold
343
+	 * @return int|float
344
+	 */
345
+	private function calculate($consider_sold = true)
346
+	{
347
+		if ($this->debug) {
348
+			echo "\n\n" . __LINE__ . ') ' . strtoupper(__METHOD__) . '()';
349
+		}
350
+		foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
351
+			$this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
352
+		}
353
+		// total spaces available is just the sum of the spaces available for each datetime
354
+		$spaces_remaining = array_sum($this->total_spaces);
355
+		if($consider_sold) {
356
+			// less the sum of all tickets sold for these datetimes
357
+			$spaces_remaining -= array_sum($this->tickets_sold);
358
+		}
359
+		if ($this->debug) {
360
+			\EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
361
+			\EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
362
+			\EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
363
+		}
364
+		return $spaces_remaining;
365
+	}
366
+
367
+
368
+
369
+	/**
370
+	 * @param string $datetime_identifier
371
+	 * @param array  $tickets
372
+	 */
373
+	private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
374
+	{
375
+		// make sure a reg limit is set for the datetime
376
+		$reg_limit = isset($this->datetime_spaces[$datetime_identifier])
377
+			? $this->datetime_spaces[$datetime_identifier]
378
+			: 0;
379
+		// and bail if it is not
380
+		if (! $reg_limit) {
381
+			if ($this->debug) {
382
+				echo "\n . {$datetime_identifier} AT CAPACITY";
383
+			}
384
+			return;
385
+		}
386
+		if ($this->debug) {
387
+			echo "\n\n{$datetime_identifier}";
388
+			echo "\n . " . 'REG LIMIT: ' . $reg_limit;
389
+		}
390
+		// set default number of available spaces
391
+		$available_spaces = 0;
392
+		$this->total_spaces[$datetime_identifier] = 0;
393
+		foreach ($tickets as $ticket_identifier) {
394
+			$available_spaces = $this->calculateAvailableSpacesForTicket(
395
+				$datetime_identifier,
396
+				$reg_limit,
397
+				$ticket_identifier,
398
+				$available_spaces
399
+			);
400
+		}
401
+		// spaces can't be negative
402
+		$available_spaces = max($available_spaces, 0);
403
+		if ($available_spaces) {
404
+			// track any non-zero values
405
+			$this->total_spaces[$datetime_identifier] += $available_spaces;
406
+			if ($this->debug) {
407
+				echo "\n . spaces: {$available_spaces}";
408
+			}
409
+		} else {
410
+			if ($this->debug) {
411
+				echo "\n . NO TICKETS AVAILABLE FOR DATETIME";
412
+			}
413
+		}
414
+		if ($this->debug) {
415
+			\EEH_Debug_Tools::printr($this->total_spaces[$datetime_identifier], '$spaces_remaining', __FILE__, __LINE__);
416
+			\EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
417
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
418
+		}
419
+	}
420
+
421
+
422
+
423
+	/**
424
+	 * @param string $datetime_identifier
425
+	 * @param int    $reg_limit
426
+	 * @param string $ticket_identifier
427
+	 * @param int    $available_spaces
428
+	 * @return int
429
+	 */
430
+	private function calculateAvailableSpacesForTicket($datetime_identifier, $reg_limit,$ticket_identifier, $available_spaces)
431
+	{
432
+		if ($this->debug) {
433
+			echo "\n . {$ticket_identifier}";
434
+		}
435
+		// make sure ticket quantity is set
436
+		$ticket_quantity = isset($this->ticket_quantities[$ticket_identifier])
437
+			? $this->ticket_quantities[$ticket_identifier]
438
+			: 0;
439
+		if ($ticket_quantity) {
440
+			if ($this->debug) {
441
+				echo "\n . . available_spaces ({$available_spaces}) <= reg_limit ({$reg_limit}) = ";
442
+				echo ($available_spaces <= $reg_limit)
443
+					? 'true'
444
+					: 'false';
445
+			}
446
+			// if the datetime is NOT at full capacity yet
447
+			if ($available_spaces <= $reg_limit) {
448
+				// then the maximum ticket quantity we can allocate is the lowest value of either:
449
+				//  the number of remaining spaces for the datetime, which is the limit - spaces already taken
450
+				//  or the maximum ticket quantity
451
+				$ticket_quantity = min(($reg_limit - $available_spaces), $ticket_quantity);
452
+				// adjust the available quantity in our tracking array
453
+				$this->ticket_quantities[$ticket_identifier] -= $ticket_quantity;
454
+				// and increment spaces allocated for this datetime
455
+				$available_spaces += $ticket_quantity;
456
+				if ($this->debug) {
457
+					echo "\n . . ticket quantity: {$ticket_quantity} ({$ticket_identifier})";
458
+					echo "\n . . . allocate {$ticket_quantity} tickets ({$ticket_identifier})";
459
+					if ($available_spaces >= $reg_limit) {
460
+						echo "\n . {$datetime_identifier} AT CAPACITY";
461
+					}
462
+				}
463
+				// now adjust all other datetimes that allow access to this ticket
464
+				$this->adjustDatetimes(
465
+					$datetime_identifier,
466
+					$available_spaces,
467
+					$reg_limit,
468
+					$ticket_identifier,
469
+					$ticket_quantity
470
+				);
471
+			}
472
+		}
473
+		return $available_spaces;
474
+	}
475
+
476
+
477
+
478
+	/**
479
+	 * subtracts ticket amounts from all datetime reg limits
480
+	 * that allow access to the ticket specified,
481
+	 * because that ticket could be used
482
+	 * to attend any of the datetimes it has access to
483
+	 *
484
+	 * @param string $datetime_identifier
485
+	 * @param int    $available_spaces
486
+	 * @param int    $reg_limit
487
+	 * @param string $ticket_identifier
488
+	 * @param int    $ticket_quantity
489
+	 */
490
+	private function adjustDatetimes($datetime_identifier, $available_spaces, $reg_limit, $ticket_identifier, $ticket_quantity)
491
+	{
492
+		foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
493
+			// if the supplied ticket has access to this datetime
494
+			if (in_array($ticket_identifier, $datetime_tickets, true)) {
495
+				// and datetime has spaces available
496
+				if (isset($this->datetime_spaces[$datetime_ID])) {
497
+					// then decrement the available spaces for the datetime
498
+					$this->datetime_spaces[$datetime_ID] -= $ticket_quantity;
499
+					// but don't let quantities go below zero
500
+					$this->datetime_spaces[$datetime_ID] = max(
501
+						$this->datetime_spaces[$datetime_ID],
502
+						0
503
+					);
504
+					if ($this->debug) {
505
+						echo "\n . . . " . $datetime_ID . " capacity reduced by {$ticket_quantity}";
506
+						echo " because it allows access to {$ticket_identifier}";
507
+					}
508
+				}
509
+				// if this datetime is at full capacity
510
+				if ($datetime_ID === $datetime_identifier && $available_spaces >= $reg_limit) {
511
+					// then all of it's tickets are now unavailable
512
+					foreach ($datetime_tickets as $datetime_ticket) {
513
+						// so  set any tracked available quantities to zero
514
+						if (isset($this->ticket_quantities[$datetime_ticket])) {
515
+							$this->ticket_quantities[$datetime_ticket] = 0;
516
+						}
517
+						if ($this->debug) {
518
+							echo "\n . . . " . $datetime_ticket . ' unavailable: ';
519
+						}
520
+					}
521
+				}
522
+			}
523
+		}
524
+	}
525 525
 
526 526
 }
527 527
 // Location: EventSpacesCalculator.php
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
      */
118 118
     public function getActiveTickets()
119 119
     {
120
-        if(empty($this->active_tickets)) {
120
+        if (empty($this->active_tickets)) {
121 121
             $this->active_tickets = $this->event->tickets(
122 122
                 array(
123 123
                     array(
@@ -141,14 +141,14 @@  discard block
 block discarded – undo
141 141
      */
142 142
     public function setActiveTickets(array $active_tickets = array())
143 143
     {
144
-        if (! empty($active_tickets)){
144
+        if ( ! empty($active_tickets)) {
145 145
             foreach ($active_tickets as $active_ticket) {
146 146
                 $this->validateTicket($active_ticket);
147 147
             }
148 148
             // sort incoming array by ticket quantity (asc)
149 149
             usort(
150 150
                 $active_tickets,
151
-                function (EE_Ticket $a, EE_Ticket $b) {
151
+                function(EE_Ticket $a, EE_Ticket $b) {
152 152
                     if ($a->qty() === $b->qty()) {
153 153
                         return 0;
154 154
                     }
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
      */
172 172
     private function validateTicket($ticket)
173 173
     {
174
-        if (! $ticket instanceof EE_Ticket) {
174
+        if ( ! $ticket instanceof EE_Ticket) {
175 175
             throw new DomainException(
176 176
                 esc_html__(
177 177
                     'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
     private function initialize()
277 277
     {
278 278
         if ($this->debug) {
279
-            echo "\n\n" . __LINE__ . ') ' . strtoupper(__METHOD__) . '()';
279
+            echo "\n\n".__LINE__.') '.strtoupper(__METHOD__).'()';
280 280
         }
281 281
         $this->datetime_tickets = array();
282 282
         $this->datetime_spaces = array();
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
         $this->tickets_sold = array();
286 286
         $this->total_spaces = array();
287 287
         $active_tickets = $this->getActiveTickets();
288
-        if (! empty($active_tickets)) {
288
+        if ( ! empty($active_tickets)) {
289 289
             foreach ($active_tickets as $ticket) {
290 290
                 $this->validateTicket($ticket);
291 291
                 // we need to index our data arrays using strings for the purpose of sorting,
@@ -345,14 +345,14 @@  discard block
 block discarded – undo
345 345
     private function calculate($consider_sold = true)
346 346
     {
347 347
         if ($this->debug) {
348
-            echo "\n\n" . __LINE__ . ') ' . strtoupper(__METHOD__) . '()';
348
+            echo "\n\n".__LINE__.') '.strtoupper(__METHOD__).'()';
349 349
         }
350 350
         foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
351 351
             $this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
352 352
         }
353 353
         // total spaces available is just the sum of the spaces available for each datetime
354 354
         $spaces_remaining = array_sum($this->total_spaces);
355
-        if($consider_sold) {
355
+        if ($consider_sold) {
356 356
             // less the sum of all tickets sold for these datetimes
357 357
             $spaces_remaining -= array_sum($this->tickets_sold);
358 358
         }
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
             ? $this->datetime_spaces[$datetime_identifier]
378 378
             : 0;
379 379
         // and bail if it is not
380
-        if (! $reg_limit) {
380
+        if ( ! $reg_limit) {
381 381
             if ($this->debug) {
382 382
                 echo "\n . {$datetime_identifier} AT CAPACITY";
383 383
             }
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
         }
386 386
         if ($this->debug) {
387 387
             echo "\n\n{$datetime_identifier}";
388
-            echo "\n . " . 'REG LIMIT: ' . $reg_limit;
388
+            echo "\n . ".'REG LIMIT: '.$reg_limit;
389 389
         }
390 390
         // set default number of available spaces
391 391
         $available_spaces = 0;
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
      * @param int    $available_spaces
428 428
      * @return int
429 429
      */
430
-    private function calculateAvailableSpacesForTicket($datetime_identifier, $reg_limit,$ticket_identifier, $available_spaces)
430
+    private function calculateAvailableSpacesForTicket($datetime_identifier, $reg_limit, $ticket_identifier, $available_spaces)
431 431
     {
432 432
         if ($this->debug) {
433 433
             echo "\n . {$ticket_identifier}";
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
                         0
503 503
                     );
504 504
                     if ($this->debug) {
505
-                        echo "\n . . . " . $datetime_ID . " capacity reduced by {$ticket_quantity}";
505
+                        echo "\n . . . ".$datetime_ID." capacity reduced by {$ticket_quantity}";
506 506
                         echo " because it allows access to {$ticket_identifier}";
507 507
                     }
508 508
                 }
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
                             $this->ticket_quantities[$datetime_ticket] = 0;
516 516
                         }
517 517
                         if ($this->debug) {
518
-                            echo "\n . . . " . $datetime_ticket . ' unavailable: ';
518
+                            echo "\n . . . ".$datetime_ticket.' unavailable: ';
519 519
                         }
520 520
                     }
521 521
                 }
Please login to merge, or discard this patch.
caffeinated/admin/extend/events/Extend_Events_Admin_Page.core.php 1 patch
Indentation   +1260 added lines, -1260 removed lines patch added patch discarded remove patch
@@ -14,1264 +14,1264 @@
 block discarded – undo
14 14
 {
15 15
 
16 16
 
17
-    /**
18
-     * Extend_Events_Admin_Page constructor.
19
-     *
20
-     * @param bool $routing
21
-     */
22
-    public function __construct($routing = true)
23
-    {
24
-        parent::__construct($routing);
25
-        if (! defined('EVENTS_CAF_TEMPLATE_PATH')) {
26
-            define('EVENTS_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'events/templates/');
27
-            define('EVENTS_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'events/assets/');
28
-            define('EVENTS_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'events/assets/');
29
-        }
30
-    }
31
-
32
-
33
-    /**
34
-     * Sets routes.
35
-     */
36
-    protected function _extend_page_config()
37
-    {
38
-        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'events';
39
-        //is there a evt_id in the request?
40
-        $evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
41
-            ? $this->_req_data['EVT_ID']
42
-            : 0;
43
-        $evt_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $evt_id;
44
-        //tkt_id?
45
-        $tkt_id             = ! empty($this->_req_data['TKT_ID']) && ! is_array($this->_req_data['TKT_ID'])
46
-            ? $this->_req_data['TKT_ID']
47
-            : 0;
48
-        $new_page_routes    = array(
49
-            'duplicate_event'          => array(
50
-                'func'       => '_duplicate_event',
51
-                'capability' => 'ee_edit_event',
52
-                'obj_id'     => $evt_id,
53
-                'noheader'   => true,
54
-            ),
55
-            'ticket_list_table'        => array(
56
-                'func'       => '_tickets_overview_list_table',
57
-                'capability' => 'ee_read_default_tickets',
58
-            ),
59
-            'trash_ticket'             => array(
60
-                'func'       => '_trash_or_restore_ticket',
61
-                'capability' => 'ee_delete_default_ticket',
62
-                'obj_id'     => $tkt_id,
63
-                'noheader'   => true,
64
-                'args'       => array('trash' => true),
65
-            ),
66
-            'trash_tickets'            => array(
67
-                'func'       => '_trash_or_restore_ticket',
68
-                'capability' => 'ee_delete_default_tickets',
69
-                'noheader'   => true,
70
-                'args'       => array('trash' => true),
71
-            ),
72
-            'restore_ticket'           => array(
73
-                'func'       => '_trash_or_restore_ticket',
74
-                'capability' => 'ee_delete_default_ticket',
75
-                'obj_id'     => $tkt_id,
76
-                'noheader'   => true,
77
-            ),
78
-            'restore_tickets'          => array(
79
-                'func'       => '_trash_or_restore_ticket',
80
-                'capability' => 'ee_delete_default_tickets',
81
-                'noheader'   => true,
82
-            ),
83
-            'delete_ticket'            => array(
84
-                'func'       => '_delete_ticket',
85
-                'capability' => 'ee_delete_default_ticket',
86
-                'obj_id'     => $tkt_id,
87
-                'noheader'   => true,
88
-            ),
89
-            'delete_tickets'           => array(
90
-                'func'       => '_delete_ticket',
91
-                'capability' => 'ee_delete_default_tickets',
92
-                'noheader'   => true,
93
-            ),
94
-            'import_page'              => array(
95
-                'func'       => '_import_page',
96
-                'capability' => 'import',
97
-            ),
98
-            'import'                   => array(
99
-                'func'       => '_import_events',
100
-                'capability' => 'import',
101
-                'noheader'   => true,
102
-            ),
103
-            'import_events'            => array(
104
-                'func'       => '_import_events',
105
-                'capability' => 'import',
106
-                'noheader'   => true,
107
-            ),
108
-            'export_events'            => array(
109
-                'func'       => '_events_export',
110
-                'capability' => 'export',
111
-                'noheader'   => true,
112
-            ),
113
-            'export_categories'        => array(
114
-                'func'       => '_categories_export',
115
-                'capability' => 'export',
116
-                'noheader'   => true,
117
-            ),
118
-            'sample_export_file'       => array(
119
-                'func'       => '_sample_export_file',
120
-                'capability' => 'export',
121
-                'noheader'   => true,
122
-            ),
123
-            'update_template_settings' => array(
124
-                'func'       => '_update_template_settings',
125
-                'capability' => 'manage_options',
126
-                'noheader'   => true,
127
-            ),
128
-        );
129
-        $this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
130
-        //partial route/config override
131
-        $this->_page_config['import_events']['metaboxes'] = $this->_default_espresso_metaboxes;
132
-        $this->_page_config['create_new']['metaboxes'][]  = '_premium_event_editor_meta_boxes';
133
-        $this->_page_config['create_new']['qtips'][]      = 'EE_Event_Editor_Tips';
134
-        $this->_page_config['edit']['qtips'][]            = 'EE_Event_Editor_Tips';
135
-        $this->_page_config['edit']['metaboxes'][]        = '_premium_event_editor_meta_boxes';
136
-        $this->_page_config['default']['list_table']      = 'Extend_Events_Admin_List_Table';
137
-        //add tickets tab but only if there are more than one default ticket!
138
-        $tkt_count = EEM_Ticket::instance()->count_deleted_and_undeleted(
139
-            array(array('TKT_is_default' => 1)),
140
-            'TKT_ID',
141
-            true
142
-        );
143
-        if ($tkt_count > 1) {
144
-            $new_page_config = array(
145
-                'ticket_list_table' => array(
146
-                    'nav'           => array(
147
-                        'label' => esc_html__('Default Tickets', 'event_espresso'),
148
-                        'order' => 60,
149
-                    ),
150
-                    'list_table'    => 'Tickets_List_Table',
151
-                    'require_nonce' => false,
152
-                ),
153
-            );
154
-        }
155
-        //template settings
156
-        $new_page_config['template_settings'] = array(
157
-            'nav'           => array(
158
-                'label' => esc_html__('Templates', 'event_espresso'),
159
-                'order' => 30,
160
-            ),
161
-            'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
162
-            'help_tabs'     => array(
163
-                'general_settings_templates_help_tab' => array(
164
-                    'title'    => esc_html__('Templates', 'event_espresso'),
165
-                    'filename' => 'general_settings_templates',
166
-                ),
167
-            ),
168
-            'help_tour'     => array('Templates_Help_Tour'),
169
-            'require_nonce' => false,
170
-        );
171
-        $this->_page_config                   = array_merge($this->_page_config, $new_page_config);
172
-        //add filters and actions
173
-        //modifying _views
174
-        add_filter(
175
-            'FHEE_event_datetime_metabox_add_additional_date_time_template',
176
-            array($this, 'add_additional_datetime_button'),
177
-            10,
178
-            2
179
-        );
180
-        add_filter(
181
-            'FHEE_event_datetime_metabox_clone_button_template',
182
-            array($this, 'add_datetime_clone_button'),
183
-            10,
184
-            2
185
-        );
186
-        add_filter(
187
-            'FHEE_event_datetime_metabox_timezones_template',
188
-            array($this, 'datetime_timezones_template'),
189
-            10,
190
-            2
191
-        );
192
-        //filters for event list table
193
-        add_filter('FHEE__Extend_Events_Admin_List_Table__filters', array($this, 'list_table_filters'), 10, 2);
194
-        add_filter(
195
-            'FHEE__Events_Admin_List_Table__column_actions__action_links',
196
-            array($this, 'extra_list_table_actions'),
197
-            10,
198
-            2
199
-        );
200
-        //legend item
201
-        add_filter('FHEE__Events_Admin_Page___event_legend_items__items', array($this, 'additional_legend_items'));
202
-        add_action('admin_init', array($this, 'admin_init'));
203
-        //heartbeat stuff
204
-        add_filter('heartbeat_received', array($this, 'heartbeat_response'), 10, 2);
205
-    }
206
-
207
-
208
-    /**
209
-     * admin_init
210
-     */
211
-    public function admin_init()
212
-    {
213
-        EE_Registry::$i18n_js_strings = array_merge(
214
-            EE_Registry::$i18n_js_strings,
215
-            array(
216
-                'image_confirm'          => esc_html__(
217
-                    'Do you really want to delete this image? Please remember to update your event to complete the removal.',
218
-                    'event_espresso'
219
-                ),
220
-                'event_starts_on'        => esc_html__('Event Starts on', 'event_espresso'),
221
-                'event_ends_on'          => esc_html__('Event Ends on', 'event_espresso'),
222
-                'event_datetime_actions' => esc_html__('Actions', 'event_espresso'),
223
-                'event_clone_dt_msg'     => esc_html__('Clone this Event Date and Time', 'event_espresso'),
224
-                'remove_event_dt_msg'    => esc_html__('Remove this Event Time', 'event_espresso'),
225
-            )
226
-        );
227
-    }
228
-
229
-
230
-    /**
231
-     * This will be used to listen for any heartbeat data packages coming via the WordPress heartbeat API and handle
232
-     * accordingly.
233
-     *
234
-     * @param array $response The existing heartbeat response array.
235
-     * @param array $data     The incoming data package.
236
-     * @return array  possibly appended response.
237
-     */
238
-    public function heartbeat_response($response, $data)
239
-    {
240
-        /**
241
-         * check whether count of tickets is approaching the potential
242
-         * limits for the server.
243
-         */
244
-        if (! empty($data['input_count'])) {
245
-            $response['max_input_vars_check'] = EE_Registry::instance()->CFG->environment->max_input_vars_limit_check(
246
-                $data['input_count']
247
-            );
248
-        }
249
-        return $response;
250
-    }
251
-
252
-
253
-    /**
254
-     * Add per page screen options to the default ticket list table view.
255
-     */
256
-    protected function _add_screen_options_ticket_list_table()
257
-    {
258
-        $this->_per_page_screen_option();
259
-    }
260
-
261
-
262
-    /**
263
-     * @param string $return
264
-     * @param int    $id
265
-     * @param string $new_title
266
-     * @param string $new_slug
267
-     * @return string
268
-     */
269
-    public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
270
-    {
271
-        $return = parent::extra_permalink_field_buttons($return, $id, $new_title, $new_slug);
272
-        //make sure this is only when editing
273
-        if (! empty($id)) {
274
-            $href   = EE_Admin_Page::add_query_args_and_nonce(
275
-                array('action' => 'duplicate_event', 'EVT_ID' => $id),
276
-                $this->_admin_base_url
277
-            );
278
-            $title  = esc_attr__('Duplicate Event', 'event_espresso');
279
-            $return .= '<a href="'
280
-                       . $href
281
-                       . '" title="'
282
-                       . $title
283
-                       . '" id="ee-duplicate-event-button" class="button button-small"  value="duplicate_event">'
284
-                       . $title
285
-                       . '</button>';
286
-        }
287
-        return $return;
288
-    }
289
-
290
-
291
-    /**
292
-     * Set the list table views for the default ticket list table view.
293
-     */
294
-    public function _set_list_table_views_ticket_list_table()
295
-    {
296
-        $this->_views = array(
297
-            'all'     => array(
298
-                'slug'        => 'all',
299
-                'label'       => esc_html__('All', 'event_espresso'),
300
-                'count'       => 0,
301
-                'bulk_action' => array(
302
-                    'trash_tickets' => esc_html__('Move to Trash', 'event_espresso'),
303
-                ),
304
-            ),
305
-            'trashed' => array(
306
-                'slug'        => 'trashed',
307
-                'label'       => esc_html__('Trash', 'event_espresso'),
308
-                'count'       => 0,
309
-                'bulk_action' => array(
310
-                    'restore_tickets' => esc_html__('Restore from Trash', 'event_espresso'),
311
-                    'delete_tickets'  => esc_html__('Delete Permanently', 'event_espresso'),
312
-                ),
313
-            ),
314
-        );
315
-    }
316
-
317
-
318
-    /**
319
-     * Enqueue scripts and styles for the event editor.
320
-     */
321
-    public function load_scripts_styles_edit()
322
-    {
323
-        wp_register_script(
324
-            'ee-event-editor-heartbeat',
325
-            EVENTS_CAF_ASSETS_URL . 'event-editor-heartbeat.js',
326
-            array('ee_admin_js', 'heartbeat'),
327
-            EVENT_ESPRESSO_VERSION,
328
-            true
329
-        );
330
-        wp_enqueue_script('ee-accounting');
331
-        //styles
332
-        wp_enqueue_style('espresso-ui-theme');
333
-        wp_enqueue_script('event_editor_js');
334
-        wp_enqueue_script('ee-event-editor-heartbeat');
335
-    }
336
-
337
-
338
-    /**
339
-     * Returns template for the additional datetime.
340
-     * @param $template
341
-     * @param $template_args
342
-     * @return mixed
343
-     * @throws DomainException
344
-     */
345
-    public function add_additional_datetime_button($template, $template_args)
346
-    {
347
-        return EEH_Template::display_template(
348
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_add_additional_time.template.php',
349
-            $template_args,
350
-            true
351
-        );
352
-    }
353
-
354
-
355
-    /**
356
-     * Returns the template for cloning a datetime.
357
-     * @param $template
358
-     * @param $template_args
359
-     * @return mixed
360
-     * @throws DomainException
361
-     */
362
-    public function add_datetime_clone_button($template, $template_args)
363
-    {
364
-        return EEH_Template::display_template(
365
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_metabox_clone_button.template.php',
366
-            $template_args,
367
-            true
368
-        );
369
-    }
370
-
371
-
372
-    /**
373
-     * Returns the template for datetime timezones.
374
-     * @param $template
375
-     * @param $template_args
376
-     * @return mixed
377
-     * @throws DomainException
378
-     */
379
-    public function datetime_timezones_template($template, $template_args)
380
-    {
381
-        return EEH_Template::display_template(
382
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_timezones.template.php',
383
-            $template_args,
384
-            true
385
-        );
386
-    }
387
-
388
-
389
-    /**
390
-     * Sets the views for the default list table view.
391
-     */
392
-    protected function _set_list_table_views_default()
393
-    {
394
-        parent::_set_list_table_views_default();
395
-        $new_views    = array(
396
-            'today' => array(
397
-                'slug'        => 'today',
398
-                'label'       => esc_html__('Today', 'event_espresso'),
399
-                'count'       => $this->total_events_today(),
400
-                'bulk_action' => array(
401
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
402
-                ),
403
-            ),
404
-            'month' => array(
405
-                'slug'        => 'month',
406
-                'label'       => esc_html__('This Month', 'event_espresso'),
407
-                'count'       => $this->total_events_this_month(),
408
-                'bulk_action' => array(
409
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
410
-                ),
411
-            ),
412
-        );
413
-        $this->_views = array_merge($this->_views, $new_views);
414
-    }
415
-
416
-
417
-    /**
418
-     * Returns the extra action links for the default list table view.
419
-     * @param array     $action_links
420
-     * @param \EE_Event $event
421
-     * @return array
422
-     * @throws EE_Error
423
-     */
424
-    public function extra_list_table_actions(array $action_links, \EE_Event $event)
425
-    {
426
-        if (EE_Registry::instance()->CAP->current_user_can(
427
-            'ee_read_registrations',
428
-            'espresso_registrations_reports',
429
-            $event->ID()
430
-        )
431
-        ) {
432
-            $reports_query_args = array(
433
-                'action' => 'reports',
434
-                'EVT_ID' => $event->ID(),
435
-            );
436
-            $reports_link       = EE_Admin_Page::add_query_args_and_nonce($reports_query_args, REG_ADMIN_URL);
437
-            $action_links[]     = '<a href="'
438
-                                  . $reports_link
439
-                                  . '" title="'
440
-                                  . esc_attr__('View Report', 'event_espresso')
441
-                                  . '"><div class="dashicons dashicons-chart-bar"></div></a>'
442
-                                  . "\n\t";
443
-        }
444
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
445
-            EE_Registry::instance()->load_helper('MSG_Template');
446
-            $action_links[] = EEH_MSG_Template::get_message_action_link(
447
-                'see_notifications_for',
448
-                null,
449
-                array('EVT_ID' => $event->ID())
450
-            );
451
-        }
452
-        return $action_links;
453
-    }
454
-
455
-
456
-    /**
457
-     * @param $items
458
-     * @return mixed
459
-     */
460
-    public function additional_legend_items($items)
461
-    {
462
-        if (EE_Registry::instance()->CAP->current_user_can(
463
-            'ee_read_registrations',
464
-            'espresso_registrations_reports'
465
-        )
466
-        ) {
467
-            $items['reports'] = array(
468
-                'class' => 'dashicons dashicons-chart-bar',
469
-                'desc'  => esc_html__('Event Reports', 'event_espresso'),
470
-            );
471
-        }
472
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
473
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
474
-            if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
475
-                $items['view_related_messages'] = array(
476
-                    'class' => $related_for_icon['css_class'],
477
-                    'desc'  => $related_for_icon['label'],
478
-                );
479
-            }
480
-        }
481
-        return $items;
482
-    }
483
-
484
-
485
-    /**
486
-     * This is the callback method for the duplicate event route
487
-     * Method looks for 'EVT_ID' in the request and retrieves that event and its details and duplicates them
488
-     * into a new event.  We add a hook so that any plugins that add extra event details can hook into this
489
-     * action.  Note that the dupe will have **DUPLICATE** as its title and slug.
490
-     * After duplication the redirect is to the new event edit page.
491
-     *
492
-     * @return void
493
-     * @access protected
494
-     * @throws EE_Error If EE_Event is not available with given ID
495
-     */
496
-    protected function _duplicate_event()
497
-    {
498
-        // first make sure the ID for the event is in the request.
499
-        //  If it isn't then we need to bail and redirect back to overview list table (cause how did we get here?)
500
-        if (! isset($this->_req_data['EVT_ID'])) {
501
-            EE_Error::add_error(
502
-                esc_html__(
503
-                    'In order to duplicate an event an Event ID is required.  None was given.',
504
-                    'event_espresso'
505
-                ),
506
-                __FILE__,
507
-                __FUNCTION__,
508
-                __LINE__
509
-            );
510
-            $this->_redirect_after_action(false, '', '', array(), true);
511
-            return;
512
-        }
513
-        //k we've got EVT_ID so let's use that to get the event we'll duplicate
514
-        $orig_event = EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']);
515
-        if (! $orig_event instanceof EE_Event) {
516
-            throw new EE_Error(
517
-                sprintf(
518
-                    esc_html__('An EE_Event object could not be retrieved for the given ID (%s)', 'event_espresso'),
519
-                    $this->_req_data['EVT_ID']
520
-                )
521
-            );
522
-        }
523
-        //k now let's clone the $orig_event before getting relations
524
-        $new_event = clone $orig_event;
525
-        //original datetimes
526
-        $orig_datetimes = $orig_event->get_many_related('Datetime');
527
-        //other original relations
528
-        $orig_ven = $orig_event->get_many_related('Venue');
529
-        //reset the ID and modify other details to make it clear this is a dupe
530
-        $new_event->set('EVT_ID', 0);
531
-        $new_name = $new_event->name() . ' ' . esc_html__('**DUPLICATE**', 'event_espresso');
532
-        $new_event->set('EVT_name', $new_name);
533
-        $new_event->set(
534
-            'EVT_slug',
535
-            wp_unique_post_slug(
536
-                sanitize_title($orig_event->name()),
537
-                0,
538
-                'publish',
539
-                'espresso_events',
540
-                0
541
-            )
542
-        );
543
-        $new_event->set('status', 'draft');
544
-        //duplicate discussion settings
545
-        $new_event->set('comment_status', $orig_event->get('comment_status'));
546
-        $new_event->set('ping_status', $orig_event->get('ping_status'));
547
-        //save the new event
548
-        $new_event->save();
549
-        //venues
550
-        foreach ($orig_ven as $ven) {
551
-            $new_event->_add_relation_to($ven, 'Venue');
552
-        }
553
-        $new_event->save();
554
-        //now we need to get the question group relations and handle that
555
-        //first primary question groups
556
-        $orig_primary_qgs = $orig_event->get_many_related(
557
-            'Question_Group',
558
-            array(array('Event_Question_Group.EQG_primary' => 1))
559
-        );
560
-        if (! empty($orig_primary_qgs)) {
561
-            foreach ($orig_primary_qgs as $id => $obj) {
562
-                if ($obj instanceof EE_Question_Group) {
563
-                    $new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 1));
564
-                }
565
-            }
566
-        }
567
-        //next additional attendee question groups
568
-        $orig_additional_qgs = $orig_event->get_many_related(
569
-            'Question_Group',
570
-            array(array('Event_Question_Group.EQG_primary' => 0))
571
-        );
572
-        if (! empty($orig_additional_qgs)) {
573
-            foreach ($orig_additional_qgs as $id => $obj) {
574
-                if ($obj instanceof EE_Question_Group) {
575
-                    $new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 0));
576
-                }
577
-            }
578
-        }
579
-
580
-        $new_event->save();
581
-
582
-        //k now that we have the new event saved we can loop through the datetimes and start adding relations.
583
-        $cloned_tickets = array();
584
-        foreach ($orig_datetimes as $orig_dtt) {
585
-            if (! $orig_dtt instanceof EE_Datetime) {
586
-                continue;
587
-            }
588
-            $new_dtt   = clone $orig_dtt;
589
-            $orig_tkts = $orig_dtt->tickets();
590
-            //save new dtt then add to event
591
-            $new_dtt->set('DTT_ID', 0);
592
-            $new_dtt->set('DTT_sold', 0);
593
-            $new_dtt->set_reserved(0);
594
-            $new_dtt->save();
595
-            $new_event->_add_relation_to($new_dtt, 'Datetime');
596
-            $new_event->save();
597
-            //now let's get the ticket relations setup.
598
-            foreach ((array)$orig_tkts as $orig_tkt) {
599
-                //it's possible a datetime will have no tickets so let's verify we HAVE a ticket first.
600
-                if (! $orig_tkt instanceof EE_Ticket) {
601
-                    continue;
602
-                }
603
-                //is this ticket archived?  If it is then let's skip
604
-                if ($orig_tkt->get('TKT_deleted')) {
605
-                    continue;
606
-                }
607
-                // does this original ticket already exist in the clone_tickets cache?
608
-                //  If so we'll just use the new ticket from it.
609
-                if (isset($cloned_tickets[$orig_tkt->ID()])) {
610
-                    $new_tkt = $cloned_tickets[$orig_tkt->ID()];
611
-                } else {
612
-                    $new_tkt = clone $orig_tkt;
613
-                    //get relations on the $orig_tkt that we need to setup.
614
-                    $orig_prices = $orig_tkt->prices();
615
-                    $new_tkt->set('TKT_ID', 0);
616
-                    $new_tkt->set('TKT_sold', 0);
617
-                    $new_tkt->set('TKT_reserved', 0);
618
-                    $new_tkt->save(); //make sure new ticket has ID.
619
-                    //price relations on new ticket need to be setup.
620
-                    foreach ($orig_prices as $orig_price) {
621
-                        $new_price = clone $orig_price;
622
-                        $new_price->set('PRC_ID', 0);
623
-                        $new_price->save();
624
-                        $new_tkt->_add_relation_to($new_price, 'Price');
625
-                        $new_tkt->save();
626
-                    }
627
-
628
-                    do_action(
629
-                        'AHEE__Extend_Events_Admin_Page___duplicate_event__duplicate_ticket__after',
630
-                        $orig_tkt,
631
-                        $new_tkt,
632
-                        $orig_prices,
633
-                        $orig_event,
634
-                        $orig_dtt,
635
-                        $new_dtt
636
-                    );
637
-                }
638
-                // k now we can add the new ticket as a relation to the new datetime
639
-                // and make sure its added to our cached $cloned_tickets array
640
-                // for use with later datetimes that have the same ticket.
641
-                $new_dtt->_add_relation_to($new_tkt, 'Ticket');
642
-                $new_dtt->save();
643
-                $cloned_tickets[$orig_tkt->ID()] = $new_tkt;
644
-            }
645
-        }
646
-        //clone taxonomy information
647
-        $taxonomies_to_clone_with = apply_filters(
648
-            'FHEE__Extend_Events_Admin_Page___duplicate_event__taxonomies_to_clone',
649
-            array('espresso_event_categories', 'espresso_event_type', 'post_tag')
650
-        );
651
-        //get terms for original event (notice)
652
-        $orig_terms = wp_get_object_terms($orig_event->ID(), $taxonomies_to_clone_with);
653
-        //loop through terms and add them to new event.
654
-        foreach ($orig_terms as $term) {
655
-            wp_set_object_terms($new_event->ID(), $term->term_id, $term->taxonomy, true);
656
-        }
657
-
658
-        //duplicate other core WP_Post items for this event.
659
-        //post thumbnail (feature image).
660
-        $feature_image_id = get_post_thumbnail_id($orig_event->ID());
661
-        if ($feature_image_id) {
662
-            update_post_meta($new_event->ID(), '_thumbnail_id', $feature_image_id);
663
-        }
664
-
665
-        //duplicate page_template setting
666
-        $page_template = get_post_meta($orig_event->ID(), '_wp_page_template', true);
667
-        if ($page_template) {
668
-            update_post_meta($new_event->ID(), '_wp_page_template', $page_template);
669
-        }
670
-
671
-        do_action('AHEE__Extend_Events_Admin_Page___duplicate_event__after', $new_event, $orig_event);
672
-        //now let's redirect to the edit page for this duplicated event if we have a new event id.
673
-        if ($new_event->ID()) {
674
-            $redirect_args = array(
675
-                'post'   => $new_event->ID(),
676
-                'action' => 'edit',
677
-            );
678
-            EE_Error::add_success(
679
-                esc_html__(
680
-                    'Event successfully duplicated.  Please review the details below and make any necessary edits',
681
-                    'event_espresso'
682
-                )
683
-            );
684
-        } else {
685
-            $redirect_args = array(
686
-                'action' => 'default',
687
-            );
688
-            EE_Error::add_error(
689
-                esc_html__('Not able to duplicate event.  Something went wrong.', 'event_espresso'),
690
-                __FILE__,
691
-                __FUNCTION__,
692
-                __LINE__
693
-            );
694
-        }
695
-        $this->_redirect_after_action(false, '', '', $redirect_args, true);
696
-    }
697
-
698
-
699
-    /**
700
-     * Generates output for the import page.
701
-     * @throws DomainException
702
-     */
703
-    protected function _import_page()
704
-    {
705
-        $title                                      = esc_html__('Import', 'event_espresso');
706
-        $intro                                      = esc_html__(
707
-            'If you have a previously exported Event Espresso 4 information in a Comma Separated Value (CSV) file format, you can upload the file here: ',
708
-            'event_espresso'
709
-        );
710
-        $form_url                                   = EVENTS_ADMIN_URL;
711
-        $action                                     = 'import_events';
712
-        $type                                       = 'csv';
713
-        $this->_template_args['form']               = EE_Import::instance()->upload_form(
714
-            $title, $intro, $form_url, $action, $type
715
-        );
716
-        $this->_template_args['sample_file_link']   = EE_Admin_Page::add_query_args_and_nonce(
717
-            array('action' => 'sample_export_file'),
718
-            $this->_admin_base_url
719
-        );
720
-        $content                                    = EEH_Template::display_template(
721
-            EVENTS_CAF_TEMPLATE_PATH . 'import_page.template.php',
722
-            $this->_template_args,
723
-            true
724
-        );
725
-        $this->_template_args['admin_page_content'] = $content;
726
-        $this->display_admin_page_with_sidebar();
727
-    }
728
-
729
-
730
-    /**
731
-     * _import_events
732
-     * This handles displaying the screen and running imports for importing events.
733
-     *
734
-     * @return void
735
-     */
736
-    protected function _import_events()
737
-    {
738
-        require_once(EE_CLASSES . 'EE_Import.class.php');
739
-        $success = EE_Import::instance()->import();
740
-        $this->_redirect_after_action($success, 'Import File', 'ran', array('action' => 'import_page'), true);
741
-    }
742
-
743
-
744
-    /**
745
-     * _events_export
746
-     * Will export all (or just the given event) to a Excel compatible file.
747
-     *
748
-     * @access protected
749
-     * @return void
750
-     */
751
-    protected function _events_export()
752
-    {
753
-        if (isset($this->_req_data['EVT_ID'])) {
754
-            $event_ids = $this->_req_data['EVT_ID'];
755
-        } elseif (isset($this->_req_data['EVT_IDs'])) {
756
-            $event_ids = $this->_req_data['EVT_IDs'];
757
-        } else {
758
-            $event_ids = null;
759
-        }
760
-        //todo: I don't like doing this but it'll do until we modify EE_Export Class.
761
-        $new_request_args = array(
762
-            'export' => 'report',
763
-            'action' => 'all_event_data',
764
-            'EVT_ID' => $event_ids,
765
-        );
766
-        $this->_req_data  = array_merge($this->_req_data, $new_request_args);
767
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
768
-            require_once(EE_CLASSES . 'EE_Export.class.php');
769
-            $EE_Export = EE_Export::instance($this->_req_data);
770
-            $EE_Export->export();
771
-        }
772
-    }
773
-
774
-
775
-    /**
776
-     * handle category exports()
777
-     *
778
-     * @return void
779
-     */
780
-    protected function _categories_export()
781
-    {
782
-        //todo: I don't like doing this but it'll do until we modify EE_Export Class.
783
-        $new_request_args = array(
784
-            'export'       => 'report',
785
-            'action'       => 'categories',
786
-            'category_ids' => $this->_req_data['EVT_CAT_ID'],
787
-        );
788
-        $this->_req_data  = array_merge($this->_req_data, $new_request_args);
789
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
790
-            require_once(EE_CLASSES . 'EE_Export.class.php');
791
-            $EE_Export = EE_Export::instance($this->_req_data);
792
-            $EE_Export->export();
793
-        }
794
-    }
795
-
796
-
797
-    /**
798
-     * Creates a sample CSV file for importing
799
-     */
800
-    protected function _sample_export_file()
801
-    {
802
-        //		require_once(EE_CLASSES . 'EE_Export.class.php');
803
-        EE_Export::instance()->export_sample();
804
-    }
805
-
806
-
807
-    /*************        Template Settings        *************/
808
-    /**
809
-     * Generates template settings page output
810
-     * @throws DomainException
811
-     * @throws EE_Error
812
-     */
813
-    protected function _template_settings()
814
-    {
815
-        $this->_template_args['values'] = $this->_yes_no_values;
816
-        /**
817
-         * Note leaving this filter in for backward compatibility this was moved in 4.6.x
818
-         * from General_Settings_Admin_Page to here.
819
-         */
820
-        $this->_template_args = apply_filters(
821
-            'FHEE__General_Settings_Admin_Page__template_settings__template_args',
822
-            $this->_template_args
823
-        );
824
-        $this->_set_add_edit_form_tags('update_template_settings');
825
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
826
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
827
-            EVENTS_CAF_TEMPLATE_PATH . 'template_settings.template.php',
828
-            $this->_template_args,
829
-            true
830
-        );
831
-        $this->display_admin_page_with_sidebar();
832
-    }
833
-
834
-
835
-    /**
836
-     * Handler for updating template settings.
837
-     */
838
-    protected function _update_template_settings()
839
-    {
840
-        /**
841
-         * Note leaving this filter in for backward compatibility this was moved in 4.6.x
842
-         * from General_Settings_Admin_Page to here.
843
-         */
844
-        EE_Registry::instance()->CFG->template_settings = apply_filters(
845
-            'FHEE__General_Settings_Admin_Page__update_template_settings__data',
846
-            EE_Registry::instance()->CFG->template_settings,
847
-            $this->_req_data
848
-        );
849
-        //update custom post type slugs and detect if we need to flush rewrite rules
850
-        $old_slug                                          = EE_Registry::instance()->CFG->core->event_cpt_slug;
851
-        EE_Registry::instance()->CFG->core->event_cpt_slug = empty($this->_req_data['event_cpt_slug'])
852
-            ? EE_Registry::instance()->CFG->core->event_cpt_slug
853
-            : sanitize_title_with_dashes($this->_req_data['event_cpt_slug']);
854
-        $what                                              = 'Template Settings';
855
-        $success                                           = $this->_update_espresso_configuration(
856
-            $what,
857
-            EE_Registry::instance()->CFG->template_settings,
858
-            __FILE__,
859
-            __FUNCTION__,
860
-            __LINE__
861
-        );
862
-        if (EE_Registry::instance()->CFG->core->event_cpt_slug != $old_slug) {
863
-            update_option('ee_flush_rewrite_rules', true);
864
-        }
865
-        $this->_redirect_after_action($success, $what, 'updated', array('action' => 'template_settings'));
866
-    }
867
-
868
-
869
-    /**
870
-     * _premium_event_editor_meta_boxes
871
-     * add all metaboxes related to the event_editor
872
-     *
873
-     * @access protected
874
-     * @return void
875
-     * @throws EE_Error
876
-     */
877
-    protected function _premium_event_editor_meta_boxes()
878
-    {
879
-        $this->verify_cpt_object();
880
-        add_meta_box(
881
-            'espresso_event_editor_event_options',
882
-            esc_html__('Event Registration Options', 'event_espresso'),
883
-            array($this, 'registration_options_meta_box'),
884
-            $this->page_slug,
885
-            'side',
886
-            'core'
887
-        );
888
-    }
889
-
890
-
891
-    /**
892
-     * override caf metabox
893
-     *
894
-     * @return void
895
-     * @throws DomainException
896
-     */
897
-    public function registration_options_meta_box()
898
-    {
899
-        $yes_no_values                                    = array(
900
-            array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
901
-            array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
902
-        );
903
-        $default_reg_status_values                        = EEM_Registration::reg_status_array(
904
-            array(
905
-                EEM_Registration::status_id_cancelled,
906
-                EEM_Registration::status_id_declined,
907
-                EEM_Registration::status_id_incomplete,
908
-                EEM_Registration::status_id_wait_list,
909
-            ),
910
-            true
911
-        );
912
-        $template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
913
-        $template_args['_event']                          = $this->_cpt_model_obj;
914
-        $template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
915
-        $template_args['default_registration_status']     = EEH_Form_Fields::select_input(
916
-            'default_reg_status',
917
-            $default_reg_status_values,
918
-            $this->_cpt_model_obj->default_registration_status()
919
-        );
920
-        $template_args['display_description']             = EEH_Form_Fields::select_input(
921
-            'display_desc',
922
-            $yes_no_values,
923
-            $this->_cpt_model_obj->display_description()
924
-        );
925
-        $template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
926
-            'display_ticket_selector',
927
-            $yes_no_values,
928
-            $this->_cpt_model_obj->display_ticket_selector(),
929
-            '',
930
-            '',
931
-            false
932
-        );
933
-        $template_args['EVT_default_registration_status'] = EEH_Form_Fields::select_input(
934
-            'EVT_default_registration_status',
935
-            $default_reg_status_values,
936
-            $this->_cpt_model_obj->default_registration_status()
937
-        );
938
-        $template_args['additional_registration_options'] = apply_filters(
939
-            'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
940
-            '',
941
-            $template_args,
942
-            $yes_no_values,
943
-            $default_reg_status_values
944
-        );
945
-        EEH_Template::display_template(
946
-            EVENTS_CAF_TEMPLATE_PATH . 'event_registration_options.template.php',
947
-            $template_args
948
-        );
949
-    }
950
-
951
-
952
-
953
-    /**
954
-     * wp_list_table_mods for caf
955
-     * ============================
956
-     */
957
-    /**
958
-     * hook into list table filters and provide filters for caffeinated list table
959
-     *
960
-     * @param  array $old_filters    any existing filters present
961
-     * @param  array $list_table_obj the list table object
962
-     * @return array                  new filters
963
-     */
964
-    public function list_table_filters($old_filters, $list_table_obj)
965
-    {
966
-        $filters = array();
967
-        //first month/year filters
968
-        $filters[] = $this->espresso_event_months_dropdown();
969
-        $status    = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
970
-        //active status dropdown
971
-        if ($status !== 'draft') {
972
-            $filters[] = $this->active_status_dropdown(
973
-                isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : ''
974
-            );
975
-        }
976
-        //category filter
977
-        $filters[] = $this->category_dropdown();
978
-        return array_merge($old_filters, $filters);
979
-    }
980
-
981
-
982
-    /**
983
-     * espresso_event_months_dropdown
984
-     *
985
-     * @access public
986
-     * @return string                dropdown listing month/year selections for events.
987
-     */
988
-    public function espresso_event_months_dropdown()
989
-    {
990
-        // what we need to do is get all PRIMARY datetimes for all events to filter on.
991
-        // Note we need to include any other filters that are set!
992
-        $status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
993
-        //categories?
994
-        $category = isset($this->_req_data['EVT_CAT']) && $this->_req_data['EVT_CAT'] > 0
995
-            ? $this->_req_data['EVT_CAT']
996
-            : null;
997
-        //active status?
998
-        $active_status = isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : null;
999
-        $cur_date      = isset($this->_req_data['month_range']) ? $this->_req_data['month_range'] : '';
1000
-        return EEH_Form_Fields::generate_event_months_dropdown($cur_date, $status, $category, $active_status);
1001
-    }
1002
-
1003
-
1004
-    /**
1005
-     * returns a list of "active" statuses on the event
1006
-     *
1007
-     * @param  string $current_value whatever the current active status is
1008
-     * @return string
1009
-     */
1010
-    public function active_status_dropdown($current_value = '')
1011
-    {
1012
-        $select_name = 'active_status';
1013
-        $values      = array(
1014
-            'none'     => esc_html__('Show Active/Inactive', 'event_espresso'),
1015
-            'active'   => esc_html__('Active', 'event_espresso'),
1016
-            'upcoming' => esc_html__('Upcoming', 'event_espresso'),
1017
-            'expired'  => esc_html__('Expired', 'event_espresso'),
1018
-            'inactive' => esc_html__('Inactive', 'event_espresso'),
1019
-        );
1020
-        $id          = 'id="espresso-active-status-dropdown-filter"';
1021
-        $class       = 'wide';
1022
-        return EEH_Form_Fields::select_input($select_name, $values, $current_value, $id, $class);
1023
-    }
1024
-
1025
-
1026
-    /**
1027
-     * output a dropdown of the categories for the category filter on the event admin list table
1028
-     *
1029
-     * @access  public
1030
-     * @return string html
1031
-     */
1032
-    public function category_dropdown()
1033
-    {
1034
-        $cur_cat = isset($this->_req_data['EVT_CAT']) ? $this->_req_data['EVT_CAT'] : -1;
1035
-        return EEH_Form_Fields::generate_event_category_dropdown($cur_cat);
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * get total number of events today
1041
-     *
1042
-     * @access public
1043
-     * @return int
1044
-     * @throws EE_Error
1045
-     */
1046
-    public function total_events_today()
1047
-    {
1048
-        $start = EEM_Datetime::instance()->convert_datetime_for_query(
1049
-            'DTT_EVT_start',
1050
-            date('Y-m-d') . ' 00:00:00',
1051
-            'Y-m-d H:i:s',
1052
-            'UTC'
1053
-        );
1054
-        $end   = EEM_Datetime::instance()->convert_datetime_for_query(
1055
-            'DTT_EVT_start',
1056
-            date('Y-m-d') . ' 23:59:59',
1057
-            'Y-m-d H:i:s',
1058
-            'UTC'
1059
-        );
1060
-        $where = array(
1061
-            'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1062
-        );
1063
-        $count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1064
-        return $count;
1065
-    }
1066
-
1067
-
1068
-    /**
1069
-     * get total number of events this month
1070
-     *
1071
-     * @access public
1072
-     * @return int
1073
-     * @throws EE_Error
1074
-     */
1075
-    public function total_events_this_month()
1076
-    {
1077
-        //Dates
1078
-        $this_year_r     = date('Y');
1079
-        $this_month_r    = date('m');
1080
-        $days_this_month = date('t');
1081
-        $start           = EEM_Datetime::instance()->convert_datetime_for_query(
1082
-            'DTT_EVT_start',
1083
-            $this_year_r . '-' . $this_month_r . '-01 00:00:00',
1084
-            'Y-m-d H:i:s',
1085
-            'UTC'
1086
-        );
1087
-        $end             = EEM_Datetime::instance()->convert_datetime_for_query(
1088
-            'DTT_EVT_start',
1089
-            $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' 23:59:59',
1090
-            'Y-m-d H:i:s',
1091
-            'UTC'
1092
-        );
1093
-        $where           = array(
1094
-            'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1095
-        );
1096
-        $count           = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1097
-        return $count;
1098
-    }
1099
-
1100
-
1101
-    /** DEFAULT TICKETS STUFF **/
1102
-
1103
-    /**
1104
-     * Output default tickets list table view.
1105
-     */
1106
-    public function _tickets_overview_list_table()
1107
-    {
1108
-        $this->_search_btn_label = esc_html__('Tickets', 'event_espresso');
1109
-        $this->display_admin_list_table_page_with_no_sidebar();
1110
-    }
1111
-
1112
-
1113
-    /**
1114
-     * @param int  $per_page
1115
-     * @param bool $count
1116
-     * @param bool $trashed
1117
-     * @return \EE_Soft_Delete_Base_Class[]|int
1118
-     */
1119
-    public function get_default_tickets($per_page = 10, $count = false, $trashed = false)
1120
-    {
1121
-        $orderby = empty($this->_req_data['orderby']) ? 'TKT_name' : $this->_req_data['orderby'];
1122
-        $order   = empty($this->_req_data['order']) ? 'ASC' : $this->_req_data['order'];
1123
-        switch ($orderby) {
1124
-            case 'TKT_name':
1125
-                $orderby = array('TKT_name' => $order);
1126
-                break;
1127
-            case 'TKT_price':
1128
-                $orderby = array('TKT_price' => $order);
1129
-                break;
1130
-            case 'TKT_uses':
1131
-                $orderby = array('TKT_uses' => $order);
1132
-                break;
1133
-            case 'TKT_min':
1134
-                $orderby = array('TKT_min' => $order);
1135
-                break;
1136
-            case 'TKT_max':
1137
-                $orderby = array('TKT_max' => $order);
1138
-                break;
1139
-            case 'TKT_qty':
1140
-                $orderby = array('TKT_qty' => $order);
1141
-                break;
1142
-        }
1143
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1144
-            ? $this->_req_data['paged']
1145
-            : 1;
1146
-        $per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1147
-            ? $this->_req_data['perpage']
1148
-            : $per_page;
1149
-        $_where       = array(
1150
-            'TKT_is_default' => 1,
1151
-            'TKT_deleted'    => $trashed,
1152
-        );
1153
-        $offset       = ($current_page - 1) * $per_page;
1154
-        $limit        = array($offset, $per_page);
1155
-        if (isset($this->_req_data['s'])) {
1156
-            $sstr         = '%' . $this->_req_data['s'] . '%';
1157
-            $_where['OR'] = array(
1158
-                'TKT_name'        => array('LIKE', $sstr),
1159
-                'TKT_description' => array('LIKE', $sstr),
1160
-            );
1161
-        }
1162
-        $query_params = array(
1163
-            $_where,
1164
-            'order_by' => $orderby,
1165
-            'limit'    => $limit,
1166
-            'group_by' => 'TKT_ID',
1167
-        );
1168
-        if ($count) {
1169
-            return EEM_Ticket::instance()->count_deleted_and_undeleted(array($_where));
1170
-        } else {
1171
-            return EEM_Ticket::instance()->get_all_deleted_and_undeleted($query_params);
1172
-        }
1173
-    }
1174
-
1175
-
1176
-    /**
1177
-     * @param bool $trash
1178
-     * @throws EE_Error
1179
-     */
1180
-    protected function _trash_or_restore_ticket($trash = false)
1181
-    {
1182
-        $success = 1;
1183
-        $TKT     = EEM_Ticket::instance();
1184
-        //checkboxes?
1185
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1186
-            //if array has more than one element then success message should be plural
1187
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1188
-            //cycle thru the boxes
1189
-            while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1190
-                if ($trash) {
1191
-                    if (! $TKT->delete_by_ID($TKT_ID)) {
1192
-                        $success = 0;
1193
-                    }
1194
-                } else {
1195
-                    if (! $TKT->restore_by_ID($TKT_ID)) {
1196
-                        $success = 0;
1197
-                    }
1198
-                }
1199
-            }
1200
-        } else {
1201
-            //grab single id and trash
1202
-            $TKT_ID = absint($this->_req_data['TKT_ID']);
1203
-            if ($trash) {
1204
-                if (! $TKT->delete_by_ID($TKT_ID)) {
1205
-                    $success = 0;
1206
-                }
1207
-            } else {
1208
-                if (! $TKT->restore_by_ID($TKT_ID)) {
1209
-                    $success = 0;
1210
-                }
1211
-            }
1212
-        }
1213
-        $action_desc = $trash ? 'moved to the trash' : 'restored';
1214
-        $query_args  = array(
1215
-            'action' => 'ticket_list_table',
1216
-            'status' => $trash ? '' : 'trashed',
1217
-        );
1218
-        $this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1219
-    }
1220
-
1221
-
1222
-    /**
1223
-     * Handles trashing default ticket.
1224
-     */
1225
-    protected function _delete_ticket()
1226
-    {
1227
-        $success = 1;
1228
-        //checkboxes?
1229
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1230
-            //if array has more than one element then success message should be plural
1231
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1232
-            //cycle thru the boxes
1233
-            while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1234
-                //delete
1235
-                if (! $this->_delete_the_ticket($TKT_ID)) {
1236
-                    $success = 0;
1237
-                }
1238
-            }
1239
-        } else {
1240
-            //grab single id and trash
1241
-            $TKT_ID = absint($this->_req_data['TKT_ID']);
1242
-            if (! $this->_delete_the_ticket($TKT_ID)) {
1243
-                $success = 0;
1244
-            }
1245
-        }
1246
-        $action_desc = 'deleted';
1247
-        $query_args  = array(
1248
-            'action' => 'ticket_list_table',
1249
-            'status' => 'trashed',
1250
-        );
1251
-        //fail safe.  If the default ticket count === 1 then we need to redirect to event overview.
1252
-        if (EEM_Ticket::instance()->count_deleted_and_undeleted(
1253
-            array(array('TKT_is_default' => 1)),
1254
-            'TKT_ID',
1255
-            true
1256
-        )
1257
-        ) {
1258
-            $query_args = array();
1259
-        }
1260
-        $this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1261
-    }
1262
-
1263
-
1264
-    /**
1265
-     * @param int $TKT_ID
1266
-     * @return bool|int
1267
-     * @throws EE_Error
1268
-     */
1269
-    protected function _delete_the_ticket($TKT_ID)
1270
-    {
1271
-        $tkt = EEM_Ticket::instance()->get_one_by_ID($TKT_ID);
1272
-        $tkt->_remove_relations('Datetime');
1273
-        //delete all related prices first
1274
-        $tkt->delete_related_permanently('Price');
1275
-        return $tkt->delete_permanently();
1276
-    }
17
+	/**
18
+	 * Extend_Events_Admin_Page constructor.
19
+	 *
20
+	 * @param bool $routing
21
+	 */
22
+	public function __construct($routing = true)
23
+	{
24
+		parent::__construct($routing);
25
+		if (! defined('EVENTS_CAF_TEMPLATE_PATH')) {
26
+			define('EVENTS_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'events/templates/');
27
+			define('EVENTS_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'events/assets/');
28
+			define('EVENTS_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'events/assets/');
29
+		}
30
+	}
31
+
32
+
33
+	/**
34
+	 * Sets routes.
35
+	 */
36
+	protected function _extend_page_config()
37
+	{
38
+		$this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'events';
39
+		//is there a evt_id in the request?
40
+		$evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
41
+			? $this->_req_data['EVT_ID']
42
+			: 0;
43
+		$evt_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $evt_id;
44
+		//tkt_id?
45
+		$tkt_id             = ! empty($this->_req_data['TKT_ID']) && ! is_array($this->_req_data['TKT_ID'])
46
+			? $this->_req_data['TKT_ID']
47
+			: 0;
48
+		$new_page_routes    = array(
49
+			'duplicate_event'          => array(
50
+				'func'       => '_duplicate_event',
51
+				'capability' => 'ee_edit_event',
52
+				'obj_id'     => $evt_id,
53
+				'noheader'   => true,
54
+			),
55
+			'ticket_list_table'        => array(
56
+				'func'       => '_tickets_overview_list_table',
57
+				'capability' => 'ee_read_default_tickets',
58
+			),
59
+			'trash_ticket'             => array(
60
+				'func'       => '_trash_or_restore_ticket',
61
+				'capability' => 'ee_delete_default_ticket',
62
+				'obj_id'     => $tkt_id,
63
+				'noheader'   => true,
64
+				'args'       => array('trash' => true),
65
+			),
66
+			'trash_tickets'            => array(
67
+				'func'       => '_trash_or_restore_ticket',
68
+				'capability' => 'ee_delete_default_tickets',
69
+				'noheader'   => true,
70
+				'args'       => array('trash' => true),
71
+			),
72
+			'restore_ticket'           => array(
73
+				'func'       => '_trash_or_restore_ticket',
74
+				'capability' => 'ee_delete_default_ticket',
75
+				'obj_id'     => $tkt_id,
76
+				'noheader'   => true,
77
+			),
78
+			'restore_tickets'          => array(
79
+				'func'       => '_trash_or_restore_ticket',
80
+				'capability' => 'ee_delete_default_tickets',
81
+				'noheader'   => true,
82
+			),
83
+			'delete_ticket'            => array(
84
+				'func'       => '_delete_ticket',
85
+				'capability' => 'ee_delete_default_ticket',
86
+				'obj_id'     => $tkt_id,
87
+				'noheader'   => true,
88
+			),
89
+			'delete_tickets'           => array(
90
+				'func'       => '_delete_ticket',
91
+				'capability' => 'ee_delete_default_tickets',
92
+				'noheader'   => true,
93
+			),
94
+			'import_page'              => array(
95
+				'func'       => '_import_page',
96
+				'capability' => 'import',
97
+			),
98
+			'import'                   => array(
99
+				'func'       => '_import_events',
100
+				'capability' => 'import',
101
+				'noheader'   => true,
102
+			),
103
+			'import_events'            => array(
104
+				'func'       => '_import_events',
105
+				'capability' => 'import',
106
+				'noheader'   => true,
107
+			),
108
+			'export_events'            => array(
109
+				'func'       => '_events_export',
110
+				'capability' => 'export',
111
+				'noheader'   => true,
112
+			),
113
+			'export_categories'        => array(
114
+				'func'       => '_categories_export',
115
+				'capability' => 'export',
116
+				'noheader'   => true,
117
+			),
118
+			'sample_export_file'       => array(
119
+				'func'       => '_sample_export_file',
120
+				'capability' => 'export',
121
+				'noheader'   => true,
122
+			),
123
+			'update_template_settings' => array(
124
+				'func'       => '_update_template_settings',
125
+				'capability' => 'manage_options',
126
+				'noheader'   => true,
127
+			),
128
+		);
129
+		$this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
130
+		//partial route/config override
131
+		$this->_page_config['import_events']['metaboxes'] = $this->_default_espresso_metaboxes;
132
+		$this->_page_config['create_new']['metaboxes'][]  = '_premium_event_editor_meta_boxes';
133
+		$this->_page_config['create_new']['qtips'][]      = 'EE_Event_Editor_Tips';
134
+		$this->_page_config['edit']['qtips'][]            = 'EE_Event_Editor_Tips';
135
+		$this->_page_config['edit']['metaboxes'][]        = '_premium_event_editor_meta_boxes';
136
+		$this->_page_config['default']['list_table']      = 'Extend_Events_Admin_List_Table';
137
+		//add tickets tab but only if there are more than one default ticket!
138
+		$tkt_count = EEM_Ticket::instance()->count_deleted_and_undeleted(
139
+			array(array('TKT_is_default' => 1)),
140
+			'TKT_ID',
141
+			true
142
+		);
143
+		if ($tkt_count > 1) {
144
+			$new_page_config = array(
145
+				'ticket_list_table' => array(
146
+					'nav'           => array(
147
+						'label' => esc_html__('Default Tickets', 'event_espresso'),
148
+						'order' => 60,
149
+					),
150
+					'list_table'    => 'Tickets_List_Table',
151
+					'require_nonce' => false,
152
+				),
153
+			);
154
+		}
155
+		//template settings
156
+		$new_page_config['template_settings'] = array(
157
+			'nav'           => array(
158
+				'label' => esc_html__('Templates', 'event_espresso'),
159
+				'order' => 30,
160
+			),
161
+			'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
162
+			'help_tabs'     => array(
163
+				'general_settings_templates_help_tab' => array(
164
+					'title'    => esc_html__('Templates', 'event_espresso'),
165
+					'filename' => 'general_settings_templates',
166
+				),
167
+			),
168
+			'help_tour'     => array('Templates_Help_Tour'),
169
+			'require_nonce' => false,
170
+		);
171
+		$this->_page_config                   = array_merge($this->_page_config, $new_page_config);
172
+		//add filters and actions
173
+		//modifying _views
174
+		add_filter(
175
+			'FHEE_event_datetime_metabox_add_additional_date_time_template',
176
+			array($this, 'add_additional_datetime_button'),
177
+			10,
178
+			2
179
+		);
180
+		add_filter(
181
+			'FHEE_event_datetime_metabox_clone_button_template',
182
+			array($this, 'add_datetime_clone_button'),
183
+			10,
184
+			2
185
+		);
186
+		add_filter(
187
+			'FHEE_event_datetime_metabox_timezones_template',
188
+			array($this, 'datetime_timezones_template'),
189
+			10,
190
+			2
191
+		);
192
+		//filters for event list table
193
+		add_filter('FHEE__Extend_Events_Admin_List_Table__filters', array($this, 'list_table_filters'), 10, 2);
194
+		add_filter(
195
+			'FHEE__Events_Admin_List_Table__column_actions__action_links',
196
+			array($this, 'extra_list_table_actions'),
197
+			10,
198
+			2
199
+		);
200
+		//legend item
201
+		add_filter('FHEE__Events_Admin_Page___event_legend_items__items', array($this, 'additional_legend_items'));
202
+		add_action('admin_init', array($this, 'admin_init'));
203
+		//heartbeat stuff
204
+		add_filter('heartbeat_received', array($this, 'heartbeat_response'), 10, 2);
205
+	}
206
+
207
+
208
+	/**
209
+	 * admin_init
210
+	 */
211
+	public function admin_init()
212
+	{
213
+		EE_Registry::$i18n_js_strings = array_merge(
214
+			EE_Registry::$i18n_js_strings,
215
+			array(
216
+				'image_confirm'          => esc_html__(
217
+					'Do you really want to delete this image? Please remember to update your event to complete the removal.',
218
+					'event_espresso'
219
+				),
220
+				'event_starts_on'        => esc_html__('Event Starts on', 'event_espresso'),
221
+				'event_ends_on'          => esc_html__('Event Ends on', 'event_espresso'),
222
+				'event_datetime_actions' => esc_html__('Actions', 'event_espresso'),
223
+				'event_clone_dt_msg'     => esc_html__('Clone this Event Date and Time', 'event_espresso'),
224
+				'remove_event_dt_msg'    => esc_html__('Remove this Event Time', 'event_espresso'),
225
+			)
226
+		);
227
+	}
228
+
229
+
230
+	/**
231
+	 * This will be used to listen for any heartbeat data packages coming via the WordPress heartbeat API and handle
232
+	 * accordingly.
233
+	 *
234
+	 * @param array $response The existing heartbeat response array.
235
+	 * @param array $data     The incoming data package.
236
+	 * @return array  possibly appended response.
237
+	 */
238
+	public function heartbeat_response($response, $data)
239
+	{
240
+		/**
241
+		 * check whether count of tickets is approaching the potential
242
+		 * limits for the server.
243
+		 */
244
+		if (! empty($data['input_count'])) {
245
+			$response['max_input_vars_check'] = EE_Registry::instance()->CFG->environment->max_input_vars_limit_check(
246
+				$data['input_count']
247
+			);
248
+		}
249
+		return $response;
250
+	}
251
+
252
+
253
+	/**
254
+	 * Add per page screen options to the default ticket list table view.
255
+	 */
256
+	protected function _add_screen_options_ticket_list_table()
257
+	{
258
+		$this->_per_page_screen_option();
259
+	}
260
+
261
+
262
+	/**
263
+	 * @param string $return
264
+	 * @param int    $id
265
+	 * @param string $new_title
266
+	 * @param string $new_slug
267
+	 * @return string
268
+	 */
269
+	public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
270
+	{
271
+		$return = parent::extra_permalink_field_buttons($return, $id, $new_title, $new_slug);
272
+		//make sure this is only when editing
273
+		if (! empty($id)) {
274
+			$href   = EE_Admin_Page::add_query_args_and_nonce(
275
+				array('action' => 'duplicate_event', 'EVT_ID' => $id),
276
+				$this->_admin_base_url
277
+			);
278
+			$title  = esc_attr__('Duplicate Event', 'event_espresso');
279
+			$return .= '<a href="'
280
+					   . $href
281
+					   . '" title="'
282
+					   . $title
283
+					   . '" id="ee-duplicate-event-button" class="button button-small"  value="duplicate_event">'
284
+					   . $title
285
+					   . '</button>';
286
+		}
287
+		return $return;
288
+	}
289
+
290
+
291
+	/**
292
+	 * Set the list table views for the default ticket list table view.
293
+	 */
294
+	public function _set_list_table_views_ticket_list_table()
295
+	{
296
+		$this->_views = array(
297
+			'all'     => array(
298
+				'slug'        => 'all',
299
+				'label'       => esc_html__('All', 'event_espresso'),
300
+				'count'       => 0,
301
+				'bulk_action' => array(
302
+					'trash_tickets' => esc_html__('Move to Trash', 'event_espresso'),
303
+				),
304
+			),
305
+			'trashed' => array(
306
+				'slug'        => 'trashed',
307
+				'label'       => esc_html__('Trash', 'event_espresso'),
308
+				'count'       => 0,
309
+				'bulk_action' => array(
310
+					'restore_tickets' => esc_html__('Restore from Trash', 'event_espresso'),
311
+					'delete_tickets'  => esc_html__('Delete Permanently', 'event_espresso'),
312
+				),
313
+			),
314
+		);
315
+	}
316
+
317
+
318
+	/**
319
+	 * Enqueue scripts and styles for the event editor.
320
+	 */
321
+	public function load_scripts_styles_edit()
322
+	{
323
+		wp_register_script(
324
+			'ee-event-editor-heartbeat',
325
+			EVENTS_CAF_ASSETS_URL . 'event-editor-heartbeat.js',
326
+			array('ee_admin_js', 'heartbeat'),
327
+			EVENT_ESPRESSO_VERSION,
328
+			true
329
+		);
330
+		wp_enqueue_script('ee-accounting');
331
+		//styles
332
+		wp_enqueue_style('espresso-ui-theme');
333
+		wp_enqueue_script('event_editor_js');
334
+		wp_enqueue_script('ee-event-editor-heartbeat');
335
+	}
336
+
337
+
338
+	/**
339
+	 * Returns template for the additional datetime.
340
+	 * @param $template
341
+	 * @param $template_args
342
+	 * @return mixed
343
+	 * @throws DomainException
344
+	 */
345
+	public function add_additional_datetime_button($template, $template_args)
346
+	{
347
+		return EEH_Template::display_template(
348
+			EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_add_additional_time.template.php',
349
+			$template_args,
350
+			true
351
+		);
352
+	}
353
+
354
+
355
+	/**
356
+	 * Returns the template for cloning a datetime.
357
+	 * @param $template
358
+	 * @param $template_args
359
+	 * @return mixed
360
+	 * @throws DomainException
361
+	 */
362
+	public function add_datetime_clone_button($template, $template_args)
363
+	{
364
+		return EEH_Template::display_template(
365
+			EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_metabox_clone_button.template.php',
366
+			$template_args,
367
+			true
368
+		);
369
+	}
370
+
371
+
372
+	/**
373
+	 * Returns the template for datetime timezones.
374
+	 * @param $template
375
+	 * @param $template_args
376
+	 * @return mixed
377
+	 * @throws DomainException
378
+	 */
379
+	public function datetime_timezones_template($template, $template_args)
380
+	{
381
+		return EEH_Template::display_template(
382
+			EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_timezones.template.php',
383
+			$template_args,
384
+			true
385
+		);
386
+	}
387
+
388
+
389
+	/**
390
+	 * Sets the views for the default list table view.
391
+	 */
392
+	protected function _set_list_table_views_default()
393
+	{
394
+		parent::_set_list_table_views_default();
395
+		$new_views    = array(
396
+			'today' => array(
397
+				'slug'        => 'today',
398
+				'label'       => esc_html__('Today', 'event_espresso'),
399
+				'count'       => $this->total_events_today(),
400
+				'bulk_action' => array(
401
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
402
+				),
403
+			),
404
+			'month' => array(
405
+				'slug'        => 'month',
406
+				'label'       => esc_html__('This Month', 'event_espresso'),
407
+				'count'       => $this->total_events_this_month(),
408
+				'bulk_action' => array(
409
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
410
+				),
411
+			),
412
+		);
413
+		$this->_views = array_merge($this->_views, $new_views);
414
+	}
415
+
416
+
417
+	/**
418
+	 * Returns the extra action links for the default list table view.
419
+	 * @param array     $action_links
420
+	 * @param \EE_Event $event
421
+	 * @return array
422
+	 * @throws EE_Error
423
+	 */
424
+	public function extra_list_table_actions(array $action_links, \EE_Event $event)
425
+	{
426
+		if (EE_Registry::instance()->CAP->current_user_can(
427
+			'ee_read_registrations',
428
+			'espresso_registrations_reports',
429
+			$event->ID()
430
+		)
431
+		) {
432
+			$reports_query_args = array(
433
+				'action' => 'reports',
434
+				'EVT_ID' => $event->ID(),
435
+			);
436
+			$reports_link       = EE_Admin_Page::add_query_args_and_nonce($reports_query_args, REG_ADMIN_URL);
437
+			$action_links[]     = '<a href="'
438
+								  . $reports_link
439
+								  . '" title="'
440
+								  . esc_attr__('View Report', 'event_espresso')
441
+								  . '"><div class="dashicons dashicons-chart-bar"></div></a>'
442
+								  . "\n\t";
443
+		}
444
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
445
+			EE_Registry::instance()->load_helper('MSG_Template');
446
+			$action_links[] = EEH_MSG_Template::get_message_action_link(
447
+				'see_notifications_for',
448
+				null,
449
+				array('EVT_ID' => $event->ID())
450
+			);
451
+		}
452
+		return $action_links;
453
+	}
454
+
455
+
456
+	/**
457
+	 * @param $items
458
+	 * @return mixed
459
+	 */
460
+	public function additional_legend_items($items)
461
+	{
462
+		if (EE_Registry::instance()->CAP->current_user_can(
463
+			'ee_read_registrations',
464
+			'espresso_registrations_reports'
465
+		)
466
+		) {
467
+			$items['reports'] = array(
468
+				'class' => 'dashicons dashicons-chart-bar',
469
+				'desc'  => esc_html__('Event Reports', 'event_espresso'),
470
+			);
471
+		}
472
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
473
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
474
+			if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
475
+				$items['view_related_messages'] = array(
476
+					'class' => $related_for_icon['css_class'],
477
+					'desc'  => $related_for_icon['label'],
478
+				);
479
+			}
480
+		}
481
+		return $items;
482
+	}
483
+
484
+
485
+	/**
486
+	 * This is the callback method for the duplicate event route
487
+	 * Method looks for 'EVT_ID' in the request and retrieves that event and its details and duplicates them
488
+	 * into a new event.  We add a hook so that any plugins that add extra event details can hook into this
489
+	 * action.  Note that the dupe will have **DUPLICATE** as its title and slug.
490
+	 * After duplication the redirect is to the new event edit page.
491
+	 *
492
+	 * @return void
493
+	 * @access protected
494
+	 * @throws EE_Error If EE_Event is not available with given ID
495
+	 */
496
+	protected function _duplicate_event()
497
+	{
498
+		// first make sure the ID for the event is in the request.
499
+		//  If it isn't then we need to bail and redirect back to overview list table (cause how did we get here?)
500
+		if (! isset($this->_req_data['EVT_ID'])) {
501
+			EE_Error::add_error(
502
+				esc_html__(
503
+					'In order to duplicate an event an Event ID is required.  None was given.',
504
+					'event_espresso'
505
+				),
506
+				__FILE__,
507
+				__FUNCTION__,
508
+				__LINE__
509
+			);
510
+			$this->_redirect_after_action(false, '', '', array(), true);
511
+			return;
512
+		}
513
+		//k we've got EVT_ID so let's use that to get the event we'll duplicate
514
+		$orig_event = EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']);
515
+		if (! $orig_event instanceof EE_Event) {
516
+			throw new EE_Error(
517
+				sprintf(
518
+					esc_html__('An EE_Event object could not be retrieved for the given ID (%s)', 'event_espresso'),
519
+					$this->_req_data['EVT_ID']
520
+				)
521
+			);
522
+		}
523
+		//k now let's clone the $orig_event before getting relations
524
+		$new_event = clone $orig_event;
525
+		//original datetimes
526
+		$orig_datetimes = $orig_event->get_many_related('Datetime');
527
+		//other original relations
528
+		$orig_ven = $orig_event->get_many_related('Venue');
529
+		//reset the ID and modify other details to make it clear this is a dupe
530
+		$new_event->set('EVT_ID', 0);
531
+		$new_name = $new_event->name() . ' ' . esc_html__('**DUPLICATE**', 'event_espresso');
532
+		$new_event->set('EVT_name', $new_name);
533
+		$new_event->set(
534
+			'EVT_slug',
535
+			wp_unique_post_slug(
536
+				sanitize_title($orig_event->name()),
537
+				0,
538
+				'publish',
539
+				'espresso_events',
540
+				0
541
+			)
542
+		);
543
+		$new_event->set('status', 'draft');
544
+		//duplicate discussion settings
545
+		$new_event->set('comment_status', $orig_event->get('comment_status'));
546
+		$new_event->set('ping_status', $orig_event->get('ping_status'));
547
+		//save the new event
548
+		$new_event->save();
549
+		//venues
550
+		foreach ($orig_ven as $ven) {
551
+			$new_event->_add_relation_to($ven, 'Venue');
552
+		}
553
+		$new_event->save();
554
+		//now we need to get the question group relations and handle that
555
+		//first primary question groups
556
+		$orig_primary_qgs = $orig_event->get_many_related(
557
+			'Question_Group',
558
+			array(array('Event_Question_Group.EQG_primary' => 1))
559
+		);
560
+		if (! empty($orig_primary_qgs)) {
561
+			foreach ($orig_primary_qgs as $id => $obj) {
562
+				if ($obj instanceof EE_Question_Group) {
563
+					$new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 1));
564
+				}
565
+			}
566
+		}
567
+		//next additional attendee question groups
568
+		$orig_additional_qgs = $orig_event->get_many_related(
569
+			'Question_Group',
570
+			array(array('Event_Question_Group.EQG_primary' => 0))
571
+		);
572
+		if (! empty($orig_additional_qgs)) {
573
+			foreach ($orig_additional_qgs as $id => $obj) {
574
+				if ($obj instanceof EE_Question_Group) {
575
+					$new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 0));
576
+				}
577
+			}
578
+		}
579
+
580
+		$new_event->save();
581
+
582
+		//k now that we have the new event saved we can loop through the datetimes and start adding relations.
583
+		$cloned_tickets = array();
584
+		foreach ($orig_datetimes as $orig_dtt) {
585
+			if (! $orig_dtt instanceof EE_Datetime) {
586
+				continue;
587
+			}
588
+			$new_dtt   = clone $orig_dtt;
589
+			$orig_tkts = $orig_dtt->tickets();
590
+			//save new dtt then add to event
591
+			$new_dtt->set('DTT_ID', 0);
592
+			$new_dtt->set('DTT_sold', 0);
593
+			$new_dtt->set_reserved(0);
594
+			$new_dtt->save();
595
+			$new_event->_add_relation_to($new_dtt, 'Datetime');
596
+			$new_event->save();
597
+			//now let's get the ticket relations setup.
598
+			foreach ((array)$orig_tkts as $orig_tkt) {
599
+				//it's possible a datetime will have no tickets so let's verify we HAVE a ticket first.
600
+				if (! $orig_tkt instanceof EE_Ticket) {
601
+					continue;
602
+				}
603
+				//is this ticket archived?  If it is then let's skip
604
+				if ($orig_tkt->get('TKT_deleted')) {
605
+					continue;
606
+				}
607
+				// does this original ticket already exist in the clone_tickets cache?
608
+				//  If so we'll just use the new ticket from it.
609
+				if (isset($cloned_tickets[$orig_tkt->ID()])) {
610
+					$new_tkt = $cloned_tickets[$orig_tkt->ID()];
611
+				} else {
612
+					$new_tkt = clone $orig_tkt;
613
+					//get relations on the $orig_tkt that we need to setup.
614
+					$orig_prices = $orig_tkt->prices();
615
+					$new_tkt->set('TKT_ID', 0);
616
+					$new_tkt->set('TKT_sold', 0);
617
+					$new_tkt->set('TKT_reserved', 0);
618
+					$new_tkt->save(); //make sure new ticket has ID.
619
+					//price relations on new ticket need to be setup.
620
+					foreach ($orig_prices as $orig_price) {
621
+						$new_price = clone $orig_price;
622
+						$new_price->set('PRC_ID', 0);
623
+						$new_price->save();
624
+						$new_tkt->_add_relation_to($new_price, 'Price');
625
+						$new_tkt->save();
626
+					}
627
+
628
+					do_action(
629
+						'AHEE__Extend_Events_Admin_Page___duplicate_event__duplicate_ticket__after',
630
+						$orig_tkt,
631
+						$new_tkt,
632
+						$orig_prices,
633
+						$orig_event,
634
+						$orig_dtt,
635
+						$new_dtt
636
+					);
637
+				}
638
+				// k now we can add the new ticket as a relation to the new datetime
639
+				// and make sure its added to our cached $cloned_tickets array
640
+				// for use with later datetimes that have the same ticket.
641
+				$new_dtt->_add_relation_to($new_tkt, 'Ticket');
642
+				$new_dtt->save();
643
+				$cloned_tickets[$orig_tkt->ID()] = $new_tkt;
644
+			}
645
+		}
646
+		//clone taxonomy information
647
+		$taxonomies_to_clone_with = apply_filters(
648
+			'FHEE__Extend_Events_Admin_Page___duplicate_event__taxonomies_to_clone',
649
+			array('espresso_event_categories', 'espresso_event_type', 'post_tag')
650
+		);
651
+		//get terms for original event (notice)
652
+		$orig_terms = wp_get_object_terms($orig_event->ID(), $taxonomies_to_clone_with);
653
+		//loop through terms and add them to new event.
654
+		foreach ($orig_terms as $term) {
655
+			wp_set_object_terms($new_event->ID(), $term->term_id, $term->taxonomy, true);
656
+		}
657
+
658
+		//duplicate other core WP_Post items for this event.
659
+		//post thumbnail (feature image).
660
+		$feature_image_id = get_post_thumbnail_id($orig_event->ID());
661
+		if ($feature_image_id) {
662
+			update_post_meta($new_event->ID(), '_thumbnail_id', $feature_image_id);
663
+		}
664
+
665
+		//duplicate page_template setting
666
+		$page_template = get_post_meta($orig_event->ID(), '_wp_page_template', true);
667
+		if ($page_template) {
668
+			update_post_meta($new_event->ID(), '_wp_page_template', $page_template);
669
+		}
670
+
671
+		do_action('AHEE__Extend_Events_Admin_Page___duplicate_event__after', $new_event, $orig_event);
672
+		//now let's redirect to the edit page for this duplicated event if we have a new event id.
673
+		if ($new_event->ID()) {
674
+			$redirect_args = array(
675
+				'post'   => $new_event->ID(),
676
+				'action' => 'edit',
677
+			);
678
+			EE_Error::add_success(
679
+				esc_html__(
680
+					'Event successfully duplicated.  Please review the details below and make any necessary edits',
681
+					'event_espresso'
682
+				)
683
+			);
684
+		} else {
685
+			$redirect_args = array(
686
+				'action' => 'default',
687
+			);
688
+			EE_Error::add_error(
689
+				esc_html__('Not able to duplicate event.  Something went wrong.', 'event_espresso'),
690
+				__FILE__,
691
+				__FUNCTION__,
692
+				__LINE__
693
+			);
694
+		}
695
+		$this->_redirect_after_action(false, '', '', $redirect_args, true);
696
+	}
697
+
698
+
699
+	/**
700
+	 * Generates output for the import page.
701
+	 * @throws DomainException
702
+	 */
703
+	protected function _import_page()
704
+	{
705
+		$title                                      = esc_html__('Import', 'event_espresso');
706
+		$intro                                      = esc_html__(
707
+			'If you have a previously exported Event Espresso 4 information in a Comma Separated Value (CSV) file format, you can upload the file here: ',
708
+			'event_espresso'
709
+		);
710
+		$form_url                                   = EVENTS_ADMIN_URL;
711
+		$action                                     = 'import_events';
712
+		$type                                       = 'csv';
713
+		$this->_template_args['form']               = EE_Import::instance()->upload_form(
714
+			$title, $intro, $form_url, $action, $type
715
+		);
716
+		$this->_template_args['sample_file_link']   = EE_Admin_Page::add_query_args_and_nonce(
717
+			array('action' => 'sample_export_file'),
718
+			$this->_admin_base_url
719
+		);
720
+		$content                                    = EEH_Template::display_template(
721
+			EVENTS_CAF_TEMPLATE_PATH . 'import_page.template.php',
722
+			$this->_template_args,
723
+			true
724
+		);
725
+		$this->_template_args['admin_page_content'] = $content;
726
+		$this->display_admin_page_with_sidebar();
727
+	}
728
+
729
+
730
+	/**
731
+	 * _import_events
732
+	 * This handles displaying the screen and running imports for importing events.
733
+	 *
734
+	 * @return void
735
+	 */
736
+	protected function _import_events()
737
+	{
738
+		require_once(EE_CLASSES . 'EE_Import.class.php');
739
+		$success = EE_Import::instance()->import();
740
+		$this->_redirect_after_action($success, 'Import File', 'ran', array('action' => 'import_page'), true);
741
+	}
742
+
743
+
744
+	/**
745
+	 * _events_export
746
+	 * Will export all (or just the given event) to a Excel compatible file.
747
+	 *
748
+	 * @access protected
749
+	 * @return void
750
+	 */
751
+	protected function _events_export()
752
+	{
753
+		if (isset($this->_req_data['EVT_ID'])) {
754
+			$event_ids = $this->_req_data['EVT_ID'];
755
+		} elseif (isset($this->_req_data['EVT_IDs'])) {
756
+			$event_ids = $this->_req_data['EVT_IDs'];
757
+		} else {
758
+			$event_ids = null;
759
+		}
760
+		//todo: I don't like doing this but it'll do until we modify EE_Export Class.
761
+		$new_request_args = array(
762
+			'export' => 'report',
763
+			'action' => 'all_event_data',
764
+			'EVT_ID' => $event_ids,
765
+		);
766
+		$this->_req_data  = array_merge($this->_req_data, $new_request_args);
767
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
768
+			require_once(EE_CLASSES . 'EE_Export.class.php');
769
+			$EE_Export = EE_Export::instance($this->_req_data);
770
+			$EE_Export->export();
771
+		}
772
+	}
773
+
774
+
775
+	/**
776
+	 * handle category exports()
777
+	 *
778
+	 * @return void
779
+	 */
780
+	protected function _categories_export()
781
+	{
782
+		//todo: I don't like doing this but it'll do until we modify EE_Export Class.
783
+		$new_request_args = array(
784
+			'export'       => 'report',
785
+			'action'       => 'categories',
786
+			'category_ids' => $this->_req_data['EVT_CAT_ID'],
787
+		);
788
+		$this->_req_data  = array_merge($this->_req_data, $new_request_args);
789
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
790
+			require_once(EE_CLASSES . 'EE_Export.class.php');
791
+			$EE_Export = EE_Export::instance($this->_req_data);
792
+			$EE_Export->export();
793
+		}
794
+	}
795
+
796
+
797
+	/**
798
+	 * Creates a sample CSV file for importing
799
+	 */
800
+	protected function _sample_export_file()
801
+	{
802
+		//		require_once(EE_CLASSES . 'EE_Export.class.php');
803
+		EE_Export::instance()->export_sample();
804
+	}
805
+
806
+
807
+	/*************        Template Settings        *************/
808
+	/**
809
+	 * Generates template settings page output
810
+	 * @throws DomainException
811
+	 * @throws EE_Error
812
+	 */
813
+	protected function _template_settings()
814
+	{
815
+		$this->_template_args['values'] = $this->_yes_no_values;
816
+		/**
817
+		 * Note leaving this filter in for backward compatibility this was moved in 4.6.x
818
+		 * from General_Settings_Admin_Page to here.
819
+		 */
820
+		$this->_template_args = apply_filters(
821
+			'FHEE__General_Settings_Admin_Page__template_settings__template_args',
822
+			$this->_template_args
823
+		);
824
+		$this->_set_add_edit_form_tags('update_template_settings');
825
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
826
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
827
+			EVENTS_CAF_TEMPLATE_PATH . 'template_settings.template.php',
828
+			$this->_template_args,
829
+			true
830
+		);
831
+		$this->display_admin_page_with_sidebar();
832
+	}
833
+
834
+
835
+	/**
836
+	 * Handler for updating template settings.
837
+	 */
838
+	protected function _update_template_settings()
839
+	{
840
+		/**
841
+		 * Note leaving this filter in for backward compatibility this was moved in 4.6.x
842
+		 * from General_Settings_Admin_Page to here.
843
+		 */
844
+		EE_Registry::instance()->CFG->template_settings = apply_filters(
845
+			'FHEE__General_Settings_Admin_Page__update_template_settings__data',
846
+			EE_Registry::instance()->CFG->template_settings,
847
+			$this->_req_data
848
+		);
849
+		//update custom post type slugs and detect if we need to flush rewrite rules
850
+		$old_slug                                          = EE_Registry::instance()->CFG->core->event_cpt_slug;
851
+		EE_Registry::instance()->CFG->core->event_cpt_slug = empty($this->_req_data['event_cpt_slug'])
852
+			? EE_Registry::instance()->CFG->core->event_cpt_slug
853
+			: sanitize_title_with_dashes($this->_req_data['event_cpt_slug']);
854
+		$what                                              = 'Template Settings';
855
+		$success                                           = $this->_update_espresso_configuration(
856
+			$what,
857
+			EE_Registry::instance()->CFG->template_settings,
858
+			__FILE__,
859
+			__FUNCTION__,
860
+			__LINE__
861
+		);
862
+		if (EE_Registry::instance()->CFG->core->event_cpt_slug != $old_slug) {
863
+			update_option('ee_flush_rewrite_rules', true);
864
+		}
865
+		$this->_redirect_after_action($success, $what, 'updated', array('action' => 'template_settings'));
866
+	}
867
+
868
+
869
+	/**
870
+	 * _premium_event_editor_meta_boxes
871
+	 * add all metaboxes related to the event_editor
872
+	 *
873
+	 * @access protected
874
+	 * @return void
875
+	 * @throws EE_Error
876
+	 */
877
+	protected function _premium_event_editor_meta_boxes()
878
+	{
879
+		$this->verify_cpt_object();
880
+		add_meta_box(
881
+			'espresso_event_editor_event_options',
882
+			esc_html__('Event Registration Options', 'event_espresso'),
883
+			array($this, 'registration_options_meta_box'),
884
+			$this->page_slug,
885
+			'side',
886
+			'core'
887
+		);
888
+	}
889
+
890
+
891
+	/**
892
+	 * override caf metabox
893
+	 *
894
+	 * @return void
895
+	 * @throws DomainException
896
+	 */
897
+	public function registration_options_meta_box()
898
+	{
899
+		$yes_no_values                                    = array(
900
+			array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
901
+			array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
902
+		);
903
+		$default_reg_status_values                        = EEM_Registration::reg_status_array(
904
+			array(
905
+				EEM_Registration::status_id_cancelled,
906
+				EEM_Registration::status_id_declined,
907
+				EEM_Registration::status_id_incomplete,
908
+				EEM_Registration::status_id_wait_list,
909
+			),
910
+			true
911
+		);
912
+		$template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
913
+		$template_args['_event']                          = $this->_cpt_model_obj;
914
+		$template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
915
+		$template_args['default_registration_status']     = EEH_Form_Fields::select_input(
916
+			'default_reg_status',
917
+			$default_reg_status_values,
918
+			$this->_cpt_model_obj->default_registration_status()
919
+		);
920
+		$template_args['display_description']             = EEH_Form_Fields::select_input(
921
+			'display_desc',
922
+			$yes_no_values,
923
+			$this->_cpt_model_obj->display_description()
924
+		);
925
+		$template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
926
+			'display_ticket_selector',
927
+			$yes_no_values,
928
+			$this->_cpt_model_obj->display_ticket_selector(),
929
+			'',
930
+			'',
931
+			false
932
+		);
933
+		$template_args['EVT_default_registration_status'] = EEH_Form_Fields::select_input(
934
+			'EVT_default_registration_status',
935
+			$default_reg_status_values,
936
+			$this->_cpt_model_obj->default_registration_status()
937
+		);
938
+		$template_args['additional_registration_options'] = apply_filters(
939
+			'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
940
+			'',
941
+			$template_args,
942
+			$yes_no_values,
943
+			$default_reg_status_values
944
+		);
945
+		EEH_Template::display_template(
946
+			EVENTS_CAF_TEMPLATE_PATH . 'event_registration_options.template.php',
947
+			$template_args
948
+		);
949
+	}
950
+
951
+
952
+
953
+	/**
954
+	 * wp_list_table_mods for caf
955
+	 * ============================
956
+	 */
957
+	/**
958
+	 * hook into list table filters and provide filters for caffeinated list table
959
+	 *
960
+	 * @param  array $old_filters    any existing filters present
961
+	 * @param  array $list_table_obj the list table object
962
+	 * @return array                  new filters
963
+	 */
964
+	public function list_table_filters($old_filters, $list_table_obj)
965
+	{
966
+		$filters = array();
967
+		//first month/year filters
968
+		$filters[] = $this->espresso_event_months_dropdown();
969
+		$status    = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
970
+		//active status dropdown
971
+		if ($status !== 'draft') {
972
+			$filters[] = $this->active_status_dropdown(
973
+				isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : ''
974
+			);
975
+		}
976
+		//category filter
977
+		$filters[] = $this->category_dropdown();
978
+		return array_merge($old_filters, $filters);
979
+	}
980
+
981
+
982
+	/**
983
+	 * espresso_event_months_dropdown
984
+	 *
985
+	 * @access public
986
+	 * @return string                dropdown listing month/year selections for events.
987
+	 */
988
+	public function espresso_event_months_dropdown()
989
+	{
990
+		// what we need to do is get all PRIMARY datetimes for all events to filter on.
991
+		// Note we need to include any other filters that are set!
992
+		$status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
993
+		//categories?
994
+		$category = isset($this->_req_data['EVT_CAT']) && $this->_req_data['EVT_CAT'] > 0
995
+			? $this->_req_data['EVT_CAT']
996
+			: null;
997
+		//active status?
998
+		$active_status = isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : null;
999
+		$cur_date      = isset($this->_req_data['month_range']) ? $this->_req_data['month_range'] : '';
1000
+		return EEH_Form_Fields::generate_event_months_dropdown($cur_date, $status, $category, $active_status);
1001
+	}
1002
+
1003
+
1004
+	/**
1005
+	 * returns a list of "active" statuses on the event
1006
+	 *
1007
+	 * @param  string $current_value whatever the current active status is
1008
+	 * @return string
1009
+	 */
1010
+	public function active_status_dropdown($current_value = '')
1011
+	{
1012
+		$select_name = 'active_status';
1013
+		$values      = array(
1014
+			'none'     => esc_html__('Show Active/Inactive', 'event_espresso'),
1015
+			'active'   => esc_html__('Active', 'event_espresso'),
1016
+			'upcoming' => esc_html__('Upcoming', 'event_espresso'),
1017
+			'expired'  => esc_html__('Expired', 'event_espresso'),
1018
+			'inactive' => esc_html__('Inactive', 'event_espresso'),
1019
+		);
1020
+		$id          = 'id="espresso-active-status-dropdown-filter"';
1021
+		$class       = 'wide';
1022
+		return EEH_Form_Fields::select_input($select_name, $values, $current_value, $id, $class);
1023
+	}
1024
+
1025
+
1026
+	/**
1027
+	 * output a dropdown of the categories for the category filter on the event admin list table
1028
+	 *
1029
+	 * @access  public
1030
+	 * @return string html
1031
+	 */
1032
+	public function category_dropdown()
1033
+	{
1034
+		$cur_cat = isset($this->_req_data['EVT_CAT']) ? $this->_req_data['EVT_CAT'] : -1;
1035
+		return EEH_Form_Fields::generate_event_category_dropdown($cur_cat);
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * get total number of events today
1041
+	 *
1042
+	 * @access public
1043
+	 * @return int
1044
+	 * @throws EE_Error
1045
+	 */
1046
+	public function total_events_today()
1047
+	{
1048
+		$start = EEM_Datetime::instance()->convert_datetime_for_query(
1049
+			'DTT_EVT_start',
1050
+			date('Y-m-d') . ' 00:00:00',
1051
+			'Y-m-d H:i:s',
1052
+			'UTC'
1053
+		);
1054
+		$end   = EEM_Datetime::instance()->convert_datetime_for_query(
1055
+			'DTT_EVT_start',
1056
+			date('Y-m-d') . ' 23:59:59',
1057
+			'Y-m-d H:i:s',
1058
+			'UTC'
1059
+		);
1060
+		$where = array(
1061
+			'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1062
+		);
1063
+		$count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1064
+		return $count;
1065
+	}
1066
+
1067
+
1068
+	/**
1069
+	 * get total number of events this month
1070
+	 *
1071
+	 * @access public
1072
+	 * @return int
1073
+	 * @throws EE_Error
1074
+	 */
1075
+	public function total_events_this_month()
1076
+	{
1077
+		//Dates
1078
+		$this_year_r     = date('Y');
1079
+		$this_month_r    = date('m');
1080
+		$days_this_month = date('t');
1081
+		$start           = EEM_Datetime::instance()->convert_datetime_for_query(
1082
+			'DTT_EVT_start',
1083
+			$this_year_r . '-' . $this_month_r . '-01 00:00:00',
1084
+			'Y-m-d H:i:s',
1085
+			'UTC'
1086
+		);
1087
+		$end             = EEM_Datetime::instance()->convert_datetime_for_query(
1088
+			'DTT_EVT_start',
1089
+			$this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' 23:59:59',
1090
+			'Y-m-d H:i:s',
1091
+			'UTC'
1092
+		);
1093
+		$where           = array(
1094
+			'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1095
+		);
1096
+		$count           = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1097
+		return $count;
1098
+	}
1099
+
1100
+
1101
+	/** DEFAULT TICKETS STUFF **/
1102
+
1103
+	/**
1104
+	 * Output default tickets list table view.
1105
+	 */
1106
+	public function _tickets_overview_list_table()
1107
+	{
1108
+		$this->_search_btn_label = esc_html__('Tickets', 'event_espresso');
1109
+		$this->display_admin_list_table_page_with_no_sidebar();
1110
+	}
1111
+
1112
+
1113
+	/**
1114
+	 * @param int  $per_page
1115
+	 * @param bool $count
1116
+	 * @param bool $trashed
1117
+	 * @return \EE_Soft_Delete_Base_Class[]|int
1118
+	 */
1119
+	public function get_default_tickets($per_page = 10, $count = false, $trashed = false)
1120
+	{
1121
+		$orderby = empty($this->_req_data['orderby']) ? 'TKT_name' : $this->_req_data['orderby'];
1122
+		$order   = empty($this->_req_data['order']) ? 'ASC' : $this->_req_data['order'];
1123
+		switch ($orderby) {
1124
+			case 'TKT_name':
1125
+				$orderby = array('TKT_name' => $order);
1126
+				break;
1127
+			case 'TKT_price':
1128
+				$orderby = array('TKT_price' => $order);
1129
+				break;
1130
+			case 'TKT_uses':
1131
+				$orderby = array('TKT_uses' => $order);
1132
+				break;
1133
+			case 'TKT_min':
1134
+				$orderby = array('TKT_min' => $order);
1135
+				break;
1136
+			case 'TKT_max':
1137
+				$orderby = array('TKT_max' => $order);
1138
+				break;
1139
+			case 'TKT_qty':
1140
+				$orderby = array('TKT_qty' => $order);
1141
+				break;
1142
+		}
1143
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1144
+			? $this->_req_data['paged']
1145
+			: 1;
1146
+		$per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1147
+			? $this->_req_data['perpage']
1148
+			: $per_page;
1149
+		$_where       = array(
1150
+			'TKT_is_default' => 1,
1151
+			'TKT_deleted'    => $trashed,
1152
+		);
1153
+		$offset       = ($current_page - 1) * $per_page;
1154
+		$limit        = array($offset, $per_page);
1155
+		if (isset($this->_req_data['s'])) {
1156
+			$sstr         = '%' . $this->_req_data['s'] . '%';
1157
+			$_where['OR'] = array(
1158
+				'TKT_name'        => array('LIKE', $sstr),
1159
+				'TKT_description' => array('LIKE', $sstr),
1160
+			);
1161
+		}
1162
+		$query_params = array(
1163
+			$_where,
1164
+			'order_by' => $orderby,
1165
+			'limit'    => $limit,
1166
+			'group_by' => 'TKT_ID',
1167
+		);
1168
+		if ($count) {
1169
+			return EEM_Ticket::instance()->count_deleted_and_undeleted(array($_where));
1170
+		} else {
1171
+			return EEM_Ticket::instance()->get_all_deleted_and_undeleted($query_params);
1172
+		}
1173
+	}
1174
+
1175
+
1176
+	/**
1177
+	 * @param bool $trash
1178
+	 * @throws EE_Error
1179
+	 */
1180
+	protected function _trash_or_restore_ticket($trash = false)
1181
+	{
1182
+		$success = 1;
1183
+		$TKT     = EEM_Ticket::instance();
1184
+		//checkboxes?
1185
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1186
+			//if array has more than one element then success message should be plural
1187
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1188
+			//cycle thru the boxes
1189
+			while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1190
+				if ($trash) {
1191
+					if (! $TKT->delete_by_ID($TKT_ID)) {
1192
+						$success = 0;
1193
+					}
1194
+				} else {
1195
+					if (! $TKT->restore_by_ID($TKT_ID)) {
1196
+						$success = 0;
1197
+					}
1198
+				}
1199
+			}
1200
+		} else {
1201
+			//grab single id and trash
1202
+			$TKT_ID = absint($this->_req_data['TKT_ID']);
1203
+			if ($trash) {
1204
+				if (! $TKT->delete_by_ID($TKT_ID)) {
1205
+					$success = 0;
1206
+				}
1207
+			} else {
1208
+				if (! $TKT->restore_by_ID($TKT_ID)) {
1209
+					$success = 0;
1210
+				}
1211
+			}
1212
+		}
1213
+		$action_desc = $trash ? 'moved to the trash' : 'restored';
1214
+		$query_args  = array(
1215
+			'action' => 'ticket_list_table',
1216
+			'status' => $trash ? '' : 'trashed',
1217
+		);
1218
+		$this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1219
+	}
1220
+
1221
+
1222
+	/**
1223
+	 * Handles trashing default ticket.
1224
+	 */
1225
+	protected function _delete_ticket()
1226
+	{
1227
+		$success = 1;
1228
+		//checkboxes?
1229
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1230
+			//if array has more than one element then success message should be plural
1231
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1232
+			//cycle thru the boxes
1233
+			while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1234
+				//delete
1235
+				if (! $this->_delete_the_ticket($TKT_ID)) {
1236
+					$success = 0;
1237
+				}
1238
+			}
1239
+		} else {
1240
+			//grab single id and trash
1241
+			$TKT_ID = absint($this->_req_data['TKT_ID']);
1242
+			if (! $this->_delete_the_ticket($TKT_ID)) {
1243
+				$success = 0;
1244
+			}
1245
+		}
1246
+		$action_desc = 'deleted';
1247
+		$query_args  = array(
1248
+			'action' => 'ticket_list_table',
1249
+			'status' => 'trashed',
1250
+		);
1251
+		//fail safe.  If the default ticket count === 1 then we need to redirect to event overview.
1252
+		if (EEM_Ticket::instance()->count_deleted_and_undeleted(
1253
+			array(array('TKT_is_default' => 1)),
1254
+			'TKT_ID',
1255
+			true
1256
+		)
1257
+		) {
1258
+			$query_args = array();
1259
+		}
1260
+		$this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1261
+	}
1262
+
1263
+
1264
+	/**
1265
+	 * @param int $TKT_ID
1266
+	 * @return bool|int
1267
+	 * @throws EE_Error
1268
+	 */
1269
+	protected function _delete_the_ticket($TKT_ID)
1270
+	{
1271
+		$tkt = EEM_Ticket::instance()->get_one_by_ID($TKT_ID);
1272
+		$tkt->_remove_relations('Datetime');
1273
+		//delete all related prices first
1274
+		$tkt->delete_related_permanently('Price');
1275
+		return $tkt->delete_permanently();
1276
+	}
1277 1277
 }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +219 added lines, -219 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,243 +40,243 @@  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.45.rc.012');
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.45.rc.012');
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
-        // for older WP versions
197
-        if ( ! defined('MONTH_IN_SECONDS')) {
198
-            define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
-        }
200
-        /**
201
-         *    espresso_plugin_activation
202
-         *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
-         */
204
-        function espresso_plugin_activation()
205
-        {
206
-            update_option('ee_espresso_activation', true);
207
-        }
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
+		// for older WP versions
197
+		if ( ! defined('MONTH_IN_SECONDS')) {
198
+			define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
+		}
200
+		/**
201
+		 *    espresso_plugin_activation
202
+		 *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
+		 */
204
+		function espresso_plugin_activation()
205
+		{
206
+			update_option('ee_espresso_activation', true);
207
+		}
208 208
 
209
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
-        /**
211
-         *    espresso_load_error_handling
212
-         *    this function loads EE's class for handling exceptions and errors
213
-         */
214
-        function espresso_load_error_handling()
215
-        {
216
-            // load debugging tools
217
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
-                require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
-                EEH_Debug_Tools::instance();
220
-            }
221
-            // load error handling
222
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
-                require_once(EE_CORE . 'EE_Error.core.php');
224
-            } else {
225
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
-            }
227
-        }
209
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
+		/**
211
+		 *    espresso_load_error_handling
212
+		 *    this function loads EE's class for handling exceptions and errors
213
+		 */
214
+		function espresso_load_error_handling()
215
+		{
216
+			// load debugging tools
217
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
+				require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
+				EEH_Debug_Tools::instance();
220
+			}
221
+			// load error handling
222
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
+				require_once(EE_CORE . 'EE_Error.core.php');
224
+			} else {
225
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
+			}
227
+		}
228 228
 
229
-        /**
230
-         *    espresso_load_required
231
-         *    given a class name and path, this function will load that file or throw an exception
232
-         *
233
-         * @param    string $classname
234
-         * @param    string $full_path_to_file
235
-         * @throws    EE_Error
236
-         */
237
-        function espresso_load_required($classname, $full_path_to_file)
238
-        {
239
-            static $error_handling_loaded = false;
240
-            if ( ! $error_handling_loaded) {
241
-                espresso_load_error_handling();
242
-                $error_handling_loaded = true;
243
-            }
244
-            if (is_readable($full_path_to_file)) {
245
-                require_once($full_path_to_file);
246
-            } else {
247
-                throw new EE_Error (
248
-                        sprintf(
249
-                                esc_html__(
250
-                                        'The %s class file could not be located or is not readable due to file permissions.',
251
-                                        'event_espresso'
252
-                                ),
253
-                                $classname
254
-                        )
255
-                );
256
-            }
257
-        }
229
+		/**
230
+		 *    espresso_load_required
231
+		 *    given a class name and path, this function will load that file or throw an exception
232
+		 *
233
+		 * @param    string $classname
234
+		 * @param    string $full_path_to_file
235
+		 * @throws    EE_Error
236
+		 */
237
+		function espresso_load_required($classname, $full_path_to_file)
238
+		{
239
+			static $error_handling_loaded = false;
240
+			if ( ! $error_handling_loaded) {
241
+				espresso_load_error_handling();
242
+				$error_handling_loaded = true;
243
+			}
244
+			if (is_readable($full_path_to_file)) {
245
+				require_once($full_path_to_file);
246
+			} else {
247
+				throw new EE_Error (
248
+						sprintf(
249
+								esc_html__(
250
+										'The %s class file could not be located or is not readable due to file permissions.',
251
+										'event_espresso'
252
+								),
253
+								$classname
254
+						)
255
+				);
256
+			}
257
+		}
258 258
 
259
-        espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
-        espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
-        espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
-        new EE_Bootstrap();
263
-    }
259
+		espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
+		espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
+		espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
+		new EE_Bootstrap();
263
+	}
264 264
 }
265 265
 if ( ! function_exists('espresso_deactivate_plugin')) {
266
-    /**
267
-     *    deactivate_plugin
268
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
-     *
270
-     * @access public
271
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
-     * @return    void
273
-     */
274
-    function espresso_deactivate_plugin($plugin_basename = '')
275
-    {
276
-        if ( ! function_exists('deactivate_plugins')) {
277
-            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
-        }
279
-        unset($_GET['activate'], $_REQUEST['activate']);
280
-        deactivate_plugins($plugin_basename);
281
-    }
266
+	/**
267
+	 *    deactivate_plugin
268
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
+	 *
270
+	 * @access public
271
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
+	 * @return    void
273
+	 */
274
+	function espresso_deactivate_plugin($plugin_basename = '')
275
+	{
276
+		if ( ! function_exists('deactivate_plugins')) {
277
+			require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
+		}
279
+		unset($_GET['activate'], $_REQUEST['activate']);
280
+		deactivate_plugins($plugin_basename);
281
+	}
282 282
 }
283 283
\ No newline at end of file
Please login to merge, or discard this patch.
core/db_classes/EE_Event.class.php 2 patches
Indentation   +1285 added lines, -1285 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\exceptions\UnexpectedEntityException;
5 5
 
6 6
 if (!defined('EVENT_ESPRESSO_VERSION')) {
7
-    exit('No direct script access allowed');
7
+	exit('No direct script access allowed');
8 8
 }
9 9
 
10 10
 
@@ -18,1289 +18,1289 @@  discard block
 block discarded – undo
18 18
 class EE_Event extends EE_CPT_Base implements EEI_Line_Item_Object, EEI_Admin_Links, EEI_Has_Icon, EEI_Event
19 19
 {
20 20
 
21
-    /**
22
-     * cached value for the the logical active status for the event
23
-     *
24
-     * @see get_active_status()
25
-     * @var string
26
-     */
27
-    protected $_active_status = '';
28
-
29
-    /**
30
-     * This is just used for caching the Primary Datetime for the Event on initial retrieval
31
-     *
32
-     * @var EE_Datetime
33
-     */
34
-    protected $_Primary_Datetime;
35
-
36
-    /**
37
-     * @var EventSpacesCalculator $available_spaces_calculator
38
-     */
39
-    protected $available_spaces_calculator;
40
-
41
-
42
-    /**
43
-     * @param array $props_n_values incoming values
44
-     * @param string $timezone incoming timezone (if not set the timezone set for the website will be
45
-     *                                        used.)
46
-     * @param array $date_formats incoming date_formats in an array where the first value is the
47
-     *                                        date_format and the second value is the time format
48
-     * @return EE_Event
49
-     * @throws EE_Error
50
-     */
51
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
-    {
53
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
54
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
55
-    }
56
-
57
-
58
-    /**
59
-     * @param array $props_n_values incoming values from the database
60
-     * @param string $timezone incoming timezone as set by the model.  If not set the timezone for
61
-     *                                the website will be used.
62
-     * @return EE_Event
63
-     * @throws EE_Error
64
-     */
65
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
66
-    {
67
-        return new self($props_n_values, true, $timezone);
68
-    }
69
-
70
-
71
-
72
-    /**
73
-     * @return EventSpacesCalculator
74
-     * @throws \EE_Error
75
-     */
76
-    public function getAvailableSpacesCalculator()
77
-    {
78
-        if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
79
-            $this->available_spaces_calculator = new EventSpacesCalculator($this);
80
-        }
81
-        return $this->available_spaces_calculator;
82
-    }
83
-
84
-
85
-
86
-    /**
87
-     * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
88
-     *
89
-     * @param string $field_name
90
-     * @param mixed $field_value
91
-     * @param bool $use_default
92
-     * @throws EE_Error
93
-     */
94
-    public function set($field_name, $field_value, $use_default = false)
95
-    {
96
-        switch ($field_name) {
97
-            case 'status' :
98
-                $this->set_status($field_value, $use_default);
99
-                break;
100
-            default :
101
-                parent::set($field_name, $field_value, $use_default);
102
-        }
103
-    }
104
-
105
-
106
-    /**
107
-     *    set_status
108
-     * Checks if event status is being changed to SOLD OUT
109
-     * and updates event meta data with previous event status
110
-     * so that we can revert things if/when the event is no longer sold out
111
-     *
112
-     * @access public
113
-     * @param string $new_status
114
-     * @param bool $use_default
115
-     * @return void
116
-     * @throws EE_Error
117
-     */
118
-    public function set_status($new_status = null, $use_default = false)
119
-    {
120
-        // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
-        if (empty($new_status) && !$use_default) {
122
-            return;
123
-        }
124
-        // get current Event status
125
-        $old_status = $this->status();
126
-        // if status has changed
127
-        if ($old_status !== $new_status) {
128
-            // TO sold_out
129
-            if ($new_status === EEM_Event::sold_out) {
130
-                // save the previous event status so that we can revert if the event is no longer sold out
131
-                $this->add_post_meta('_previous_event_status', $old_status);
132
-                do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $new_status);
133
-                // OR FROM  sold_out
134
-            } else if ($old_status === EEM_Event::sold_out) {
135
-                $this->delete_post_meta('_previous_event_status');
136
-                do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $new_status);
137
-            }
138
-            // update status
139
-            parent::set('status', $new_status, $use_default);
140
-            do_action('AHEE__EE_Event__set_status__after_update', $this);
141
-            return;
142
-        }
143
-        // even though the old value matches the new value, it's still good to
144
-        // allow the parent set method to have a say
145
-        parent::set('status', $new_status, $use_default);
146
-    }
147
-
148
-
149
-    /**
150
-     * Gets all the datetimes for this event
151
-     *
152
-     * @param array $query_params like EEM_Base::get_all
153
-     * @return EE_Base_Class[]|EE_Datetime[]
154
-     * @throws EE_Error
155
-     */
156
-    public function datetimes($query_params = array())
157
-    {
158
-        return $this->get_many_related('Datetime', $query_params);
159
-    }
160
-
161
-
162
-    /**
163
-     * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
164
-     *
165
-     * @return EE_Base_Class[]|EE_Datetime[]
166
-     * @throws EE_Error
167
-     */
168
-    public function datetimes_in_chronological_order()
169
-    {
170
-        return $this->get_many_related('Datetime', array('order_by' => array('DTT_EVT_start' => 'ASC')));
171
-    }
172
-
173
-
174
-    /**
175
-     * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
176
-     * @darren, we should probably UNSET timezone on the EEM_Datetime model
177
-     * after running our query, so that this timezone isn't set for EVERY query
178
-     * on EEM_Datetime for the rest of the request, no?
179
-     *
180
-     * @param boolean $show_expired whether or not to include expired events
181
-     * @param boolean $show_deleted whether or not to include deleted events
182
-     * @param null $limit
183
-     * @return EE_Datetime[]
184
-     * @throws EE_Error
185
-     */
186
-    public function datetimes_ordered($show_expired = true, $show_deleted = false, $limit = null)
187
-    {
188
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
189
-            $this->ID(),
190
-            $show_expired,
191
-            $show_deleted,
192
-            $limit
193
-        );
194
-    }
195
-
196
-
197
-    /**
198
-     * Returns one related datetime. Mostly only used by some legacy code.
199
-     *
200
-     * @return EE_Base_Class|EE_Datetime
201
-     * @throws EE_Error
202
-     */
203
-    public function first_datetime()
204
-    {
205
-        return $this->get_first_related('Datetime');
206
-    }
207
-
208
-
209
-    /**
210
-     * Returns the 'primary' datetime for the event
211
-     *
212
-     * @param bool $try_to_exclude_expired
213
-     * @param bool $try_to_exclude_deleted
214
-     * @return EE_Datetime
215
-     * @throws EE_Error
216
-     */
217
-    public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
218
-    {
219
-        if (!empty ($this->_Primary_Datetime)) {
220
-            return $this->_Primary_Datetime;
221
-        }
222
-        $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
223
-            $this->ID(),
224
-            $try_to_exclude_expired,
225
-            $try_to_exclude_deleted
226
-        );
227
-        return $this->_Primary_Datetime;
228
-    }
229
-
230
-
231
-    /**
232
-     * Gets all the tickets available for purchase of this event
233
-     *
234
-     * @param array $query_params like EEM_Base::get_all
235
-     * @return EE_Base_Class[]|EE_Ticket[]
236
-     * @throws EE_Error
237
-     */
238
-    public function tickets($query_params = array())
239
-    {
240
-        //first get all datetimes
241
-        $datetimes = $this->datetimes_ordered();
242
-        if (!$datetimes) {
243
-            return array();
244
-        }
245
-        $datetime_ids = array();
246
-        foreach ($datetimes as $datetime) {
247
-            $datetime_ids[] = $datetime->ID();
248
-        }
249
-        $where_params = array('Datetime.DTT_ID' => array('IN', $datetime_ids));
250
-        //if incoming $query_params has where conditions let's merge but not override existing.
251
-        if (is_array($query_params) && isset($query_params[0])) {
252
-            $where_params = array_merge($query_params[0], $where_params);
253
-            unset($query_params[0]);
254
-        }
255
-        //now add $where_params to $query_params
256
-        $query_params[0] = $where_params;
257
-        return EEM_Ticket::instance()->get_all($query_params);
258
-    }
259
-
260
-
261
-    /**
262
-     * get all unexpired untrashed tickets
263
-     *
264
-     * @return EE_Ticket[]
265
-     * @throws EE_Error
266
-     */
267
-    public function active_tickets()
268
-    {
269
-        return $this->tickets(array(
270
-            array(
271
-                'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
272
-                'TKT_deleted' => false,
273
-            ),
274
-        ));
275
-    }
276
-
277
-
278
-    /**
279
-     * @return bool
280
-     * @throws EE_Error
281
-     */
282
-    public function additional_limit()
283
-    {
284
-        return $this->get('EVT_additional_limit');
285
-    }
286
-
287
-
288
-    /**
289
-     * @return bool
290
-     * @throws EE_Error
291
-     */
292
-    public function allow_overflow()
293
-    {
294
-        return $this->get('EVT_allow_overflow');
295
-    }
296
-
297
-
298
-    /**
299
-     * @return bool
300
-     * @throws EE_Error
301
-     */
302
-    public function created()
303
-    {
304
-        return $this->get('EVT_created');
305
-    }
306
-
307
-
308
-    /**
309
-     * @return bool
310
-     * @throws EE_Error
311
-     */
312
-    public function description()
313
-    {
314
-        return $this->get('EVT_desc');
315
-    }
316
-
317
-
318
-    /**
319
-     * Runs do_shortcode and wpautop on the description
320
-     *
321
-     * @return string of html
322
-     * @throws EE_Error
323
-     */
324
-    public function description_filtered()
325
-    {
326
-        return $this->get_pretty('EVT_desc');
327
-    }
328
-
329
-
330
-    /**
331
-     * @return bool
332
-     * @throws EE_Error
333
-     */
334
-    public function display_description()
335
-    {
336
-        return $this->get('EVT_display_desc');
337
-    }
338
-
339
-
340
-    /**
341
-     * @return bool
342
-     * @throws EE_Error
343
-     */
344
-    public function display_ticket_selector()
345
-    {
346
-        return (bool)$this->get('EVT_display_ticket_selector');
347
-    }
348
-
349
-
350
-    /**
351
-     * @return bool
352
-     * @throws EE_Error
353
-     */
354
-    public function external_url()
355
-    {
356
-        return $this->get('EVT_external_URL');
357
-    }
358
-
359
-
360
-    /**
361
-     * @return bool
362
-     * @throws EE_Error
363
-     */
364
-    public function member_only()
365
-    {
366
-        return $this->get('EVT_member_only');
367
-    }
368
-
369
-
370
-    /**
371
-     * @return bool
372
-     * @throws EE_Error
373
-     */
374
-    public function phone()
375
-    {
376
-        return $this->get('EVT_phone');
377
-    }
378
-
379
-
380
-    /**
381
-     * @return bool
382
-     * @throws EE_Error
383
-     */
384
-    public function modified()
385
-    {
386
-        return $this->get('EVT_modified');
387
-    }
388
-
389
-
390
-    /**
391
-     * @return bool
392
-     * @throws EE_Error
393
-     */
394
-    public function name()
395
-    {
396
-        return $this->get('EVT_name');
397
-    }
398
-
399
-
400
-    /**
401
-     * @return bool
402
-     * @throws EE_Error
403
-     */
404
-    public function order()
405
-    {
406
-        return $this->get('EVT_order');
407
-    }
408
-
409
-
410
-    /**
411
-     * @return bool|string
412
-     * @throws EE_Error
413
-     */
414
-    public function default_registration_status()
415
-    {
416
-        $event_default_registration_status = $this->get('EVT_default_registration_status');
417
-        return !empty($event_default_registration_status)
418
-            ? $event_default_registration_status
419
-            : EE_Registry::instance()->CFG->registration->default_STS_ID;
420
-    }
421
-
422
-
423
-    /**
424
-     * @param int $num_words
425
-     * @param null $more
426
-     * @param bool $not_full_desc
427
-     * @return bool|string
428
-     * @throws EE_Error
429
-     */
430
-    public function short_description($num_words = 55, $more = null, $not_full_desc = false)
431
-    {
432
-        $short_desc = $this->get('EVT_short_desc');
433
-        if (!empty($short_desc) || $not_full_desc) {
434
-            return $short_desc;
435
-        }
436
-        $full_desc = $this->get('EVT_desc');
437
-        return wp_trim_words($full_desc, $num_words, $more);
438
-    }
439
-
440
-
441
-    /**
442
-     * @return bool
443
-     * @throws EE_Error
444
-     */
445
-    public function slug()
446
-    {
447
-        return $this->get('EVT_slug');
448
-    }
449
-
450
-
451
-    /**
452
-     * @return bool
453
-     * @throws EE_Error
454
-     */
455
-    public function timezone_string()
456
-    {
457
-        return $this->get('EVT_timezone_string');
458
-    }
459
-
460
-
461
-    /**
462
-     * @return bool
463
-     * @throws EE_Error
464
-     */
465
-    public function visible_on()
466
-    {
467
-        return $this->get('EVT_visible_on');
468
-    }
469
-
470
-
471
-    /**
472
-     * @return int
473
-     * @throws EE_Error
474
-     */
475
-    public function wp_user()
476
-    {
477
-        return $this->get('EVT_wp_user');
478
-    }
479
-
480
-
481
-    /**
482
-     * @return bool
483
-     * @throws EE_Error
484
-     */
485
-    public function donations()
486
-    {
487
-        return $this->get('EVT_donations');
488
-    }
489
-
490
-
491
-    /**
492
-     * @param $limit
493
-     * @throws EE_Error
494
-     */
495
-    public function set_additional_limit($limit)
496
-    {
497
-        $this->set('EVT_additional_limit', $limit);
498
-    }
499
-
500
-
501
-    /**
502
-     * @param $created
503
-     * @throws EE_Error
504
-     */
505
-    public function set_created($created)
506
-    {
507
-        $this->set('EVT_created', $created);
508
-    }
509
-
510
-
511
-    /**
512
-     * @param $desc
513
-     * @throws EE_Error
514
-     */
515
-    public function set_description($desc)
516
-    {
517
-        $this->set('EVT_desc', $desc);
518
-    }
519
-
520
-
521
-    /**
522
-     * @param $display_desc
523
-     * @throws EE_Error
524
-     */
525
-    public function set_display_description($display_desc)
526
-    {
527
-        $this->set('EVT_display_desc', $display_desc);
528
-    }
529
-
530
-
531
-    /**
532
-     * @param $display_ticket_selector
533
-     * @throws EE_Error
534
-     */
535
-    public function set_display_ticket_selector($display_ticket_selector)
536
-    {
537
-        $this->set('EVT_display_ticket_selector', $display_ticket_selector);
538
-    }
539
-
540
-
541
-    /**
542
-     * @param $external_url
543
-     * @throws EE_Error
544
-     */
545
-    public function set_external_url($external_url)
546
-    {
547
-        $this->set('EVT_external_URL', $external_url);
548
-    }
549
-
550
-
551
-    /**
552
-     * @param $member_only
553
-     * @throws EE_Error
554
-     */
555
-    public function set_member_only($member_only)
556
-    {
557
-        $this->set('EVT_member_only', $member_only);
558
-    }
559
-
560
-
561
-    /**
562
-     * @param $event_phone
563
-     * @throws EE_Error
564
-     */
565
-    public function set_event_phone($event_phone)
566
-    {
567
-        $this->set('EVT_phone', $event_phone);
568
-    }
569
-
570
-
571
-    /**
572
-     * @param $modified
573
-     * @throws EE_Error
574
-     */
575
-    public function set_modified($modified)
576
-    {
577
-        $this->set('EVT_modified', $modified);
578
-    }
579
-
580
-
581
-    /**
582
-     * @param $name
583
-     * @throws EE_Error
584
-     */
585
-    public function set_name($name)
586
-    {
587
-        $this->set('EVT_name', $name);
588
-    }
589
-
590
-
591
-    /**
592
-     * @param $order
593
-     * @throws EE_Error
594
-     */
595
-    public function set_order($order)
596
-    {
597
-        $this->set('EVT_order', $order);
598
-    }
599
-
600
-
601
-    /**
602
-     * @param $short_desc
603
-     * @throws EE_Error
604
-     */
605
-    public function set_short_description($short_desc)
606
-    {
607
-        $this->set('EVT_short_desc', $short_desc);
608
-    }
609
-
610
-
611
-    /**
612
-     * @param $slug
613
-     * @throws EE_Error
614
-     */
615
-    public function set_slug($slug)
616
-    {
617
-        $this->set('EVT_slug', $slug);
618
-    }
619
-
620
-
621
-    /**
622
-     * @param $timezone_string
623
-     * @throws EE_Error
624
-     */
625
-    public function set_timezone_string($timezone_string)
626
-    {
627
-        $this->set('EVT_timezone_string', $timezone_string);
628
-    }
629
-
630
-
631
-    /**
632
-     * @param $visible_on
633
-     * @throws EE_Error
634
-     */
635
-    public function set_visible_on($visible_on)
636
-    {
637
-        $this->set('EVT_visible_on', $visible_on);
638
-    }
639
-
640
-
641
-    /**
642
-     * @param $wp_user
643
-     * @throws EE_Error
644
-     */
645
-    public function set_wp_user($wp_user)
646
-    {
647
-        $this->set('EVT_wp_user', $wp_user);
648
-    }
649
-
650
-
651
-    /**
652
-     * @param $default_registration_status
653
-     * @throws EE_Error
654
-     */
655
-    public function set_default_registration_status($default_registration_status)
656
-    {
657
-        $this->set('EVT_default_registration_status', $default_registration_status);
658
-    }
659
-
660
-
661
-    /**
662
-     * @param $donations
663
-     * @throws EE_Error
664
-     */
665
-    public function set_donations($donations)
666
-    {
667
-        $this->set('EVT_donations', $donations);
668
-    }
669
-
670
-
671
-    /**
672
-     * Adds a venue to this event
673
-     *
674
-     * @param EE_Venue /int $venue_id_or_obj
675
-     * @return EE_Base_Class|EE_Venue
676
-     * @throws EE_Error
677
-     */
678
-    public function add_venue($venue_id_or_obj)
679
-    {
680
-        return $this->_add_relation_to($venue_id_or_obj, 'Venue');
681
-    }
682
-
683
-
684
-    /**
685
-     * Removes a venue from the event
686
-     *
687
-     * @param EE_Venue /int $venue_id_or_obj
688
-     * @return EE_Base_Class|EE_Venue
689
-     * @throws EE_Error
690
-     */
691
-    public function remove_venue($venue_id_or_obj)
692
-    {
693
-        return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
694
-    }
695
-
696
-
697
-    /**
698
-     * Gets all the venues related ot the event. May provide additional $query_params if desired
699
-     *
700
-     * @param array $query_params like EEM_Base::get_all's $query_params
701
-     * @return EE_Base_Class[]|EE_Venue[]
702
-     * @throws EE_Error
703
-     */
704
-    public function venues($query_params = array())
705
-    {
706
-        return $this->get_many_related('Venue', $query_params);
707
-    }
708
-
709
-
710
-    /**
711
-     * check if event id is present and if event is published
712
-     *
713
-     * @access public
714
-     * @return boolean true yes, false no
715
-     * @throws EE_Error
716
-     */
717
-    private function _has_ID_and_is_published()
718
-    {
719
-        // first check if event id is present and not NULL,
720
-        // then check if this event is published (or any of the equivalent "published" statuses)
721
-        return
722
-            $this->ID() && $this->ID() !== null
723
-            && (
724
-                $this->status() === 'publish'
725
-                || $this->status() === EEM_Event::sold_out
726
-                || $this->status() === EEM_Event::postponed
727
-                || $this->status() === EEM_Event::cancelled
728
-            );
729
-    }
730
-
731
-
732
-    /**
733
-     * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
734
-     *
735
-     * @access public
736
-     * @return boolean true yes, false no
737
-     * @throws EE_Error
738
-     */
739
-    public function is_upcoming()
740
-    {
741
-        // check if event id is present and if this event is published
742
-        if ($this->is_inactive()) {
743
-            return false;
744
-        }
745
-        // set initial value
746
-        $upcoming = false;
747
-        //next let's get all datetimes and loop through them
748
-        $datetimes = $this->datetimes_in_chronological_order();
749
-        foreach ($datetimes as $datetime) {
750
-            if ($datetime instanceof EE_Datetime) {
751
-                //if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
752
-                if ($datetime->is_expired()) {
753
-                    continue;
754
-                }
755
-                //if this dtt is active then we return false.
756
-                if ($datetime->is_active()) {
757
-                    return false;
758
-                }
759
-                //otherwise let's check upcoming status
760
-                $upcoming = $datetime->is_upcoming();
761
-            }
762
-        }
763
-        return $upcoming;
764
-    }
765
-
766
-
767
-    /**
768
-     * @return bool
769
-     * @throws EE_Error
770
-     */
771
-    public function is_active()
772
-    {
773
-        // check if event id is present and if this event is published
774
-        if ($this->is_inactive()) {
775
-            return false;
776
-        }
777
-        // set initial value
778
-        $active = false;
779
-        //next let's get all datetimes and loop through them
780
-        $datetimes = $this->datetimes_in_chronological_order();
781
-        foreach ($datetimes as $datetime) {
782
-            if ($datetime instanceof EE_Datetime) {
783
-                //if this dtt is expired then we continue cause one of the other datetimes might be active.
784
-                if ($datetime->is_expired()) {
785
-                    continue;
786
-                }
787
-                //if this dtt is upcoming then we return false.
788
-                if ($datetime->is_upcoming()) {
789
-                    return false;
790
-                }
791
-                //otherwise let's check active status
792
-                $active = $datetime->is_active();
793
-            }
794
-        }
795
-        return $active;
796
-    }
797
-
798
-
799
-    /**
800
-     * @return bool
801
-     * @throws EE_Error
802
-     */
803
-    public function is_expired()
804
-    {
805
-        // check if event id is present and if this event is published
806
-        if ($this->is_inactive()) {
807
-            return false;
808
-        }
809
-        // set initial value
810
-        $expired = false;
811
-        //first let's get all datetimes and loop through them
812
-        $datetimes = $this->datetimes_in_chronological_order();
813
-        foreach ($datetimes as $datetime) {
814
-            if ($datetime instanceof EE_Datetime) {
815
-                //if this dtt is upcoming or active then we return false.
816
-                if ($datetime->is_upcoming() || $datetime->is_active()) {
817
-                    return false;
818
-                }
819
-                //otherwise let's check active status
820
-                $expired = $datetime->is_expired();
821
-            }
822
-        }
823
-        return $expired;
824
-    }
825
-
826
-
827
-    /**
828
-     * @return bool
829
-     * @throws EE_Error
830
-     */
831
-    public function is_inactive()
832
-    {
833
-        // check if event id is present and if this event is published
834
-        if ($this->_has_ID_and_is_published()) {
835
-            return false;
836
-        }
837
-        return true;
838
-    }
839
-
840
-
841
-    /**
842
-     * calculate spaces remaining based on "saleable" tickets
843
-     *
844
-     * @param array $tickets
845
-     * @param bool $filtered
846
-     * @return int|float
847
-     * @throws EE_Error
848
-     * @throws DomainException
849
-     * @throws UnexpectedEntityException
850
-     */
851
-    public function spaces_remaining($tickets = array(), $filtered = true)
852
-    {
853
-        $this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
854
-        $spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
855
-        return $filtered
856
-            ? apply_filters(
857
-                'FHEE_EE_Event__spaces_remaining',
858
-                $spaces_remaining,
859
-                $this,
860
-                $tickets
861
-            )
862
-            : $spaces_remaining;
863
-    }
864
-
865
-
866
-    /**
867
-     *    perform_sold_out_status_check
868
-     *    checks all of this events's datetime  reg_limit - sold values to determine if ANY datetimes have spaces available...
869
-     *    if NOT, then the event status will get toggled to 'sold_out'
870
-     *
871
-     * @return bool    return the ACTUAL sold out state.
872
-     * @throws EE_Error
873
-     * @throws DomainException
874
-     * @throws UnexpectedEntityException
875
-     */
876
-    public function perform_sold_out_status_check()
877
-    {
878
-        // get all unexpired untrashed tickets
879
-        $tickets = $this->active_tickets();
880
-        // if all the tickets are just expired, then don't update the event status to sold out
881
-        if (empty($tickets)) {
882
-            return true;
883
-        }
884
-        $spaces_remaining = $this->spaces_remaining($tickets);
885
-        if ($spaces_remaining < 1) {
886
-            $this->set_status(EEM_Event::sold_out);
887
-            $this->save();
888
-            $sold_out = true;
889
-        } else {
890
-            $sold_out = false;
891
-            // was event previously marked as sold out ?
892
-            if ($this->status() === EEM_Event::sold_out) {
893
-                // revert status to previous value, if it was set
894
-                $previous_event_status = $this->get_post_meta('_previous_event_status', true);
895
-                if ($previous_event_status) {
896
-                    $this->set_status($previous_event_status);
897
-                    $this->save();
898
-                }
899
-            }
900
-        }
901
-        do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
902
-        return $sold_out;
903
-    }
904
-
905
-
906
-
907
-    /**
908
-     * This returns the total remaining spaces for sale on this event.
909
-     *
910
-     * @uses EE_Event::total_available_spaces()
911
-     * @return float|int
912
-     * @throws EE_Error
913
-     * @throws DomainException
914
-     * @throws UnexpectedEntityException
915
-     */
916
-    public function spaces_remaining_for_sale()
917
-    {
918
-        return $this->total_available_spaces(true);
919
-    }
920
-
921
-
922
-
923
-    /**
924
-     * This returns the total spaces available for an event
925
-     * while considering all the qtys on the tickets and the reg limits
926
-     * on the datetimes attached to this event.
927
-     *
928
-     * @param   bool $consider_sold Whether to consider any tickets that have already sold in our calculation.
929
-     *                              If this is false, then we return the most tickets that could ever be sold
930
-     *                              for this event with the datetime and tickets setup on the event under optimal
931
-     *                              selling conditions.  Otherwise we return a live calculation of spaces available
932
-     *                              based on tickets sold.  Depending on setup and stage of sales, this
933
-     *                              may appear to equal remaining tickets.  However, the more tickets are
934
-     *                              sold out, the more accurate the "live" total is.
935
-     * @return float|int
936
-     * @throws EE_Error
937
-     * @throws DomainException
938
-     * @throws UnexpectedEntityException
939
-     */
940
-    public function total_available_spaces($consider_sold = false)
941
-    {
942
-        $spaces_available = $consider_sold
943
-            ? $this->getAvailableSpacesCalculator()->spacesRemaining()
944
-            : $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
945
-        return apply_filters(
946
-            'FHEE_EE_Event__total_available_spaces__spaces_available',
947
-            $spaces_available,
948
-            $this,
949
-            $this->getAvailableSpacesCalculator()->getDatetimes(),
950
-            $this->getAvailableSpacesCalculator()->getActiveTickets()
951
-        );
952
-    }
953
-
954
-
955
-    /**
956
-     * Checks if the event is set to sold out
957
-     *
958
-     * @param  bool $actual whether or not to perform calculations to not only figure the
959
-     *                      actual status but also to flip the status if necessary to sold
960
-     *                      out If false, we just check the existing status of the event
961
-     * @return boolean
962
-     * @throws EE_Error
963
-     */
964
-    public function is_sold_out($actual = false)
965
-    {
966
-        if (!$actual) {
967
-            return $this->status() === EEM_Event::sold_out;
968
-        }
969
-        return $this->perform_sold_out_status_check();
970
-    }
971
-
972
-
973
-    /**
974
-     * Checks if the event is marked as postponed
975
-     *
976
-     * @return boolean
977
-     */
978
-    public function is_postponed()
979
-    {
980
-        return $this->status() === EEM_Event::postponed;
981
-    }
982
-
983
-
984
-    /**
985
-     * Checks if the event is marked as cancelled
986
-     *
987
-     * @return boolean
988
-     */
989
-    public function is_cancelled()
990
-    {
991
-        return $this->status() === EEM_Event::cancelled;
992
-    }
993
-
994
-
995
-    /**
996
-     * Get the logical active status in a hierarchical order for all the datetimes.  Note
997
-     * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
998
-     * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
999
-     * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1000
-     * the event is considered expired.
1001
-     * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a status
1002
-     * set on the EVENT when it is not published and thus is done
1003
-     *
1004
-     * @param bool $reset
1005
-     * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1006
-     * @throws EE_Error
1007
-     */
1008
-    public function get_active_status($reset = false)
1009
-    {
1010
-        // if the active status has already been set, then just use that value (unless we are resetting it)
1011
-        if (!empty($this->_active_status) && !$reset) {
1012
-            return $this->_active_status;
1013
-        }
1014
-        //first check if event id is present on this object
1015
-        if (!$this->ID()) {
1016
-            return false;
1017
-        }
1018
-        $where_params_for_event = array(array('EVT_ID' => $this->ID()));
1019
-        //if event is published:
1020
-        if ($this->status() === 'publish') {
1021
-            //active?
1022
-            if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::active, $where_params_for_event) > 0) {
1023
-                $this->_active_status = EE_Datetime::active;
1024
-            } else {
1025
-                //upcoming?
1026
-                if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::upcoming, $where_params_for_event) > 0) {
1027
-                    $this->_active_status = EE_Datetime::upcoming;
1028
-                } else {
1029
-                    //expired?
1030
-                    if (
1031
-                        EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::expired, $where_params_for_event) > 0
1032
-                    ) {
1033
-                        $this->_active_status = EE_Datetime::expired;
1034
-                    } else {
1035
-                        //it would be odd if things make it this far because it basically means there are no datetime's
1036
-                        //attached to the event.  So in this case it will just be considered inactive.
1037
-                        $this->_active_status = EE_Datetime::inactive;
1038
-                    }
1039
-                }
1040
-            }
1041
-        } else {
1042
-            //the event is not published, so let's just set it's active status according to its' post status
1043
-            switch ($this->status()) {
1044
-                case EEM_Event::sold_out :
1045
-                    $this->_active_status = EE_Datetime::sold_out;
1046
-                    break;
1047
-                case EEM_Event::cancelled :
1048
-                    $this->_active_status = EE_Datetime::cancelled;
1049
-                    break;
1050
-                case EEM_Event::postponed :
1051
-                    $this->_active_status = EE_Datetime::postponed;
1052
-                    break;
1053
-                default :
1054
-                    $this->_active_status = EE_Datetime::inactive;
1055
-            }
1056
-        }
1057
-        return $this->_active_status;
1058
-    }
1059
-
1060
-
1061
-    /**
1062
-     *    pretty_active_status
1063
-     *
1064
-     * @access public
1065
-     * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1066
-     * @return mixed void|string
1067
-     * @throws EE_Error
1068
-     */
1069
-    public function pretty_active_status($echo = true)
1070
-    {
1071
-        $active_status = $this->get_active_status();
1072
-        $status = '<span class="ee-status event-active-status-'
1073
-            . $active_status
1074
-            . '">'
1075
-            . EEH_Template::pretty_status($active_status, false, 'sentence')
1076
-            . '</span>';
1077
-        if ($echo) {
1078
-            echo $status;
1079
-            return '';
1080
-        }
1081
-        return $status;
1082
-    }
1083
-
1084
-
1085
-    /**
1086
-     * @return bool|int
1087
-     * @throws EE_Error
1088
-     */
1089
-    public function get_number_of_tickets_sold()
1090
-    {
1091
-        $tkt_sold = 0;
1092
-        if (!$this->ID()) {
1093
-            return 0;
1094
-        }
1095
-        $datetimes = $this->datetimes();
1096
-        foreach ($datetimes as $datetime) {
1097
-            if ($datetime instanceof EE_Datetime) {
1098
-                $tkt_sold += $datetime->sold();
1099
-            }
1100
-        }
1101
-        return $tkt_sold;
1102
-    }
1103
-
1104
-
1105
-    /**
1106
-     * This just returns a count of all the registrations for this event
1107
-     *
1108
-     * @access  public
1109
-     * @return int
1110
-     * @throws EE_Error
1111
-     */
1112
-    public function get_count_of_all_registrations()
1113
-    {
1114
-        return EEM_Event::instance()->count_related($this, 'Registration');
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     * This returns the ticket with the earliest start time that is
1120
-     * available for this event (across all datetimes attached to the event)
1121
-     *
1122
-     * @return EE_Base_Class|EE_Ticket|null
1123
-     * @throws EE_Error
1124
-     */
1125
-    public function get_ticket_with_earliest_start_time()
1126
-    {
1127
-        $where['Datetime.EVT_ID'] = $this->ID();
1128
-        $query_params = array($where, 'order_by' => array('TKT_start_date' => 'ASC'));
1129
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1130
-    }
1131
-
1132
-
1133
-    /**
1134
-     * This returns the ticket with the latest end time that is available
1135
-     * for this event (across all datetimes attached to the event)
1136
-     *
1137
-     * @return EE_Base_Class|EE_Ticket|null
1138
-     * @throws EE_Error
1139
-     */
1140
-    public function get_ticket_with_latest_end_time()
1141
-    {
1142
-        $where['Datetime.EVT_ID'] = $this->ID();
1143
-        $query_params = array($where, 'order_by' => array('TKT_end_date' => 'DESC'));
1144
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1145
-    }
1146
-
1147
-
1148
-    /**
1149
-     * This returns whether there are any tickets on sale for this event.
1150
-     *
1151
-     * @return bool true = YES tickets on sale.
1152
-     * @throws EE_Error
1153
-     */
1154
-    public function tickets_on_sale()
1155
-    {
1156
-        $earliest_ticket = $this->get_ticket_with_earliest_start_time();
1157
-        $latest_ticket = $this->get_ticket_with_latest_end_time();
1158
-        if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1159
-            return false;
1160
-        }
1161
-        //check on sale for these two tickets.
1162
-        if ($latest_ticket->is_on_sale() || $earliest_ticket->is_on_sale()) {
1163
-            return true;
1164
-        }
1165
-        return false;
1166
-    }
1167
-
1168
-
1169
-    /**
1170
-     * Gets the URL for viewing this event on the front-end. Overrides parent
1171
-     * to check for an external URL first
1172
-     *
1173
-     * @return string
1174
-     * @throws EE_Error
1175
-     */
1176
-    public function get_permalink()
1177
-    {
1178
-        if ($this->external_url()) {
1179
-            return $this->external_url();
1180
-        }
1181
-        return parent::get_permalink();
1182
-    }
1183
-
1184
-
1185
-    /**
1186
-     * Gets the first term for 'espresso_event_categories' we can find
1187
-     *
1188
-     * @param array $query_params like EEM_Base::get_all
1189
-     * @return EE_Base_Class|EE_Term|null
1190
-     * @throws EE_Error
1191
-     */
1192
-    public function first_event_category($query_params = array())
1193
-    {
1194
-        $query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1195
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1196
-        return EEM_Term::instance()->get_one($query_params);
1197
-    }
1198
-
1199
-
1200
-    /**
1201
-     * Gets all terms for 'espresso_event_categories' we can find
1202
-     *
1203
-     * @param array $query_params
1204
-     * @return EE_Base_Class[]|EE_Term[]
1205
-     * @throws EE_Error
1206
-     */
1207
-    public function get_all_event_categories($query_params = array())
1208
-    {
1209
-        $query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1210
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1211
-        return EEM_Term::instance()->get_all($query_params);
1212
-    }
1213
-
1214
-
1215
-    /**
1216
-     * Gets all the question groups, ordering them by QSG_order ascending
1217
-     *
1218
-     * @param array $query_params @see EEM_Base::get_all
1219
-     * @return EE_Base_Class[]|EE_Question_Group[]
1220
-     * @throws EE_Error
1221
-     */
1222
-    public function question_groups($query_params = array())
1223
-    {
1224
-        $query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1225
-        return $this->get_many_related('Question_Group', $query_params);
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * Implementation for EEI_Has_Icon interface method.
1231
-     *
1232
-     * @see EEI_Visual_Representation for comments
1233
-     * @return string
1234
-     */
1235
-    public function get_icon()
1236
-    {
1237
-        return '<span class="dashicons dashicons-flag"></span>';
1238
-    }
1239
-
1240
-
1241
-    /**
1242
-     * Implementation for EEI_Admin_Links interface method.
1243
-     *
1244
-     * @see EEI_Admin_Links for comments
1245
-     * @return string
1246
-     * @throws EE_Error
1247
-     */
1248
-    public function get_admin_details_link()
1249
-    {
1250
-        return $this->get_admin_edit_link();
1251
-    }
1252
-
1253
-
1254
-    /**
1255
-     * Implementation for EEI_Admin_Links interface method.
1256
-     *
1257
-     * @see EEI_Admin_Links for comments
1258
-     * @return string
1259
-     * @throws EE_Error
1260
-     */
1261
-    public function get_admin_edit_link()
1262
-    {
1263
-        return EEH_URL::add_query_args_and_nonce(array(
1264
-            'page' => 'espresso_events',
1265
-            'action' => 'edit',
1266
-            'post' => $this->ID(),
1267
-        ),
1268
-            admin_url('admin.php')
1269
-        );
1270
-    }
1271
-
1272
-
1273
-    /**
1274
-     * Implementation for EEI_Admin_Links interface method.
1275
-     *
1276
-     * @see EEI_Admin_Links for comments
1277
-     * @return string
1278
-     */
1279
-    public function get_admin_settings_link()
1280
-    {
1281
-        return EEH_URL::add_query_args_and_nonce(array(
1282
-            'page' => 'espresso_events',
1283
-            'action' => 'default_event_settings',
1284
-        ),
1285
-            admin_url('admin.php')
1286
-        );
1287
-    }
1288
-
1289
-
1290
-    /**
1291
-     * Implementation for EEI_Admin_Links interface method.
1292
-     *
1293
-     * @see EEI_Admin_Links for comments
1294
-     * @return string
1295
-     */
1296
-    public function get_admin_overview_link()
1297
-    {
1298
-        return EEH_URL::add_query_args_and_nonce(array(
1299
-            'page' => 'espresso_events',
1300
-            'action' => 'default',
1301
-        ),
1302
-            admin_url('admin.php')
1303
-        );
1304
-    }
21
+	/**
22
+	 * cached value for the the logical active status for the event
23
+	 *
24
+	 * @see get_active_status()
25
+	 * @var string
26
+	 */
27
+	protected $_active_status = '';
28
+
29
+	/**
30
+	 * This is just used for caching the Primary Datetime for the Event on initial retrieval
31
+	 *
32
+	 * @var EE_Datetime
33
+	 */
34
+	protected $_Primary_Datetime;
35
+
36
+	/**
37
+	 * @var EventSpacesCalculator $available_spaces_calculator
38
+	 */
39
+	protected $available_spaces_calculator;
40
+
41
+
42
+	/**
43
+	 * @param array $props_n_values incoming values
44
+	 * @param string $timezone incoming timezone (if not set the timezone set for the website will be
45
+	 *                                        used.)
46
+	 * @param array $date_formats incoming date_formats in an array where the first value is the
47
+	 *                                        date_format and the second value is the time format
48
+	 * @return EE_Event
49
+	 * @throws EE_Error
50
+	 */
51
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
+	{
53
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
54
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
55
+	}
56
+
57
+
58
+	/**
59
+	 * @param array $props_n_values incoming values from the database
60
+	 * @param string $timezone incoming timezone as set by the model.  If not set the timezone for
61
+	 *                                the website will be used.
62
+	 * @return EE_Event
63
+	 * @throws EE_Error
64
+	 */
65
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
66
+	{
67
+		return new self($props_n_values, true, $timezone);
68
+	}
69
+
70
+
71
+
72
+	/**
73
+	 * @return EventSpacesCalculator
74
+	 * @throws \EE_Error
75
+	 */
76
+	public function getAvailableSpacesCalculator()
77
+	{
78
+		if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
79
+			$this->available_spaces_calculator = new EventSpacesCalculator($this);
80
+		}
81
+		return $this->available_spaces_calculator;
82
+	}
83
+
84
+
85
+
86
+	/**
87
+	 * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
88
+	 *
89
+	 * @param string $field_name
90
+	 * @param mixed $field_value
91
+	 * @param bool $use_default
92
+	 * @throws EE_Error
93
+	 */
94
+	public function set($field_name, $field_value, $use_default = false)
95
+	{
96
+		switch ($field_name) {
97
+			case 'status' :
98
+				$this->set_status($field_value, $use_default);
99
+				break;
100
+			default :
101
+				parent::set($field_name, $field_value, $use_default);
102
+		}
103
+	}
104
+
105
+
106
+	/**
107
+	 *    set_status
108
+	 * Checks if event status is being changed to SOLD OUT
109
+	 * and updates event meta data with previous event status
110
+	 * so that we can revert things if/when the event is no longer sold out
111
+	 *
112
+	 * @access public
113
+	 * @param string $new_status
114
+	 * @param bool $use_default
115
+	 * @return void
116
+	 * @throws EE_Error
117
+	 */
118
+	public function set_status($new_status = null, $use_default = false)
119
+	{
120
+		// if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
+		if (empty($new_status) && !$use_default) {
122
+			return;
123
+		}
124
+		// get current Event status
125
+		$old_status = $this->status();
126
+		// if status has changed
127
+		if ($old_status !== $new_status) {
128
+			// TO sold_out
129
+			if ($new_status === EEM_Event::sold_out) {
130
+				// save the previous event status so that we can revert if the event is no longer sold out
131
+				$this->add_post_meta('_previous_event_status', $old_status);
132
+				do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $new_status);
133
+				// OR FROM  sold_out
134
+			} else if ($old_status === EEM_Event::sold_out) {
135
+				$this->delete_post_meta('_previous_event_status');
136
+				do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $new_status);
137
+			}
138
+			// update status
139
+			parent::set('status', $new_status, $use_default);
140
+			do_action('AHEE__EE_Event__set_status__after_update', $this);
141
+			return;
142
+		}
143
+		// even though the old value matches the new value, it's still good to
144
+		// allow the parent set method to have a say
145
+		parent::set('status', $new_status, $use_default);
146
+	}
147
+
148
+
149
+	/**
150
+	 * Gets all the datetimes for this event
151
+	 *
152
+	 * @param array $query_params like EEM_Base::get_all
153
+	 * @return EE_Base_Class[]|EE_Datetime[]
154
+	 * @throws EE_Error
155
+	 */
156
+	public function datetimes($query_params = array())
157
+	{
158
+		return $this->get_many_related('Datetime', $query_params);
159
+	}
160
+
161
+
162
+	/**
163
+	 * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
164
+	 *
165
+	 * @return EE_Base_Class[]|EE_Datetime[]
166
+	 * @throws EE_Error
167
+	 */
168
+	public function datetimes_in_chronological_order()
169
+	{
170
+		return $this->get_many_related('Datetime', array('order_by' => array('DTT_EVT_start' => 'ASC')));
171
+	}
172
+
173
+
174
+	/**
175
+	 * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
176
+	 * @darren, we should probably UNSET timezone on the EEM_Datetime model
177
+	 * after running our query, so that this timezone isn't set for EVERY query
178
+	 * on EEM_Datetime for the rest of the request, no?
179
+	 *
180
+	 * @param boolean $show_expired whether or not to include expired events
181
+	 * @param boolean $show_deleted whether or not to include deleted events
182
+	 * @param null $limit
183
+	 * @return EE_Datetime[]
184
+	 * @throws EE_Error
185
+	 */
186
+	public function datetimes_ordered($show_expired = true, $show_deleted = false, $limit = null)
187
+	{
188
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
189
+			$this->ID(),
190
+			$show_expired,
191
+			$show_deleted,
192
+			$limit
193
+		);
194
+	}
195
+
196
+
197
+	/**
198
+	 * Returns one related datetime. Mostly only used by some legacy code.
199
+	 *
200
+	 * @return EE_Base_Class|EE_Datetime
201
+	 * @throws EE_Error
202
+	 */
203
+	public function first_datetime()
204
+	{
205
+		return $this->get_first_related('Datetime');
206
+	}
207
+
208
+
209
+	/**
210
+	 * Returns the 'primary' datetime for the event
211
+	 *
212
+	 * @param bool $try_to_exclude_expired
213
+	 * @param bool $try_to_exclude_deleted
214
+	 * @return EE_Datetime
215
+	 * @throws EE_Error
216
+	 */
217
+	public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
218
+	{
219
+		if (!empty ($this->_Primary_Datetime)) {
220
+			return $this->_Primary_Datetime;
221
+		}
222
+		$this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
223
+			$this->ID(),
224
+			$try_to_exclude_expired,
225
+			$try_to_exclude_deleted
226
+		);
227
+		return $this->_Primary_Datetime;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Gets all the tickets available for purchase of this event
233
+	 *
234
+	 * @param array $query_params like EEM_Base::get_all
235
+	 * @return EE_Base_Class[]|EE_Ticket[]
236
+	 * @throws EE_Error
237
+	 */
238
+	public function tickets($query_params = array())
239
+	{
240
+		//first get all datetimes
241
+		$datetimes = $this->datetimes_ordered();
242
+		if (!$datetimes) {
243
+			return array();
244
+		}
245
+		$datetime_ids = array();
246
+		foreach ($datetimes as $datetime) {
247
+			$datetime_ids[] = $datetime->ID();
248
+		}
249
+		$where_params = array('Datetime.DTT_ID' => array('IN', $datetime_ids));
250
+		//if incoming $query_params has where conditions let's merge but not override existing.
251
+		if (is_array($query_params) && isset($query_params[0])) {
252
+			$where_params = array_merge($query_params[0], $where_params);
253
+			unset($query_params[0]);
254
+		}
255
+		//now add $where_params to $query_params
256
+		$query_params[0] = $where_params;
257
+		return EEM_Ticket::instance()->get_all($query_params);
258
+	}
259
+
260
+
261
+	/**
262
+	 * get all unexpired untrashed tickets
263
+	 *
264
+	 * @return EE_Ticket[]
265
+	 * @throws EE_Error
266
+	 */
267
+	public function active_tickets()
268
+	{
269
+		return $this->tickets(array(
270
+			array(
271
+				'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
272
+				'TKT_deleted' => false,
273
+			),
274
+		));
275
+	}
276
+
277
+
278
+	/**
279
+	 * @return bool
280
+	 * @throws EE_Error
281
+	 */
282
+	public function additional_limit()
283
+	{
284
+		return $this->get('EVT_additional_limit');
285
+	}
286
+
287
+
288
+	/**
289
+	 * @return bool
290
+	 * @throws EE_Error
291
+	 */
292
+	public function allow_overflow()
293
+	{
294
+		return $this->get('EVT_allow_overflow');
295
+	}
296
+
297
+
298
+	/**
299
+	 * @return bool
300
+	 * @throws EE_Error
301
+	 */
302
+	public function created()
303
+	{
304
+		return $this->get('EVT_created');
305
+	}
306
+
307
+
308
+	/**
309
+	 * @return bool
310
+	 * @throws EE_Error
311
+	 */
312
+	public function description()
313
+	{
314
+		return $this->get('EVT_desc');
315
+	}
316
+
317
+
318
+	/**
319
+	 * Runs do_shortcode and wpautop on the description
320
+	 *
321
+	 * @return string of html
322
+	 * @throws EE_Error
323
+	 */
324
+	public function description_filtered()
325
+	{
326
+		return $this->get_pretty('EVT_desc');
327
+	}
328
+
329
+
330
+	/**
331
+	 * @return bool
332
+	 * @throws EE_Error
333
+	 */
334
+	public function display_description()
335
+	{
336
+		return $this->get('EVT_display_desc');
337
+	}
338
+
339
+
340
+	/**
341
+	 * @return bool
342
+	 * @throws EE_Error
343
+	 */
344
+	public function display_ticket_selector()
345
+	{
346
+		return (bool)$this->get('EVT_display_ticket_selector');
347
+	}
348
+
349
+
350
+	/**
351
+	 * @return bool
352
+	 * @throws EE_Error
353
+	 */
354
+	public function external_url()
355
+	{
356
+		return $this->get('EVT_external_URL');
357
+	}
358
+
359
+
360
+	/**
361
+	 * @return bool
362
+	 * @throws EE_Error
363
+	 */
364
+	public function member_only()
365
+	{
366
+		return $this->get('EVT_member_only');
367
+	}
368
+
369
+
370
+	/**
371
+	 * @return bool
372
+	 * @throws EE_Error
373
+	 */
374
+	public function phone()
375
+	{
376
+		return $this->get('EVT_phone');
377
+	}
378
+
379
+
380
+	/**
381
+	 * @return bool
382
+	 * @throws EE_Error
383
+	 */
384
+	public function modified()
385
+	{
386
+		return $this->get('EVT_modified');
387
+	}
388
+
389
+
390
+	/**
391
+	 * @return bool
392
+	 * @throws EE_Error
393
+	 */
394
+	public function name()
395
+	{
396
+		return $this->get('EVT_name');
397
+	}
398
+
399
+
400
+	/**
401
+	 * @return bool
402
+	 * @throws EE_Error
403
+	 */
404
+	public function order()
405
+	{
406
+		return $this->get('EVT_order');
407
+	}
408
+
409
+
410
+	/**
411
+	 * @return bool|string
412
+	 * @throws EE_Error
413
+	 */
414
+	public function default_registration_status()
415
+	{
416
+		$event_default_registration_status = $this->get('EVT_default_registration_status');
417
+		return !empty($event_default_registration_status)
418
+			? $event_default_registration_status
419
+			: EE_Registry::instance()->CFG->registration->default_STS_ID;
420
+	}
421
+
422
+
423
+	/**
424
+	 * @param int $num_words
425
+	 * @param null $more
426
+	 * @param bool $not_full_desc
427
+	 * @return bool|string
428
+	 * @throws EE_Error
429
+	 */
430
+	public function short_description($num_words = 55, $more = null, $not_full_desc = false)
431
+	{
432
+		$short_desc = $this->get('EVT_short_desc');
433
+		if (!empty($short_desc) || $not_full_desc) {
434
+			return $short_desc;
435
+		}
436
+		$full_desc = $this->get('EVT_desc');
437
+		return wp_trim_words($full_desc, $num_words, $more);
438
+	}
439
+
440
+
441
+	/**
442
+	 * @return bool
443
+	 * @throws EE_Error
444
+	 */
445
+	public function slug()
446
+	{
447
+		return $this->get('EVT_slug');
448
+	}
449
+
450
+
451
+	/**
452
+	 * @return bool
453
+	 * @throws EE_Error
454
+	 */
455
+	public function timezone_string()
456
+	{
457
+		return $this->get('EVT_timezone_string');
458
+	}
459
+
460
+
461
+	/**
462
+	 * @return bool
463
+	 * @throws EE_Error
464
+	 */
465
+	public function visible_on()
466
+	{
467
+		return $this->get('EVT_visible_on');
468
+	}
469
+
470
+
471
+	/**
472
+	 * @return int
473
+	 * @throws EE_Error
474
+	 */
475
+	public function wp_user()
476
+	{
477
+		return $this->get('EVT_wp_user');
478
+	}
479
+
480
+
481
+	/**
482
+	 * @return bool
483
+	 * @throws EE_Error
484
+	 */
485
+	public function donations()
486
+	{
487
+		return $this->get('EVT_donations');
488
+	}
489
+
490
+
491
+	/**
492
+	 * @param $limit
493
+	 * @throws EE_Error
494
+	 */
495
+	public function set_additional_limit($limit)
496
+	{
497
+		$this->set('EVT_additional_limit', $limit);
498
+	}
499
+
500
+
501
+	/**
502
+	 * @param $created
503
+	 * @throws EE_Error
504
+	 */
505
+	public function set_created($created)
506
+	{
507
+		$this->set('EVT_created', $created);
508
+	}
509
+
510
+
511
+	/**
512
+	 * @param $desc
513
+	 * @throws EE_Error
514
+	 */
515
+	public function set_description($desc)
516
+	{
517
+		$this->set('EVT_desc', $desc);
518
+	}
519
+
520
+
521
+	/**
522
+	 * @param $display_desc
523
+	 * @throws EE_Error
524
+	 */
525
+	public function set_display_description($display_desc)
526
+	{
527
+		$this->set('EVT_display_desc', $display_desc);
528
+	}
529
+
530
+
531
+	/**
532
+	 * @param $display_ticket_selector
533
+	 * @throws EE_Error
534
+	 */
535
+	public function set_display_ticket_selector($display_ticket_selector)
536
+	{
537
+		$this->set('EVT_display_ticket_selector', $display_ticket_selector);
538
+	}
539
+
540
+
541
+	/**
542
+	 * @param $external_url
543
+	 * @throws EE_Error
544
+	 */
545
+	public function set_external_url($external_url)
546
+	{
547
+		$this->set('EVT_external_URL', $external_url);
548
+	}
549
+
550
+
551
+	/**
552
+	 * @param $member_only
553
+	 * @throws EE_Error
554
+	 */
555
+	public function set_member_only($member_only)
556
+	{
557
+		$this->set('EVT_member_only', $member_only);
558
+	}
559
+
560
+
561
+	/**
562
+	 * @param $event_phone
563
+	 * @throws EE_Error
564
+	 */
565
+	public function set_event_phone($event_phone)
566
+	{
567
+		$this->set('EVT_phone', $event_phone);
568
+	}
569
+
570
+
571
+	/**
572
+	 * @param $modified
573
+	 * @throws EE_Error
574
+	 */
575
+	public function set_modified($modified)
576
+	{
577
+		$this->set('EVT_modified', $modified);
578
+	}
579
+
580
+
581
+	/**
582
+	 * @param $name
583
+	 * @throws EE_Error
584
+	 */
585
+	public function set_name($name)
586
+	{
587
+		$this->set('EVT_name', $name);
588
+	}
589
+
590
+
591
+	/**
592
+	 * @param $order
593
+	 * @throws EE_Error
594
+	 */
595
+	public function set_order($order)
596
+	{
597
+		$this->set('EVT_order', $order);
598
+	}
599
+
600
+
601
+	/**
602
+	 * @param $short_desc
603
+	 * @throws EE_Error
604
+	 */
605
+	public function set_short_description($short_desc)
606
+	{
607
+		$this->set('EVT_short_desc', $short_desc);
608
+	}
609
+
610
+
611
+	/**
612
+	 * @param $slug
613
+	 * @throws EE_Error
614
+	 */
615
+	public function set_slug($slug)
616
+	{
617
+		$this->set('EVT_slug', $slug);
618
+	}
619
+
620
+
621
+	/**
622
+	 * @param $timezone_string
623
+	 * @throws EE_Error
624
+	 */
625
+	public function set_timezone_string($timezone_string)
626
+	{
627
+		$this->set('EVT_timezone_string', $timezone_string);
628
+	}
629
+
630
+
631
+	/**
632
+	 * @param $visible_on
633
+	 * @throws EE_Error
634
+	 */
635
+	public function set_visible_on($visible_on)
636
+	{
637
+		$this->set('EVT_visible_on', $visible_on);
638
+	}
639
+
640
+
641
+	/**
642
+	 * @param $wp_user
643
+	 * @throws EE_Error
644
+	 */
645
+	public function set_wp_user($wp_user)
646
+	{
647
+		$this->set('EVT_wp_user', $wp_user);
648
+	}
649
+
650
+
651
+	/**
652
+	 * @param $default_registration_status
653
+	 * @throws EE_Error
654
+	 */
655
+	public function set_default_registration_status($default_registration_status)
656
+	{
657
+		$this->set('EVT_default_registration_status', $default_registration_status);
658
+	}
659
+
660
+
661
+	/**
662
+	 * @param $donations
663
+	 * @throws EE_Error
664
+	 */
665
+	public function set_donations($donations)
666
+	{
667
+		$this->set('EVT_donations', $donations);
668
+	}
669
+
670
+
671
+	/**
672
+	 * Adds a venue to this event
673
+	 *
674
+	 * @param EE_Venue /int $venue_id_or_obj
675
+	 * @return EE_Base_Class|EE_Venue
676
+	 * @throws EE_Error
677
+	 */
678
+	public function add_venue($venue_id_or_obj)
679
+	{
680
+		return $this->_add_relation_to($venue_id_or_obj, 'Venue');
681
+	}
682
+
683
+
684
+	/**
685
+	 * Removes a venue from the event
686
+	 *
687
+	 * @param EE_Venue /int $venue_id_or_obj
688
+	 * @return EE_Base_Class|EE_Venue
689
+	 * @throws EE_Error
690
+	 */
691
+	public function remove_venue($venue_id_or_obj)
692
+	{
693
+		return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
694
+	}
695
+
696
+
697
+	/**
698
+	 * Gets all the venues related ot the event. May provide additional $query_params if desired
699
+	 *
700
+	 * @param array $query_params like EEM_Base::get_all's $query_params
701
+	 * @return EE_Base_Class[]|EE_Venue[]
702
+	 * @throws EE_Error
703
+	 */
704
+	public function venues($query_params = array())
705
+	{
706
+		return $this->get_many_related('Venue', $query_params);
707
+	}
708
+
709
+
710
+	/**
711
+	 * check if event id is present and if event is published
712
+	 *
713
+	 * @access public
714
+	 * @return boolean true yes, false no
715
+	 * @throws EE_Error
716
+	 */
717
+	private function _has_ID_and_is_published()
718
+	{
719
+		// first check if event id is present and not NULL,
720
+		// then check if this event is published (or any of the equivalent "published" statuses)
721
+		return
722
+			$this->ID() && $this->ID() !== null
723
+			&& (
724
+				$this->status() === 'publish'
725
+				|| $this->status() === EEM_Event::sold_out
726
+				|| $this->status() === EEM_Event::postponed
727
+				|| $this->status() === EEM_Event::cancelled
728
+			);
729
+	}
730
+
731
+
732
+	/**
733
+	 * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
734
+	 *
735
+	 * @access public
736
+	 * @return boolean true yes, false no
737
+	 * @throws EE_Error
738
+	 */
739
+	public function is_upcoming()
740
+	{
741
+		// check if event id is present and if this event is published
742
+		if ($this->is_inactive()) {
743
+			return false;
744
+		}
745
+		// set initial value
746
+		$upcoming = false;
747
+		//next let's get all datetimes and loop through them
748
+		$datetimes = $this->datetimes_in_chronological_order();
749
+		foreach ($datetimes as $datetime) {
750
+			if ($datetime instanceof EE_Datetime) {
751
+				//if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
752
+				if ($datetime->is_expired()) {
753
+					continue;
754
+				}
755
+				//if this dtt is active then we return false.
756
+				if ($datetime->is_active()) {
757
+					return false;
758
+				}
759
+				//otherwise let's check upcoming status
760
+				$upcoming = $datetime->is_upcoming();
761
+			}
762
+		}
763
+		return $upcoming;
764
+	}
765
+
766
+
767
+	/**
768
+	 * @return bool
769
+	 * @throws EE_Error
770
+	 */
771
+	public function is_active()
772
+	{
773
+		// check if event id is present and if this event is published
774
+		if ($this->is_inactive()) {
775
+			return false;
776
+		}
777
+		// set initial value
778
+		$active = false;
779
+		//next let's get all datetimes and loop through them
780
+		$datetimes = $this->datetimes_in_chronological_order();
781
+		foreach ($datetimes as $datetime) {
782
+			if ($datetime instanceof EE_Datetime) {
783
+				//if this dtt is expired then we continue cause one of the other datetimes might be active.
784
+				if ($datetime->is_expired()) {
785
+					continue;
786
+				}
787
+				//if this dtt is upcoming then we return false.
788
+				if ($datetime->is_upcoming()) {
789
+					return false;
790
+				}
791
+				//otherwise let's check active status
792
+				$active = $datetime->is_active();
793
+			}
794
+		}
795
+		return $active;
796
+	}
797
+
798
+
799
+	/**
800
+	 * @return bool
801
+	 * @throws EE_Error
802
+	 */
803
+	public function is_expired()
804
+	{
805
+		// check if event id is present and if this event is published
806
+		if ($this->is_inactive()) {
807
+			return false;
808
+		}
809
+		// set initial value
810
+		$expired = false;
811
+		//first let's get all datetimes and loop through them
812
+		$datetimes = $this->datetimes_in_chronological_order();
813
+		foreach ($datetimes as $datetime) {
814
+			if ($datetime instanceof EE_Datetime) {
815
+				//if this dtt is upcoming or active then we return false.
816
+				if ($datetime->is_upcoming() || $datetime->is_active()) {
817
+					return false;
818
+				}
819
+				//otherwise let's check active status
820
+				$expired = $datetime->is_expired();
821
+			}
822
+		}
823
+		return $expired;
824
+	}
825
+
826
+
827
+	/**
828
+	 * @return bool
829
+	 * @throws EE_Error
830
+	 */
831
+	public function is_inactive()
832
+	{
833
+		// check if event id is present and if this event is published
834
+		if ($this->_has_ID_and_is_published()) {
835
+			return false;
836
+		}
837
+		return true;
838
+	}
839
+
840
+
841
+	/**
842
+	 * calculate spaces remaining based on "saleable" tickets
843
+	 *
844
+	 * @param array $tickets
845
+	 * @param bool $filtered
846
+	 * @return int|float
847
+	 * @throws EE_Error
848
+	 * @throws DomainException
849
+	 * @throws UnexpectedEntityException
850
+	 */
851
+	public function spaces_remaining($tickets = array(), $filtered = true)
852
+	{
853
+		$this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
854
+		$spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
855
+		return $filtered
856
+			? apply_filters(
857
+				'FHEE_EE_Event__spaces_remaining',
858
+				$spaces_remaining,
859
+				$this,
860
+				$tickets
861
+			)
862
+			: $spaces_remaining;
863
+	}
864
+
865
+
866
+	/**
867
+	 *    perform_sold_out_status_check
868
+	 *    checks all of this events's datetime  reg_limit - sold values to determine if ANY datetimes have spaces available...
869
+	 *    if NOT, then the event status will get toggled to 'sold_out'
870
+	 *
871
+	 * @return bool    return the ACTUAL sold out state.
872
+	 * @throws EE_Error
873
+	 * @throws DomainException
874
+	 * @throws UnexpectedEntityException
875
+	 */
876
+	public function perform_sold_out_status_check()
877
+	{
878
+		// get all unexpired untrashed tickets
879
+		$tickets = $this->active_tickets();
880
+		// if all the tickets are just expired, then don't update the event status to sold out
881
+		if (empty($tickets)) {
882
+			return true;
883
+		}
884
+		$spaces_remaining = $this->spaces_remaining($tickets);
885
+		if ($spaces_remaining < 1) {
886
+			$this->set_status(EEM_Event::sold_out);
887
+			$this->save();
888
+			$sold_out = true;
889
+		} else {
890
+			$sold_out = false;
891
+			// was event previously marked as sold out ?
892
+			if ($this->status() === EEM_Event::sold_out) {
893
+				// revert status to previous value, if it was set
894
+				$previous_event_status = $this->get_post_meta('_previous_event_status', true);
895
+				if ($previous_event_status) {
896
+					$this->set_status($previous_event_status);
897
+					$this->save();
898
+				}
899
+			}
900
+		}
901
+		do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
902
+		return $sold_out;
903
+	}
904
+
905
+
906
+
907
+	/**
908
+	 * This returns the total remaining spaces for sale on this event.
909
+	 *
910
+	 * @uses EE_Event::total_available_spaces()
911
+	 * @return float|int
912
+	 * @throws EE_Error
913
+	 * @throws DomainException
914
+	 * @throws UnexpectedEntityException
915
+	 */
916
+	public function spaces_remaining_for_sale()
917
+	{
918
+		return $this->total_available_spaces(true);
919
+	}
920
+
921
+
922
+
923
+	/**
924
+	 * This returns the total spaces available for an event
925
+	 * while considering all the qtys on the tickets and the reg limits
926
+	 * on the datetimes attached to this event.
927
+	 *
928
+	 * @param   bool $consider_sold Whether to consider any tickets that have already sold in our calculation.
929
+	 *                              If this is false, then we return the most tickets that could ever be sold
930
+	 *                              for this event with the datetime and tickets setup on the event under optimal
931
+	 *                              selling conditions.  Otherwise we return a live calculation of spaces available
932
+	 *                              based on tickets sold.  Depending on setup and stage of sales, this
933
+	 *                              may appear to equal remaining tickets.  However, the more tickets are
934
+	 *                              sold out, the more accurate the "live" total is.
935
+	 * @return float|int
936
+	 * @throws EE_Error
937
+	 * @throws DomainException
938
+	 * @throws UnexpectedEntityException
939
+	 */
940
+	public function total_available_spaces($consider_sold = false)
941
+	{
942
+		$spaces_available = $consider_sold
943
+			? $this->getAvailableSpacesCalculator()->spacesRemaining()
944
+			: $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
945
+		return apply_filters(
946
+			'FHEE_EE_Event__total_available_spaces__spaces_available',
947
+			$spaces_available,
948
+			$this,
949
+			$this->getAvailableSpacesCalculator()->getDatetimes(),
950
+			$this->getAvailableSpacesCalculator()->getActiveTickets()
951
+		);
952
+	}
953
+
954
+
955
+	/**
956
+	 * Checks if the event is set to sold out
957
+	 *
958
+	 * @param  bool $actual whether or not to perform calculations to not only figure the
959
+	 *                      actual status but also to flip the status if necessary to sold
960
+	 *                      out If false, we just check the existing status of the event
961
+	 * @return boolean
962
+	 * @throws EE_Error
963
+	 */
964
+	public function is_sold_out($actual = false)
965
+	{
966
+		if (!$actual) {
967
+			return $this->status() === EEM_Event::sold_out;
968
+		}
969
+		return $this->perform_sold_out_status_check();
970
+	}
971
+
972
+
973
+	/**
974
+	 * Checks if the event is marked as postponed
975
+	 *
976
+	 * @return boolean
977
+	 */
978
+	public function is_postponed()
979
+	{
980
+		return $this->status() === EEM_Event::postponed;
981
+	}
982
+
983
+
984
+	/**
985
+	 * Checks if the event is marked as cancelled
986
+	 *
987
+	 * @return boolean
988
+	 */
989
+	public function is_cancelled()
990
+	{
991
+		return $this->status() === EEM_Event::cancelled;
992
+	}
993
+
994
+
995
+	/**
996
+	 * Get the logical active status in a hierarchical order for all the datetimes.  Note
997
+	 * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
998
+	 * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
999
+	 * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1000
+	 * the event is considered expired.
1001
+	 * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a status
1002
+	 * set on the EVENT when it is not published and thus is done
1003
+	 *
1004
+	 * @param bool $reset
1005
+	 * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1006
+	 * @throws EE_Error
1007
+	 */
1008
+	public function get_active_status($reset = false)
1009
+	{
1010
+		// if the active status has already been set, then just use that value (unless we are resetting it)
1011
+		if (!empty($this->_active_status) && !$reset) {
1012
+			return $this->_active_status;
1013
+		}
1014
+		//first check if event id is present on this object
1015
+		if (!$this->ID()) {
1016
+			return false;
1017
+		}
1018
+		$where_params_for_event = array(array('EVT_ID' => $this->ID()));
1019
+		//if event is published:
1020
+		if ($this->status() === 'publish') {
1021
+			//active?
1022
+			if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::active, $where_params_for_event) > 0) {
1023
+				$this->_active_status = EE_Datetime::active;
1024
+			} else {
1025
+				//upcoming?
1026
+				if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::upcoming, $where_params_for_event) > 0) {
1027
+					$this->_active_status = EE_Datetime::upcoming;
1028
+				} else {
1029
+					//expired?
1030
+					if (
1031
+						EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::expired, $where_params_for_event) > 0
1032
+					) {
1033
+						$this->_active_status = EE_Datetime::expired;
1034
+					} else {
1035
+						//it would be odd if things make it this far because it basically means there are no datetime's
1036
+						//attached to the event.  So in this case it will just be considered inactive.
1037
+						$this->_active_status = EE_Datetime::inactive;
1038
+					}
1039
+				}
1040
+			}
1041
+		} else {
1042
+			//the event is not published, so let's just set it's active status according to its' post status
1043
+			switch ($this->status()) {
1044
+				case EEM_Event::sold_out :
1045
+					$this->_active_status = EE_Datetime::sold_out;
1046
+					break;
1047
+				case EEM_Event::cancelled :
1048
+					$this->_active_status = EE_Datetime::cancelled;
1049
+					break;
1050
+				case EEM_Event::postponed :
1051
+					$this->_active_status = EE_Datetime::postponed;
1052
+					break;
1053
+				default :
1054
+					$this->_active_status = EE_Datetime::inactive;
1055
+			}
1056
+		}
1057
+		return $this->_active_status;
1058
+	}
1059
+
1060
+
1061
+	/**
1062
+	 *    pretty_active_status
1063
+	 *
1064
+	 * @access public
1065
+	 * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1066
+	 * @return mixed void|string
1067
+	 * @throws EE_Error
1068
+	 */
1069
+	public function pretty_active_status($echo = true)
1070
+	{
1071
+		$active_status = $this->get_active_status();
1072
+		$status = '<span class="ee-status event-active-status-'
1073
+			. $active_status
1074
+			. '">'
1075
+			. EEH_Template::pretty_status($active_status, false, 'sentence')
1076
+			. '</span>';
1077
+		if ($echo) {
1078
+			echo $status;
1079
+			return '';
1080
+		}
1081
+		return $status;
1082
+	}
1083
+
1084
+
1085
+	/**
1086
+	 * @return bool|int
1087
+	 * @throws EE_Error
1088
+	 */
1089
+	public function get_number_of_tickets_sold()
1090
+	{
1091
+		$tkt_sold = 0;
1092
+		if (!$this->ID()) {
1093
+			return 0;
1094
+		}
1095
+		$datetimes = $this->datetimes();
1096
+		foreach ($datetimes as $datetime) {
1097
+			if ($datetime instanceof EE_Datetime) {
1098
+				$tkt_sold += $datetime->sold();
1099
+			}
1100
+		}
1101
+		return $tkt_sold;
1102
+	}
1103
+
1104
+
1105
+	/**
1106
+	 * This just returns a count of all the registrations for this event
1107
+	 *
1108
+	 * @access  public
1109
+	 * @return int
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	public function get_count_of_all_registrations()
1113
+	{
1114
+		return EEM_Event::instance()->count_related($this, 'Registration');
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 * This returns the ticket with the earliest start time that is
1120
+	 * available for this event (across all datetimes attached to the event)
1121
+	 *
1122
+	 * @return EE_Base_Class|EE_Ticket|null
1123
+	 * @throws EE_Error
1124
+	 */
1125
+	public function get_ticket_with_earliest_start_time()
1126
+	{
1127
+		$where['Datetime.EVT_ID'] = $this->ID();
1128
+		$query_params = array($where, 'order_by' => array('TKT_start_date' => 'ASC'));
1129
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1130
+	}
1131
+
1132
+
1133
+	/**
1134
+	 * This returns the ticket with the latest end time that is available
1135
+	 * for this event (across all datetimes attached to the event)
1136
+	 *
1137
+	 * @return EE_Base_Class|EE_Ticket|null
1138
+	 * @throws EE_Error
1139
+	 */
1140
+	public function get_ticket_with_latest_end_time()
1141
+	{
1142
+		$where['Datetime.EVT_ID'] = $this->ID();
1143
+		$query_params = array($where, 'order_by' => array('TKT_end_date' => 'DESC'));
1144
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1145
+	}
1146
+
1147
+
1148
+	/**
1149
+	 * This returns whether there are any tickets on sale for this event.
1150
+	 *
1151
+	 * @return bool true = YES tickets on sale.
1152
+	 * @throws EE_Error
1153
+	 */
1154
+	public function tickets_on_sale()
1155
+	{
1156
+		$earliest_ticket = $this->get_ticket_with_earliest_start_time();
1157
+		$latest_ticket = $this->get_ticket_with_latest_end_time();
1158
+		if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1159
+			return false;
1160
+		}
1161
+		//check on sale for these two tickets.
1162
+		if ($latest_ticket->is_on_sale() || $earliest_ticket->is_on_sale()) {
1163
+			return true;
1164
+		}
1165
+		return false;
1166
+	}
1167
+
1168
+
1169
+	/**
1170
+	 * Gets the URL for viewing this event on the front-end. Overrides parent
1171
+	 * to check for an external URL first
1172
+	 *
1173
+	 * @return string
1174
+	 * @throws EE_Error
1175
+	 */
1176
+	public function get_permalink()
1177
+	{
1178
+		if ($this->external_url()) {
1179
+			return $this->external_url();
1180
+		}
1181
+		return parent::get_permalink();
1182
+	}
1183
+
1184
+
1185
+	/**
1186
+	 * Gets the first term for 'espresso_event_categories' we can find
1187
+	 *
1188
+	 * @param array $query_params like EEM_Base::get_all
1189
+	 * @return EE_Base_Class|EE_Term|null
1190
+	 * @throws EE_Error
1191
+	 */
1192
+	public function first_event_category($query_params = array())
1193
+	{
1194
+		$query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1195
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1196
+		return EEM_Term::instance()->get_one($query_params);
1197
+	}
1198
+
1199
+
1200
+	/**
1201
+	 * Gets all terms for 'espresso_event_categories' we can find
1202
+	 *
1203
+	 * @param array $query_params
1204
+	 * @return EE_Base_Class[]|EE_Term[]
1205
+	 * @throws EE_Error
1206
+	 */
1207
+	public function get_all_event_categories($query_params = array())
1208
+	{
1209
+		$query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1210
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1211
+		return EEM_Term::instance()->get_all($query_params);
1212
+	}
1213
+
1214
+
1215
+	/**
1216
+	 * Gets all the question groups, ordering them by QSG_order ascending
1217
+	 *
1218
+	 * @param array $query_params @see EEM_Base::get_all
1219
+	 * @return EE_Base_Class[]|EE_Question_Group[]
1220
+	 * @throws EE_Error
1221
+	 */
1222
+	public function question_groups($query_params = array())
1223
+	{
1224
+		$query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1225
+		return $this->get_many_related('Question_Group', $query_params);
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * Implementation for EEI_Has_Icon interface method.
1231
+	 *
1232
+	 * @see EEI_Visual_Representation for comments
1233
+	 * @return string
1234
+	 */
1235
+	public function get_icon()
1236
+	{
1237
+		return '<span class="dashicons dashicons-flag"></span>';
1238
+	}
1239
+
1240
+
1241
+	/**
1242
+	 * Implementation for EEI_Admin_Links interface method.
1243
+	 *
1244
+	 * @see EEI_Admin_Links for comments
1245
+	 * @return string
1246
+	 * @throws EE_Error
1247
+	 */
1248
+	public function get_admin_details_link()
1249
+	{
1250
+		return $this->get_admin_edit_link();
1251
+	}
1252
+
1253
+
1254
+	/**
1255
+	 * Implementation for EEI_Admin_Links interface method.
1256
+	 *
1257
+	 * @see EEI_Admin_Links for comments
1258
+	 * @return string
1259
+	 * @throws EE_Error
1260
+	 */
1261
+	public function get_admin_edit_link()
1262
+	{
1263
+		return EEH_URL::add_query_args_and_nonce(array(
1264
+			'page' => 'espresso_events',
1265
+			'action' => 'edit',
1266
+			'post' => $this->ID(),
1267
+		),
1268
+			admin_url('admin.php')
1269
+		);
1270
+	}
1271
+
1272
+
1273
+	/**
1274
+	 * Implementation for EEI_Admin_Links interface method.
1275
+	 *
1276
+	 * @see EEI_Admin_Links for comments
1277
+	 * @return string
1278
+	 */
1279
+	public function get_admin_settings_link()
1280
+	{
1281
+		return EEH_URL::add_query_args_and_nonce(array(
1282
+			'page' => 'espresso_events',
1283
+			'action' => 'default_event_settings',
1284
+		),
1285
+			admin_url('admin.php')
1286
+		);
1287
+	}
1288
+
1289
+
1290
+	/**
1291
+	 * Implementation for EEI_Admin_Links interface method.
1292
+	 *
1293
+	 * @see EEI_Admin_Links for comments
1294
+	 * @return string
1295
+	 */
1296
+	public function get_admin_overview_link()
1297
+	{
1298
+		return EEH_URL::add_query_args_and_nonce(array(
1299
+			'page' => 'espresso_events',
1300
+			'action' => 'default',
1301
+		),
1302
+			admin_url('admin.php')
1303
+		);
1304
+	}
1305 1305
 
1306 1306
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
 use EventEspresso\core\domain\services\event\EventSpacesCalculator;
4 4
 use EventEspresso\core\exceptions\UnexpectedEntityException;
5 5
 
6
-if (!defined('EVENT_ESPRESSO_VERSION')) {
6
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
7 7
     exit('No direct script access allowed');
8 8
 }
9 9
 
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
      */
76 76
     public function getAvailableSpacesCalculator()
77 77
     {
78
-        if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
78
+        if ( ! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
79 79
             $this->available_spaces_calculator = new EventSpacesCalculator($this);
80 80
         }
81 81
         return $this->available_spaces_calculator;
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
     public function set_status($new_status = null, $use_default = false)
119 119
     {
120 120
         // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
-        if (empty($new_status) && !$use_default) {
121
+        if (empty($new_status) && ! $use_default) {
122 122
             return;
123 123
         }
124 124
         // get current Event status
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
      */
217 217
     public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
218 218
     {
219
-        if (!empty ($this->_Primary_Datetime)) {
219
+        if ( ! empty ($this->_Primary_Datetime)) {
220 220
             return $this->_Primary_Datetime;
221 221
         }
222 222
         $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
     {
240 240
         //first get all datetimes
241 241
         $datetimes = $this->datetimes_ordered();
242
-        if (!$datetimes) {
242
+        if ( ! $datetimes) {
243 243
             return array();
244 244
         }
245 245
         $datetime_ids = array();
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
      */
344 344
     public function display_ticket_selector()
345 345
     {
346
-        return (bool)$this->get('EVT_display_ticket_selector');
346
+        return (bool) $this->get('EVT_display_ticket_selector');
347 347
     }
348 348
 
349 349
 
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
     public function default_registration_status()
415 415
     {
416 416
         $event_default_registration_status = $this->get('EVT_default_registration_status');
417
-        return !empty($event_default_registration_status)
417
+        return ! empty($event_default_registration_status)
418 418
             ? $event_default_registration_status
419 419
             : EE_Registry::instance()->CFG->registration->default_STS_ID;
420 420
     }
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
     public function short_description($num_words = 55, $more = null, $not_full_desc = false)
431 431
     {
432 432
         $short_desc = $this->get('EVT_short_desc');
433
-        if (!empty($short_desc) || $not_full_desc) {
433
+        if ( ! empty($short_desc) || $not_full_desc) {
434 434
             return $short_desc;
435 435
         }
436 436
         $full_desc = $this->get('EVT_desc');
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
      */
964 964
     public function is_sold_out($actual = false)
965 965
     {
966
-        if (!$actual) {
966
+        if ( ! $actual) {
967 967
             return $this->status() === EEM_Event::sold_out;
968 968
         }
969 969
         return $this->perform_sold_out_status_check();
@@ -1008,11 +1008,11 @@  discard block
 block discarded – undo
1008 1008
     public function get_active_status($reset = false)
1009 1009
     {
1010 1010
         // if the active status has already been set, then just use that value (unless we are resetting it)
1011
-        if (!empty($this->_active_status) && !$reset) {
1011
+        if ( ! empty($this->_active_status) && ! $reset) {
1012 1012
             return $this->_active_status;
1013 1013
         }
1014 1014
         //first check if event id is present on this object
1015
-        if (!$this->ID()) {
1015
+        if ( ! $this->ID()) {
1016 1016
             return false;
1017 1017
         }
1018 1018
         $where_params_for_event = array(array('EVT_ID' => $this->ID()));
@@ -1089,7 +1089,7 @@  discard block
 block discarded – undo
1089 1089
     public function get_number_of_tickets_sold()
1090 1090
     {
1091 1091
         $tkt_sold = 0;
1092
-        if (!$this->ID()) {
1092
+        if ( ! $this->ID()) {
1093 1093
             return 0;
1094 1094
         }
1095 1095
         $datetimes = $this->datetimes();
@@ -1155,7 +1155,7 @@  discard block
 block discarded – undo
1155 1155
     {
1156 1156
         $earliest_ticket = $this->get_ticket_with_earliest_start_time();
1157 1157
         $latest_ticket = $this->get_ticket_with_latest_end_time();
1158
-        if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1158
+        if ( ! $latest_ticket instanceof EE_Ticket && ! $earliest_ticket instanceof EE_Ticket) {
1159 1159
             return false;
1160 1160
         }
1161 1161
         //check on sale for these two tickets.
@@ -1221,7 +1221,7 @@  discard block
 block discarded – undo
1221 1221
      */
1222 1222
     public function question_groups($query_params = array())
1223 1223
     {
1224
-        $query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1224
+        $query_params = ! empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1225 1225
         return $this->get_many_related('Question_Group', $query_params);
1226 1226
     }
1227 1227
 
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 1 patch
Indentation   +5823 added lines, -5823 removed lines patch added patch discarded remove patch
@@ -28,5831 +28,5831 @@
 block discarded – undo
28 28
 abstract class EEM_Base extends EE_Base implements EventEspresso\core\interfaces\ResettableInterface
29 29
 {
30 30
 
31
-    //admin posty
32
-    //basic -> grants access to mine -> if they don't have it, select none
33
-    //*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
-    //*_published -> grants access to published -> if they dont have it, select non-published
36
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
38
-    //frontend posty
39
-    //by default has access to published
40
-    //basic -> grants access to mine that aren't published, and all published
41
-    //*_others ->grants access to others that aren't private, all mine
42
-    //*_private -> grants full access
43
-    //frontend non-posty
44
-    //like admin posty
45
-    //category-y
46
-    //assign -> grants access to join-table
47
-    //(delete, edit)
48
-    //payment-method-y
49
-    //for each registered payment method,
50
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
-    /**
52
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
-     * They almost always WILL NOT, but it's not necessarily a requirement.
55
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
-     *
57
-     * @var boolean
58
-     */
59
-    private $_values_already_prepared_by_model_object = 0;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the data is just like form input that needs to have the model fields'
64
-     * prepare_for_set and prepare_for_use_in_db called on it
65
-     */
66
-    const not_prepared_by_model_object = 0;
67
-
68
-    /**
69
-     * when $_values_already_prepared_by_model_object equals this, we
70
-     * assume this value is coming from a model object and doesn't need to have
71
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
72
-     */
73
-    const prepared_by_model_object = 1;
74
-
75
-    /**
76
-     * when $_values_already_prepared_by_model_object equals this, we assume
77
-     * the values are already to be used in the database (ie no processing is done
78
-     * on them by the model's fields)
79
-     */
80
-    const prepared_for_use_in_db = 2;
81
-
82
-
83
-    protected $singular_item = 'Item';
84
-
85
-    protected $plural_item   = 'Items';
86
-
87
-    /**
88
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
-     */
90
-    protected $_tables;
91
-
92
-    /**
93
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
-     *
97
-     * @var \EE_Model_Field_Base[] $_fields
98
-     */
99
-    protected $_fields;
100
-
101
-    /**
102
-     * array of different kinds of relations
103
-     *
104
-     * @var \EE_Model_Relation_Base[] $_model_relations
105
-     */
106
-    protected $_model_relations;
107
-
108
-    /**
109
-     * @var \EE_Index[] $_indexes
110
-     */
111
-    protected $_indexes = array();
112
-
113
-    /**
114
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
115
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
-     * by setting the same columns as used in these queries in the query yourself.
117
-     *
118
-     * @var EE_Default_Where_Conditions
119
-     */
120
-    protected $_default_where_conditions_strategy;
121
-
122
-    /**
123
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
-     * This is particularly useful when you want something between 'none' and 'default'
125
-     *
126
-     * @var EE_Default_Where_Conditions
127
-     */
128
-    protected $_minimum_where_conditions_strategy;
129
-
130
-    /**
131
-     * String describing how to find the "owner" of this model's objects.
132
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
-     * But when there isn't, this indicates which related model, or transiently-related model,
134
-     * has the foreign key to the wp_users table.
135
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
-     * related to events, and events have a foreign key to wp_users.
137
-     * On EEM_Transaction, this would be 'Transaction.Event'
138
-     *
139
-     * @var string
140
-     */
141
-    protected $_model_chain_to_wp_user = '';
142
-
143
-    /**
144
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
-     * don't need it (particularly CPT models)
146
-     *
147
-     * @var bool
148
-     */
149
-    protected $_ignore_where_strategy = false;
150
-
151
-    /**
152
-     * String used in caps relating to this model. Eg, if the caps relating to this
153
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
-     *
155
-     * @var string. If null it hasn't been initialized yet. If false then we
156
-     * have indicated capabilities don't apply to this
157
-     */
158
-    protected $_caps_slug = null;
159
-
160
-    /**
161
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
-     * and next-level keys are capability names, and each's value is a
163
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
-     * they specify which context to use (ie, frontend, backend, edit or delete)
165
-     * and then each capability in the corresponding sub-array that they're missing
166
-     * adds the where conditions onto the query.
167
-     *
168
-     * @var array
169
-     */
170
-    protected $_cap_restrictions = array(
171
-        self::caps_read       => array(),
172
-        self::caps_read_admin => array(),
173
-        self::caps_edit       => array(),
174
-        self::caps_delete     => array(),
175
-    );
176
-
177
-    /**
178
-     * Array defining which cap restriction generators to use to create default
179
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
180
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
-     * automatically set this to false (not just null).
183
-     *
184
-     * @var EE_Restriction_Generator_Base[]
185
-     */
186
-    protected $_cap_restriction_generators = array();
187
-
188
-    /**
189
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
-     */
191
-    const caps_read       = 'read';
192
-
193
-    const caps_read_admin = 'read_admin';
194
-
195
-    const caps_edit       = 'edit';
196
-
197
-    const caps_delete     = 'delete';
198
-
199
-    /**
200
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
-     * maps to 'read' because when looking for relevant permissions we're going to use
203
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
204
-     *
205
-     * @var array
206
-     */
207
-    protected $_cap_contexts_to_cap_action_map = array(
208
-        self::caps_read       => 'read',
209
-        self::caps_read_admin => 'read',
210
-        self::caps_edit       => 'edit',
211
-        self::caps_delete     => 'delete',
212
-    );
213
-
214
-    /**
215
-     * Timezone
216
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
-     * EE_Datetime_Field data type will have access to it.
220
-     *
221
-     * @var string
222
-     */
223
-    protected $_timezone;
224
-
225
-
226
-    /**
227
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
-     * multisite.
229
-     *
230
-     * @var int
231
-     */
232
-    protected static $_model_query_blog_id;
233
-
234
-    /**
235
-     * A copy of _fields, except the array keys are the model names pointed to by
236
-     * the field
237
-     *
238
-     * @var EE_Model_Field_Base[]
239
-     */
240
-    private $_cache_foreign_key_to_fields = array();
241
-
242
-    /**
243
-     * Cached list of all the fields on the model, indexed by their name
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cached_fields = null;
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, except those that are
251
-     * marked as only pertinent to the database
252
-     *
253
-     * @var EE_Model_Field_Base[]
254
-     */
255
-    private $_cached_fields_non_db_only = null;
256
-
257
-    /**
258
-     * A cached reference to the primary key for quick lookup
259
-     *
260
-     * @var EE_Model_Field_Base
261
-     */
262
-    private $_primary_key_field = null;
263
-
264
-    /**
265
-     * Flag indicating whether this model has a primary key or not
266
-     *
267
-     * @var boolean
268
-     */
269
-    protected $_has_primary_key_field = null;
270
-
271
-    /**
272
-     * Whether or not this model is based off a table in WP core only (CPTs should set
273
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
-     *
275
-     * @var boolean
276
-     */
277
-    protected $_wp_core_model = false;
278
-
279
-    /**
280
-     *    List of valid operators that can be used for querying.
281
-     * The keys are all operators we'll accept, the values are the real SQL
282
-     * operators used
283
-     *
284
-     * @var array
285
-     */
286
-    protected $_valid_operators = array(
287
-        '='           => '=',
288
-        '<='          => '<=',
289
-        '<'           => '<',
290
-        '>='          => '>=',
291
-        '>'           => '>',
292
-        '!='          => '!=',
293
-        'LIKE'        => 'LIKE',
294
-        'like'        => 'LIKE',
295
-        'NOT_LIKE'    => 'NOT LIKE',
296
-        'not_like'    => 'NOT LIKE',
297
-        'NOT LIKE'    => 'NOT LIKE',
298
-        'not like'    => 'NOT LIKE',
299
-        'IN'          => 'IN',
300
-        'in'          => 'IN',
301
-        'NOT_IN'      => 'NOT IN',
302
-        'not_in'      => 'NOT IN',
303
-        'NOT IN'      => 'NOT IN',
304
-        'not in'      => 'NOT IN',
305
-        'between'     => 'BETWEEN',
306
-        'BETWEEN'     => 'BETWEEN',
307
-        'IS_NOT_NULL' => 'IS NOT NULL',
308
-        'is_not_null' => 'IS NOT NULL',
309
-        'IS NOT NULL' => 'IS NOT NULL',
310
-        'is not null' => 'IS NOT NULL',
311
-        'IS_NULL'     => 'IS NULL',
312
-        'is_null'     => 'IS NULL',
313
-        'IS NULL'     => 'IS NULL',
314
-        'is null'     => 'IS NULL',
315
-        'REGEXP'      => 'REGEXP',
316
-        'regexp'      => 'REGEXP',
317
-        'NOT_REGEXP'  => 'NOT REGEXP',
318
-        'not_regexp'  => 'NOT REGEXP',
319
-        'NOT REGEXP'  => 'NOT REGEXP',
320
-        'not regexp'  => 'NOT REGEXP',
321
-    );
322
-
323
-    /**
324
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
-     *
326
-     * @var array
327
-     */
328
-    protected $_in_style_operators = array('IN', 'NOT IN');
329
-
330
-    /**
331
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
-     * '12-31-2012'"
333
-     *
334
-     * @var array
335
-     */
336
-    protected $_between_style_operators = array('BETWEEN');
337
-
338
-    /**
339
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
-     * on a join table.
341
-     *
342
-     * @var array
343
-     */
344
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
-
346
-    /**
347
-     * Allowed values for $query_params['order'] for ordering in queries
348
-     *
349
-     * @var array
350
-     */
351
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
-
353
-    /**
354
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
356
-     *
357
-     * @var array
358
-     */
359
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
-
361
-    /**
362
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
364
-     *
365
-     * @var array
366
-     */
367
-    private $_allowed_query_params = array(
368
-        0,
369
-        'limit',
370
-        'order_by',
371
-        'group_by',
372
-        'having',
373
-        'force_join',
374
-        'order',
375
-        'on_join_limit',
376
-        'default_where_conditions',
377
-        'caps',
378
-    );
379
-
380
-    /**
381
-     * All the data types that can be used in $wpdb->prepare statements.
382
-     *
383
-     * @var array
384
-     */
385
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
-
387
-    /**
388
-     *    EE_Registry Object
389
-     *
390
-     * @var    object
391
-     * @access    protected
392
-     */
393
-    protected $EE = null;
394
-
395
-
396
-    /**
397
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
-     *
399
-     * @var int
400
-     */
401
-    protected $_show_next_x_db_queries = 0;
402
-
403
-    /**
404
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
-     *
407
-     * @var array
408
-     */
409
-    protected $_custom_selections = array();
410
-
411
-    /**
412
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
-     * caches every model object we've fetched from the DB on this request
414
-     *
415
-     * @var array
416
-     */
417
-    protected $_entity_map;
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws \EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
520
-                sprintf(
521
-                    __('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.',
522
-                        'event_espresso'),
523
-                    get_class($this)
524
-                )
525
-            );
526
-        }
527
-        /**
528
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
-         */
530
-        if (empty(EEM_Base::$_model_query_blog_id)) {
531
-            EEM_Base::set_model_query_blog_id();
532
-        }
533
-        /**
534
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
-         * just use EE_Register_Model_Extension
536
-         *
537
-         * @var EE_Table_Base[] $_tables
538
-         */
539
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
-        foreach ($this->_tables as $table_alias => $table_obj) {
541
-            /** @var $table_obj EE_Table_Base */
542
-            $table_obj->_construct_finalize_with_alias($table_alias);
543
-            if ($table_obj instanceof EE_Secondary_Table) {
544
-                /** @var $table_obj EE_Secondary_Table */
545
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
-            }
547
-        }
548
-        /**
549
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
-         * EE_Register_Model_Extension
551
-         *
552
-         * @param EE_Model_Field_Base[] $_fields
553
-         */
554
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
-        $this->_invalidate_field_caches();
556
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
-            }
561
-            foreach ($fields_for_table as $field_name => $field_obj) {
562
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
-                //primary key field base has a slightly different _construct_finalize
564
-                /** @var $field_obj EE_Model_Field_Base */
565
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
-            }
567
-        }
568
-        // everything is related to Extra_Meta
569
-        if (get_class($this) !== 'EEM_Extra_Meta') {
570
-            //make extra meta related to everything, but don't block deleting things just
571
-            //because they have related extra meta info. For now just orphan those extra meta
572
-            //in the future we should automatically delete them
573
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        //and change logs
576
-        if (get_class($this) !== 'EEM_Change_Log') {
577
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        /**
580
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
-         * EE_Register_Model_Extension
582
-         *
583
-         * @param EE_Model_Relation_Base[] $_model_relations
584
-         */
585
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
-            $this->_model_relations);
587
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
588
-            /** @var $relation_obj EE_Model_Relation_Base */
589
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
-        }
591
-        foreach ($this->_indexes as $index_name => $index_obj) {
592
-            /** @var $index_obj EE_Index */
593
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
-        }
595
-        $this->set_timezone($timezone);
596
-        //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
603
-            //nothing was set during child constructor, so set default
604
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
-        }
606
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
608
-        //to indicate to NOT set it, set it to the logical default
609
-        if ($this->_caps_slug === null) {
610
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
-        }
612
-        //initialize the standard cap restriction generators if none were specified by the child constructor
613
-        if ($this->_cap_restriction_generators !== false) {
614
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
617
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
-                        new EE_Restriction_Generator_Protected(),
619
-                        $cap_context,
620
-                        $this
621
-                    );
622
-                }
623
-            }
624
-        }
625
-        //if there are cap restriction generators, use them to make the default cap restrictions
626
-        if ($this->_cap_restriction_generators !== false) {
627
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
629
-                    continue;
630
-                }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
-                    throw new EE_Error(
633
-                        sprintf(
634
-                            __('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.',
635
-                                'event_espresso'),
636
-                            $context,
637
-                            $this->get_this_model_name()
638
-                        )
639
-                    );
640
-                }
641
-                $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
643
-                    $generator_object->_construct_finalize($this, $action);
644
-                }
645
-            }
646
-        }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
-    }
649
-
650
-
651
-
652
-    /**
653
-     * Generates the cap restrictions for the given context, or if they were
654
-     * already generated just gets what's cached
655
-     *
656
-     * @param string $context one of EEM_Base::valid_cap_contexts()
657
-     * @return EE_Default_Where_Conditions[]
658
-     */
659
-    protected function _generate_cap_restrictions($context)
660
-    {
661
-        if (isset($this->_cap_restriction_generators[$context])
662
-            && $this->_cap_restriction_generators[$context]
663
-               instanceof
664
-               EE_Restriction_Generator_Base
665
-        ) {
666
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
-        } else {
668
-            return array();
669
-        }
670
-    }
671
-
672
-
673
-
674
-    /**
675
-     * Used to set the $_model_query_blog_id static property.
676
-     *
677
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
-     *                      value for get_current_blog_id() will be used.
679
-     */
680
-    public static function set_model_query_blog_id($blog_id = 0)
681
-    {
682
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
-    }
684
-
685
-
686
-
687
-    /**
688
-     * Returns whatever is set as the internal $model_query_blog_id.
689
-     *
690
-     * @return int
691
-     */
692
-    public static function get_model_query_blog_id()
693
-    {
694
-        return EEM_Base::$_model_query_blog_id;
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     *        This function is a singleton method used to instantiate the Espresso_model object
701
-     *
702
-     * @access public
703
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
-     *                         timezone in the 'timezone_string' wp option)
707
-     * @return static (as in the concrete child class)
708
-     */
709
-    public static function instance($timezone = null)
710
-    {
711
-        // check if instance of Espresso_model already exists
712
-        if (! static::$_instance instanceof static) {
713
-            // instantiate Espresso_model
714
-            static::$_instance = new static($timezone);
715
-        }
716
-        //we might have a timezone set, let set_timezone decide what to do with it
717
-        static::$_instance->set_timezone($timezone);
718
-        // Espresso_model object
719
-        return static::$_instance;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * resets the model and returns it
726
-     *
727
-     * @param null | string $timezone
728
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
-     * all its properties reset; if it wasn't instantiated, returns null)
730
-     */
731
-    public static function reset($timezone = null)
732
-    {
733
-        if (static::$_instance instanceof EEM_Base) {
734
-            //let's try to NOT swap out the current instance for a new one
735
-            //because if someone has a reference to it, we can't remove their reference
736
-            //so it's best to keep using the same reference, but change the original object
737
-            //reset all its properties to their original values as defined in the class
738
-            $r = new ReflectionClass(get_class(static::$_instance));
739
-            $static_properties = $r->getStaticProperties();
740
-            foreach ($r->getDefaultProperties() as $property => $value) {
741
-                //don't set instance to null like it was originally,
742
-                //but it's static anyways, and we're ignoring static properties (for now at least)
743
-                if (! isset($static_properties[$property])) {
744
-                    static::$_instance->{$property} = $value;
745
-                }
746
-            }
747
-            //and then directly call its constructor again, like we would if we
748
-            //were creating a new one
749
-            static::$_instance->__construct($timezone);
750
-            return self::instance();
751
-        }
752
-        return null;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
-     *
760
-     * @param  boolean $translated return localized strings or JUST the array.
761
-     * @return array
762
-     * @throws \EE_Error
763
-     */
764
-    public function status_array($translated = false)
765
-    {
766
-        if (! array_key_exists('Status', $this->_model_relations)) {
767
-            return array();
768
-        }
769
-        $model_name = $this->get_this_model_name();
770
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
-        $status_array = array();
773
-        foreach ($stati as $status) {
774
-            $status_array[$status->ID()] = $status->get('STS_code');
775
-        }
776
-        return $translated
777
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
-            : $status_array;
779
-    }
780
-
781
-
782
-
783
-    /**
784
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
-     *
786
-     * @param array $query_params             {
787
-     * @var array $0 (where) array {
788
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
-     *                                        conditions based on related models (and even
792
-     *                                        models-related-to-related-models) prepend the model's name onto the field
793
-     *                                        name. Eg,
794
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
-     *                                        to Venues (even when each of those models actually consisted of two
802
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
803
-     *                                        just having
804
-     *                                        "Venue.VNU_ID", you could have
805
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
-     *                                        events are related to Registrations, which are related to Attendees). You
807
-     *                                        can take it even further with
808
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
-     *                                        (from the default of '='), change the value to an numerically-indexed
810
-     *                                        array, where the first item in the list is the operator. eg: array(
811
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
819
-     *                                        the value is a field, simply provide a third array item (true) to the
820
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
-     *                                        Note: you can also use related model field names like you would any other
823
-     *                                        field name. eg:
824
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
-     *                                        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__>' =>
826
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
833
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
-     *                                        "stick" until you specify an AND. eg
835
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
-     *                                        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 >>
840
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
-     *                                        too, eg:
843
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
848
-     *                                        the OFFSET, the 2nd is the LIMIT
849
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
-     *                                        following format array('on_join_limit'
852
-     *                                        => array( 'table_alias', array(1,2) ) ).
853
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
-     *                                        values are either 'ASC' or 'DESC'.
855
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
-     *                                        DESC..." respectively. Like the
858
-     *                                        'where' conditions, these fields can be on related models. Eg
859
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
861
-     *                                        Attendee, Price, Datetime, etc.)
862
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
864
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
-     *                                        order by the primary key. Eg,
867
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
-     *                                        //(will join with the Datetime model's table(s) and order by its field
869
-     *                                        DTT_EVT_start) or
870
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
-     *                                        'group_by'=>'VNU_ID', or
874
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
-     *                                        if no
876
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
877
-     *                                        model's primary key (or combined primary keys). This avoids some
878
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
879
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
-     *                                        results)
883
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
-     *                                        array where values are models to be joined in the query.Eg
885
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
887
-     *                                        probably only want to do this in hopes of increasing efficiency, as
888
-     *                                        related models which belongs to the current model
889
-     *                                        (ie, the current model has a foreign key to them, like how Registration
890
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
891
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
894
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
-     *                                        default where conditions set it to 'other_models_only'. If you only want
896
-     *                                        this model's default where conditions added to the query, use
897
-     *                                        'this_model_only'. If you want to use all default where conditions
898
-     *                                        (default), set to 'all'.
899
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
-     *                                        everything? Or should we only show the current user items they should be
902
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
-     *                                        }
905
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
-     *                                        array( array(
911
-     *                                        'OR'=>array(
912
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
-     *                                        )
915
-     *                                        ),
916
-     *                                        'limit'=>10,
917
-     *                                        'group_by'=>'TXN_ID'
918
-     *                                        ));
919
-     *                                        get all the answers to the question titled "shirt size" for event with id
920
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
-     *                                        'Question.QST_display_text'=>'shirt size',
922
-     *                                        'Registration.Event.EVT_ID'=>12
923
-     *                                        ),
924
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
925
-     *                                        ));
926
-     * @throws \EE_Error
927
-     */
928
-    public function get_all($query_params = array())
929
-    {
930
-        if (isset($query_params['limit'])
931
-            && ! isset($query_params['group_by'])
932
-        ) {
933
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
-        }
935
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
-    }
937
-
938
-
939
-
940
-    /**
941
-     * Modifies the query parameters so we only get back model objects
942
-     * that "belong" to the current user
943
-     *
944
-     * @param array $query_params @see EEM_Base::get_all()
945
-     * @return array like EEM_Base::get_all
946
-     */
947
-    public function alter_query_params_to_only_include_mine($query_params = array())
948
-    {
949
-        $wp_user_field_name = $this->wp_user_field_name();
950
-        if ($wp_user_field_name) {
951
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
952
-        }
953
-        return $query_params;
954
-    }
955
-
956
-
957
-
958
-    /**
959
-     * Returns the name of the field's name that points to the WP_User table
960
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
-     * foreign key to the WP_User table)
962
-     *
963
-     * @return string|boolean string on success, boolean false when there is no
964
-     * foreign key to the WP_User table
965
-     */
966
-    public function wp_user_field_name()
967
-    {
968
-        try {
969
-            if (! empty($this->_model_chain_to_wp_user)) {
970
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
-                $last_model_name = end($models_to_follow_to_wp_users);
972
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
-            } else {
975
-                $model_with_fk_to_wp_users = $this;
976
-                $model_chain_to_wp_user = '';
977
-            }
978
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
980
-        } catch (EE_Error $e) {
981
-            return false;
982
-        }
983
-    }
984
-
985
-
986
-
987
-    /**
988
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
989
-     * (or transiently-related model) has a foreign key to the wp_users table;
990
-     * useful for finding if model objects of this type are 'owned' by the current user.
991
-     * This is an empty string when the foreign key is on this model and when it isn't,
992
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
993
-     * (or transiently-related model)
994
-     *
995
-     * @return string
996
-     */
997
-    public function model_chain_to_wp_user()
998
-    {
999
-        return $this->_model_chain_to_wp_user;
1000
-    }
1001
-
1002
-
1003
-
1004
-    /**
1005
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
-     * like how registrations don't have a foreign key to wp_users, but the
1007
-     * events they are for are), or is unrelated to wp users.
1008
-     * generally available
1009
-     *
1010
-     * @return boolean
1011
-     */
1012
-    public function is_owned()
1013
-    {
1014
-        if ($this->model_chain_to_wp_user()) {
1015
-            return true;
1016
-        } else {
1017
-            try {
1018
-                $this->get_foreign_key_to('WP_User');
1019
-                return true;
1020
-            } catch (EE_Error $e) {
1021
-                return false;
1022
-            }
1023
-        }
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
-     * the model)
1032
-     *
1033
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1037
-     *                                  override this and set the select to "*", or a specific column name, like
1038
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
-     *                                  the aliases used to refer to this selection, and values are to be
1041
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
-     * @throws \EE_Error
1045
-     */
1046
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
-    {
1048
-        // remember the custom selections, if any, and type cast as array
1049
-        // (unless $columns_to_select is an object, then just set as an empty array)
1050
-        // Note: (array) 'some string' === array( 'some string' )
1051
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
-        $select_expressions = $columns_to_select !== null
1054
-            ? $this->_construct_select_from_input($columns_to_select)
1055
-            : $this->_construct_default_select_sql($model_query_info);
1056
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
-    }
1059
-
1060
-
1061
-
1062
-    /**
1063
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1064
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
-     * take care of joins, field preparation etc.
1066
-     *
1067
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1071
-     *                                  override this and set the select to "*", or a specific column name, like
1072
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
-     *                                  the aliases used to refer to this selection, and values are to be
1075
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
-     * @throws \EE_Error
1079
-     */
1080
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
-    {
1082
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
-    }
1084
-
1085
-
1086
-
1087
-    /**
1088
-     * For creating a custom select statement
1089
-     *
1090
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
-     *                                 SQL, and 1=>is the datatype
1093
-     * @throws EE_Error
1094
-     * @return string
1095
-     */
1096
-    private function _construct_select_from_input($columns_to_select)
1097
-    {
1098
-        if (is_array($columns_to_select)) {
1099
-            $select_sql_array = array();
1100
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
-                    throw new EE_Error(
1103
-                        sprintf(
1104
-                            __(
1105
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
-                                "event_espresso"
1107
-                            ),
1108
-                            $selection_and_datatype,
1109
-                            $alias
1110
-                        )
1111
-                    );
1112
-                }
1113
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
-                    throw new EE_Error(
1115
-                        sprintf(
1116
-                            __(
1117
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
-                                "event_espresso"
1119
-                            ),
1120
-                            $selection_and_datatype[1],
1121
-                            $selection_and_datatype[0],
1122
-                            $alias,
1123
-                            implode(",", $this->_valid_wpdb_data_types)
1124
-                        )
1125
-                    );
1126
-                }
1127
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
-            }
1129
-            $columns_to_select_string = implode(", ", $select_sql_array);
1130
-        } else {
1131
-            $columns_to_select_string = $columns_to_select;
1132
-        }
1133
-        return $columns_to_select_string;
1134
-    }
1135
-
1136
-
1137
-
1138
-    /**
1139
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
-     *
1141
-     * @return string
1142
-     * @throws \EE_Error
1143
-     */
1144
-    public function primary_key_name()
1145
-    {
1146
-        return $this->get_primary_key_field()->get_name();
1147
-    }
1148
-
1149
-
1150
-
1151
-    /**
1152
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
-     * If there is no primary key on this model, $id is treated as primary key string
1154
-     *
1155
-     * @param mixed $id int or string, depending on the type of the model's primary key
1156
-     * @return EE_Base_Class
1157
-     */
1158
-    public function get_one_by_ID($id)
1159
-    {
1160
-        if ($this->get_from_entity_map($id)) {
1161
-            return $this->get_from_entity_map($id);
1162
-        }
1163
-        return $this->get_one(
1164
-            $this->alter_query_params_to_restrict_by_ID(
1165
-                $id,
1166
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
-            )
1168
-        );
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Alters query parameters to only get items with this ID are returned.
1175
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
-     * or could just be a simple primary key ID
1177
-     *
1178
-     * @param int   $id
1179
-     * @param array $query_params
1180
-     * @return array of normal query params, @see EEM_Base::get_all
1181
-     * @throws \EE_Error
1182
-     */
1183
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
-    {
1185
-        if (! isset($query_params[0])) {
1186
-            $query_params[0] = array();
1187
-        }
1188
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1189
-        if ($conditions_from_id === null) {
1190
-            $query_params[0][$this->primary_key_name()] = $id;
1191
-        } else {
1192
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1193
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
-        }
1195
-        return $query_params;
1196
-    }
1197
-
1198
-
1199
-
1200
-    /**
1201
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
-     * array. If no item is found, null is returned.
1203
-     *
1204
-     * @param array $query_params like EEM_Base's $query_params variable.
1205
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
-     * @throws \EE_Error
1207
-     */
1208
-    public function get_one($query_params = array())
1209
-    {
1210
-        if (! is_array($query_params)) {
1211
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
-                    gettype($query_params)), '4.6.0');
1214
-            $query_params = array();
1215
-        }
1216
-        $query_params['limit'] = 1;
1217
-        $items = $this->get_all($query_params);
1218
-        if (empty($items)) {
1219
-            return null;
1220
-        } else {
1221
-            return array_shift($items);
1222
-        }
1223
-    }
1224
-
1225
-
1226
-
1227
-    /**
1228
-     * Returns the next x number of items in sequence from the given value as
1229
-     * found in the database matching the given query conditions.
1230
-     *
1231
-     * @param mixed $current_field_value    Value used for the reference point.
1232
-     * @param null  $field_to_order_by      What field is used for the
1233
-     *                                      reference point.
1234
-     * @param int   $limit                  How many to return.
1235
-     * @param array $query_params           Extra conditions on the query.
1236
-     * @param null  $columns_to_select      If left null, then an array of
1237
-     *                                      EE_Base_Class objects is returned,
1238
-     *                                      otherwise you can indicate just the
1239
-     *                                      columns you want returned.
1240
-     * @return EE_Base_Class[]|array
1241
-     * @throws \EE_Error
1242
-     */
1243
-    public function next_x(
1244
-        $current_field_value,
1245
-        $field_to_order_by = null,
1246
-        $limit = 1,
1247
-        $query_params = array(),
1248
-        $columns_to_select = null
1249
-    ) {
1250
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
-            $columns_to_select);
1252
-    }
1253
-
1254
-
1255
-
1256
-    /**
1257
-     * Returns the previous x number of items in sequence from the given value
1258
-     * as found in the database matching the given query conditions.
1259
-     *
1260
-     * @param mixed $current_field_value    Value used for the reference point.
1261
-     * @param null  $field_to_order_by      What field is used for the
1262
-     *                                      reference point.
1263
-     * @param int   $limit                  How many to return.
1264
-     * @param array $query_params           Extra conditions on the query.
1265
-     * @param null  $columns_to_select      If left null, then an array of
1266
-     *                                      EE_Base_Class objects is returned,
1267
-     *                                      otherwise you can indicate just the
1268
-     *                                      columns you want returned.
1269
-     * @return EE_Base_Class[]|array
1270
-     * @throws \EE_Error
1271
-     */
1272
-    public function previous_x(
1273
-        $current_field_value,
1274
-        $field_to_order_by = null,
1275
-        $limit = 1,
1276
-        $query_params = array(),
1277
-        $columns_to_select = null
1278
-    ) {
1279
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
-            $columns_to_select);
1281
-    }
1282
-
1283
-
1284
-
1285
-    /**
1286
-     * Returns the next item in sequence from the given value as found in the
1287
-     * database matching the given query conditions.
1288
-     *
1289
-     * @param mixed $current_field_value    Value used for the reference point.
1290
-     * @param null  $field_to_order_by      What field is used for the
1291
-     *                                      reference point.
1292
-     * @param array $query_params           Extra conditions on the query.
1293
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
-     *                                      object is returned, otherwise you
1295
-     *                                      can indicate just the columns you
1296
-     *                                      want and a single array indexed by
1297
-     *                                      the columns will be returned.
1298
-     * @return EE_Base_Class|null|array()
1299
-     * @throws \EE_Error
1300
-     */
1301
-    public function next(
1302
-        $current_field_value,
1303
-        $field_to_order_by = null,
1304
-        $query_params = array(),
1305
-        $columns_to_select = null
1306
-    ) {
1307
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
-            $columns_to_select);
1309
-        return empty($results) ? null : reset($results);
1310
-    }
1311
-
1312
-
1313
-
1314
-    /**
1315
-     * Returns the previous item in sequence from the given value as found in
1316
-     * the database matching the given query conditions.
1317
-     *
1318
-     * @param mixed $current_field_value    Value used for the reference point.
1319
-     * @param null  $field_to_order_by      What field is used for the
1320
-     *                                      reference point.
1321
-     * @param array $query_params           Extra conditions on the query.
1322
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
-     *                                      object is returned, otherwise you
1324
-     *                                      can indicate just the columns you
1325
-     *                                      want and a single array indexed by
1326
-     *                                      the columns will be returned.
1327
-     * @return EE_Base_Class|null|array()
1328
-     * @throws EE_Error
1329
-     */
1330
-    public function previous(
1331
-        $current_field_value,
1332
-        $field_to_order_by = null,
1333
-        $query_params = array(),
1334
-        $columns_to_select = null
1335
-    ) {
1336
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
-            $columns_to_select);
1338
-        return empty($results) ? null : reset($results);
1339
-    }
1340
-
1341
-
1342
-
1343
-    /**
1344
-     * Returns the a consecutive number of items in sequence from the given
1345
-     * value as found in the database matching the given query conditions.
1346
-     *
1347
-     * @param mixed  $current_field_value   Value used for the reference point.
1348
-     * @param string $operand               What operand is used for the sequence.
1349
-     * @param string $field_to_order_by     What field is used for the reference point.
1350
-     * @param int    $limit                 How many to return.
1351
-     * @param array  $query_params          Extra conditions on the query.
1352
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
-     *                                      otherwise you can indicate just the columns you want returned.
1354
-     * @return EE_Base_Class[]|array
1355
-     * @throws EE_Error
1356
-     */
1357
-    protected function _get_consecutive(
1358
-        $current_field_value,
1359
-        $operand = '>',
1360
-        $field_to_order_by = null,
1361
-        $limit = 1,
1362
-        $query_params = array(),
1363
-        $columns_to_select = null
1364
-    ) {
1365
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
-        if (empty($field_to_order_by)) {
1367
-            if ($this->has_primary_key_field()) {
1368
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1369
-            } else {
1370
-                if (WP_DEBUG) {
1371
-                    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).',
1372
-                        'event_espresso'));
1373
-                }
1374
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
-                return array();
1376
-            }
1377
-        }
1378
-        if (! is_array($query_params)) {
1379
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
-                    gettype($query_params)), '4.6.0');
1382
-            $query_params = array();
1383
-        }
1384
-        //let's add the where query param for consecutive look up.
1385
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
-        $query_params['limit'] = $limit;
1387
-        //set direction
1388
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
-        $query_params['order_by'] = $operand === '>'
1390
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
-        if (empty($columns_to_select)) {
1394
-            return $this->get_all($query_params);
1395
-        } else {
1396
-            //getting just the fields
1397
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
-        }
1399
-    }
1400
-
1401
-
1402
-
1403
-    /**
1404
-     * This sets the _timezone property after model object has been instantiated.
1405
-     *
1406
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
-     */
1408
-    public function set_timezone($timezone)
1409
-    {
1410
-        if ($timezone !== null) {
1411
-            $this->_timezone = $timezone;
1412
-        }
1413
-        //note we need to loop through relations and set the timezone on those objects as well.
1414
-        foreach ($this->_model_relations as $relation) {
1415
-            $relation->set_timezone($timezone);
1416
-        }
1417
-        //and finally we do the same for any datetime fields
1418
-        foreach ($this->_fields as $field) {
1419
-            if ($field instanceof EE_Datetime_Field) {
1420
-                $field->set_timezone($timezone);
1421
-            }
1422
-        }
1423
-    }
1424
-
1425
-
1426
-
1427
-    /**
1428
-     * This just returns whatever is set for the current timezone.
1429
-     *
1430
-     * @access public
1431
-     * @return string
1432
-     */
1433
-    public function get_timezone()
1434
-    {
1435
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
-        if (empty($this->_timezone)) {
1437
-            foreach ($this->_fields as $field) {
1438
-                if ($field instanceof EE_Datetime_Field) {
1439
-                    $this->set_timezone($field->get_timezone());
1440
-                    break;
1441
-                }
1442
-            }
1443
-        }
1444
-        //if timezone STILL empty then return the default timezone for the site.
1445
-        if (empty($this->_timezone)) {
1446
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
-        }
1448
-        return $this->_timezone;
1449
-    }
1450
-
1451
-
1452
-
1453
-    /**
1454
-     * This returns the date formats set for the given field name and also ensures that
1455
-     * $this->_timezone property is set correctly.
1456
-     *
1457
-     * @since 4.6.x
1458
-     * @param string $field_name The name of the field the formats are being retrieved for.
1459
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
-     * @return array formats in an array with the date format first, and the time format last.
1462
-     */
1463
-    public function get_formats_for($field_name, $pretty = false)
1464
-    {
1465
-        $field_settings = $this->field_settings_for($field_name);
1466
-        //if not a valid EE_Datetime_Field then throw error
1467
-        if (! $field_settings instanceof EE_Datetime_Field) {
1468
-            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.',
1469
-                'event_espresso'), $field_name));
1470
-        }
1471
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
-        //the field.
1473
-        $this->_timezone = $field_settings->get_timezone();
1474
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
-    }
1476
-
1477
-
1478
-
1479
-    /**
1480
-     * This returns the current time in a format setup for a query on this model.
1481
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
-     * it will return:
1483
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
-     *  NOW
1485
-     *  - or a unix timestamp (equivalent to time())
1486
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1487
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1488
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1489
-     * @since 4.6.x
1490
-     * @param string $field_name       The field the current time is needed for.
1491
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1492
-     *                                 formatted string matching the set format for the field in the set timezone will
1493
-     *                                 be returned.
1494
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1495
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1496
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497
-     *                                 exception is triggered.
1498
-     */
1499
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1500
-    {
1501
-        $formats = $this->get_formats_for($field_name);
1502
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1503
-        if ($timestamp) {
1504
-            return $DateTime->format('U');
1505
-        }
1506
-        //not returning timestamp, so return formatted string in timezone.
1507
-        switch ($what) {
1508
-            case 'time' :
1509
-                return $DateTime->format($formats[1]);
1510
-                break;
1511
-            case 'date' :
1512
-                return $DateTime->format($formats[0]);
1513
-                break;
1514
-            default :
1515
-                return $DateTime->format(implode(' ', $formats));
1516
-                break;
1517
-        }
1518
-    }
1519
-
1520
-
1521
-
1522
-    /**
1523
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1524
-     * for the model are.  Returns a DateTime object.
1525
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1526
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1527
-     * ignored.
1528
-     *
1529
-     * @param string $field_name      The field being setup.
1530
-     * @param string $timestring      The date time string being used.
1531
-     * @param string $incoming_format The format for the time string.
1532
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1533
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1534
-     *                                format is
1535
-     *                                'U', this is ignored.
1536
-     * @return DateTime
1537
-     * @throws \EE_Error
1538
-     */
1539
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1540
-    {
1541
-        //just using this to ensure the timezone is set correctly internally
1542
-        $this->get_formats_for($field_name);
1543
-        //load EEH_DTT_Helper
1544
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1545
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1546
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1547
-    }
1548
-
1549
-
1550
-
1551
-    /**
1552
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1553
-     *
1554
-     * @return EE_Table_Base[]
1555
-     */
1556
-    public function get_tables()
1557
-    {
1558
-        return $this->_tables;
1559
-    }
1560
-
1561
-
1562
-
1563
-    /**
1564
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1565
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1566
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1567
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1568
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1569
-     * model object with EVT_ID = 1
1570
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1571
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1572
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1573
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1574
-     * are not specified)
1575
-     *
1576
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1577
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1578
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1579
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1580
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1581
-     *                                         ID=34, we'd use this method as follows:
1582
-     *                                         EEM_Transaction::instance()->update(
1583
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1584
-     *                                         array(array('TXN_ID'=>34)));
1585
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1586
-     *                                         in client code into what's expected to be stored on each field. Eg,
1587
-     *                                         consider updating Question's QST_admin_label field is of type
1588
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1589
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1590
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1591
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1592
-     *                                         TRUE, it is assumed that you've already called
1593
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1594
-     *                                         malicious javascript. However, if
1595
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1596
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1597
-     *                                         and every other field, before insertion. We provide this parameter
1598
-     *                                         because model objects perform their prepare_for_set function on all
1599
-     *                                         their values, and so don't need to be called again (and in many cases,
1600
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1601
-     *                                         prepare_for_set method...)
1602
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1603
-     *                                         in this model's entity map according to $fields_n_values that match
1604
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1605
-     *                                         by setting this to FALSE, but be aware that model objects being used
1606
-     *                                         could get out-of-sync with the database
1607
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1608
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1609
-     *                                         bad)
1610
-     * @throws \EE_Error
1611
-     */
1612
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1613
-    {
1614
-        if (! is_array($query_params)) {
1615
-            EE_Error::doing_it_wrong('EEM_Base::update',
1616
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1617
-                    gettype($query_params)), '4.6.0');
1618
-            $query_params = array();
1619
-        }
1620
-        /**
1621
-         * Action called before a model update call has been made.
1622
-         *
1623
-         * @param EEM_Base $model
1624
-         * @param array    $fields_n_values the updated fields and their new values
1625
-         * @param array    $query_params    @see EEM_Base::get_all()
1626
-         */
1627
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1628
-        /**
1629
-         * Filters the fields about to be updated given the query parameters. You can provide the
1630
-         * $query_params to $this->get_all() to find exactly which records will be updated
1631
-         *
1632
-         * @param array    $fields_n_values fields and their new values
1633
-         * @param EEM_Base $model           the model being queried
1634
-         * @param array    $query_params    see EEM_Base::get_all()
1635
-         */
1636
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1637
-            $query_params);
1638
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1639
-        //to do that, for each table, verify that it's PK isn't null.
1640
-        $tables = $this->get_tables();
1641
-        //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
1642
-        //NOTE: we should make this code more efficient by NOT querying twice
1643
-        //before the real update, but that needs to first go through ALPHA testing
1644
-        //as it's dangerous. says Mike August 8 2014
1645
-        //we want to make sure the default_where strategy is ignored
1646
-        $this->_ignore_where_strategy = true;
1647
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1648
-        foreach ($wpdb_select_results as $wpdb_result) {
1649
-            // type cast stdClass as array
1650
-            $wpdb_result = (array)$wpdb_result;
1651
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1652
-            if ($this->has_primary_key_field()) {
1653
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1654
-            } else {
1655
-                //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)
1656
-                $main_table_pk_value = null;
1657
-            }
1658
-            //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
1659
-            //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
1660
-            if (count($tables) > 1) {
1661
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1662
-                //in that table, and so we'll want to insert one
1663
-                foreach ($tables as $table_obj) {
1664
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1665
-                    //if there is no private key for this table on the results, it means there's no entry
1666
-                    //in this table, right? so insert a row in the current table, using any fields available
1667
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1668
-                           && $wpdb_result[$this_table_pk_column])
1669
-                    ) {
1670
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1671
-                            $main_table_pk_value);
1672
-                        //if we died here, report the error
1673
-                        if (! $success) {
1674
-                            return false;
1675
-                        }
1676
-                    }
1677
-                }
1678
-            }
1679
-            //				//and now check that if we have cached any models by that ID on the model, that
1680
-            //				//they also get updated properly
1681
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1682
-            //				if( $model_object ){
1683
-            //					foreach( $fields_n_values as $field => $value ){
1684
-            //						$model_object->set($field, $value);
1685
-            //let's make sure default_where strategy is followed now
1686
-            $this->_ignore_where_strategy = false;
1687
-        }
1688
-        //if we want to keep model objects in sync, AND
1689
-        //if this wasn't called from a model object (to update itself)
1690
-        //then we want to make sure we keep all the existing
1691
-        //model objects in sync with the db
1692
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1693
-            if ($this->has_primary_key_field()) {
1694
-                $model_objs_affected_ids = $this->get_col($query_params);
1695
-            } else {
1696
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1697
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1698
-                $model_objs_affected_ids = array();
1699
-                foreach ($models_affected_key_columns as $row) {
1700
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1701
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1702
-                }
1703
-            }
1704
-            if (! $model_objs_affected_ids) {
1705
-                //wait wait wait- if nothing was affected let's stop here
1706
-                return 0;
1707
-            }
1708
-            foreach ($model_objs_affected_ids as $id) {
1709
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1710
-                if ($model_obj_in_entity_map) {
1711
-                    foreach ($fields_n_values as $field => $new_value) {
1712
-                        $model_obj_in_entity_map->set($field, $new_value);
1713
-                    }
1714
-                }
1715
-            }
1716
-            //if there is a primary key on this model, we can now do a slight optimization
1717
-            if ($this->has_primary_key_field()) {
1718
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1719
-                $query_params = array(
1720
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1721
-                    'limit'                    => count($model_objs_affected_ids),
1722
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1723
-                );
1724
-            }
1725
-        }
1726
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1727
-        $SQL = "UPDATE "
1728
-               . $model_query_info->get_full_join_sql()
1729
-               . " SET "
1730
-               . $this->_construct_update_sql($fields_n_values)
1731
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1732
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1733
-        /**
1734
-         * Action called after a model update call has been made.
1735
-         *
1736
-         * @param EEM_Base $model
1737
-         * @param array    $fields_n_values the updated fields and their new values
1738
-         * @param array    $query_params    @see EEM_Base::get_all()
1739
-         * @param int      $rows_affected
1740
-         */
1741
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1742
-        return $rows_affected;//how many supposedly got updated
1743
-    }
1744
-
1745
-
1746
-
1747
-    /**
1748
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1749
-     * are teh values of the field specified (or by default the primary key field)
1750
-     * that matched the query params. Note that you should pass the name of the
1751
-     * model FIELD, not the database table's column name.
1752
-     *
1753
-     * @param array  $query_params @see EEM_Base::get_all()
1754
-     * @param string $field_to_select
1755
-     * @return array just like $wpdb->get_col()
1756
-     * @throws \EE_Error
1757
-     */
1758
-    public function get_col($query_params = array(), $field_to_select = null)
1759
-    {
1760
-        if ($field_to_select) {
1761
-            $field = $this->field_settings_for($field_to_select);
1762
-        } elseif ($this->has_primary_key_field()) {
1763
-            $field = $this->get_primary_key_field();
1764
-        } else {
1765
-            //no primary key, just grab the first column
1766
-            $field = reset($this->field_settings());
1767
-        }
1768
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1769
-        $select_expressions = $field->get_qualified_column();
1770
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1771
-        return $this->_do_wpdb_query('get_col', array($SQL));
1772
-    }
1773
-
1774
-
1775
-
1776
-    /**
1777
-     * Returns a single column value for a single row from the database
1778
-     *
1779
-     * @param array  $query_params    @see EEM_Base::get_all()
1780
-     * @param string $field_to_select @see EEM_Base::get_col()
1781
-     * @return string
1782
-     * @throws \EE_Error
1783
-     */
1784
-    public function get_var($query_params = array(), $field_to_select = null)
1785
-    {
1786
-        $query_params['limit'] = 1;
1787
-        $col = $this->get_col($query_params, $field_to_select);
1788
-        if (! empty($col)) {
1789
-            return reset($col);
1790
-        } else {
1791
-            return null;
1792
-        }
1793
-    }
1794
-
1795
-
1796
-
1797
-    /**
1798
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1799
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1800
-     * injection, but currently no further filtering is done
1801
-     *
1802
-     * @global      $wpdb
1803
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1804
-     *                               be updated to in the DB
1805
-     * @return string of SQL
1806
-     * @throws \EE_Error
1807
-     */
1808
-    public function _construct_update_sql($fields_n_values)
1809
-    {
1810
-        /** @type WPDB $wpdb */
1811
-        global $wpdb;
1812
-        $cols_n_values = array();
1813
-        foreach ($fields_n_values as $field_name => $value) {
1814
-            $field_obj = $this->field_settings_for($field_name);
1815
-            //if the value is NULL, we want to assign the value to that.
1816
-            //wpdb->prepare doesn't really handle that properly
1817
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1818
-            $value_sql = $prepared_value === null ? 'NULL'
1819
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1820
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1821
-        }
1822
-        return implode(",", $cols_n_values);
1823
-    }
1824
-
1825
-
1826
-
1827
-    /**
1828
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1829
-     * Performs a HARD delete, meaning the database row should always be removed,
1830
-     * not just have a flag field on it switched
1831
-     * Wrapper for EEM_Base::delete_permanently()
1832
-     *
1833
-     * @param mixed $id
1834
-     * @return boolean whether the row got deleted or not
1835
-     * @throws \EE_Error
1836
-     */
1837
-    public function delete_permanently_by_ID($id)
1838
-    {
1839
-        return $this->delete_permanently(
1840
-            array(
1841
-                array($this->get_primary_key_field()->get_name() => $id),
1842
-                'limit' => 1,
1843
-            )
1844
-        );
1845
-    }
1846
-
1847
-
1848
-
1849
-    /**
1850
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
-     * Wrapper for EEM_Base::delete()
1852
-     *
1853
-     * @param mixed $id
1854
-     * @return boolean whether the row got deleted or not
1855
-     * @throws \EE_Error
1856
-     */
1857
-    public function delete_by_ID($id)
1858
-    {
1859
-        return $this->delete(
1860
-            array(
1861
-                array($this->get_primary_key_field()->get_name() => $id),
1862
-                'limit' => 1,
1863
-            )
1864
-        );
1865
-    }
1866
-
1867
-
1868
-
1869
-    /**
1870
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1871
-     * meaning if the model has a field that indicates its been "trashed" or
1872
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1873
-     *
1874
-     * @see EEM_Base::delete_permanently
1875
-     * @param array   $query_params
1876
-     * @param boolean $allow_blocking
1877
-     * @return int how many rows got deleted
1878
-     * @throws \EE_Error
1879
-     */
1880
-    public function delete($query_params, $allow_blocking = true)
1881
-    {
1882
-        return $this->delete_permanently($query_params, $allow_blocking);
1883
-    }
1884
-
1885
-
1886
-
1887
-    /**
1888
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1889
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1890
-     * as archived, not actually deleted
1891
-     *
1892
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1893
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1894
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1895
-     *                                deletes regardless of other objects which may depend on it. Its generally
1896
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1897
-     *                                DB
1898
-     * @return int how many rows got deleted
1899
-     * @throws \EE_Error
1900
-     */
1901
-    public function delete_permanently($query_params, $allow_blocking = true)
1902
-    {
1903
-        /**
1904
-         * Action called just before performing a real deletion query. You can use the
1905
-         * model and its $query_params to find exactly which items will be deleted
1906
-         *
1907
-         * @param EEM_Base $model
1908
-         * @param array    $query_params   @see EEM_Base::get_all()
1909
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1910
-         *                                 to block (prevent) this deletion
1911
-         */
1912
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1913
-        //some MySQL databases may be running safe mode, which may restrict
1914
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1915
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1916
-        //to delete them
1917
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1918
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1919
-        if ($deletion_where) {
1920
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1921
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1922
-            $table_aliases = array_keys($this->_tables);
1923
-            $SQL = "DELETE "
1924
-                   . implode(", ", $table_aliases)
1925
-                   . " FROM "
1926
-                   . $model_query_info->get_full_join_sql()
1927
-                   . " WHERE "
1928
-                   . $deletion_where;
1929
-            //		/echo "delete sql:$SQL";
1930
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1931
-        } else {
1932
-            $rows_deleted = 0;
1933
-        }
1934
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1935
-        if ($this->has_primary_key_field()) {
1936
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1937
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1938
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1939
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1940
-                }
1941
-            }
1942
-        }
1943
-        /**
1944
-         * Action called just after performing a real deletion query. Although at this point the
1945
-         * items should have been deleted
1946
-         *
1947
-         * @param EEM_Base $model
1948
-         * @param array    $query_params @see EEM_Base::get_all()
1949
-         * @param int      $rows_deleted
1950
-         */
1951
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1952
-        return $rows_deleted;//how many supposedly got deleted
1953
-    }
1954
-
1955
-
1956
-
1957
-    /**
1958
-     * Checks all the relations that throw error messages when there are blocking related objects
1959
-     * for related model objects. If there are any related model objects on those relations,
1960
-     * adds an EE_Error, and return true
1961
-     *
1962
-     * @param EE_Base_Class|int $this_model_obj_or_id
1963
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1964
-     *                                                 should be ignored when determining whether there are related
1965
-     *                                                 model objects which block this model object's deletion. Useful
1966
-     *                                                 if you know A is related to B and are considering deleting A,
1967
-     *                                                 but want to see if A has any other objects blocking its deletion
1968
-     *                                                 before removing the relation between A and B
1969
-     * @return boolean
1970
-     * @throws \EE_Error
1971
-     */
1972
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1973
-    {
1974
-        //first, if $ignore_this_model_obj was supplied, get its model
1975
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1976
-            $ignored_model = $ignore_this_model_obj->get_model();
1977
-        } else {
1978
-            $ignored_model = null;
1979
-        }
1980
-        //now check all the relations of $this_model_obj_or_id and see if there
1981
-        //are any related model objects blocking it?
1982
-        $is_blocked = false;
1983
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1984
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1985
-                //if $ignore_this_model_obj was supplied, then for the query
1986
-                //on that model needs to be told to ignore $ignore_this_model_obj
1987
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1988
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1989
-                        array(
1990
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1991
-                                '!=',
1992
-                                $ignore_this_model_obj->ID(),
1993
-                            ),
1994
-                        ),
1995
-                    ));
1996
-                } else {
1997
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1998
-                }
1999
-                if ($related_model_objects) {
2000
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2001
-                    $is_blocked = true;
2002
-                }
2003
-            }
2004
-        }
2005
-        return $is_blocked;
2006
-    }
2007
-
2008
-
2009
-
2010
-    /**
2011
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2012
-     * well.
2013
-     *
2014
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2015
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2016
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
2017
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
2018
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
2019
-     *                                      easily corrupt your DB
2020
-     * @throws EE_Error
2021
-     * @return string    everything that comes after the WHERE statement.
2022
-     */
2023
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2024
-    {
2025
-        if ($this->has_primary_key_field()) {
2026
-            $primary_table = $this->_get_main_table();
2027
-            $other_tables = $this->_get_other_tables();
2028
-            $deletes = $query = array();
2029
-            foreach ($objects_for_deletion as $delete_object) {
2030
-                //before we mark this object for deletion,
2031
-                //make sure there's no related objects blocking its deletion (if we're checking)
2032
-                if (
2033
-                    $allow_blocking
2034
-                    && $this->delete_is_blocked_by_related_models(
2035
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
2036
-                    )
2037
-                ) {
2038
-                    continue;
2039
-                }
2040
-                //primary table deletes
2041
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2042
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2043
-                }
2044
-                //other tables
2045
-                if (! empty($other_tables)) {
2046
-                    foreach ($other_tables as $ot) {
2047
-                        //first check if we've got the foreign key column here.
2048
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2049
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2050
-                        }
2051
-                        // wait! it's entirely possible that we'll have a the primary key
2052
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
2053
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2054
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2055
-                        }
2056
-                        // finally, it is possible that the fk for this table is found
2057
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
2058
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2059
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2060
-                        }
2061
-                    }
2062
-                }
2063
-            }
2064
-            //we should have deletes now, so let's just go through and setup the where statement
2065
-            foreach ($deletes as $column => $values) {
2066
-                //make sure we have unique $values;
2067
-                $values = array_unique($values);
2068
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2069
-            }
2070
-            return ! empty($query) ? implode(' AND ', $query) : '';
2071
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2072
-            $ways_to_identify_a_row = array();
2073
-            $fields = $this->get_combined_primary_key_fields();
2074
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2075
-            foreach ($objects_for_deletion as $delete_object) {
2076
-                $values_for_each_cpk_for_a_row = array();
2077
-                foreach ($fields as $cpk_field) {
2078
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2079
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2080
-                                                           . "="
2081
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
2082
-                    }
2083
-                }
2084
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2085
-            }
2086
-            return implode(" OR ", $ways_to_identify_a_row);
2087
-        } else {
2088
-            //so there's no primary key and no combined key...
2089
-            //sorry, can't help you
2090
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2091
-                "event_espresso"), get_class($this)));
2092
-        }
2093
-    }
2094
-
2095
-
2096
-
2097
-    /**
2098
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2099
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2100
-     * column
2101
-     *
2102
-     * @param array  $query_params   like EEM_Base::get_all's
2103
-     * @param string $field_to_count field on model to count by (not column name)
2104
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2105
-     *                               that by the setting $distinct to TRUE;
2106
-     * @return int
2107
-     * @throws \EE_Error
2108
-     */
2109
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2110
-    {
2111
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2112
-        if ($field_to_count) {
2113
-            $field_obj = $this->field_settings_for($field_to_count);
2114
-            $column_to_count = $field_obj->get_qualified_column();
2115
-        } elseif ($this->has_primary_key_field()) {
2116
-            $pk_field_obj = $this->get_primary_key_field();
2117
-            $column_to_count = $pk_field_obj->get_qualified_column();
2118
-        } else {
2119
-            //there's no primary key
2120
-            //if we're counting distinct items, and there's no primary key,
2121
-            //we need to list out the columns for distinction;
2122
-            //otherwise we can just use star
2123
-            if ($distinct) {
2124
-                $columns_to_use = array();
2125
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2126
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2127
-                }
2128
-                $column_to_count = implode(',', $columns_to_use);
2129
-            } else {
2130
-                $column_to_count = '*';
2131
-            }
2132
-        }
2133
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2134
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2135
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2136
-    }
2137
-
2138
-
2139
-
2140
-    /**
2141
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2142
-     *
2143
-     * @param array  $query_params like EEM_Base::get_all
2144
-     * @param string $field_to_sum name of field (array key in $_fields array)
2145
-     * @return float
2146
-     * @throws \EE_Error
2147
-     */
2148
-    public function sum($query_params, $field_to_sum = null)
2149
-    {
2150
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2151
-        if ($field_to_sum) {
2152
-            $field_obj = $this->field_settings_for($field_to_sum);
2153
-        } else {
2154
-            $field_obj = $this->get_primary_key_field();
2155
-        }
2156
-        $column_to_count = $field_obj->get_qualified_column();
2157
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2158
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2159
-        $data_type = $field_obj->get_wpdb_data_type();
2160
-        if ($data_type === '%d' || $data_type === '%s') {
2161
-            return (float)$return_value;
2162
-        } else {//must be %f
2163
-            return (float)$return_value;
2164
-        }
2165
-    }
2166
-
2167
-
2168
-
2169
-    /**
2170
-     * Just calls the specified method on $wpdb with the given arguments
2171
-     * Consolidates a little extra error handling code
2172
-     *
2173
-     * @param string $wpdb_method
2174
-     * @param array  $arguments_to_provide
2175
-     * @throws EE_Error
2176
-     * @global wpdb  $wpdb
2177
-     * @return mixed
2178
-     */
2179
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2180
-    {
2181
-        //if we're in maintenance mode level 2, DON'T run any queries
2182
-        //because level 2 indicates the database needs updating and
2183
-        //is probably out of sync with the code
2184
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2185
-            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.",
2186
-                "event_espresso")));
2187
-        }
2188
-        /** @type WPDB $wpdb */
2189
-        global $wpdb;
2190
-        if (! method_exists($wpdb, $wpdb_method)) {
2191
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2192
-                'event_espresso'), $wpdb_method));
2193
-        }
2194
-        if (WP_DEBUG) {
2195
-            $old_show_errors_value = $wpdb->show_errors;
2196
-            $wpdb->show_errors(false);
2197
-        }
2198
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2199
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2200
-        if (WP_DEBUG) {
2201
-            $wpdb->show_errors($old_show_errors_value);
2202
-            if (! empty($wpdb->last_error)) {
2203
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2204
-            } elseif ($result === false) {
2205
-                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"',
2206
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2207
-            }
2208
-        } elseif ($result === false) {
2209
-            EE_Error::add_error(
2210
-                sprintf(
2211
-                    __('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"',
2212
-                        'event_espresso'),
2213
-                    $wpdb_method,
2214
-                    var_export($arguments_to_provide, true),
2215
-                    $wpdb->last_error
2216
-                ),
2217
-                __FILE__,
2218
-                __FUNCTION__,
2219
-                __LINE__
2220
-            );
2221
-        }
2222
-        return $result;
2223
-    }
2224
-
2225
-
2226
-
2227
-    /**
2228
-     * Attempts to run the indicated WPDB method with the provided arguments,
2229
-     * and if there's an error tries to verify the DB is correct. Uses
2230
-     * the static property EEM_Base::$_db_verification_level to determine whether
2231
-     * we should try to fix the EE core db, the addons, or just give up
2232
-     *
2233
-     * @param string $wpdb_method
2234
-     * @param array  $arguments_to_provide
2235
-     * @return mixed
2236
-     */
2237
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2238
-    {
2239
-        /** @type WPDB $wpdb */
2240
-        global $wpdb;
2241
-        $wpdb->last_error = null;
2242
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2243
-        // was there an error running the query? but we don't care on new activations
2244
-        // (we're going to setup the DB anyway on new activations)
2245
-        if (($result === false || ! empty($wpdb->last_error))
2246
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2247
-        ) {
2248
-            switch (EEM_Base::$_db_verification_level) {
2249
-                case EEM_Base::db_verified_none :
2250
-                    // let's double-check core's DB
2251
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2252
-                    break;
2253
-                case EEM_Base::db_verified_core :
2254
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2255
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2256
-                    break;
2257
-                case EEM_Base::db_verified_addons :
2258
-                    // ummmm... you in trouble
2259
-                    return $result;
2260
-                    break;
2261
-            }
2262
-            if (! empty($error_message)) {
2263
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2264
-                trigger_error($error_message);
2265
-            }
2266
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2267
-        }
2268
-        return $result;
2269
-    }
2270
-
2271
-
2272
-
2273
-    /**
2274
-     * Verifies the EE core database is up-to-date and records that we've done it on
2275
-     * EEM_Base::$_db_verification_level
2276
-     *
2277
-     * @param string $wpdb_method
2278
-     * @param array  $arguments_to_provide
2279
-     * @return string
2280
-     */
2281
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2282
-    {
2283
-        /** @type WPDB $wpdb */
2284
-        global $wpdb;
2285
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2286
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2287
-        $error_message = sprintf(
2288
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2289
-                'event_espresso'),
2290
-            $wpdb->last_error,
2291
-            $wpdb_method,
2292
-            wp_json_encode($arguments_to_provide)
2293
-        );
2294
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2295
-        return $error_message;
2296
-    }
2297
-
2298
-
2299
-
2300
-    /**
2301
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2302
-     * EEM_Base::$_db_verification_level
2303
-     *
2304
-     * @param $wpdb_method
2305
-     * @param $arguments_to_provide
2306
-     * @return string
2307
-     */
2308
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2309
-    {
2310
-        /** @type WPDB $wpdb */
2311
-        global $wpdb;
2312
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2313
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2314
-        $error_message = sprintf(
2315
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2316
-                'event_espresso'),
2317
-            $wpdb->last_error,
2318
-            $wpdb_method,
2319
-            wp_json_encode($arguments_to_provide)
2320
-        );
2321
-        EE_System::instance()->initialize_addons();
2322
-        return $error_message;
2323
-    }
2324
-
2325
-
2326
-
2327
-    /**
2328
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2329
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2330
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2331
-     * ..."
2332
-     *
2333
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2334
-     * @return string
2335
-     */
2336
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2337
-    {
2338
-        return " FROM " . $model_query_info->get_full_join_sql() .
2339
-               $model_query_info->get_where_sql() .
2340
-               $model_query_info->get_group_by_sql() .
2341
-               $model_query_info->get_having_sql() .
2342
-               $model_query_info->get_order_by_sql() .
2343
-               $model_query_info->get_limit_sql();
2344
-    }
2345
-
2346
-
2347
-
2348
-    /**
2349
-     * Set to easily debug the next X queries ran from this model.
2350
-     *
2351
-     * @param int $count
2352
-     */
2353
-    public function show_next_x_db_queries($count = 1)
2354
-    {
2355
-        $this->_show_next_x_db_queries = $count;
2356
-    }
2357
-
2358
-
2359
-
2360
-    /**
2361
-     * @param $sql_query
2362
-     */
2363
-    public function show_db_query_if_previously_requested($sql_query)
2364
-    {
2365
-        if ($this->_show_next_x_db_queries > 0) {
2366
-            echo $sql_query;
2367
-            $this->_show_next_x_db_queries--;
2368
-        }
2369
-    }
2370
-
2371
-
2372
-
2373
-    /**
2374
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2375
-     * There are the 3 cases:
2376
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2377
-     * $otherModelObject has no ID, it is first saved.
2378
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2379
-     * has no ID, it is first saved.
2380
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2381
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2382
-     * join table
2383
-     *
2384
-     * @param        EE_Base_Class                     /int $thisModelObject
2385
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2386
-     * @param string $relationName                     , key in EEM_Base::_relations
2387
-     *                                                 an attendee to a group, you also want to specify which role they
2388
-     *                                                 will have in that group. So you would use this parameter to
2389
-     *                                                 specify array('role-column-name'=>'role-id')
2390
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2391
-     *                                                 to for relation to methods that allow you to further specify
2392
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2393
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2394
-     *                                                 because these will be inserted in any new rows created as well.
2395
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2396
-     * @throws \EE_Error
2397
-     */
2398
-    public function add_relationship_to(
2399
-        $id_or_obj,
2400
-        $other_model_id_or_obj,
2401
-        $relationName,
2402
-        $extra_join_model_fields_n_values = array()
2403
-    ) {
2404
-        $relation_obj = $this->related_settings_for($relationName);
2405
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2406
-    }
2407
-
2408
-
2409
-
2410
-    /**
2411
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2412
-     * There are the 3 cases:
2413
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2414
-     * error
2415
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2416
-     * an error
2417
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2418
-     *
2419
-     * @param        EE_Base_Class /int $id_or_obj
2420
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2421
-     * @param string $relationName key in EEM_Base::_relations
2422
-     * @return boolean of success
2423
-     * @throws \EE_Error
2424
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2425
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2426
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2427
-     *                             because these will be inserted in any new rows created as well.
2428
-     */
2429
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2430
-    {
2431
-        $relation_obj = $this->related_settings_for($relationName);
2432
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2433
-    }
2434
-
2435
-
2436
-
2437
-    /**
2438
-     * @param mixed           $id_or_obj
2439
-     * @param string          $relationName
2440
-     * @param array           $where_query_params
2441
-     * @param EE_Base_Class[] objects to which relations were removed
2442
-     * @return \EE_Base_Class[]
2443
-     * @throws \EE_Error
2444
-     */
2445
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2446
-    {
2447
-        $relation_obj = $this->related_settings_for($relationName);
2448
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2449
-    }
2450
-
2451
-
2452
-
2453
-    /**
2454
-     * Gets all the related items of the specified $model_name, using $query_params.
2455
-     * Note: by default, we remove the "default query params"
2456
-     * because we want to get even deleted items etc.
2457
-     *
2458
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2459
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2460
-     * @param array  $query_params like EEM_Base::get_all
2461
-     * @return EE_Base_Class[]
2462
-     * @throws \EE_Error
2463
-     */
2464
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2465
-    {
2466
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2467
-        $relation_settings = $this->related_settings_for($model_name);
2468
-        return $relation_settings->get_all_related($model_obj, $query_params);
2469
-    }
2470
-
2471
-
2472
-
2473
-    /**
2474
-     * Deletes all the model objects across the relation indicated by $model_name
2475
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2476
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2477
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2478
-     *
2479
-     * @param EE_Base_Class|int|string $id_or_obj
2480
-     * @param string                   $model_name
2481
-     * @param array                    $query_params
2482
-     * @return int how many deleted
2483
-     * @throws \EE_Error
2484
-     */
2485
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2486
-    {
2487
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2488
-        $relation_settings = $this->related_settings_for($model_name);
2489
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2490
-    }
2491
-
2492
-
2493
-
2494
-    /**
2495
-     * Hard deletes all the model objects across the relation indicated by $model_name
2496
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2497
-     * the model objects can't be hard deleted because of blocking related model objects,
2498
-     * just does a soft-delete on them instead.
2499
-     *
2500
-     * @param EE_Base_Class|int|string $id_or_obj
2501
-     * @param string                   $model_name
2502
-     * @param array                    $query_params
2503
-     * @return int how many deleted
2504
-     * @throws \EE_Error
2505
-     */
2506
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2507
-    {
2508
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2509
-        $relation_settings = $this->related_settings_for($model_name);
2510
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2511
-    }
2512
-
2513
-
2514
-
2515
-    /**
2516
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2517
-     * unless otherwise specified in the $query_params
2518
-     *
2519
-     * @param        int             /EE_Base_Class $id_or_obj
2520
-     * @param string $model_name     like 'Event', or 'Registration'
2521
-     * @param array  $query_params   like EEM_Base::get_all's
2522
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2523
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2524
-     *                               that by the setting $distinct to TRUE;
2525
-     * @return int
2526
-     * @throws \EE_Error
2527
-     */
2528
-    public function count_related(
2529
-        $id_or_obj,
2530
-        $model_name,
2531
-        $query_params = array(),
2532
-        $field_to_count = null,
2533
-        $distinct = false
2534
-    ) {
2535
-        $related_model = $this->get_related_model_obj($model_name);
2536
-        //we're just going to use the query params on the related model's normal get_all query,
2537
-        //except add a condition to say to match the current mod
2538
-        if (! isset($query_params['default_where_conditions'])) {
2539
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2540
-        }
2541
-        $this_model_name = $this->get_this_model_name();
2542
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2543
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2544
-        return $related_model->count($query_params, $field_to_count, $distinct);
2545
-    }
2546
-
2547
-
2548
-
2549
-    /**
2550
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2551
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2552
-     *
2553
-     * @param        int           /EE_Base_Class $id_or_obj
2554
-     * @param string $model_name   like 'Event', or 'Registration'
2555
-     * @param array  $query_params like EEM_Base::get_all's
2556
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2557
-     * @return float
2558
-     * @throws \EE_Error
2559
-     */
2560
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2561
-    {
2562
-        $related_model = $this->get_related_model_obj($model_name);
2563
-        if (! is_array($query_params)) {
2564
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2565
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2566
-                    gettype($query_params)), '4.6.0');
2567
-            $query_params = array();
2568
-        }
2569
-        //we're just going to use the query params on the related model's normal get_all query,
2570
-        //except add a condition to say to match the current mod
2571
-        if (! isset($query_params['default_where_conditions'])) {
2572
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2573
-        }
2574
-        $this_model_name = $this->get_this_model_name();
2575
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2576
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2577
-        return $related_model->sum($query_params, $field_to_sum);
2578
-    }
2579
-
2580
-
2581
-
2582
-    /**
2583
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2584
-     * $modelObject
2585
-     *
2586
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2587
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2588
-     * @param array               $query_params     like EEM_Base::get_all's
2589
-     * @return EE_Base_Class
2590
-     * @throws \EE_Error
2591
-     */
2592
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2593
-    {
2594
-        $query_params['limit'] = 1;
2595
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2596
-        if ($results) {
2597
-            return array_shift($results);
2598
-        } else {
2599
-            return null;
2600
-        }
2601
-    }
2602
-
2603
-
2604
-
2605
-    /**
2606
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2607
-     *
2608
-     * @return string
2609
-     */
2610
-    public function get_this_model_name()
2611
-    {
2612
-        return str_replace("EEM_", "", get_class($this));
2613
-    }
2614
-
2615
-
2616
-
2617
-    /**
2618
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2619
-     *
2620
-     * @return EE_Any_Foreign_Model_Name_Field
2621
-     * @throws EE_Error
2622
-     */
2623
-    public function get_field_containing_related_model_name()
2624
-    {
2625
-        foreach ($this->field_settings(true) as $field) {
2626
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2627
-                $field_with_model_name = $field;
2628
-            }
2629
-        }
2630
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2631
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2632
-                $this->get_this_model_name()));
2633
-        }
2634
-        return $field_with_model_name;
2635
-    }
2636
-
2637
-
2638
-
2639
-    /**
2640
-     * Inserts a new entry into the database, for each table.
2641
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2642
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2643
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2644
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2645
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2646
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2647
-     *
2648
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2649
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2650
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2651
-     *                              of EEM_Base)
2652
-     * @return int new primary key on main table that got inserted
2653
-     * @throws EE_Error
2654
-     */
2655
-    public function insert($field_n_values)
2656
-    {
2657
-        /**
2658
-         * Filters the fields and their values before inserting an item using the models
2659
-         *
2660
-         * @param array    $fields_n_values keys are the fields and values are their new values
2661
-         * @param EEM_Base $model           the model used
2662
-         */
2663
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2664
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2665
-            $main_table = $this->_get_main_table();
2666
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2667
-            if ($new_id !== false) {
2668
-                foreach ($this->_get_other_tables() as $other_table) {
2669
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2670
-                }
2671
-            }
2672
-            /**
2673
-             * Done just after attempting to insert a new model object
2674
-             *
2675
-             * @param EEM_Base   $model           used
2676
-             * @param array      $fields_n_values fields and their values
2677
-             * @param int|string the              ID of the newly-inserted model object
2678
-             */
2679
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2680
-            return $new_id;
2681
-        } else {
2682
-            return false;
2683
-        }
2684
-    }
2685
-
2686
-
2687
-
2688
-    /**
2689
-     * Checks that the result would satisfy the unique indexes on this model
2690
-     *
2691
-     * @param array  $field_n_values
2692
-     * @param string $action
2693
-     * @return boolean
2694
-     * @throws \EE_Error
2695
-     */
2696
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2697
-    {
2698
-        foreach ($this->unique_indexes() as $index_name => $index) {
2699
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2700
-            if ($this->exists(array($uniqueness_where_params))) {
2701
-                EE_Error::add_error(
2702
-                    sprintf(
2703
-                        __(
2704
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2705
-                            "event_espresso"
2706
-                        ),
2707
-                        $action,
2708
-                        $this->_get_class_name(),
2709
-                        $index_name,
2710
-                        implode(",", $index->field_names()),
2711
-                        http_build_query($uniqueness_where_params)
2712
-                    ),
2713
-                    __FILE__,
2714
-                    __FUNCTION__,
2715
-                    __LINE__
2716
-                );
2717
-                return false;
2718
-            }
2719
-        }
2720
-        return true;
2721
-    }
2722
-
2723
-
2724
-
2725
-    /**
2726
-     * Checks the database for an item that conflicts (ie, if this item were
2727
-     * saved to the DB would break some uniqueness requirement, like a primary key
2728
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2729
-     * can be either an EE_Base_Class or an array of fields n values
2730
-     *
2731
-     * @param EE_Base_Class|array $obj_or_fields_array
2732
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2733
-     *                                                 when looking for conflicts
2734
-     *                                                 (ie, if false, we ignore the model object's primary key
2735
-     *                                                 when finding "conflicts". If true, it's also considered).
2736
-     *                                                 Only works for INT primary key,
2737
-     *                                                 STRING primary keys cannot be ignored
2738
-     * @throws EE_Error
2739
-     * @return EE_Base_Class|array
2740
-     */
2741
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2742
-    {
2743
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2744
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2745
-        } elseif (is_array($obj_or_fields_array)) {
2746
-            $fields_n_values = $obj_or_fields_array;
2747
-        } else {
2748
-            throw new EE_Error(
2749
-                sprintf(
2750
-                    __(
2751
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2752
-                        "event_espresso"
2753
-                    ),
2754
-                    get_class($this),
2755
-                    $obj_or_fields_array
2756
-                )
2757
-            );
2758
-        }
2759
-        $query_params = array();
2760
-        if ($this->has_primary_key_field()
2761
-            && ($include_primary_key
2762
-                || $this->get_primary_key_field()
2763
-                   instanceof
2764
-                   EE_Primary_Key_String_Field)
2765
-            && isset($fields_n_values[$this->primary_key_name()])
2766
-        ) {
2767
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2768
-        }
2769
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2770
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2771
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2772
-        }
2773
-        //if there is nothing to base this search on, then we shouldn't find anything
2774
-        if (empty($query_params)) {
2775
-            return array();
2776
-        } else {
2777
-            return $this->get_one($query_params);
2778
-        }
2779
-    }
2780
-
2781
-
2782
-
2783
-    /**
2784
-     * Like count, but is optimized and returns a boolean instead of an int
2785
-     *
2786
-     * @param array $query_params
2787
-     * @return boolean
2788
-     * @throws \EE_Error
2789
-     */
2790
-    public function exists($query_params)
2791
-    {
2792
-        $query_params['limit'] = 1;
2793
-        return $this->count($query_params) > 0;
2794
-    }
2795
-
2796
-
2797
-
2798
-    /**
2799
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2800
-     *
2801
-     * @param int|string $id
2802
-     * @return boolean
2803
-     * @throws \EE_Error
2804
-     */
2805
-    public function exists_by_ID($id)
2806
-    {
2807
-        return $this->exists(
2808
-            array(
2809
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2810
-                array(
2811
-                    $this->primary_key_name() => $id,
2812
-                ),
2813
-            )
2814
-        );
2815
-    }
2816
-
2817
-
2818
-
2819
-    /**
2820
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2821
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2822
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2823
-     * on the main table)
2824
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2825
-     * cases where we want to call it directly rather than via insert().
2826
-     *
2827
-     * @access   protected
2828
-     * @param EE_Table_Base $table
2829
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2830
-     *                                       float
2831
-     * @param int           $new_id          for now we assume only int keys
2832
-     * @throws EE_Error
2833
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2834
-     * @return int ID of new row inserted, or FALSE on failure
2835
-     */
2836
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2837
-    {
2838
-        global $wpdb;
2839
-        $insertion_col_n_values = array();
2840
-        $format_for_insertion = array();
2841
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2842
-        foreach ($fields_on_table as $field_name => $field_obj) {
2843
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2844
-            if ($field_obj->is_auto_increment()) {
2845
-                continue;
2846
-            }
2847
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2848
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2849
-            if ($prepared_value !== null) {
2850
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2851
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2852
-            }
2853
-        }
2854
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2855
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2856
-            //so add the fk to the main table as a column
2857
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2858
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2859
-        }
2860
-        //insert the new entry
2861
-        $result = $this->_do_wpdb_query('insert',
2862
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2863
-        if ($result === false) {
2864
-            return false;
2865
-        }
2866
-        //ok, now what do we return for the ID of the newly-inserted thing?
2867
-        if ($this->has_primary_key_field()) {
2868
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2869
-                return $wpdb->insert_id;
2870
-            } else {
2871
-                //it's not an auto-increment primary key, so
2872
-                //it must have been supplied
2873
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2874
-            }
2875
-        } else {
2876
-            //we can't return a  primary key because there is none. instead return
2877
-            //a unique string indicating this model
2878
-            return $this->get_index_primary_key_string($fields_n_values);
2879
-        }
2880
-    }
2881
-
2882
-
2883
-
2884
-    /**
2885
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2886
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2887
-     * and there is no default, we pass it along. WPDB will take care of it)
2888
-     *
2889
-     * @param EE_Model_Field_Base $field_obj
2890
-     * @param array               $fields_n_values
2891
-     * @return mixed string|int|float depending on what the table column will be expecting
2892
-     * @throws \EE_Error
2893
-     */
2894
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2895
-    {
2896
-        //if this field doesn't allow nullable, don't allow it
2897
-        if (
2898
-            ! $field_obj->is_nullable()
2899
-            && (
2900
-                ! isset($fields_n_values[$field_obj->get_name()])
2901
-                || $fields_n_values[$field_obj->get_name()] === null
2902
-            )
2903
-        ) {
2904
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2905
-        }
2906
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2907
-            ? $fields_n_values[$field_obj->get_name()]
2908
-            : null;
2909
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2910
-    }
2911
-
2912
-
2913
-
2914
-    /**
2915
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2916
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2917
-     * the field's prepare_for_set() method.
2918
-     *
2919
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2920
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2921
-     *                                   top of file)
2922
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2923
-     *                                   $value is a custom selection
2924
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2925
-     */
2926
-    private function _prepare_value_for_use_in_db($value, $field)
2927
-    {
2928
-        if ($field && $field instanceof EE_Model_Field_Base) {
2929
-            switch ($this->_values_already_prepared_by_model_object) {
2930
-                /** @noinspection PhpMissingBreakStatementInspection */
2931
-                case self::not_prepared_by_model_object:
2932
-                    $value = $field->prepare_for_set($value);
2933
-                //purposefully left out "return"
2934
-                case self::prepared_by_model_object:
2935
-                    $value = $field->prepare_for_use_in_db($value);
2936
-                case self::prepared_for_use_in_db:
2937
-                    //leave the value alone
2938
-            }
2939
-            return $value;
2940
-        } else {
2941
-            return $value;
2942
-        }
2943
-    }
2944
-
2945
-
2946
-
2947
-    /**
2948
-     * Returns the main table on this model
2949
-     *
2950
-     * @return EE_Primary_Table
2951
-     * @throws EE_Error
2952
-     */
2953
-    protected function _get_main_table()
2954
-    {
2955
-        foreach ($this->_tables as $table) {
2956
-            if ($table instanceof EE_Primary_Table) {
2957
-                return $table;
2958
-            }
2959
-        }
2960
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2961
-            'event_espresso'), get_class($this)));
2962
-    }
2963
-
2964
-
2965
-
2966
-    /**
2967
-     * table
2968
-     * returns EE_Primary_Table table name
2969
-     *
2970
-     * @return string
2971
-     * @throws \EE_Error
2972
-     */
2973
-    public function table()
2974
-    {
2975
-        return $this->_get_main_table()->get_table_name();
2976
-    }
2977
-
2978
-
2979
-
2980
-    /**
2981
-     * table
2982
-     * returns first EE_Secondary_Table table name
2983
-     *
2984
-     * @return string
2985
-     */
2986
-    public function second_table()
2987
-    {
2988
-        // grab second table from tables array
2989
-        $second_table = end($this->_tables);
2990
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2991
-    }
2992
-
2993
-
2994
-
2995
-    /**
2996
-     * get_table_obj_by_alias
2997
-     * returns table name given it's alias
2998
-     *
2999
-     * @param string $table_alias
3000
-     * @return EE_Primary_Table | EE_Secondary_Table
3001
-     */
3002
-    public function get_table_obj_by_alias($table_alias = '')
3003
-    {
3004
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3005
-    }
3006
-
3007
-
3008
-
3009
-    /**
3010
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3011
-     *
3012
-     * @return EE_Secondary_Table[]
3013
-     */
3014
-    protected function _get_other_tables()
3015
-    {
3016
-        $other_tables = array();
3017
-        foreach ($this->_tables as $table_alias => $table) {
3018
-            if ($table instanceof EE_Secondary_Table) {
3019
-                $other_tables[$table_alias] = $table;
3020
-            }
3021
-        }
3022
-        return $other_tables;
3023
-    }
3024
-
3025
-
3026
-
3027
-    /**
3028
-     * Finds all the fields that correspond to the given table
3029
-     *
3030
-     * @param string $table_alias , array key in EEM_Base::_tables
3031
-     * @return EE_Model_Field_Base[]
3032
-     */
3033
-    public function _get_fields_for_table($table_alias)
3034
-    {
3035
-        return $this->_fields[$table_alias];
3036
-    }
3037
-
3038
-
3039
-
3040
-    /**
3041
-     * Recurses through all the where parameters, and finds all the related models we'll need
3042
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3043
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3044
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3045
-     * related Registration, Transaction, and Payment models.
3046
-     *
3047
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3048
-     * @return EE_Model_Query_Info_Carrier
3049
-     * @throws \EE_Error
3050
-     */
3051
-    public function _extract_related_models_from_query($query_params)
3052
-    {
3053
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3054
-        if (array_key_exists(0, $query_params)) {
3055
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3056
-        }
3057
-        if (array_key_exists('group_by', $query_params)) {
3058
-            if (is_array($query_params['group_by'])) {
3059
-                $this->_extract_related_models_from_sub_params_array_values(
3060
-                    $query_params['group_by'],
3061
-                    $query_info_carrier,
3062
-                    'group_by'
3063
-                );
3064
-            } elseif (! empty ($query_params['group_by'])) {
3065
-                $this->_extract_related_model_info_from_query_param(
3066
-                    $query_params['group_by'],
3067
-                    $query_info_carrier,
3068
-                    'group_by'
3069
-                );
3070
-            }
3071
-        }
3072
-        if (array_key_exists('having', $query_params)) {
3073
-            $this->_extract_related_models_from_sub_params_array_keys(
3074
-                $query_params[0],
3075
-                $query_info_carrier,
3076
-                'having'
3077
-            );
3078
-        }
3079
-        if (array_key_exists('order_by', $query_params)) {
3080
-            if (is_array($query_params['order_by'])) {
3081
-                $this->_extract_related_models_from_sub_params_array_keys(
3082
-                    $query_params['order_by'],
3083
-                    $query_info_carrier,
3084
-                    'order_by'
3085
-                );
3086
-            } elseif (! empty($query_params['order_by'])) {
3087
-                $this->_extract_related_model_info_from_query_param(
3088
-                    $query_params['order_by'],
3089
-                    $query_info_carrier,
3090
-                    'order_by'
3091
-                );
3092
-            }
3093
-        }
3094
-        if (array_key_exists('force_join', $query_params)) {
3095
-            $this->_extract_related_models_from_sub_params_array_values(
3096
-                $query_params['force_join'],
3097
-                $query_info_carrier,
3098
-                'force_join'
3099
-            );
3100
-        }
3101
-        return $query_info_carrier;
3102
-    }
3103
-
3104
-
3105
-
3106
-    /**
3107
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3108
-     *
3109
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3110
-     *                                                      $query_params['having']
3111
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3112
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3113
-     * @throws EE_Error
3114
-     * @return \EE_Model_Query_Info_Carrier
3115
-     */
3116
-    private function _extract_related_models_from_sub_params_array_keys(
3117
-        $sub_query_params,
3118
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3119
-        $query_param_type
3120
-    ) {
3121
-        if (! empty($sub_query_params)) {
3122
-            $sub_query_params = (array)$sub_query_params;
3123
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3124
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3125
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3126
-                    $query_param_type);
3127
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3128
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3129
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3130
-                //of array('Registration.TXN_ID'=>23)
3131
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3132
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3133
-                    if (! is_array($possibly_array_of_params)) {
3134
-                        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'))",
3135
-                            "event_espresso"),
3136
-                            $param, $possibly_array_of_params));
3137
-                    } else {
3138
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3139
-                            $model_query_info_carrier, $query_param_type);
3140
-                    }
3141
-                } elseif ($query_param_type === 0 //ie WHERE
3142
-                          && is_array($possibly_array_of_params)
3143
-                          && isset($possibly_array_of_params[2])
3144
-                          && $possibly_array_of_params[2] == true
3145
-                ) {
3146
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3147
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3148
-                    //from which we should extract query parameters!
3149
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3150
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3151
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3152
-                    }
3153
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3154
-                        $model_query_info_carrier, $query_param_type);
3155
-                }
3156
-            }
3157
-        }
3158
-        return $model_query_info_carrier;
3159
-    }
3160
-
3161
-
3162
-
3163
-    /**
3164
-     * For extracting related models from forced_joins, where the array values contain the info about what
3165
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3166
-     *
3167
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3168
-     *                                                      $query_params['having']
3169
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3170
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3171
-     * @throws EE_Error
3172
-     * @return \EE_Model_Query_Info_Carrier
3173
-     */
3174
-    private function _extract_related_models_from_sub_params_array_values(
3175
-        $sub_query_params,
3176
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3177
-        $query_param_type
3178
-    ) {
3179
-        if (! empty($sub_query_params)) {
3180
-            if (! is_array($sub_query_params)) {
3181
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3182
-                    $sub_query_params));
3183
-            }
3184
-            foreach ($sub_query_params as $param) {
3185
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3186
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3187
-                    $query_param_type);
3188
-            }
3189
-        }
3190
-        return $model_query_info_carrier;
3191
-    }
3192
-
3193
-
3194
-
3195
-    /**
3196
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3197
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3198
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3199
-     * but use them in a different order. Eg, we need to know what models we are querying
3200
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3201
-     * other models before we can finalize the where clause SQL.
3202
-     *
3203
-     * @param array $query_params
3204
-     * @throws EE_Error
3205
-     * @return EE_Model_Query_Info_Carrier
3206
-     */
3207
-    public function _create_model_query_info_carrier($query_params)
3208
-    {
3209
-        if (! is_array($query_params)) {
3210
-            EE_Error::doing_it_wrong(
3211
-                'EEM_Base::_create_model_query_info_carrier',
3212
-                sprintf(
3213
-                    __(
3214
-                        '$query_params should be an array, you passed a variable of type %s',
3215
-                        'event_espresso'
3216
-                    ),
3217
-                    gettype($query_params)
3218
-                ),
3219
-                '4.6.0'
3220
-            );
3221
-            $query_params = array();
3222
-        }
3223
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3224
-        //first check if we should alter the query to account for caps or not
3225
-        //because the caps might require us to do extra joins
3226
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3227
-            $query_params[0] = $where_query_params = array_replace_recursive(
3228
-                $where_query_params,
3229
-                $this->caps_where_conditions(
3230
-                    $query_params['caps']
3231
-                )
3232
-            );
3233
-        }
3234
-        $query_object = $this->_extract_related_models_from_query($query_params);
3235
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3236
-        foreach ($where_query_params as $key => $value) {
3237
-            if (is_int($key)) {
3238
-                throw new EE_Error(
3239
-                    sprintf(
3240
-                        __(
3241
-                            "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.",
3242
-                            "event_espresso"
3243
-                        ),
3244
-                        $key,
3245
-                        var_export($value, true),
3246
-                        var_export($query_params, true),
3247
-                        get_class($this)
3248
-                    )
3249
-                );
3250
-            }
3251
-        }
3252
-        if (
3253
-            array_key_exists('default_where_conditions', $query_params)
3254
-            && ! empty($query_params['default_where_conditions'])
3255
-        ) {
3256
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3257
-        } else {
3258
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3259
-        }
3260
-        $where_query_params = array_merge(
3261
-            $this->_get_default_where_conditions_for_models_in_query(
3262
-                $query_object,
3263
-                $use_default_where_conditions,
3264
-                $where_query_params
3265
-            ),
3266
-            $where_query_params
3267
-        );
3268
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3269
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3270
-        // So we need to setup a subquery and use that for the main join.
3271
-        // Note for now this only works on the primary table for the model.
3272
-        // So for instance, you could set the limit array like this:
3273
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3274
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3275
-            $query_object->set_main_model_join_sql(
3276
-                $this->_construct_limit_join_select(
3277
-                    $query_params['on_join_limit'][0],
3278
-                    $query_params['on_join_limit'][1]
3279
-                )
3280
-            );
3281
-        }
3282
-        //set limit
3283
-        if (array_key_exists('limit', $query_params)) {
3284
-            if (is_array($query_params['limit'])) {
3285
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3286
-                    $e = sprintf(
3287
-                        __(
3288
-                            "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)",
3289
-                            "event_espresso"
3290
-                        ),
3291
-                        http_build_query($query_params['limit'])
3292
-                    );
3293
-                    throw new EE_Error($e . "|" . $e);
3294
-                }
3295
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3296
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3297
-            } elseif (! empty ($query_params['limit'])) {
3298
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3299
-            }
3300
-        }
3301
-        //set order by
3302
-        if (array_key_exists('order_by', $query_params)) {
3303
-            if (is_array($query_params['order_by'])) {
3304
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3305
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3306
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3307
-                if (array_key_exists('order', $query_params)) {
3308
-                    throw new EE_Error(
3309
-                        sprintf(
3310
-                            __(
3311
-                                "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 ",
3312
-                                "event_espresso"
3313
-                            ),
3314
-                            get_class($this),
3315
-                            implode(", ", array_keys($query_params['order_by'])),
3316
-                            implode(", ", $query_params['order_by']),
3317
-                            $query_params['order']
3318
-                        )
3319
-                    );
3320
-                }
3321
-                $this->_extract_related_models_from_sub_params_array_keys(
3322
-                    $query_params['order_by'],
3323
-                    $query_object,
3324
-                    'order_by'
3325
-                );
3326
-                //assume it's an array of fields to order by
3327
-                $order_array = array();
3328
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3329
-                    $order = $this->_extract_order($order);
3330
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3331
-                }
3332
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3333
-            } elseif (! empty ($query_params['order_by'])) {
3334
-                $this->_extract_related_model_info_from_query_param(
3335
-                    $query_params['order_by'],
3336
-                    $query_object,
3337
-                    'order',
3338
-                    $query_params['order_by']
3339
-                );
3340
-                $order = isset($query_params['order'])
3341
-                    ? $this->_extract_order($query_params['order'])
3342
-                    : 'DESC';
3343
-                $query_object->set_order_by_sql(
3344
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3345
-                );
3346
-            }
3347
-        }
3348
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3349
-        if (! array_key_exists('order_by', $query_params)
3350
-            && array_key_exists('order', $query_params)
3351
-            && ! empty($query_params['order'])
3352
-        ) {
3353
-            $pk_field = $this->get_primary_key_field();
3354
-            $order = $this->_extract_order($query_params['order']);
3355
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3356
-        }
3357
-        //set group by
3358
-        if (array_key_exists('group_by', $query_params)) {
3359
-            if (is_array($query_params['group_by'])) {
3360
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3361
-                $group_by_array = array();
3362
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3363
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3364
-                }
3365
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3366
-            } elseif (! empty ($query_params['group_by'])) {
3367
-                $query_object->set_group_by_sql(
3368
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3369
-                );
3370
-            }
3371
-        }
3372
-        //set having
3373
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3374
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3375
-        }
3376
-        //now, just verify they didn't pass anything wack
3377
-        foreach ($query_params as $query_key => $query_value) {
3378
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3379
-                throw new EE_Error(
3380
-                    sprintf(
3381
-                        __(
3382
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3383
-                            'event_espresso'
3384
-                        ),
3385
-                        $query_key,
3386
-                        get_class($this),
3387
-                        //						print_r( $this->_allowed_query_params, TRUE )
3388
-                        implode(',', $this->_allowed_query_params)
3389
-                    )
3390
-                );
3391
-            }
3392
-        }
3393
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3394
-        if (empty($main_model_join_sql)) {
3395
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3396
-        }
3397
-        return $query_object;
3398
-    }
3399
-
3400
-
3401
-
3402
-    /**
3403
-     * Gets the where conditions that should be imposed on the query based on the
3404
-     * context (eg reading frontend, backend, edit or delete).
3405
-     *
3406
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3407
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3408
-     * @throws \EE_Error
3409
-     */
3410
-    public function caps_where_conditions($context = self::caps_read)
3411
-    {
3412
-        EEM_Base::verify_is_valid_cap_context($context);
3413
-        $cap_where_conditions = array();
3414
-        $cap_restrictions = $this->caps_missing($context);
3415
-        /**
3416
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3417
-         */
3418
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3419
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3420
-                $restriction_if_no_cap->get_default_where_conditions());
3421
-        }
3422
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3423
-            $cap_restrictions);
3424
-    }
3425
-
3426
-
3427
-
3428
-    /**
3429
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3430
-     * otherwise throws an exception
3431
-     *
3432
-     * @param string $should_be_order_string
3433
-     * @return string either ASC, asc, DESC or desc
3434
-     * @throws EE_Error
3435
-     */
3436
-    private function _extract_order($should_be_order_string)
3437
-    {
3438
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3439
-            return $should_be_order_string;
3440
-        } else {
3441
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3442
-                "event_espresso"), get_class($this), $should_be_order_string));
3443
-        }
3444
-    }
3445
-
3446
-
3447
-
3448
-    /**
3449
-     * Looks at all the models which are included in this query, and asks each
3450
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3451
-     * so they can be merged
3452
-     *
3453
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3454
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3455
-     *                                                                  'none' means NO default where conditions will
3456
-     *                                                                  be used AT ALL during this query.
3457
-     *                                                                  'other_models_only' means default where
3458
-     *                                                                  conditions from other models will be used, but
3459
-     *                                                                  not for this primary model. 'all', the default,
3460
-     *                                                                  means default where conditions will apply as
3461
-     *                                                                  normal
3462
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3463
-     * @throws EE_Error
3464
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3465
-     */
3466
-    private function _get_default_where_conditions_for_models_in_query(
3467
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3468
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3469
-        $where_query_params = array()
3470
-    ) {
3471
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3472
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3473
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3474
-                "event_espresso"), $use_default_where_conditions,
3475
-                implode(", ", $allowed_used_default_where_conditions_values)));
3476
-        }
3477
-        $universal_query_params = array();
3478
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3479
-            $universal_query_params = $this->_get_default_where_conditions();
3480
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3481
-            $universal_query_params = $this->_get_minimum_where_conditions();
3482
-        }
3483
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3484
-            $related_model = $this->get_related_model_obj($model_name);
3485
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3486
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3487
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3488
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3489
-            } else {
3490
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3491
-                continue;
3492
-            }
3493
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3494
-                $related_model_universal_where_params,
3495
-                $where_query_params,
3496
-                $related_model,
3497
-                $model_relation_path
3498
-            );
3499
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3500
-                $universal_query_params,
3501
-                $overrides
3502
-            );
3503
-        }
3504
-        return $universal_query_params;
3505
-    }
3506
-
3507
-
3508
-
3509
-    /**
3510
-     * Determines whether or not we should use default where conditions for the model in question
3511
-     * (this model, or other related models).
3512
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3513
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3514
-     * We should use default where conditions on related models when they requested to use default where conditions
3515
-     * on all models, or specifically just on other related models
3516
-     * @param      $default_where_conditions_value
3517
-     * @param bool $for_this_model false means this is for OTHER related models
3518
-     * @return bool
3519
-     */
3520
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3521
-    {
3522
-        return (
3523
-                   $for_this_model
3524
-                   && in_array(
3525
-                       $default_where_conditions_value,
3526
-                       array(
3527
-                           EEM_Base::default_where_conditions_all,
3528
-                           EEM_Base::default_where_conditions_this_only,
3529
-                           EEM_Base::default_where_conditions_minimum_others,
3530
-                       ),
3531
-                       true
3532
-                   )
3533
-               )
3534
-               || (
3535
-                   ! $for_this_model
3536
-                   && in_array(
3537
-                       $default_where_conditions_value,
3538
-                       array(
3539
-                           EEM_Base::default_where_conditions_all,
3540
-                           EEM_Base::default_where_conditions_others_only,
3541
-                       ),
3542
-                       true
3543
-                   )
3544
-               );
3545
-    }
3546
-
3547
-    /**
3548
-     * Determines whether or not we should use default minimum conditions for the model in question
3549
-     * (this model, or other related models).
3550
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3551
-     * where conditions.
3552
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3553
-     * on this model or others
3554
-     * @param      $default_where_conditions_value
3555
-     * @param bool $for_this_model false means this is for OTHER related models
3556
-     * @return bool
3557
-     */
3558
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3559
-    {
3560
-        return (
3561
-                   $for_this_model
3562
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3563
-               )
3564
-               || (
3565
-                   ! $for_this_model
3566
-                   && in_array(
3567
-                       $default_where_conditions_value,
3568
-                       array(
3569
-                           EEM_Base::default_where_conditions_minimum_others,
3570
-                           EEM_Base::default_where_conditions_minimum_all,
3571
-                       ),
3572
-                       true
3573
-                   )
3574
-               );
3575
-    }
3576
-
3577
-
3578
-    /**
3579
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3580
-     * then we also add a special where condition which allows for that model's primary key
3581
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3582
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3583
-     *
3584
-     * @param array    $default_where_conditions
3585
-     * @param array    $provided_where_conditions
3586
-     * @param EEM_Base $model
3587
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3588
-     * @return array like EEM_Base::get_all's $query_params[0]
3589
-     * @throws \EE_Error
3590
-     */
3591
-    private function _override_defaults_or_make_null_friendly(
3592
-        $default_where_conditions,
3593
-        $provided_where_conditions,
3594
-        $model,
3595
-        $model_relation_path
3596
-    ) {
3597
-        $null_friendly_where_conditions = array();
3598
-        $none_overridden = true;
3599
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3600
-        foreach ($default_where_conditions as $key => $val) {
3601
-            if (isset($provided_where_conditions[$key])) {
3602
-                $none_overridden = false;
3603
-            } else {
3604
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3605
-            }
3606
-        }
3607
-        if ($none_overridden && $default_where_conditions) {
3608
-            if ($model->has_primary_key_field()) {
3609
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3610
-                                                                                . "."
3611
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3612
-            }/*else{
31
+	//admin posty
32
+	//basic -> grants access to mine -> if they don't have it, select none
33
+	//*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
+	//*_published -> grants access to published -> if they dont have it, select non-published
36
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
38
+	//frontend posty
39
+	//by default has access to published
40
+	//basic -> grants access to mine that aren't published, and all published
41
+	//*_others ->grants access to others that aren't private, all mine
42
+	//*_private -> grants full access
43
+	//frontend non-posty
44
+	//like admin posty
45
+	//category-y
46
+	//assign -> grants access to join-table
47
+	//(delete, edit)
48
+	//payment-method-y
49
+	//for each registered payment method,
50
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
+	/**
52
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
55
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
+	 *
57
+	 * @var boolean
58
+	 */
59
+	private $_values_already_prepared_by_model_object = 0;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the data is just like form input that needs to have the model fields'
64
+	 * prepare_for_set and prepare_for_use_in_db called on it
65
+	 */
66
+	const not_prepared_by_model_object = 0;
67
+
68
+	/**
69
+	 * when $_values_already_prepared_by_model_object equals this, we
70
+	 * assume this value is coming from a model object and doesn't need to have
71
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
72
+	 */
73
+	const prepared_by_model_object = 1;
74
+
75
+	/**
76
+	 * when $_values_already_prepared_by_model_object equals this, we assume
77
+	 * the values are already to be used in the database (ie no processing is done
78
+	 * on them by the model's fields)
79
+	 */
80
+	const prepared_for_use_in_db = 2;
81
+
82
+
83
+	protected $singular_item = 'Item';
84
+
85
+	protected $plural_item   = 'Items';
86
+
87
+	/**
88
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
+	 */
90
+	protected $_tables;
91
+
92
+	/**
93
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
+	 *
97
+	 * @var \EE_Model_Field_Base[] $_fields
98
+	 */
99
+	protected $_fields;
100
+
101
+	/**
102
+	 * array of different kinds of relations
103
+	 *
104
+	 * @var \EE_Model_Relation_Base[] $_model_relations
105
+	 */
106
+	protected $_model_relations;
107
+
108
+	/**
109
+	 * @var \EE_Index[] $_indexes
110
+	 */
111
+	protected $_indexes = array();
112
+
113
+	/**
114
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
115
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
+	 * by setting the same columns as used in these queries in the query yourself.
117
+	 *
118
+	 * @var EE_Default_Where_Conditions
119
+	 */
120
+	protected $_default_where_conditions_strategy;
121
+
122
+	/**
123
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
+	 * This is particularly useful when you want something between 'none' and 'default'
125
+	 *
126
+	 * @var EE_Default_Where_Conditions
127
+	 */
128
+	protected $_minimum_where_conditions_strategy;
129
+
130
+	/**
131
+	 * String describing how to find the "owner" of this model's objects.
132
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
+	 * But when there isn't, this indicates which related model, or transiently-related model,
134
+	 * has the foreign key to the wp_users table.
135
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
+	 * related to events, and events have a foreign key to wp_users.
137
+	 * On EEM_Transaction, this would be 'Transaction.Event'
138
+	 *
139
+	 * @var string
140
+	 */
141
+	protected $_model_chain_to_wp_user = '';
142
+
143
+	/**
144
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
+	 * don't need it (particularly CPT models)
146
+	 *
147
+	 * @var bool
148
+	 */
149
+	protected $_ignore_where_strategy = false;
150
+
151
+	/**
152
+	 * String used in caps relating to this model. Eg, if the caps relating to this
153
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
+	 *
155
+	 * @var string. If null it hasn't been initialized yet. If false then we
156
+	 * have indicated capabilities don't apply to this
157
+	 */
158
+	protected $_caps_slug = null;
159
+
160
+	/**
161
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
+	 * and next-level keys are capability names, and each's value is a
163
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
165
+	 * and then each capability in the corresponding sub-array that they're missing
166
+	 * adds the where conditions onto the query.
167
+	 *
168
+	 * @var array
169
+	 */
170
+	protected $_cap_restrictions = array(
171
+		self::caps_read       => array(),
172
+		self::caps_read_admin => array(),
173
+		self::caps_edit       => array(),
174
+		self::caps_delete     => array(),
175
+	);
176
+
177
+	/**
178
+	 * Array defining which cap restriction generators to use to create default
179
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
180
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
+	 * automatically set this to false (not just null).
183
+	 *
184
+	 * @var EE_Restriction_Generator_Base[]
185
+	 */
186
+	protected $_cap_restriction_generators = array();
187
+
188
+	/**
189
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
+	 */
191
+	const caps_read       = 'read';
192
+
193
+	const caps_read_admin = 'read_admin';
194
+
195
+	const caps_edit       = 'edit';
196
+
197
+	const caps_delete     = 'delete';
198
+
199
+	/**
200
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
+	 * maps to 'read' because when looking for relevant permissions we're going to use
203
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
204
+	 *
205
+	 * @var array
206
+	 */
207
+	protected $_cap_contexts_to_cap_action_map = array(
208
+		self::caps_read       => 'read',
209
+		self::caps_read_admin => 'read',
210
+		self::caps_edit       => 'edit',
211
+		self::caps_delete     => 'delete',
212
+	);
213
+
214
+	/**
215
+	 * Timezone
216
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
+	 * EE_Datetime_Field data type will have access to it.
220
+	 *
221
+	 * @var string
222
+	 */
223
+	protected $_timezone;
224
+
225
+
226
+	/**
227
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
+	 * multisite.
229
+	 *
230
+	 * @var int
231
+	 */
232
+	protected static $_model_query_blog_id;
233
+
234
+	/**
235
+	 * A copy of _fields, except the array keys are the model names pointed to by
236
+	 * the field
237
+	 *
238
+	 * @var EE_Model_Field_Base[]
239
+	 */
240
+	private $_cache_foreign_key_to_fields = array();
241
+
242
+	/**
243
+	 * Cached list of all the fields on the model, indexed by their name
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cached_fields = null;
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, except those that are
251
+	 * marked as only pertinent to the database
252
+	 *
253
+	 * @var EE_Model_Field_Base[]
254
+	 */
255
+	private $_cached_fields_non_db_only = null;
256
+
257
+	/**
258
+	 * A cached reference to the primary key for quick lookup
259
+	 *
260
+	 * @var EE_Model_Field_Base
261
+	 */
262
+	private $_primary_key_field = null;
263
+
264
+	/**
265
+	 * Flag indicating whether this model has a primary key or not
266
+	 *
267
+	 * @var boolean
268
+	 */
269
+	protected $_has_primary_key_field = null;
270
+
271
+	/**
272
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
273
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
+	 *
275
+	 * @var boolean
276
+	 */
277
+	protected $_wp_core_model = false;
278
+
279
+	/**
280
+	 *    List of valid operators that can be used for querying.
281
+	 * The keys are all operators we'll accept, the values are the real SQL
282
+	 * operators used
283
+	 *
284
+	 * @var array
285
+	 */
286
+	protected $_valid_operators = array(
287
+		'='           => '=',
288
+		'<='          => '<=',
289
+		'<'           => '<',
290
+		'>='          => '>=',
291
+		'>'           => '>',
292
+		'!='          => '!=',
293
+		'LIKE'        => 'LIKE',
294
+		'like'        => 'LIKE',
295
+		'NOT_LIKE'    => 'NOT LIKE',
296
+		'not_like'    => 'NOT LIKE',
297
+		'NOT LIKE'    => 'NOT LIKE',
298
+		'not like'    => 'NOT LIKE',
299
+		'IN'          => 'IN',
300
+		'in'          => 'IN',
301
+		'NOT_IN'      => 'NOT IN',
302
+		'not_in'      => 'NOT IN',
303
+		'NOT IN'      => 'NOT IN',
304
+		'not in'      => 'NOT IN',
305
+		'between'     => 'BETWEEN',
306
+		'BETWEEN'     => 'BETWEEN',
307
+		'IS_NOT_NULL' => 'IS NOT NULL',
308
+		'is_not_null' => 'IS NOT NULL',
309
+		'IS NOT NULL' => 'IS NOT NULL',
310
+		'is not null' => 'IS NOT NULL',
311
+		'IS_NULL'     => 'IS NULL',
312
+		'is_null'     => 'IS NULL',
313
+		'IS NULL'     => 'IS NULL',
314
+		'is null'     => 'IS NULL',
315
+		'REGEXP'      => 'REGEXP',
316
+		'regexp'      => 'REGEXP',
317
+		'NOT_REGEXP'  => 'NOT REGEXP',
318
+		'not_regexp'  => 'NOT REGEXP',
319
+		'NOT REGEXP'  => 'NOT REGEXP',
320
+		'not regexp'  => 'NOT REGEXP',
321
+	);
322
+
323
+	/**
324
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
+	 *
326
+	 * @var array
327
+	 */
328
+	protected $_in_style_operators = array('IN', 'NOT IN');
329
+
330
+	/**
331
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
+	 * '12-31-2012'"
333
+	 *
334
+	 * @var array
335
+	 */
336
+	protected $_between_style_operators = array('BETWEEN');
337
+
338
+	/**
339
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
+	 * on a join table.
341
+	 *
342
+	 * @var array
343
+	 */
344
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
+
346
+	/**
347
+	 * Allowed values for $query_params['order'] for ordering in queries
348
+	 *
349
+	 * @var array
350
+	 */
351
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
+
353
+	/**
354
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
356
+	 *
357
+	 * @var array
358
+	 */
359
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
+
361
+	/**
362
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
364
+	 *
365
+	 * @var array
366
+	 */
367
+	private $_allowed_query_params = array(
368
+		0,
369
+		'limit',
370
+		'order_by',
371
+		'group_by',
372
+		'having',
373
+		'force_join',
374
+		'order',
375
+		'on_join_limit',
376
+		'default_where_conditions',
377
+		'caps',
378
+	);
379
+
380
+	/**
381
+	 * All the data types that can be used in $wpdb->prepare statements.
382
+	 *
383
+	 * @var array
384
+	 */
385
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
+
387
+	/**
388
+	 *    EE_Registry Object
389
+	 *
390
+	 * @var    object
391
+	 * @access    protected
392
+	 */
393
+	protected $EE = null;
394
+
395
+
396
+	/**
397
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
+	 *
399
+	 * @var int
400
+	 */
401
+	protected $_show_next_x_db_queries = 0;
402
+
403
+	/**
404
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
+	 *
407
+	 * @var array
408
+	 */
409
+	protected $_custom_selections = array();
410
+
411
+	/**
412
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
+	 * caches every model object we've fetched from the DB on this request
414
+	 *
415
+	 * @var array
416
+	 */
417
+	protected $_entity_map;
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws \EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error (
520
+				sprintf(
521
+					__('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.',
522
+						'event_espresso'),
523
+					get_class($this)
524
+				)
525
+			);
526
+		}
527
+		/**
528
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
+		 */
530
+		if (empty(EEM_Base::$_model_query_blog_id)) {
531
+			EEM_Base::set_model_query_blog_id();
532
+		}
533
+		/**
534
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
+		 * just use EE_Register_Model_Extension
536
+		 *
537
+		 * @var EE_Table_Base[] $_tables
538
+		 */
539
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+		foreach ($this->_tables as $table_alias => $table_obj) {
541
+			/** @var $table_obj EE_Table_Base */
542
+			$table_obj->_construct_finalize_with_alias($table_alias);
543
+			if ($table_obj instanceof EE_Secondary_Table) {
544
+				/** @var $table_obj EE_Secondary_Table */
545
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
+			}
547
+		}
548
+		/**
549
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
+		 * EE_Register_Model_Extension
551
+		 *
552
+		 * @param EE_Model_Field_Base[] $_fields
553
+		 */
554
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+		$this->_invalidate_field_caches();
556
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
557
+			if (! array_key_exists($table_alias, $this->_tables)) {
558
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
+			}
561
+			foreach ($fields_for_table as $field_name => $field_obj) {
562
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
+				//primary key field base has a slightly different _construct_finalize
564
+				/** @var $field_obj EE_Model_Field_Base */
565
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
+			}
567
+		}
568
+		// everything is related to Extra_Meta
569
+		if (get_class($this) !== 'EEM_Extra_Meta') {
570
+			//make extra meta related to everything, but don't block deleting things just
571
+			//because they have related extra meta info. For now just orphan those extra meta
572
+			//in the future we should automatically delete them
573
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		//and change logs
576
+		if (get_class($this) !== 'EEM_Change_Log') {
577
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		/**
580
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
+		 * EE_Register_Model_Extension
582
+		 *
583
+		 * @param EE_Model_Relation_Base[] $_model_relations
584
+		 */
585
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+			$this->_model_relations);
587
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
588
+			/** @var $relation_obj EE_Model_Relation_Base */
589
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
+		}
591
+		foreach ($this->_indexes as $index_name => $index_obj) {
592
+			/** @var $index_obj EE_Index */
593
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
+		}
595
+		$this->set_timezone($timezone);
596
+		//finalize default where condition strategy, or set default
597
+		if (! $this->_default_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
602
+		if (! $this->_minimum_where_conditions_strategy) {
603
+			//nothing was set during child constructor, so set default
604
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
+		}
606
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
608
+		//to indicate to NOT set it, set it to the logical default
609
+		if ($this->_caps_slug === null) {
610
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
+		}
612
+		//initialize the standard cap restriction generators if none were specified by the child constructor
613
+		if ($this->_cap_restriction_generators !== false) {
614
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
617
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
+						new EE_Restriction_Generator_Protected(),
619
+						$cap_context,
620
+						$this
621
+					);
622
+				}
623
+			}
624
+		}
625
+		//if there are cap restriction generators, use them to make the default cap restrictions
626
+		if ($this->_cap_restriction_generators !== false) {
627
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
+				if (! $generator_object) {
629
+					continue;
630
+				}
631
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+					throw new EE_Error(
633
+						sprintf(
634
+							__('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.',
635
+								'event_espresso'),
636
+							$context,
637
+							$this->get_this_model_name()
638
+						)
639
+					);
640
+				}
641
+				$action = $this->cap_action_for_context($context);
642
+				if (! $generator_object->construction_finalized()) {
643
+					$generator_object->_construct_finalize($this, $action);
644
+				}
645
+			}
646
+		}
647
+		do_action('AHEE__' . get_class($this) . '__construct__end');
648
+	}
649
+
650
+
651
+
652
+	/**
653
+	 * Generates the cap restrictions for the given context, or if they were
654
+	 * already generated just gets what's cached
655
+	 *
656
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
657
+	 * @return EE_Default_Where_Conditions[]
658
+	 */
659
+	protected function _generate_cap_restrictions($context)
660
+	{
661
+		if (isset($this->_cap_restriction_generators[$context])
662
+			&& $this->_cap_restriction_generators[$context]
663
+			   instanceof
664
+			   EE_Restriction_Generator_Base
665
+		) {
666
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
+		} else {
668
+			return array();
669
+		}
670
+	}
671
+
672
+
673
+
674
+	/**
675
+	 * Used to set the $_model_query_blog_id static property.
676
+	 *
677
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
+	 *                      value for get_current_blog_id() will be used.
679
+	 */
680
+	public static function set_model_query_blog_id($blog_id = 0)
681
+	{
682
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
+	}
684
+
685
+
686
+
687
+	/**
688
+	 * Returns whatever is set as the internal $model_query_blog_id.
689
+	 *
690
+	 * @return int
691
+	 */
692
+	public static function get_model_query_blog_id()
693
+	{
694
+		return EEM_Base::$_model_query_blog_id;
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 *        This function is a singleton method used to instantiate the Espresso_model object
701
+	 *
702
+	 * @access public
703
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
+	 *                         timezone in the 'timezone_string' wp option)
707
+	 * @return static (as in the concrete child class)
708
+	 */
709
+	public static function instance($timezone = null)
710
+	{
711
+		// check if instance of Espresso_model already exists
712
+		if (! static::$_instance instanceof static) {
713
+			// instantiate Espresso_model
714
+			static::$_instance = new static($timezone);
715
+		}
716
+		//we might have a timezone set, let set_timezone decide what to do with it
717
+		static::$_instance->set_timezone($timezone);
718
+		// Espresso_model object
719
+		return static::$_instance;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * resets the model and returns it
726
+	 *
727
+	 * @param null | string $timezone
728
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
+	 * all its properties reset; if it wasn't instantiated, returns null)
730
+	 */
731
+	public static function reset($timezone = null)
732
+	{
733
+		if (static::$_instance instanceof EEM_Base) {
734
+			//let's try to NOT swap out the current instance for a new one
735
+			//because if someone has a reference to it, we can't remove their reference
736
+			//so it's best to keep using the same reference, but change the original object
737
+			//reset all its properties to their original values as defined in the class
738
+			$r = new ReflectionClass(get_class(static::$_instance));
739
+			$static_properties = $r->getStaticProperties();
740
+			foreach ($r->getDefaultProperties() as $property => $value) {
741
+				//don't set instance to null like it was originally,
742
+				//but it's static anyways, and we're ignoring static properties (for now at least)
743
+				if (! isset($static_properties[$property])) {
744
+					static::$_instance->{$property} = $value;
745
+				}
746
+			}
747
+			//and then directly call its constructor again, like we would if we
748
+			//were creating a new one
749
+			static::$_instance->__construct($timezone);
750
+			return self::instance();
751
+		}
752
+		return null;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
+	 *
760
+	 * @param  boolean $translated return localized strings or JUST the array.
761
+	 * @return array
762
+	 * @throws \EE_Error
763
+	 */
764
+	public function status_array($translated = false)
765
+	{
766
+		if (! array_key_exists('Status', $this->_model_relations)) {
767
+			return array();
768
+		}
769
+		$model_name = $this->get_this_model_name();
770
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
+		$status_array = array();
773
+		foreach ($stati as $status) {
774
+			$status_array[$status->ID()] = $status->get('STS_code');
775
+		}
776
+		return $translated
777
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
+			: $status_array;
779
+	}
780
+
781
+
782
+
783
+	/**
784
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
+	 *
786
+	 * @param array $query_params             {
787
+	 * @var array $0 (where) array {
788
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
+	 *                                        conditions based on related models (and even
792
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
793
+	 *                                        name. Eg,
794
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
+	 *                                        to Venues (even when each of those models actually consisted of two
802
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
803
+	 *                                        just having
804
+	 *                                        "Venue.VNU_ID", you could have
805
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
+	 *                                        events are related to Registrations, which are related to Attendees). You
807
+	 *                                        can take it even further with
808
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
+	 *                                        (from the default of '='), change the value to an numerically-indexed
810
+	 *                                        array, where the first item in the list is the operator. eg: array(
811
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
819
+	 *                                        the value is a field, simply provide a third array item (true) to the
820
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
+	 *                                        Note: you can also use related model field names like you would any other
823
+	 *                                        field name. eg:
824
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
+	 *                                        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__>' =>
826
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
833
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
+	 *                                        "stick" until you specify an AND. eg
835
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
+	 *                                        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 >>
840
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
+	 *                                        too, eg:
843
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
848
+	 *                                        the OFFSET, the 2nd is the LIMIT
849
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
+	 *                                        following format array('on_join_limit'
852
+	 *                                        => array( 'table_alias', array(1,2) ) ).
853
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
+	 *                                        values are either 'ASC' or 'DESC'.
855
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
+	 *                                        DESC..." respectively. Like the
858
+	 *                                        'where' conditions, these fields can be on related models. Eg
859
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
861
+	 *                                        Attendee, Price, Datetime, etc.)
862
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
864
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
+	 *                                        order by the primary key. Eg,
867
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
869
+	 *                                        DTT_EVT_start) or
870
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
+	 *                                        'group_by'=>'VNU_ID', or
874
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
+	 *                                        if no
876
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
877
+	 *                                        model's primary key (or combined primary keys). This avoids some
878
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
879
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
+	 *                                        results)
883
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
+	 *                                        array where values are models to be joined in the query.Eg
885
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
887
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
888
+	 *                                        related models which belongs to the current model
889
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
890
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
891
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
894
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
896
+	 *                                        this model's default where conditions added to the query, use
897
+	 *                                        'this_model_only'. If you want to use all default where conditions
898
+	 *                                        (default), set to 'all'.
899
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
+	 *                                        everything? Or should we only show the current user items they should be
902
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
+	 *                                        }
905
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
+	 *                                        array( array(
911
+	 *                                        'OR'=>array(
912
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
+	 *                                        )
915
+	 *                                        ),
916
+	 *                                        'limit'=>10,
917
+	 *                                        'group_by'=>'TXN_ID'
918
+	 *                                        ));
919
+	 *                                        get all the answers to the question titled "shirt size" for event with id
920
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
+	 *                                        'Question.QST_display_text'=>'shirt size',
922
+	 *                                        'Registration.Event.EVT_ID'=>12
923
+	 *                                        ),
924
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
925
+	 *                                        ));
926
+	 * @throws \EE_Error
927
+	 */
928
+	public function get_all($query_params = array())
929
+	{
930
+		if (isset($query_params['limit'])
931
+			&& ! isset($query_params['group_by'])
932
+		) {
933
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
+		}
935
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
+	}
937
+
938
+
939
+
940
+	/**
941
+	 * Modifies the query parameters so we only get back model objects
942
+	 * that "belong" to the current user
943
+	 *
944
+	 * @param array $query_params @see EEM_Base::get_all()
945
+	 * @return array like EEM_Base::get_all
946
+	 */
947
+	public function alter_query_params_to_only_include_mine($query_params = array())
948
+	{
949
+		$wp_user_field_name = $this->wp_user_field_name();
950
+		if ($wp_user_field_name) {
951
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
952
+		}
953
+		return $query_params;
954
+	}
955
+
956
+
957
+
958
+	/**
959
+	 * Returns the name of the field's name that points to the WP_User table
960
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
+	 * foreign key to the WP_User table)
962
+	 *
963
+	 * @return string|boolean string on success, boolean false when there is no
964
+	 * foreign key to the WP_User table
965
+	 */
966
+	public function wp_user_field_name()
967
+	{
968
+		try {
969
+			if (! empty($this->_model_chain_to_wp_user)) {
970
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
+				$last_model_name = end($models_to_follow_to_wp_users);
972
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
+			} else {
975
+				$model_with_fk_to_wp_users = $this;
976
+				$model_chain_to_wp_user = '';
977
+			}
978
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
980
+		} catch (EE_Error $e) {
981
+			return false;
982
+		}
983
+	}
984
+
985
+
986
+
987
+	/**
988
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
989
+	 * (or transiently-related model) has a foreign key to the wp_users table;
990
+	 * useful for finding if model objects of this type are 'owned' by the current user.
991
+	 * This is an empty string when the foreign key is on this model and when it isn't,
992
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
993
+	 * (or transiently-related model)
994
+	 *
995
+	 * @return string
996
+	 */
997
+	public function model_chain_to_wp_user()
998
+	{
999
+		return $this->_model_chain_to_wp_user;
1000
+	}
1001
+
1002
+
1003
+
1004
+	/**
1005
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
+	 * like how registrations don't have a foreign key to wp_users, but the
1007
+	 * events they are for are), or is unrelated to wp users.
1008
+	 * generally available
1009
+	 *
1010
+	 * @return boolean
1011
+	 */
1012
+	public function is_owned()
1013
+	{
1014
+		if ($this->model_chain_to_wp_user()) {
1015
+			return true;
1016
+		} else {
1017
+			try {
1018
+				$this->get_foreign_key_to('WP_User');
1019
+				return true;
1020
+			} catch (EE_Error $e) {
1021
+				return false;
1022
+			}
1023
+		}
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
+	 * the model)
1032
+	 *
1033
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1037
+	 *                                  override this and set the select to "*", or a specific column name, like
1038
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
+	 *                                  the aliases used to refer to this selection, and values are to be
1041
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
+	 * @throws \EE_Error
1045
+	 */
1046
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
+	{
1048
+		// remember the custom selections, if any, and type cast as array
1049
+		// (unless $columns_to_select is an object, then just set as an empty array)
1050
+		// Note: (array) 'some string' === array( 'some string' )
1051
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
+		$select_expressions = $columns_to_select !== null
1054
+			? $this->_construct_select_from_input($columns_to_select)
1055
+			: $this->_construct_default_select_sql($model_query_info);
1056
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
+	}
1059
+
1060
+
1061
+
1062
+	/**
1063
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1064
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
+	 * take care of joins, field preparation etc.
1066
+	 *
1067
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1071
+	 *                                  override this and set the select to "*", or a specific column name, like
1072
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
+	 *                                  the aliases used to refer to this selection, and values are to be
1075
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
+	 * @throws \EE_Error
1079
+	 */
1080
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
+	{
1082
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
+	}
1084
+
1085
+
1086
+
1087
+	/**
1088
+	 * For creating a custom select statement
1089
+	 *
1090
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
+	 *                                 SQL, and 1=>is the datatype
1093
+	 * @throws EE_Error
1094
+	 * @return string
1095
+	 */
1096
+	private function _construct_select_from_input($columns_to_select)
1097
+	{
1098
+		if (is_array($columns_to_select)) {
1099
+			$select_sql_array = array();
1100
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
+					throw new EE_Error(
1103
+						sprintf(
1104
+							__(
1105
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
+								"event_espresso"
1107
+							),
1108
+							$selection_and_datatype,
1109
+							$alias
1110
+						)
1111
+					);
1112
+				}
1113
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
+					throw new EE_Error(
1115
+						sprintf(
1116
+							__(
1117
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
+								"event_espresso"
1119
+							),
1120
+							$selection_and_datatype[1],
1121
+							$selection_and_datatype[0],
1122
+							$alias,
1123
+							implode(",", $this->_valid_wpdb_data_types)
1124
+						)
1125
+					);
1126
+				}
1127
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
+			}
1129
+			$columns_to_select_string = implode(", ", $select_sql_array);
1130
+		} else {
1131
+			$columns_to_select_string = $columns_to_select;
1132
+		}
1133
+		return $columns_to_select_string;
1134
+	}
1135
+
1136
+
1137
+
1138
+	/**
1139
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
+	 *
1141
+	 * @return string
1142
+	 * @throws \EE_Error
1143
+	 */
1144
+	public function primary_key_name()
1145
+	{
1146
+		return $this->get_primary_key_field()->get_name();
1147
+	}
1148
+
1149
+
1150
+
1151
+	/**
1152
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
+	 * If there is no primary key on this model, $id is treated as primary key string
1154
+	 *
1155
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1156
+	 * @return EE_Base_Class
1157
+	 */
1158
+	public function get_one_by_ID($id)
1159
+	{
1160
+		if ($this->get_from_entity_map($id)) {
1161
+			return $this->get_from_entity_map($id);
1162
+		}
1163
+		return $this->get_one(
1164
+			$this->alter_query_params_to_restrict_by_ID(
1165
+				$id,
1166
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
+			)
1168
+		);
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Alters query parameters to only get items with this ID are returned.
1175
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
+	 * or could just be a simple primary key ID
1177
+	 *
1178
+	 * @param int   $id
1179
+	 * @param array $query_params
1180
+	 * @return array of normal query params, @see EEM_Base::get_all
1181
+	 * @throws \EE_Error
1182
+	 */
1183
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
+	{
1185
+		if (! isset($query_params[0])) {
1186
+			$query_params[0] = array();
1187
+		}
1188
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1189
+		if ($conditions_from_id === null) {
1190
+			$query_params[0][$this->primary_key_name()] = $id;
1191
+		} else {
1192
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1193
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
+		}
1195
+		return $query_params;
1196
+	}
1197
+
1198
+
1199
+
1200
+	/**
1201
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
+	 * array. If no item is found, null is returned.
1203
+	 *
1204
+	 * @param array $query_params like EEM_Base's $query_params variable.
1205
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
+	 * @throws \EE_Error
1207
+	 */
1208
+	public function get_one($query_params = array())
1209
+	{
1210
+		if (! is_array($query_params)) {
1211
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
+					gettype($query_params)), '4.6.0');
1214
+			$query_params = array();
1215
+		}
1216
+		$query_params['limit'] = 1;
1217
+		$items = $this->get_all($query_params);
1218
+		if (empty($items)) {
1219
+			return null;
1220
+		} else {
1221
+			return array_shift($items);
1222
+		}
1223
+	}
1224
+
1225
+
1226
+
1227
+	/**
1228
+	 * Returns the next x number of items in sequence from the given value as
1229
+	 * found in the database matching the given query conditions.
1230
+	 *
1231
+	 * @param mixed $current_field_value    Value used for the reference point.
1232
+	 * @param null  $field_to_order_by      What field is used for the
1233
+	 *                                      reference point.
1234
+	 * @param int   $limit                  How many to return.
1235
+	 * @param array $query_params           Extra conditions on the query.
1236
+	 * @param null  $columns_to_select      If left null, then an array of
1237
+	 *                                      EE_Base_Class objects is returned,
1238
+	 *                                      otherwise you can indicate just the
1239
+	 *                                      columns you want returned.
1240
+	 * @return EE_Base_Class[]|array
1241
+	 * @throws \EE_Error
1242
+	 */
1243
+	public function next_x(
1244
+		$current_field_value,
1245
+		$field_to_order_by = null,
1246
+		$limit = 1,
1247
+		$query_params = array(),
1248
+		$columns_to_select = null
1249
+	) {
1250
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
+			$columns_to_select);
1252
+	}
1253
+
1254
+
1255
+
1256
+	/**
1257
+	 * Returns the previous x number of items in sequence from the given value
1258
+	 * as found in the database matching the given query conditions.
1259
+	 *
1260
+	 * @param mixed $current_field_value    Value used for the reference point.
1261
+	 * @param null  $field_to_order_by      What field is used for the
1262
+	 *                                      reference point.
1263
+	 * @param int   $limit                  How many to return.
1264
+	 * @param array $query_params           Extra conditions on the query.
1265
+	 * @param null  $columns_to_select      If left null, then an array of
1266
+	 *                                      EE_Base_Class objects is returned,
1267
+	 *                                      otherwise you can indicate just the
1268
+	 *                                      columns you want returned.
1269
+	 * @return EE_Base_Class[]|array
1270
+	 * @throws \EE_Error
1271
+	 */
1272
+	public function previous_x(
1273
+		$current_field_value,
1274
+		$field_to_order_by = null,
1275
+		$limit = 1,
1276
+		$query_params = array(),
1277
+		$columns_to_select = null
1278
+	) {
1279
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
+			$columns_to_select);
1281
+	}
1282
+
1283
+
1284
+
1285
+	/**
1286
+	 * Returns the next item in sequence from the given value as found in the
1287
+	 * database matching the given query conditions.
1288
+	 *
1289
+	 * @param mixed $current_field_value    Value used for the reference point.
1290
+	 * @param null  $field_to_order_by      What field is used for the
1291
+	 *                                      reference point.
1292
+	 * @param array $query_params           Extra conditions on the query.
1293
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
+	 *                                      object is returned, otherwise you
1295
+	 *                                      can indicate just the columns you
1296
+	 *                                      want and a single array indexed by
1297
+	 *                                      the columns will be returned.
1298
+	 * @return EE_Base_Class|null|array()
1299
+	 * @throws \EE_Error
1300
+	 */
1301
+	public function next(
1302
+		$current_field_value,
1303
+		$field_to_order_by = null,
1304
+		$query_params = array(),
1305
+		$columns_to_select = null
1306
+	) {
1307
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
+			$columns_to_select);
1309
+		return empty($results) ? null : reset($results);
1310
+	}
1311
+
1312
+
1313
+
1314
+	/**
1315
+	 * Returns the previous item in sequence from the given value as found in
1316
+	 * the database matching the given query conditions.
1317
+	 *
1318
+	 * @param mixed $current_field_value    Value used for the reference point.
1319
+	 * @param null  $field_to_order_by      What field is used for the
1320
+	 *                                      reference point.
1321
+	 * @param array $query_params           Extra conditions on the query.
1322
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
+	 *                                      object is returned, otherwise you
1324
+	 *                                      can indicate just the columns you
1325
+	 *                                      want and a single array indexed by
1326
+	 *                                      the columns will be returned.
1327
+	 * @return EE_Base_Class|null|array()
1328
+	 * @throws EE_Error
1329
+	 */
1330
+	public function previous(
1331
+		$current_field_value,
1332
+		$field_to_order_by = null,
1333
+		$query_params = array(),
1334
+		$columns_to_select = null
1335
+	) {
1336
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
+			$columns_to_select);
1338
+		return empty($results) ? null : reset($results);
1339
+	}
1340
+
1341
+
1342
+
1343
+	/**
1344
+	 * Returns the a consecutive number of items in sequence from the given
1345
+	 * value as found in the database matching the given query conditions.
1346
+	 *
1347
+	 * @param mixed  $current_field_value   Value used for the reference point.
1348
+	 * @param string $operand               What operand is used for the sequence.
1349
+	 * @param string $field_to_order_by     What field is used for the reference point.
1350
+	 * @param int    $limit                 How many to return.
1351
+	 * @param array  $query_params          Extra conditions on the query.
1352
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
+	 *                                      otherwise you can indicate just the columns you want returned.
1354
+	 * @return EE_Base_Class[]|array
1355
+	 * @throws EE_Error
1356
+	 */
1357
+	protected function _get_consecutive(
1358
+		$current_field_value,
1359
+		$operand = '>',
1360
+		$field_to_order_by = null,
1361
+		$limit = 1,
1362
+		$query_params = array(),
1363
+		$columns_to_select = null
1364
+	) {
1365
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
+		if (empty($field_to_order_by)) {
1367
+			if ($this->has_primary_key_field()) {
1368
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1369
+			} else {
1370
+				if (WP_DEBUG) {
1371
+					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).',
1372
+						'event_espresso'));
1373
+				}
1374
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
+				return array();
1376
+			}
1377
+		}
1378
+		if (! is_array($query_params)) {
1379
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
+					gettype($query_params)), '4.6.0');
1382
+			$query_params = array();
1383
+		}
1384
+		//let's add the where query param for consecutive look up.
1385
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
+		$query_params['limit'] = $limit;
1387
+		//set direction
1388
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
+		$query_params['order_by'] = $operand === '>'
1390
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
+		if (empty($columns_to_select)) {
1394
+			return $this->get_all($query_params);
1395
+		} else {
1396
+			//getting just the fields
1397
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
+		}
1399
+	}
1400
+
1401
+
1402
+
1403
+	/**
1404
+	 * This sets the _timezone property after model object has been instantiated.
1405
+	 *
1406
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
+	 */
1408
+	public function set_timezone($timezone)
1409
+	{
1410
+		if ($timezone !== null) {
1411
+			$this->_timezone = $timezone;
1412
+		}
1413
+		//note we need to loop through relations and set the timezone on those objects as well.
1414
+		foreach ($this->_model_relations as $relation) {
1415
+			$relation->set_timezone($timezone);
1416
+		}
1417
+		//and finally we do the same for any datetime fields
1418
+		foreach ($this->_fields as $field) {
1419
+			if ($field instanceof EE_Datetime_Field) {
1420
+				$field->set_timezone($timezone);
1421
+			}
1422
+		}
1423
+	}
1424
+
1425
+
1426
+
1427
+	/**
1428
+	 * This just returns whatever is set for the current timezone.
1429
+	 *
1430
+	 * @access public
1431
+	 * @return string
1432
+	 */
1433
+	public function get_timezone()
1434
+	{
1435
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
+		if (empty($this->_timezone)) {
1437
+			foreach ($this->_fields as $field) {
1438
+				if ($field instanceof EE_Datetime_Field) {
1439
+					$this->set_timezone($field->get_timezone());
1440
+					break;
1441
+				}
1442
+			}
1443
+		}
1444
+		//if timezone STILL empty then return the default timezone for the site.
1445
+		if (empty($this->_timezone)) {
1446
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
+		}
1448
+		return $this->_timezone;
1449
+	}
1450
+
1451
+
1452
+
1453
+	/**
1454
+	 * This returns the date formats set for the given field name and also ensures that
1455
+	 * $this->_timezone property is set correctly.
1456
+	 *
1457
+	 * @since 4.6.x
1458
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1459
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
+	 * @return array formats in an array with the date format first, and the time format last.
1462
+	 */
1463
+	public function get_formats_for($field_name, $pretty = false)
1464
+	{
1465
+		$field_settings = $this->field_settings_for($field_name);
1466
+		//if not a valid EE_Datetime_Field then throw error
1467
+		if (! $field_settings instanceof EE_Datetime_Field) {
1468
+			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.',
1469
+				'event_espresso'), $field_name));
1470
+		}
1471
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
+		//the field.
1473
+		$this->_timezone = $field_settings->get_timezone();
1474
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
+	}
1476
+
1477
+
1478
+
1479
+	/**
1480
+	 * This returns the current time in a format setup for a query on this model.
1481
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
+	 * it will return:
1483
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
+	 *  NOW
1485
+	 *  - or a unix timestamp (equivalent to time())
1486
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1487
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1488
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1489
+	 * @since 4.6.x
1490
+	 * @param string $field_name       The field the current time is needed for.
1491
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1492
+	 *                                 formatted string matching the set format for the field in the set timezone will
1493
+	 *                                 be returned.
1494
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1495
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1496
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497
+	 *                                 exception is triggered.
1498
+	 */
1499
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1500
+	{
1501
+		$formats = $this->get_formats_for($field_name);
1502
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1503
+		if ($timestamp) {
1504
+			return $DateTime->format('U');
1505
+		}
1506
+		//not returning timestamp, so return formatted string in timezone.
1507
+		switch ($what) {
1508
+			case 'time' :
1509
+				return $DateTime->format($formats[1]);
1510
+				break;
1511
+			case 'date' :
1512
+				return $DateTime->format($formats[0]);
1513
+				break;
1514
+			default :
1515
+				return $DateTime->format(implode(' ', $formats));
1516
+				break;
1517
+		}
1518
+	}
1519
+
1520
+
1521
+
1522
+	/**
1523
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1524
+	 * for the model are.  Returns a DateTime object.
1525
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1526
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1527
+	 * ignored.
1528
+	 *
1529
+	 * @param string $field_name      The field being setup.
1530
+	 * @param string $timestring      The date time string being used.
1531
+	 * @param string $incoming_format The format for the time string.
1532
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1533
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1534
+	 *                                format is
1535
+	 *                                'U', this is ignored.
1536
+	 * @return DateTime
1537
+	 * @throws \EE_Error
1538
+	 */
1539
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1540
+	{
1541
+		//just using this to ensure the timezone is set correctly internally
1542
+		$this->get_formats_for($field_name);
1543
+		//load EEH_DTT_Helper
1544
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1545
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1546
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1547
+	}
1548
+
1549
+
1550
+
1551
+	/**
1552
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1553
+	 *
1554
+	 * @return EE_Table_Base[]
1555
+	 */
1556
+	public function get_tables()
1557
+	{
1558
+		return $this->_tables;
1559
+	}
1560
+
1561
+
1562
+
1563
+	/**
1564
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1565
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1566
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1567
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1568
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1569
+	 * model object with EVT_ID = 1
1570
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1571
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1572
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1573
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1574
+	 * are not specified)
1575
+	 *
1576
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1577
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1578
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1579
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1580
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1581
+	 *                                         ID=34, we'd use this method as follows:
1582
+	 *                                         EEM_Transaction::instance()->update(
1583
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1584
+	 *                                         array(array('TXN_ID'=>34)));
1585
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1586
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1587
+	 *                                         consider updating Question's QST_admin_label field is of type
1588
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1589
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1590
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1591
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1592
+	 *                                         TRUE, it is assumed that you've already called
1593
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1594
+	 *                                         malicious javascript. However, if
1595
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1596
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1597
+	 *                                         and every other field, before insertion. We provide this parameter
1598
+	 *                                         because model objects perform their prepare_for_set function on all
1599
+	 *                                         their values, and so don't need to be called again (and in many cases,
1600
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1601
+	 *                                         prepare_for_set method...)
1602
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1603
+	 *                                         in this model's entity map according to $fields_n_values that match
1604
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1605
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1606
+	 *                                         could get out-of-sync with the database
1607
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1608
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1609
+	 *                                         bad)
1610
+	 * @throws \EE_Error
1611
+	 */
1612
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1613
+	{
1614
+		if (! is_array($query_params)) {
1615
+			EE_Error::doing_it_wrong('EEM_Base::update',
1616
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1617
+					gettype($query_params)), '4.6.0');
1618
+			$query_params = array();
1619
+		}
1620
+		/**
1621
+		 * Action called before a model update call has been made.
1622
+		 *
1623
+		 * @param EEM_Base $model
1624
+		 * @param array    $fields_n_values the updated fields and their new values
1625
+		 * @param array    $query_params    @see EEM_Base::get_all()
1626
+		 */
1627
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1628
+		/**
1629
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1630
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1631
+		 *
1632
+		 * @param array    $fields_n_values fields and their new values
1633
+		 * @param EEM_Base $model           the model being queried
1634
+		 * @param array    $query_params    see EEM_Base::get_all()
1635
+		 */
1636
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1637
+			$query_params);
1638
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1639
+		//to do that, for each table, verify that it's PK isn't null.
1640
+		$tables = $this->get_tables();
1641
+		//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
1642
+		//NOTE: we should make this code more efficient by NOT querying twice
1643
+		//before the real update, but that needs to first go through ALPHA testing
1644
+		//as it's dangerous. says Mike August 8 2014
1645
+		//we want to make sure the default_where strategy is ignored
1646
+		$this->_ignore_where_strategy = true;
1647
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1648
+		foreach ($wpdb_select_results as $wpdb_result) {
1649
+			// type cast stdClass as array
1650
+			$wpdb_result = (array)$wpdb_result;
1651
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1652
+			if ($this->has_primary_key_field()) {
1653
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1654
+			} else {
1655
+				//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)
1656
+				$main_table_pk_value = null;
1657
+			}
1658
+			//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
1659
+			//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
1660
+			if (count($tables) > 1) {
1661
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1662
+				//in that table, and so we'll want to insert one
1663
+				foreach ($tables as $table_obj) {
1664
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1665
+					//if there is no private key for this table on the results, it means there's no entry
1666
+					//in this table, right? so insert a row in the current table, using any fields available
1667
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1668
+						   && $wpdb_result[$this_table_pk_column])
1669
+					) {
1670
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1671
+							$main_table_pk_value);
1672
+						//if we died here, report the error
1673
+						if (! $success) {
1674
+							return false;
1675
+						}
1676
+					}
1677
+				}
1678
+			}
1679
+			//				//and now check that if we have cached any models by that ID on the model, that
1680
+			//				//they also get updated properly
1681
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1682
+			//				if( $model_object ){
1683
+			//					foreach( $fields_n_values as $field => $value ){
1684
+			//						$model_object->set($field, $value);
1685
+			//let's make sure default_where strategy is followed now
1686
+			$this->_ignore_where_strategy = false;
1687
+		}
1688
+		//if we want to keep model objects in sync, AND
1689
+		//if this wasn't called from a model object (to update itself)
1690
+		//then we want to make sure we keep all the existing
1691
+		//model objects in sync with the db
1692
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1693
+			if ($this->has_primary_key_field()) {
1694
+				$model_objs_affected_ids = $this->get_col($query_params);
1695
+			} else {
1696
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1697
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1698
+				$model_objs_affected_ids = array();
1699
+				foreach ($models_affected_key_columns as $row) {
1700
+					$combined_index_key = $this->get_index_primary_key_string($row);
1701
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1702
+				}
1703
+			}
1704
+			if (! $model_objs_affected_ids) {
1705
+				//wait wait wait- if nothing was affected let's stop here
1706
+				return 0;
1707
+			}
1708
+			foreach ($model_objs_affected_ids as $id) {
1709
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1710
+				if ($model_obj_in_entity_map) {
1711
+					foreach ($fields_n_values as $field => $new_value) {
1712
+						$model_obj_in_entity_map->set($field, $new_value);
1713
+					}
1714
+				}
1715
+			}
1716
+			//if there is a primary key on this model, we can now do a slight optimization
1717
+			if ($this->has_primary_key_field()) {
1718
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1719
+				$query_params = array(
1720
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1721
+					'limit'                    => count($model_objs_affected_ids),
1722
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1723
+				);
1724
+			}
1725
+		}
1726
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1727
+		$SQL = "UPDATE "
1728
+			   . $model_query_info->get_full_join_sql()
1729
+			   . " SET "
1730
+			   . $this->_construct_update_sql($fields_n_values)
1731
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1732
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1733
+		/**
1734
+		 * Action called after a model update call has been made.
1735
+		 *
1736
+		 * @param EEM_Base $model
1737
+		 * @param array    $fields_n_values the updated fields and their new values
1738
+		 * @param array    $query_params    @see EEM_Base::get_all()
1739
+		 * @param int      $rows_affected
1740
+		 */
1741
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1742
+		return $rows_affected;//how many supposedly got updated
1743
+	}
1744
+
1745
+
1746
+
1747
+	/**
1748
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1749
+	 * are teh values of the field specified (or by default the primary key field)
1750
+	 * that matched the query params. Note that you should pass the name of the
1751
+	 * model FIELD, not the database table's column name.
1752
+	 *
1753
+	 * @param array  $query_params @see EEM_Base::get_all()
1754
+	 * @param string $field_to_select
1755
+	 * @return array just like $wpdb->get_col()
1756
+	 * @throws \EE_Error
1757
+	 */
1758
+	public function get_col($query_params = array(), $field_to_select = null)
1759
+	{
1760
+		if ($field_to_select) {
1761
+			$field = $this->field_settings_for($field_to_select);
1762
+		} elseif ($this->has_primary_key_field()) {
1763
+			$field = $this->get_primary_key_field();
1764
+		} else {
1765
+			//no primary key, just grab the first column
1766
+			$field = reset($this->field_settings());
1767
+		}
1768
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1769
+		$select_expressions = $field->get_qualified_column();
1770
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1771
+		return $this->_do_wpdb_query('get_col', array($SQL));
1772
+	}
1773
+
1774
+
1775
+
1776
+	/**
1777
+	 * Returns a single column value for a single row from the database
1778
+	 *
1779
+	 * @param array  $query_params    @see EEM_Base::get_all()
1780
+	 * @param string $field_to_select @see EEM_Base::get_col()
1781
+	 * @return string
1782
+	 * @throws \EE_Error
1783
+	 */
1784
+	public function get_var($query_params = array(), $field_to_select = null)
1785
+	{
1786
+		$query_params['limit'] = 1;
1787
+		$col = $this->get_col($query_params, $field_to_select);
1788
+		if (! empty($col)) {
1789
+			return reset($col);
1790
+		} else {
1791
+			return null;
1792
+		}
1793
+	}
1794
+
1795
+
1796
+
1797
+	/**
1798
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1799
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1800
+	 * injection, but currently no further filtering is done
1801
+	 *
1802
+	 * @global      $wpdb
1803
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1804
+	 *                               be updated to in the DB
1805
+	 * @return string of SQL
1806
+	 * @throws \EE_Error
1807
+	 */
1808
+	public function _construct_update_sql($fields_n_values)
1809
+	{
1810
+		/** @type WPDB $wpdb */
1811
+		global $wpdb;
1812
+		$cols_n_values = array();
1813
+		foreach ($fields_n_values as $field_name => $value) {
1814
+			$field_obj = $this->field_settings_for($field_name);
1815
+			//if the value is NULL, we want to assign the value to that.
1816
+			//wpdb->prepare doesn't really handle that properly
1817
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1818
+			$value_sql = $prepared_value === null ? 'NULL'
1819
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1820
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1821
+		}
1822
+		return implode(",", $cols_n_values);
1823
+	}
1824
+
1825
+
1826
+
1827
+	/**
1828
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1829
+	 * Performs a HARD delete, meaning the database row should always be removed,
1830
+	 * not just have a flag field on it switched
1831
+	 * Wrapper for EEM_Base::delete_permanently()
1832
+	 *
1833
+	 * @param mixed $id
1834
+	 * @return boolean whether the row got deleted or not
1835
+	 * @throws \EE_Error
1836
+	 */
1837
+	public function delete_permanently_by_ID($id)
1838
+	{
1839
+		return $this->delete_permanently(
1840
+			array(
1841
+				array($this->get_primary_key_field()->get_name() => $id),
1842
+				'limit' => 1,
1843
+			)
1844
+		);
1845
+	}
1846
+
1847
+
1848
+
1849
+	/**
1850
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
+	 * Wrapper for EEM_Base::delete()
1852
+	 *
1853
+	 * @param mixed $id
1854
+	 * @return boolean whether the row got deleted or not
1855
+	 * @throws \EE_Error
1856
+	 */
1857
+	public function delete_by_ID($id)
1858
+	{
1859
+		return $this->delete(
1860
+			array(
1861
+				array($this->get_primary_key_field()->get_name() => $id),
1862
+				'limit' => 1,
1863
+			)
1864
+		);
1865
+	}
1866
+
1867
+
1868
+
1869
+	/**
1870
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1871
+	 * meaning if the model has a field that indicates its been "trashed" or
1872
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1873
+	 *
1874
+	 * @see EEM_Base::delete_permanently
1875
+	 * @param array   $query_params
1876
+	 * @param boolean $allow_blocking
1877
+	 * @return int how many rows got deleted
1878
+	 * @throws \EE_Error
1879
+	 */
1880
+	public function delete($query_params, $allow_blocking = true)
1881
+	{
1882
+		return $this->delete_permanently($query_params, $allow_blocking);
1883
+	}
1884
+
1885
+
1886
+
1887
+	/**
1888
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1889
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1890
+	 * as archived, not actually deleted
1891
+	 *
1892
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1893
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1894
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1895
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1896
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1897
+	 *                                DB
1898
+	 * @return int how many rows got deleted
1899
+	 * @throws \EE_Error
1900
+	 */
1901
+	public function delete_permanently($query_params, $allow_blocking = true)
1902
+	{
1903
+		/**
1904
+		 * Action called just before performing a real deletion query. You can use the
1905
+		 * model and its $query_params to find exactly which items will be deleted
1906
+		 *
1907
+		 * @param EEM_Base $model
1908
+		 * @param array    $query_params   @see EEM_Base::get_all()
1909
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1910
+		 *                                 to block (prevent) this deletion
1911
+		 */
1912
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1913
+		//some MySQL databases may be running safe mode, which may restrict
1914
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1915
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1916
+		//to delete them
1917
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1918
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1919
+		if ($deletion_where) {
1920
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1921
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1922
+			$table_aliases = array_keys($this->_tables);
1923
+			$SQL = "DELETE "
1924
+				   . implode(", ", $table_aliases)
1925
+				   . " FROM "
1926
+				   . $model_query_info->get_full_join_sql()
1927
+				   . " WHERE "
1928
+				   . $deletion_where;
1929
+			//		/echo "delete sql:$SQL";
1930
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1931
+		} else {
1932
+			$rows_deleted = 0;
1933
+		}
1934
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1935
+		if ($this->has_primary_key_field()) {
1936
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1937
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1938
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1939
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1940
+				}
1941
+			}
1942
+		}
1943
+		/**
1944
+		 * Action called just after performing a real deletion query. Although at this point the
1945
+		 * items should have been deleted
1946
+		 *
1947
+		 * @param EEM_Base $model
1948
+		 * @param array    $query_params @see EEM_Base::get_all()
1949
+		 * @param int      $rows_deleted
1950
+		 */
1951
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1952
+		return $rows_deleted;//how many supposedly got deleted
1953
+	}
1954
+
1955
+
1956
+
1957
+	/**
1958
+	 * Checks all the relations that throw error messages when there are blocking related objects
1959
+	 * for related model objects. If there are any related model objects on those relations,
1960
+	 * adds an EE_Error, and return true
1961
+	 *
1962
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1963
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1964
+	 *                                                 should be ignored when determining whether there are related
1965
+	 *                                                 model objects which block this model object's deletion. Useful
1966
+	 *                                                 if you know A is related to B and are considering deleting A,
1967
+	 *                                                 but want to see if A has any other objects blocking its deletion
1968
+	 *                                                 before removing the relation between A and B
1969
+	 * @return boolean
1970
+	 * @throws \EE_Error
1971
+	 */
1972
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1973
+	{
1974
+		//first, if $ignore_this_model_obj was supplied, get its model
1975
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1976
+			$ignored_model = $ignore_this_model_obj->get_model();
1977
+		} else {
1978
+			$ignored_model = null;
1979
+		}
1980
+		//now check all the relations of $this_model_obj_or_id and see if there
1981
+		//are any related model objects blocking it?
1982
+		$is_blocked = false;
1983
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1984
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1985
+				//if $ignore_this_model_obj was supplied, then for the query
1986
+				//on that model needs to be told to ignore $ignore_this_model_obj
1987
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1988
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1989
+						array(
1990
+							$ignored_model->get_primary_key_field()->get_name() => array(
1991
+								'!=',
1992
+								$ignore_this_model_obj->ID(),
1993
+							),
1994
+						),
1995
+					));
1996
+				} else {
1997
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1998
+				}
1999
+				if ($related_model_objects) {
2000
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2001
+					$is_blocked = true;
2002
+				}
2003
+			}
2004
+		}
2005
+		return $is_blocked;
2006
+	}
2007
+
2008
+
2009
+
2010
+	/**
2011
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2012
+	 * well.
2013
+	 *
2014
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2015
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2016
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
2017
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
2018
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
2019
+	 *                                      easily corrupt your DB
2020
+	 * @throws EE_Error
2021
+	 * @return string    everything that comes after the WHERE statement.
2022
+	 */
2023
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2024
+	{
2025
+		if ($this->has_primary_key_field()) {
2026
+			$primary_table = $this->_get_main_table();
2027
+			$other_tables = $this->_get_other_tables();
2028
+			$deletes = $query = array();
2029
+			foreach ($objects_for_deletion as $delete_object) {
2030
+				//before we mark this object for deletion,
2031
+				//make sure there's no related objects blocking its deletion (if we're checking)
2032
+				if (
2033
+					$allow_blocking
2034
+					&& $this->delete_is_blocked_by_related_models(
2035
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
2036
+					)
2037
+				) {
2038
+					continue;
2039
+				}
2040
+				//primary table deletes
2041
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2042
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2043
+				}
2044
+				//other tables
2045
+				if (! empty($other_tables)) {
2046
+					foreach ($other_tables as $ot) {
2047
+						//first check if we've got the foreign key column here.
2048
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2049
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2050
+						}
2051
+						// wait! it's entirely possible that we'll have a the primary key
2052
+						// for this table in here, if it's a foreign key for one of the other secondary tables
2053
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2054
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2055
+						}
2056
+						// finally, it is possible that the fk for this table is found
2057
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
2058
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2059
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2060
+						}
2061
+					}
2062
+				}
2063
+			}
2064
+			//we should have deletes now, so let's just go through and setup the where statement
2065
+			foreach ($deletes as $column => $values) {
2066
+				//make sure we have unique $values;
2067
+				$values = array_unique($values);
2068
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
2069
+			}
2070
+			return ! empty($query) ? implode(' AND ', $query) : '';
2071
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2072
+			$ways_to_identify_a_row = array();
2073
+			$fields = $this->get_combined_primary_key_fields();
2074
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2075
+			foreach ($objects_for_deletion as $delete_object) {
2076
+				$values_for_each_cpk_for_a_row = array();
2077
+				foreach ($fields as $cpk_field) {
2078
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2079
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2080
+														   . "="
2081
+														   . $delete_object[$cpk_field->get_qualified_column()];
2082
+					}
2083
+				}
2084
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2085
+			}
2086
+			return implode(" OR ", $ways_to_identify_a_row);
2087
+		} else {
2088
+			//so there's no primary key and no combined key...
2089
+			//sorry, can't help you
2090
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2091
+				"event_espresso"), get_class($this)));
2092
+		}
2093
+	}
2094
+
2095
+
2096
+
2097
+	/**
2098
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2099
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2100
+	 * column
2101
+	 *
2102
+	 * @param array  $query_params   like EEM_Base::get_all's
2103
+	 * @param string $field_to_count field on model to count by (not column name)
2104
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2105
+	 *                               that by the setting $distinct to TRUE;
2106
+	 * @return int
2107
+	 * @throws \EE_Error
2108
+	 */
2109
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2110
+	{
2111
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2112
+		if ($field_to_count) {
2113
+			$field_obj = $this->field_settings_for($field_to_count);
2114
+			$column_to_count = $field_obj->get_qualified_column();
2115
+		} elseif ($this->has_primary_key_field()) {
2116
+			$pk_field_obj = $this->get_primary_key_field();
2117
+			$column_to_count = $pk_field_obj->get_qualified_column();
2118
+		} else {
2119
+			//there's no primary key
2120
+			//if we're counting distinct items, and there's no primary key,
2121
+			//we need to list out the columns for distinction;
2122
+			//otherwise we can just use star
2123
+			if ($distinct) {
2124
+				$columns_to_use = array();
2125
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2126
+					$columns_to_use[] = $field_obj->get_qualified_column();
2127
+				}
2128
+				$column_to_count = implode(',', $columns_to_use);
2129
+			} else {
2130
+				$column_to_count = '*';
2131
+			}
2132
+		}
2133
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2134
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2135
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2136
+	}
2137
+
2138
+
2139
+
2140
+	/**
2141
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2142
+	 *
2143
+	 * @param array  $query_params like EEM_Base::get_all
2144
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2145
+	 * @return float
2146
+	 * @throws \EE_Error
2147
+	 */
2148
+	public function sum($query_params, $field_to_sum = null)
2149
+	{
2150
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2151
+		if ($field_to_sum) {
2152
+			$field_obj = $this->field_settings_for($field_to_sum);
2153
+		} else {
2154
+			$field_obj = $this->get_primary_key_field();
2155
+		}
2156
+		$column_to_count = $field_obj->get_qualified_column();
2157
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2158
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2159
+		$data_type = $field_obj->get_wpdb_data_type();
2160
+		if ($data_type === '%d' || $data_type === '%s') {
2161
+			return (float)$return_value;
2162
+		} else {//must be %f
2163
+			return (float)$return_value;
2164
+		}
2165
+	}
2166
+
2167
+
2168
+
2169
+	/**
2170
+	 * Just calls the specified method on $wpdb with the given arguments
2171
+	 * Consolidates a little extra error handling code
2172
+	 *
2173
+	 * @param string $wpdb_method
2174
+	 * @param array  $arguments_to_provide
2175
+	 * @throws EE_Error
2176
+	 * @global wpdb  $wpdb
2177
+	 * @return mixed
2178
+	 */
2179
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2180
+	{
2181
+		//if we're in maintenance mode level 2, DON'T run any queries
2182
+		//because level 2 indicates the database needs updating and
2183
+		//is probably out of sync with the code
2184
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2185
+			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.",
2186
+				"event_espresso")));
2187
+		}
2188
+		/** @type WPDB $wpdb */
2189
+		global $wpdb;
2190
+		if (! method_exists($wpdb, $wpdb_method)) {
2191
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2192
+				'event_espresso'), $wpdb_method));
2193
+		}
2194
+		if (WP_DEBUG) {
2195
+			$old_show_errors_value = $wpdb->show_errors;
2196
+			$wpdb->show_errors(false);
2197
+		}
2198
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2199
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2200
+		if (WP_DEBUG) {
2201
+			$wpdb->show_errors($old_show_errors_value);
2202
+			if (! empty($wpdb->last_error)) {
2203
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2204
+			} elseif ($result === false) {
2205
+				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"',
2206
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2207
+			}
2208
+		} elseif ($result === false) {
2209
+			EE_Error::add_error(
2210
+				sprintf(
2211
+					__('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"',
2212
+						'event_espresso'),
2213
+					$wpdb_method,
2214
+					var_export($arguments_to_provide, true),
2215
+					$wpdb->last_error
2216
+				),
2217
+				__FILE__,
2218
+				__FUNCTION__,
2219
+				__LINE__
2220
+			);
2221
+		}
2222
+		return $result;
2223
+	}
2224
+
2225
+
2226
+
2227
+	/**
2228
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2229
+	 * and if there's an error tries to verify the DB is correct. Uses
2230
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2231
+	 * we should try to fix the EE core db, the addons, or just give up
2232
+	 *
2233
+	 * @param string $wpdb_method
2234
+	 * @param array  $arguments_to_provide
2235
+	 * @return mixed
2236
+	 */
2237
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2238
+	{
2239
+		/** @type WPDB $wpdb */
2240
+		global $wpdb;
2241
+		$wpdb->last_error = null;
2242
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2243
+		// was there an error running the query? but we don't care on new activations
2244
+		// (we're going to setup the DB anyway on new activations)
2245
+		if (($result === false || ! empty($wpdb->last_error))
2246
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2247
+		) {
2248
+			switch (EEM_Base::$_db_verification_level) {
2249
+				case EEM_Base::db_verified_none :
2250
+					// let's double-check core's DB
2251
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2252
+					break;
2253
+				case EEM_Base::db_verified_core :
2254
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2255
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2256
+					break;
2257
+				case EEM_Base::db_verified_addons :
2258
+					// ummmm... you in trouble
2259
+					return $result;
2260
+					break;
2261
+			}
2262
+			if (! empty($error_message)) {
2263
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2264
+				trigger_error($error_message);
2265
+			}
2266
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2267
+		}
2268
+		return $result;
2269
+	}
2270
+
2271
+
2272
+
2273
+	/**
2274
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2275
+	 * EEM_Base::$_db_verification_level
2276
+	 *
2277
+	 * @param string $wpdb_method
2278
+	 * @param array  $arguments_to_provide
2279
+	 * @return string
2280
+	 */
2281
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2282
+	{
2283
+		/** @type WPDB $wpdb */
2284
+		global $wpdb;
2285
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2286
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2287
+		$error_message = sprintf(
2288
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2289
+				'event_espresso'),
2290
+			$wpdb->last_error,
2291
+			$wpdb_method,
2292
+			wp_json_encode($arguments_to_provide)
2293
+		);
2294
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2295
+		return $error_message;
2296
+	}
2297
+
2298
+
2299
+
2300
+	/**
2301
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2302
+	 * EEM_Base::$_db_verification_level
2303
+	 *
2304
+	 * @param $wpdb_method
2305
+	 * @param $arguments_to_provide
2306
+	 * @return string
2307
+	 */
2308
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2309
+	{
2310
+		/** @type WPDB $wpdb */
2311
+		global $wpdb;
2312
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2313
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2314
+		$error_message = sprintf(
2315
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2316
+				'event_espresso'),
2317
+			$wpdb->last_error,
2318
+			$wpdb_method,
2319
+			wp_json_encode($arguments_to_provide)
2320
+		);
2321
+		EE_System::instance()->initialize_addons();
2322
+		return $error_message;
2323
+	}
2324
+
2325
+
2326
+
2327
+	/**
2328
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2329
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2330
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2331
+	 * ..."
2332
+	 *
2333
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2334
+	 * @return string
2335
+	 */
2336
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2337
+	{
2338
+		return " FROM " . $model_query_info->get_full_join_sql() .
2339
+			   $model_query_info->get_where_sql() .
2340
+			   $model_query_info->get_group_by_sql() .
2341
+			   $model_query_info->get_having_sql() .
2342
+			   $model_query_info->get_order_by_sql() .
2343
+			   $model_query_info->get_limit_sql();
2344
+	}
2345
+
2346
+
2347
+
2348
+	/**
2349
+	 * Set to easily debug the next X queries ran from this model.
2350
+	 *
2351
+	 * @param int $count
2352
+	 */
2353
+	public function show_next_x_db_queries($count = 1)
2354
+	{
2355
+		$this->_show_next_x_db_queries = $count;
2356
+	}
2357
+
2358
+
2359
+
2360
+	/**
2361
+	 * @param $sql_query
2362
+	 */
2363
+	public function show_db_query_if_previously_requested($sql_query)
2364
+	{
2365
+		if ($this->_show_next_x_db_queries > 0) {
2366
+			echo $sql_query;
2367
+			$this->_show_next_x_db_queries--;
2368
+		}
2369
+	}
2370
+
2371
+
2372
+
2373
+	/**
2374
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2375
+	 * There are the 3 cases:
2376
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2377
+	 * $otherModelObject has no ID, it is first saved.
2378
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2379
+	 * has no ID, it is first saved.
2380
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2381
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2382
+	 * join table
2383
+	 *
2384
+	 * @param        EE_Base_Class                     /int $thisModelObject
2385
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2386
+	 * @param string $relationName                     , key in EEM_Base::_relations
2387
+	 *                                                 an attendee to a group, you also want to specify which role they
2388
+	 *                                                 will have in that group. So you would use this parameter to
2389
+	 *                                                 specify array('role-column-name'=>'role-id')
2390
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2391
+	 *                                                 to for relation to methods that allow you to further specify
2392
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2393
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2394
+	 *                                                 because these will be inserted in any new rows created as well.
2395
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2396
+	 * @throws \EE_Error
2397
+	 */
2398
+	public function add_relationship_to(
2399
+		$id_or_obj,
2400
+		$other_model_id_or_obj,
2401
+		$relationName,
2402
+		$extra_join_model_fields_n_values = array()
2403
+	) {
2404
+		$relation_obj = $this->related_settings_for($relationName);
2405
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2406
+	}
2407
+
2408
+
2409
+
2410
+	/**
2411
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2412
+	 * There are the 3 cases:
2413
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2414
+	 * error
2415
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2416
+	 * an error
2417
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2418
+	 *
2419
+	 * @param        EE_Base_Class /int $id_or_obj
2420
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2421
+	 * @param string $relationName key in EEM_Base::_relations
2422
+	 * @return boolean of success
2423
+	 * @throws \EE_Error
2424
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2425
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2426
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2427
+	 *                             because these will be inserted in any new rows created as well.
2428
+	 */
2429
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2430
+	{
2431
+		$relation_obj = $this->related_settings_for($relationName);
2432
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2433
+	}
2434
+
2435
+
2436
+
2437
+	/**
2438
+	 * @param mixed           $id_or_obj
2439
+	 * @param string          $relationName
2440
+	 * @param array           $where_query_params
2441
+	 * @param EE_Base_Class[] objects to which relations were removed
2442
+	 * @return \EE_Base_Class[]
2443
+	 * @throws \EE_Error
2444
+	 */
2445
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2446
+	{
2447
+		$relation_obj = $this->related_settings_for($relationName);
2448
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2449
+	}
2450
+
2451
+
2452
+
2453
+	/**
2454
+	 * Gets all the related items of the specified $model_name, using $query_params.
2455
+	 * Note: by default, we remove the "default query params"
2456
+	 * because we want to get even deleted items etc.
2457
+	 *
2458
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2459
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2460
+	 * @param array  $query_params like EEM_Base::get_all
2461
+	 * @return EE_Base_Class[]
2462
+	 * @throws \EE_Error
2463
+	 */
2464
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2465
+	{
2466
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2467
+		$relation_settings = $this->related_settings_for($model_name);
2468
+		return $relation_settings->get_all_related($model_obj, $query_params);
2469
+	}
2470
+
2471
+
2472
+
2473
+	/**
2474
+	 * Deletes all the model objects across the relation indicated by $model_name
2475
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2476
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2477
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2478
+	 *
2479
+	 * @param EE_Base_Class|int|string $id_or_obj
2480
+	 * @param string                   $model_name
2481
+	 * @param array                    $query_params
2482
+	 * @return int how many deleted
2483
+	 * @throws \EE_Error
2484
+	 */
2485
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2486
+	{
2487
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2488
+		$relation_settings = $this->related_settings_for($model_name);
2489
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2490
+	}
2491
+
2492
+
2493
+
2494
+	/**
2495
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2496
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2497
+	 * the model objects can't be hard deleted because of blocking related model objects,
2498
+	 * just does a soft-delete on them instead.
2499
+	 *
2500
+	 * @param EE_Base_Class|int|string $id_or_obj
2501
+	 * @param string                   $model_name
2502
+	 * @param array                    $query_params
2503
+	 * @return int how many deleted
2504
+	 * @throws \EE_Error
2505
+	 */
2506
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2507
+	{
2508
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2509
+		$relation_settings = $this->related_settings_for($model_name);
2510
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2511
+	}
2512
+
2513
+
2514
+
2515
+	/**
2516
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2517
+	 * unless otherwise specified in the $query_params
2518
+	 *
2519
+	 * @param        int             /EE_Base_Class $id_or_obj
2520
+	 * @param string $model_name     like 'Event', or 'Registration'
2521
+	 * @param array  $query_params   like EEM_Base::get_all's
2522
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2523
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2524
+	 *                               that by the setting $distinct to TRUE;
2525
+	 * @return int
2526
+	 * @throws \EE_Error
2527
+	 */
2528
+	public function count_related(
2529
+		$id_or_obj,
2530
+		$model_name,
2531
+		$query_params = array(),
2532
+		$field_to_count = null,
2533
+		$distinct = false
2534
+	) {
2535
+		$related_model = $this->get_related_model_obj($model_name);
2536
+		//we're just going to use the query params on the related model's normal get_all query,
2537
+		//except add a condition to say to match the current mod
2538
+		if (! isset($query_params['default_where_conditions'])) {
2539
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2540
+		}
2541
+		$this_model_name = $this->get_this_model_name();
2542
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2543
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2544
+		return $related_model->count($query_params, $field_to_count, $distinct);
2545
+	}
2546
+
2547
+
2548
+
2549
+	/**
2550
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2551
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2552
+	 *
2553
+	 * @param        int           /EE_Base_Class $id_or_obj
2554
+	 * @param string $model_name   like 'Event', or 'Registration'
2555
+	 * @param array  $query_params like EEM_Base::get_all's
2556
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2557
+	 * @return float
2558
+	 * @throws \EE_Error
2559
+	 */
2560
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2561
+	{
2562
+		$related_model = $this->get_related_model_obj($model_name);
2563
+		if (! is_array($query_params)) {
2564
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2565
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2566
+					gettype($query_params)), '4.6.0');
2567
+			$query_params = array();
2568
+		}
2569
+		//we're just going to use the query params on the related model's normal get_all query,
2570
+		//except add a condition to say to match the current mod
2571
+		if (! isset($query_params['default_where_conditions'])) {
2572
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2573
+		}
2574
+		$this_model_name = $this->get_this_model_name();
2575
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2576
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2577
+		return $related_model->sum($query_params, $field_to_sum);
2578
+	}
2579
+
2580
+
2581
+
2582
+	/**
2583
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2584
+	 * $modelObject
2585
+	 *
2586
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2587
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2588
+	 * @param array               $query_params     like EEM_Base::get_all's
2589
+	 * @return EE_Base_Class
2590
+	 * @throws \EE_Error
2591
+	 */
2592
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2593
+	{
2594
+		$query_params['limit'] = 1;
2595
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2596
+		if ($results) {
2597
+			return array_shift($results);
2598
+		} else {
2599
+			return null;
2600
+		}
2601
+	}
2602
+
2603
+
2604
+
2605
+	/**
2606
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2607
+	 *
2608
+	 * @return string
2609
+	 */
2610
+	public function get_this_model_name()
2611
+	{
2612
+		return str_replace("EEM_", "", get_class($this));
2613
+	}
2614
+
2615
+
2616
+
2617
+	/**
2618
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2619
+	 *
2620
+	 * @return EE_Any_Foreign_Model_Name_Field
2621
+	 * @throws EE_Error
2622
+	 */
2623
+	public function get_field_containing_related_model_name()
2624
+	{
2625
+		foreach ($this->field_settings(true) as $field) {
2626
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2627
+				$field_with_model_name = $field;
2628
+			}
2629
+		}
2630
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2631
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2632
+				$this->get_this_model_name()));
2633
+		}
2634
+		return $field_with_model_name;
2635
+	}
2636
+
2637
+
2638
+
2639
+	/**
2640
+	 * Inserts a new entry into the database, for each table.
2641
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2642
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2643
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2644
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2645
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2646
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2647
+	 *
2648
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2649
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2650
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2651
+	 *                              of EEM_Base)
2652
+	 * @return int new primary key on main table that got inserted
2653
+	 * @throws EE_Error
2654
+	 */
2655
+	public function insert($field_n_values)
2656
+	{
2657
+		/**
2658
+		 * Filters the fields and their values before inserting an item using the models
2659
+		 *
2660
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2661
+		 * @param EEM_Base $model           the model used
2662
+		 */
2663
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2664
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2665
+			$main_table = $this->_get_main_table();
2666
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2667
+			if ($new_id !== false) {
2668
+				foreach ($this->_get_other_tables() as $other_table) {
2669
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2670
+				}
2671
+			}
2672
+			/**
2673
+			 * Done just after attempting to insert a new model object
2674
+			 *
2675
+			 * @param EEM_Base   $model           used
2676
+			 * @param array      $fields_n_values fields and their values
2677
+			 * @param int|string the              ID of the newly-inserted model object
2678
+			 */
2679
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2680
+			return $new_id;
2681
+		} else {
2682
+			return false;
2683
+		}
2684
+	}
2685
+
2686
+
2687
+
2688
+	/**
2689
+	 * Checks that the result would satisfy the unique indexes on this model
2690
+	 *
2691
+	 * @param array  $field_n_values
2692
+	 * @param string $action
2693
+	 * @return boolean
2694
+	 * @throws \EE_Error
2695
+	 */
2696
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2697
+	{
2698
+		foreach ($this->unique_indexes() as $index_name => $index) {
2699
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2700
+			if ($this->exists(array($uniqueness_where_params))) {
2701
+				EE_Error::add_error(
2702
+					sprintf(
2703
+						__(
2704
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2705
+							"event_espresso"
2706
+						),
2707
+						$action,
2708
+						$this->_get_class_name(),
2709
+						$index_name,
2710
+						implode(",", $index->field_names()),
2711
+						http_build_query($uniqueness_where_params)
2712
+					),
2713
+					__FILE__,
2714
+					__FUNCTION__,
2715
+					__LINE__
2716
+				);
2717
+				return false;
2718
+			}
2719
+		}
2720
+		return true;
2721
+	}
2722
+
2723
+
2724
+
2725
+	/**
2726
+	 * Checks the database for an item that conflicts (ie, if this item were
2727
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2728
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2729
+	 * can be either an EE_Base_Class or an array of fields n values
2730
+	 *
2731
+	 * @param EE_Base_Class|array $obj_or_fields_array
2732
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2733
+	 *                                                 when looking for conflicts
2734
+	 *                                                 (ie, if false, we ignore the model object's primary key
2735
+	 *                                                 when finding "conflicts". If true, it's also considered).
2736
+	 *                                                 Only works for INT primary key,
2737
+	 *                                                 STRING primary keys cannot be ignored
2738
+	 * @throws EE_Error
2739
+	 * @return EE_Base_Class|array
2740
+	 */
2741
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2742
+	{
2743
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2744
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2745
+		} elseif (is_array($obj_or_fields_array)) {
2746
+			$fields_n_values = $obj_or_fields_array;
2747
+		} else {
2748
+			throw new EE_Error(
2749
+				sprintf(
2750
+					__(
2751
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2752
+						"event_espresso"
2753
+					),
2754
+					get_class($this),
2755
+					$obj_or_fields_array
2756
+				)
2757
+			);
2758
+		}
2759
+		$query_params = array();
2760
+		if ($this->has_primary_key_field()
2761
+			&& ($include_primary_key
2762
+				|| $this->get_primary_key_field()
2763
+				   instanceof
2764
+				   EE_Primary_Key_String_Field)
2765
+			&& isset($fields_n_values[$this->primary_key_name()])
2766
+		) {
2767
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2768
+		}
2769
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2770
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2771
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2772
+		}
2773
+		//if there is nothing to base this search on, then we shouldn't find anything
2774
+		if (empty($query_params)) {
2775
+			return array();
2776
+		} else {
2777
+			return $this->get_one($query_params);
2778
+		}
2779
+	}
2780
+
2781
+
2782
+
2783
+	/**
2784
+	 * Like count, but is optimized and returns a boolean instead of an int
2785
+	 *
2786
+	 * @param array $query_params
2787
+	 * @return boolean
2788
+	 * @throws \EE_Error
2789
+	 */
2790
+	public function exists($query_params)
2791
+	{
2792
+		$query_params['limit'] = 1;
2793
+		return $this->count($query_params) > 0;
2794
+	}
2795
+
2796
+
2797
+
2798
+	/**
2799
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2800
+	 *
2801
+	 * @param int|string $id
2802
+	 * @return boolean
2803
+	 * @throws \EE_Error
2804
+	 */
2805
+	public function exists_by_ID($id)
2806
+	{
2807
+		return $this->exists(
2808
+			array(
2809
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2810
+				array(
2811
+					$this->primary_key_name() => $id,
2812
+				),
2813
+			)
2814
+		);
2815
+	}
2816
+
2817
+
2818
+
2819
+	/**
2820
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2821
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2822
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2823
+	 * on the main table)
2824
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2825
+	 * cases where we want to call it directly rather than via insert().
2826
+	 *
2827
+	 * @access   protected
2828
+	 * @param EE_Table_Base $table
2829
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2830
+	 *                                       float
2831
+	 * @param int           $new_id          for now we assume only int keys
2832
+	 * @throws EE_Error
2833
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2834
+	 * @return int ID of new row inserted, or FALSE on failure
2835
+	 */
2836
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2837
+	{
2838
+		global $wpdb;
2839
+		$insertion_col_n_values = array();
2840
+		$format_for_insertion = array();
2841
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2842
+		foreach ($fields_on_table as $field_name => $field_obj) {
2843
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2844
+			if ($field_obj->is_auto_increment()) {
2845
+				continue;
2846
+			}
2847
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2848
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2849
+			if ($prepared_value !== null) {
2850
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2851
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2852
+			}
2853
+		}
2854
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2855
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2856
+			//so add the fk to the main table as a column
2857
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2858
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2859
+		}
2860
+		//insert the new entry
2861
+		$result = $this->_do_wpdb_query('insert',
2862
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2863
+		if ($result === false) {
2864
+			return false;
2865
+		}
2866
+		//ok, now what do we return for the ID of the newly-inserted thing?
2867
+		if ($this->has_primary_key_field()) {
2868
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2869
+				return $wpdb->insert_id;
2870
+			} else {
2871
+				//it's not an auto-increment primary key, so
2872
+				//it must have been supplied
2873
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2874
+			}
2875
+		} else {
2876
+			//we can't return a  primary key because there is none. instead return
2877
+			//a unique string indicating this model
2878
+			return $this->get_index_primary_key_string($fields_n_values);
2879
+		}
2880
+	}
2881
+
2882
+
2883
+
2884
+	/**
2885
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2886
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2887
+	 * and there is no default, we pass it along. WPDB will take care of it)
2888
+	 *
2889
+	 * @param EE_Model_Field_Base $field_obj
2890
+	 * @param array               $fields_n_values
2891
+	 * @return mixed string|int|float depending on what the table column will be expecting
2892
+	 * @throws \EE_Error
2893
+	 */
2894
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2895
+	{
2896
+		//if this field doesn't allow nullable, don't allow it
2897
+		if (
2898
+			! $field_obj->is_nullable()
2899
+			&& (
2900
+				! isset($fields_n_values[$field_obj->get_name()])
2901
+				|| $fields_n_values[$field_obj->get_name()] === null
2902
+			)
2903
+		) {
2904
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2905
+		}
2906
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2907
+			? $fields_n_values[$field_obj->get_name()]
2908
+			: null;
2909
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2910
+	}
2911
+
2912
+
2913
+
2914
+	/**
2915
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2916
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2917
+	 * the field's prepare_for_set() method.
2918
+	 *
2919
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2920
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2921
+	 *                                   top of file)
2922
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2923
+	 *                                   $value is a custom selection
2924
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2925
+	 */
2926
+	private function _prepare_value_for_use_in_db($value, $field)
2927
+	{
2928
+		if ($field && $field instanceof EE_Model_Field_Base) {
2929
+			switch ($this->_values_already_prepared_by_model_object) {
2930
+				/** @noinspection PhpMissingBreakStatementInspection */
2931
+				case self::not_prepared_by_model_object:
2932
+					$value = $field->prepare_for_set($value);
2933
+				//purposefully left out "return"
2934
+				case self::prepared_by_model_object:
2935
+					$value = $field->prepare_for_use_in_db($value);
2936
+				case self::prepared_for_use_in_db:
2937
+					//leave the value alone
2938
+			}
2939
+			return $value;
2940
+		} else {
2941
+			return $value;
2942
+		}
2943
+	}
2944
+
2945
+
2946
+
2947
+	/**
2948
+	 * Returns the main table on this model
2949
+	 *
2950
+	 * @return EE_Primary_Table
2951
+	 * @throws EE_Error
2952
+	 */
2953
+	protected function _get_main_table()
2954
+	{
2955
+		foreach ($this->_tables as $table) {
2956
+			if ($table instanceof EE_Primary_Table) {
2957
+				return $table;
2958
+			}
2959
+		}
2960
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2961
+			'event_espresso'), get_class($this)));
2962
+	}
2963
+
2964
+
2965
+
2966
+	/**
2967
+	 * table
2968
+	 * returns EE_Primary_Table table name
2969
+	 *
2970
+	 * @return string
2971
+	 * @throws \EE_Error
2972
+	 */
2973
+	public function table()
2974
+	{
2975
+		return $this->_get_main_table()->get_table_name();
2976
+	}
2977
+
2978
+
2979
+
2980
+	/**
2981
+	 * table
2982
+	 * returns first EE_Secondary_Table table name
2983
+	 *
2984
+	 * @return string
2985
+	 */
2986
+	public function second_table()
2987
+	{
2988
+		// grab second table from tables array
2989
+		$second_table = end($this->_tables);
2990
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2991
+	}
2992
+
2993
+
2994
+
2995
+	/**
2996
+	 * get_table_obj_by_alias
2997
+	 * returns table name given it's alias
2998
+	 *
2999
+	 * @param string $table_alias
3000
+	 * @return EE_Primary_Table | EE_Secondary_Table
3001
+	 */
3002
+	public function get_table_obj_by_alias($table_alias = '')
3003
+	{
3004
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3005
+	}
3006
+
3007
+
3008
+
3009
+	/**
3010
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3011
+	 *
3012
+	 * @return EE_Secondary_Table[]
3013
+	 */
3014
+	protected function _get_other_tables()
3015
+	{
3016
+		$other_tables = array();
3017
+		foreach ($this->_tables as $table_alias => $table) {
3018
+			if ($table instanceof EE_Secondary_Table) {
3019
+				$other_tables[$table_alias] = $table;
3020
+			}
3021
+		}
3022
+		return $other_tables;
3023
+	}
3024
+
3025
+
3026
+
3027
+	/**
3028
+	 * Finds all the fields that correspond to the given table
3029
+	 *
3030
+	 * @param string $table_alias , array key in EEM_Base::_tables
3031
+	 * @return EE_Model_Field_Base[]
3032
+	 */
3033
+	public function _get_fields_for_table($table_alias)
3034
+	{
3035
+		return $this->_fields[$table_alias];
3036
+	}
3037
+
3038
+
3039
+
3040
+	/**
3041
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3042
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3043
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3044
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3045
+	 * related Registration, Transaction, and Payment models.
3046
+	 *
3047
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3048
+	 * @return EE_Model_Query_Info_Carrier
3049
+	 * @throws \EE_Error
3050
+	 */
3051
+	public function _extract_related_models_from_query($query_params)
3052
+	{
3053
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3054
+		if (array_key_exists(0, $query_params)) {
3055
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3056
+		}
3057
+		if (array_key_exists('group_by', $query_params)) {
3058
+			if (is_array($query_params['group_by'])) {
3059
+				$this->_extract_related_models_from_sub_params_array_values(
3060
+					$query_params['group_by'],
3061
+					$query_info_carrier,
3062
+					'group_by'
3063
+				);
3064
+			} elseif (! empty ($query_params['group_by'])) {
3065
+				$this->_extract_related_model_info_from_query_param(
3066
+					$query_params['group_by'],
3067
+					$query_info_carrier,
3068
+					'group_by'
3069
+				);
3070
+			}
3071
+		}
3072
+		if (array_key_exists('having', $query_params)) {
3073
+			$this->_extract_related_models_from_sub_params_array_keys(
3074
+				$query_params[0],
3075
+				$query_info_carrier,
3076
+				'having'
3077
+			);
3078
+		}
3079
+		if (array_key_exists('order_by', $query_params)) {
3080
+			if (is_array($query_params['order_by'])) {
3081
+				$this->_extract_related_models_from_sub_params_array_keys(
3082
+					$query_params['order_by'],
3083
+					$query_info_carrier,
3084
+					'order_by'
3085
+				);
3086
+			} elseif (! empty($query_params['order_by'])) {
3087
+				$this->_extract_related_model_info_from_query_param(
3088
+					$query_params['order_by'],
3089
+					$query_info_carrier,
3090
+					'order_by'
3091
+				);
3092
+			}
3093
+		}
3094
+		if (array_key_exists('force_join', $query_params)) {
3095
+			$this->_extract_related_models_from_sub_params_array_values(
3096
+				$query_params['force_join'],
3097
+				$query_info_carrier,
3098
+				'force_join'
3099
+			);
3100
+		}
3101
+		return $query_info_carrier;
3102
+	}
3103
+
3104
+
3105
+
3106
+	/**
3107
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3108
+	 *
3109
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3110
+	 *                                                      $query_params['having']
3111
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3112
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3113
+	 * @throws EE_Error
3114
+	 * @return \EE_Model_Query_Info_Carrier
3115
+	 */
3116
+	private function _extract_related_models_from_sub_params_array_keys(
3117
+		$sub_query_params,
3118
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3119
+		$query_param_type
3120
+	) {
3121
+		if (! empty($sub_query_params)) {
3122
+			$sub_query_params = (array)$sub_query_params;
3123
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3124
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3125
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3126
+					$query_param_type);
3127
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3128
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3129
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3130
+				//of array('Registration.TXN_ID'=>23)
3131
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3132
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3133
+					if (! is_array($possibly_array_of_params)) {
3134
+						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'))",
3135
+							"event_espresso"),
3136
+							$param, $possibly_array_of_params));
3137
+					} else {
3138
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3139
+							$model_query_info_carrier, $query_param_type);
3140
+					}
3141
+				} elseif ($query_param_type === 0 //ie WHERE
3142
+						  && is_array($possibly_array_of_params)
3143
+						  && isset($possibly_array_of_params[2])
3144
+						  && $possibly_array_of_params[2] == true
3145
+				) {
3146
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3147
+					//indicating that $possible_array_of_params[1] is actually a field name,
3148
+					//from which we should extract query parameters!
3149
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3150
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3151
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3152
+					}
3153
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3154
+						$model_query_info_carrier, $query_param_type);
3155
+				}
3156
+			}
3157
+		}
3158
+		return $model_query_info_carrier;
3159
+	}
3160
+
3161
+
3162
+
3163
+	/**
3164
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3165
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3166
+	 *
3167
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3168
+	 *                                                      $query_params['having']
3169
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3170
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3171
+	 * @throws EE_Error
3172
+	 * @return \EE_Model_Query_Info_Carrier
3173
+	 */
3174
+	private function _extract_related_models_from_sub_params_array_values(
3175
+		$sub_query_params,
3176
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3177
+		$query_param_type
3178
+	) {
3179
+		if (! empty($sub_query_params)) {
3180
+			if (! is_array($sub_query_params)) {
3181
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3182
+					$sub_query_params));
3183
+			}
3184
+			foreach ($sub_query_params as $param) {
3185
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3186
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3187
+					$query_param_type);
3188
+			}
3189
+		}
3190
+		return $model_query_info_carrier;
3191
+	}
3192
+
3193
+
3194
+
3195
+	/**
3196
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3197
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3198
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3199
+	 * but use them in a different order. Eg, we need to know what models we are querying
3200
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3201
+	 * other models before we can finalize the where clause SQL.
3202
+	 *
3203
+	 * @param array $query_params
3204
+	 * @throws EE_Error
3205
+	 * @return EE_Model_Query_Info_Carrier
3206
+	 */
3207
+	public function _create_model_query_info_carrier($query_params)
3208
+	{
3209
+		if (! is_array($query_params)) {
3210
+			EE_Error::doing_it_wrong(
3211
+				'EEM_Base::_create_model_query_info_carrier',
3212
+				sprintf(
3213
+					__(
3214
+						'$query_params should be an array, you passed a variable of type %s',
3215
+						'event_espresso'
3216
+					),
3217
+					gettype($query_params)
3218
+				),
3219
+				'4.6.0'
3220
+			);
3221
+			$query_params = array();
3222
+		}
3223
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3224
+		//first check if we should alter the query to account for caps or not
3225
+		//because the caps might require us to do extra joins
3226
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3227
+			$query_params[0] = $where_query_params = array_replace_recursive(
3228
+				$where_query_params,
3229
+				$this->caps_where_conditions(
3230
+					$query_params['caps']
3231
+				)
3232
+			);
3233
+		}
3234
+		$query_object = $this->_extract_related_models_from_query($query_params);
3235
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3236
+		foreach ($where_query_params as $key => $value) {
3237
+			if (is_int($key)) {
3238
+				throw new EE_Error(
3239
+					sprintf(
3240
+						__(
3241
+							"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.",
3242
+							"event_espresso"
3243
+						),
3244
+						$key,
3245
+						var_export($value, true),
3246
+						var_export($query_params, true),
3247
+						get_class($this)
3248
+					)
3249
+				);
3250
+			}
3251
+		}
3252
+		if (
3253
+			array_key_exists('default_where_conditions', $query_params)
3254
+			&& ! empty($query_params['default_where_conditions'])
3255
+		) {
3256
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3257
+		} else {
3258
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3259
+		}
3260
+		$where_query_params = array_merge(
3261
+			$this->_get_default_where_conditions_for_models_in_query(
3262
+				$query_object,
3263
+				$use_default_where_conditions,
3264
+				$where_query_params
3265
+			),
3266
+			$where_query_params
3267
+		);
3268
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3269
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3270
+		// So we need to setup a subquery and use that for the main join.
3271
+		// Note for now this only works on the primary table for the model.
3272
+		// So for instance, you could set the limit array like this:
3273
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3274
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3275
+			$query_object->set_main_model_join_sql(
3276
+				$this->_construct_limit_join_select(
3277
+					$query_params['on_join_limit'][0],
3278
+					$query_params['on_join_limit'][1]
3279
+				)
3280
+			);
3281
+		}
3282
+		//set limit
3283
+		if (array_key_exists('limit', $query_params)) {
3284
+			if (is_array($query_params['limit'])) {
3285
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3286
+					$e = sprintf(
3287
+						__(
3288
+							"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)",
3289
+							"event_espresso"
3290
+						),
3291
+						http_build_query($query_params['limit'])
3292
+					);
3293
+					throw new EE_Error($e . "|" . $e);
3294
+				}
3295
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3296
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3297
+			} elseif (! empty ($query_params['limit'])) {
3298
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3299
+			}
3300
+		}
3301
+		//set order by
3302
+		if (array_key_exists('order_by', $query_params)) {
3303
+			if (is_array($query_params['order_by'])) {
3304
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3305
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3306
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3307
+				if (array_key_exists('order', $query_params)) {
3308
+					throw new EE_Error(
3309
+						sprintf(
3310
+							__(
3311
+								"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 ",
3312
+								"event_espresso"
3313
+							),
3314
+							get_class($this),
3315
+							implode(", ", array_keys($query_params['order_by'])),
3316
+							implode(", ", $query_params['order_by']),
3317
+							$query_params['order']
3318
+						)
3319
+					);
3320
+				}
3321
+				$this->_extract_related_models_from_sub_params_array_keys(
3322
+					$query_params['order_by'],
3323
+					$query_object,
3324
+					'order_by'
3325
+				);
3326
+				//assume it's an array of fields to order by
3327
+				$order_array = array();
3328
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3329
+					$order = $this->_extract_order($order);
3330
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3331
+				}
3332
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3333
+			} elseif (! empty ($query_params['order_by'])) {
3334
+				$this->_extract_related_model_info_from_query_param(
3335
+					$query_params['order_by'],
3336
+					$query_object,
3337
+					'order',
3338
+					$query_params['order_by']
3339
+				);
3340
+				$order = isset($query_params['order'])
3341
+					? $this->_extract_order($query_params['order'])
3342
+					: 'DESC';
3343
+				$query_object->set_order_by_sql(
3344
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3345
+				);
3346
+			}
3347
+		}
3348
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3349
+		if (! array_key_exists('order_by', $query_params)
3350
+			&& array_key_exists('order', $query_params)
3351
+			&& ! empty($query_params['order'])
3352
+		) {
3353
+			$pk_field = $this->get_primary_key_field();
3354
+			$order = $this->_extract_order($query_params['order']);
3355
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3356
+		}
3357
+		//set group by
3358
+		if (array_key_exists('group_by', $query_params)) {
3359
+			if (is_array($query_params['group_by'])) {
3360
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3361
+				$group_by_array = array();
3362
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3363
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3364
+				}
3365
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3366
+			} elseif (! empty ($query_params['group_by'])) {
3367
+				$query_object->set_group_by_sql(
3368
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3369
+				);
3370
+			}
3371
+		}
3372
+		//set having
3373
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3374
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3375
+		}
3376
+		//now, just verify they didn't pass anything wack
3377
+		foreach ($query_params as $query_key => $query_value) {
3378
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3379
+				throw new EE_Error(
3380
+					sprintf(
3381
+						__(
3382
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3383
+							'event_espresso'
3384
+						),
3385
+						$query_key,
3386
+						get_class($this),
3387
+						//						print_r( $this->_allowed_query_params, TRUE )
3388
+						implode(',', $this->_allowed_query_params)
3389
+					)
3390
+				);
3391
+			}
3392
+		}
3393
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3394
+		if (empty($main_model_join_sql)) {
3395
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3396
+		}
3397
+		return $query_object;
3398
+	}
3399
+
3400
+
3401
+
3402
+	/**
3403
+	 * Gets the where conditions that should be imposed on the query based on the
3404
+	 * context (eg reading frontend, backend, edit or delete).
3405
+	 *
3406
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3407
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3408
+	 * @throws \EE_Error
3409
+	 */
3410
+	public function caps_where_conditions($context = self::caps_read)
3411
+	{
3412
+		EEM_Base::verify_is_valid_cap_context($context);
3413
+		$cap_where_conditions = array();
3414
+		$cap_restrictions = $this->caps_missing($context);
3415
+		/**
3416
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3417
+		 */
3418
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3419
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3420
+				$restriction_if_no_cap->get_default_where_conditions());
3421
+		}
3422
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3423
+			$cap_restrictions);
3424
+	}
3425
+
3426
+
3427
+
3428
+	/**
3429
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3430
+	 * otherwise throws an exception
3431
+	 *
3432
+	 * @param string $should_be_order_string
3433
+	 * @return string either ASC, asc, DESC or desc
3434
+	 * @throws EE_Error
3435
+	 */
3436
+	private function _extract_order($should_be_order_string)
3437
+	{
3438
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3439
+			return $should_be_order_string;
3440
+		} else {
3441
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3442
+				"event_espresso"), get_class($this), $should_be_order_string));
3443
+		}
3444
+	}
3445
+
3446
+
3447
+
3448
+	/**
3449
+	 * Looks at all the models which are included in this query, and asks each
3450
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3451
+	 * so they can be merged
3452
+	 *
3453
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3454
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3455
+	 *                                                                  'none' means NO default where conditions will
3456
+	 *                                                                  be used AT ALL during this query.
3457
+	 *                                                                  'other_models_only' means default where
3458
+	 *                                                                  conditions from other models will be used, but
3459
+	 *                                                                  not for this primary model. 'all', the default,
3460
+	 *                                                                  means default where conditions will apply as
3461
+	 *                                                                  normal
3462
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3463
+	 * @throws EE_Error
3464
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3465
+	 */
3466
+	private function _get_default_where_conditions_for_models_in_query(
3467
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3468
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3469
+		$where_query_params = array()
3470
+	) {
3471
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3472
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3473
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3474
+				"event_espresso"), $use_default_where_conditions,
3475
+				implode(", ", $allowed_used_default_where_conditions_values)));
3476
+		}
3477
+		$universal_query_params = array();
3478
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3479
+			$universal_query_params = $this->_get_default_where_conditions();
3480
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3481
+			$universal_query_params = $this->_get_minimum_where_conditions();
3482
+		}
3483
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3484
+			$related_model = $this->get_related_model_obj($model_name);
3485
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3486
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3487
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3488
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3489
+			} else {
3490
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3491
+				continue;
3492
+			}
3493
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3494
+				$related_model_universal_where_params,
3495
+				$where_query_params,
3496
+				$related_model,
3497
+				$model_relation_path
3498
+			);
3499
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3500
+				$universal_query_params,
3501
+				$overrides
3502
+			);
3503
+		}
3504
+		return $universal_query_params;
3505
+	}
3506
+
3507
+
3508
+
3509
+	/**
3510
+	 * Determines whether or not we should use default where conditions for the model in question
3511
+	 * (this model, or other related models).
3512
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3513
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3514
+	 * We should use default where conditions on related models when they requested to use default where conditions
3515
+	 * on all models, or specifically just on other related models
3516
+	 * @param      $default_where_conditions_value
3517
+	 * @param bool $for_this_model false means this is for OTHER related models
3518
+	 * @return bool
3519
+	 */
3520
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3521
+	{
3522
+		return (
3523
+				   $for_this_model
3524
+				   && in_array(
3525
+					   $default_where_conditions_value,
3526
+					   array(
3527
+						   EEM_Base::default_where_conditions_all,
3528
+						   EEM_Base::default_where_conditions_this_only,
3529
+						   EEM_Base::default_where_conditions_minimum_others,
3530
+					   ),
3531
+					   true
3532
+				   )
3533
+			   )
3534
+			   || (
3535
+				   ! $for_this_model
3536
+				   && in_array(
3537
+					   $default_where_conditions_value,
3538
+					   array(
3539
+						   EEM_Base::default_where_conditions_all,
3540
+						   EEM_Base::default_where_conditions_others_only,
3541
+					   ),
3542
+					   true
3543
+				   )
3544
+			   );
3545
+	}
3546
+
3547
+	/**
3548
+	 * Determines whether or not we should use default minimum conditions for the model in question
3549
+	 * (this model, or other related models).
3550
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3551
+	 * where conditions.
3552
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3553
+	 * on this model or others
3554
+	 * @param      $default_where_conditions_value
3555
+	 * @param bool $for_this_model false means this is for OTHER related models
3556
+	 * @return bool
3557
+	 */
3558
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3559
+	{
3560
+		return (
3561
+				   $for_this_model
3562
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3563
+			   )
3564
+			   || (
3565
+				   ! $for_this_model
3566
+				   && in_array(
3567
+					   $default_where_conditions_value,
3568
+					   array(
3569
+						   EEM_Base::default_where_conditions_minimum_others,
3570
+						   EEM_Base::default_where_conditions_minimum_all,
3571
+					   ),
3572
+					   true
3573
+				   )
3574
+			   );
3575
+	}
3576
+
3577
+
3578
+	/**
3579
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3580
+	 * then we also add a special where condition which allows for that model's primary key
3581
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3582
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3583
+	 *
3584
+	 * @param array    $default_where_conditions
3585
+	 * @param array    $provided_where_conditions
3586
+	 * @param EEM_Base $model
3587
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3588
+	 * @return array like EEM_Base::get_all's $query_params[0]
3589
+	 * @throws \EE_Error
3590
+	 */
3591
+	private function _override_defaults_or_make_null_friendly(
3592
+		$default_where_conditions,
3593
+		$provided_where_conditions,
3594
+		$model,
3595
+		$model_relation_path
3596
+	) {
3597
+		$null_friendly_where_conditions = array();
3598
+		$none_overridden = true;
3599
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3600
+		foreach ($default_where_conditions as $key => $val) {
3601
+			if (isset($provided_where_conditions[$key])) {
3602
+				$none_overridden = false;
3603
+			} else {
3604
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3605
+			}
3606
+		}
3607
+		if ($none_overridden && $default_where_conditions) {
3608
+			if ($model->has_primary_key_field()) {
3609
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3610
+																				. "."
3611
+																				. $model->primary_key_name()] = array('IS NULL');
3612
+			}/*else{
3613 3613
 				//@todo NO PK, use other defaults
3614 3614
 			}*/
3615
-        }
3616
-        return $null_friendly_where_conditions;
3617
-    }
3618
-
3619
-
3620
-
3621
-    /**
3622
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3623
-     * default where conditions on all get_all, update, and delete queries done by this model.
3624
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3625
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3626
-     *
3627
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3628
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3629
-     */
3630
-    private function _get_default_where_conditions($model_relation_path = null)
3631
-    {
3632
-        if ($this->_ignore_where_strategy) {
3633
-            return array();
3634
-        }
3635
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3636
-    }
3637
-
3638
-
3639
-
3640
-    /**
3641
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3642
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3643
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3644
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3645
-     * Similar to _get_default_where_conditions
3646
-     *
3647
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3648
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3649
-     */
3650
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3651
-    {
3652
-        if ($this->_ignore_where_strategy) {
3653
-            return array();
3654
-        }
3655
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3656
-    }
3657
-
3658
-
3659
-
3660
-    /**
3661
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3662
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3663
-     *
3664
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3665
-     * @return string
3666
-     * @throws \EE_Error
3667
-     */
3668
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3669
-    {
3670
-        $selects = $this->_get_columns_to_select_for_this_model();
3671
-        foreach (
3672
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3673
-            $name_of_other_model_included
3674
-        ) {
3675
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3676
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3677
-            foreach ($other_model_selects as $key => $value) {
3678
-                $selects[] = $value;
3679
-            }
3680
-        }
3681
-        return implode(", ", $selects);
3682
-    }
3683
-
3684
-
3685
-
3686
-    /**
3687
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3688
-     * So that's going to be the columns for all the fields on the model
3689
-     *
3690
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3691
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3692
-     */
3693
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3694
-    {
3695
-        $fields = $this->field_settings();
3696
-        $selects = array();
3697
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3698
-            $this->get_this_model_name());
3699
-        foreach ($fields as $field_obj) {
3700
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3701
-                         . $field_obj->get_table_alias()
3702
-                         . "."
3703
-                         . $field_obj->get_table_column()
3704
-                         . " AS '"
3705
-                         . $table_alias_with_model_relation_chain_prefix
3706
-                         . $field_obj->get_table_alias()
3707
-                         . "."
3708
-                         . $field_obj->get_table_column()
3709
-                         . "'";
3710
-        }
3711
-        //make sure we are also getting the PKs of each table
3712
-        $tables = $this->get_tables();
3713
-        if (count($tables) > 1) {
3714
-            foreach ($tables as $table_obj) {
3715
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3716
-                                       . $table_obj->get_fully_qualified_pk_column();
3717
-                if (! in_array($qualified_pk_column, $selects)) {
3718
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3719
-                }
3720
-            }
3721
-        }
3722
-        return $selects;
3723
-    }
3724
-
3725
-
3726
-
3727
-    /**
3728
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3729
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3730
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3731
-     * SQL for joining, and the data types
3732
-     *
3733
-     * @param null|string                 $original_query_param
3734
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3735
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3736
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3737
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3738
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3739
-     *                                                          or 'Registration's
3740
-     * @param string                      $original_query_param what it originally was (eg
3741
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3742
-     *                                                          matches $query_param
3743
-     * @throws EE_Error
3744
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3745
-     */
3746
-    private function _extract_related_model_info_from_query_param(
3747
-        $query_param,
3748
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3749
-        $query_param_type,
3750
-        $original_query_param = null
3751
-    ) {
3752
-        if ($original_query_param === null) {
3753
-            $original_query_param = $query_param;
3754
-        }
3755
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3756
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3757
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3758
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3759
-        //check to see if we have a field on this model
3760
-        $this_model_fields = $this->field_settings(true);
3761
-        if (array_key_exists($query_param, $this_model_fields)) {
3762
-            if ($allow_fields) {
3763
-                return;
3764
-            } else {
3765
-                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",
3766
-                    "event_espresso"),
3767
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3768
-            }
3769
-        } //check if this is a special logic query param
3770
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3771
-            if ($allow_logic_query_params) {
3772
-                return;
3773
-            } else {
3774
-                throw new EE_Error(
3775
-                    sprintf(
3776
-                        __('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',
3777
-                            'event_espresso'),
3778
-                        implode('", "', $this->_logic_query_param_keys),
3779
-                        $query_param,
3780
-                        get_class($this),
3781
-                        '<br />',
3782
-                        "\t"
3783
-                        . ' $passed_in_query_info = <pre>'
3784
-                        . print_r($passed_in_query_info, true)
3785
-                        . '</pre>'
3786
-                        . "\n\t"
3787
-                        . ' $query_param_type = '
3788
-                        . $query_param_type
3789
-                        . "\n\t"
3790
-                        . ' $original_query_param = '
3791
-                        . $original_query_param
3792
-                    )
3793
-                );
3794
-            }
3795
-        } //check if it's a custom selection
3796
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3797
-            return;
3798
-        }
3799
-        //check if has a model name at the beginning
3800
-        //and
3801
-        //check if it's a field on a related model
3802
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3803
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3804
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3805
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3806
-                if ($query_param === '') {
3807
-                    //nothing left to $query_param
3808
-                    //we should actually end in a field name, not a model like this!
3809
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3810
-                        "event_espresso"),
3811
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3812
-                } else {
3813
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3814
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3815
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3816
-                    return;
3817
-                }
3818
-            } elseif ($query_param === $valid_related_model_name) {
3819
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3820
-                return;
3821
-            }
3822
-        }
3823
-        //ok so $query_param didn't start with a model name
3824
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3825
-        //it's wack, that's what it is
3826
-        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",
3827
-            "event_espresso"),
3828
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3829
-    }
3830
-
3831
-
3832
-
3833
-    /**
3834
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3835
-     * and store it on $passed_in_query_info
3836
-     *
3837
-     * @param string                      $model_name
3838
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3839
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3840
-     *                                                          model and $model_name. Eg, if we are querying Event,
3841
-     *                                                          and are adding a join to 'Payment' with the original
3842
-     *                                                          query param key
3843
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3844
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3845
-     *                                                          Payment wants to add default query params so that it
3846
-     *                                                          will know what models to prepend onto its default query
3847
-     *                                                          params or in case it wants to rename tables (in case
3848
-     *                                                          there are multiple joins to the same table)
3849
-     * @return void
3850
-     * @throws \EE_Error
3851
-     */
3852
-    private function _add_join_to_model(
3853
-        $model_name,
3854
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3855
-        $original_query_param
3856
-    ) {
3857
-        $relation_obj = $this->related_settings_for($model_name);
3858
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3859
-        //check if the relation is HABTM, because then we're essentially doing two joins
3860
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3861
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3862
-            $join_model_obj = $relation_obj->get_join_model();
3863
-            //replace the model specified with the join model for this relation chain, whi
3864
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3865
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3866
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3867
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3868
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3869
-            $passed_in_query_info->merge($new_query_info);
3870
-        }
3871
-        //now just join to the other table pointed to by the relation object, and add its data types
3872
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3873
-            array($model_relation_chain => $model_name),
3874
-            $relation_obj->get_join_statement($model_relation_chain));
3875
-        $passed_in_query_info->merge($new_query_info);
3876
-    }
3877
-
3878
-
3879
-
3880
-    /**
3881
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3882
-     *
3883
-     * @param array $where_params like EEM_Base::get_all
3884
-     * @return string of SQL
3885
-     * @throws \EE_Error
3886
-     */
3887
-    private function _construct_where_clause($where_params)
3888
-    {
3889
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3890
-        if ($SQL) {
3891
-            return " WHERE " . $SQL;
3892
-        } else {
3893
-            return '';
3894
-        }
3895
-    }
3896
-
3897
-
3898
-
3899
-    /**
3900
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3901
-     * and should be passed HAVING parameters, not WHERE parameters
3902
-     *
3903
-     * @param array $having_params
3904
-     * @return string
3905
-     * @throws \EE_Error
3906
-     */
3907
-    private function _construct_having_clause($having_params)
3908
-    {
3909
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3910
-        if ($SQL) {
3911
-            return " HAVING " . $SQL;
3912
-        } else {
3913
-            return '';
3914
-        }
3915
-    }
3916
-
3917
-
3918
-
3919
-    /**
3920
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3921
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3922
-     * EEM_Attendee.
3923
-     *
3924
-     * @param string $field_name
3925
-     * @param string $model_name
3926
-     * @return EE_Model_Field_Base
3927
-     * @throws EE_Error
3928
-     */
3929
-    protected function _get_field_on_model($field_name, $model_name)
3930
-    {
3931
-        $model_class = 'EEM_' . $model_name;
3932
-        $model_filepath = $model_class . ".model.php";
3933
-        if (is_readable($model_filepath)) {
3934
-            require_once($model_filepath);
3935
-            $model_instance = call_user_func($model_name . "::instance");
3936
-            /* @var $model_instance EEM_Base */
3937
-            return $model_instance->field_settings_for($field_name);
3938
-        } else {
3939
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3940
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3941
-        }
3942
-    }
3943
-
3944
-
3945
-
3946
-    /**
3947
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3948
-     * Event_Meta.meta_value = 'foo'))"
3949
-     *
3950
-     * @param array  $where_params see EEM_Base::get_all for documentation
3951
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3952
-     * @throws EE_Error
3953
-     * @return string of SQL
3954
-     */
3955
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3956
-    {
3957
-        $where_clauses = array();
3958
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3959
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3960
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3961
-                switch ($query_param) {
3962
-                    case 'not':
3963
-                    case 'NOT':
3964
-                        $where_clauses[] = "! ("
3965
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3966
-                                $glue)
3967
-                                           . ")";
3968
-                        break;
3969
-                    case 'and':
3970
-                    case 'AND':
3971
-                        $where_clauses[] = " ("
3972
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3973
-                                ' AND ')
3974
-                                           . ")";
3975
-                        break;
3976
-                    case 'or':
3977
-                    case 'OR':
3978
-                        $where_clauses[] = " ("
3979
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3980
-                                ' OR ')
3981
-                                           . ")";
3982
-                        break;
3983
-                }
3984
-            } else {
3985
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3986
-                //if it's not a normal field, maybe it's a custom selection?
3987
-                if (! $field_obj) {
3988
-                    if (isset($this->_custom_selections[$query_param][1])) {
3989
-                        $field_obj = $this->_custom_selections[$query_param][1];
3990
-                    } else {
3991
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3992
-                            "event_espresso"), $query_param));
3993
-                    }
3994
-                }
3995
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3996
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3997
-            }
3998
-        }
3999
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4000
-    }
4001
-
4002
-
4003
-
4004
-    /**
4005
-     * Takes the input parameter and extract the table name (alias) and column name
4006
-     *
4007
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4008
-     * @throws EE_Error
4009
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4010
-     */
4011
-    private function _deduce_column_name_from_query_param($query_param)
4012
-    {
4013
-        $field = $this->_deduce_field_from_query_param($query_param);
4014
-        if ($field) {
4015
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4016
-                $query_param);
4017
-            return $table_alias_prefix . $field->get_qualified_column();
4018
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4019
-            //maybe it's custom selection item?
4020
-            //if so, just use it as the "column name"
4021
-            return $query_param;
4022
-        } else {
4023
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4024
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4025
-        }
4026
-    }
4027
-
4028
-
4029
-
4030
-    /**
4031
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4032
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4033
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4034
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4035
-     *
4036
-     * @param string $condition_query_param_key
4037
-     * @return string
4038
-     */
4039
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4040
-    {
4041
-        $pos_of_star = strpos($condition_query_param_key, '*');
4042
-        if ($pos_of_star === false) {
4043
-            return $condition_query_param_key;
4044
-        } else {
4045
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4046
-            return $condition_query_param_sans_star;
4047
-        }
4048
-    }
4049
-
4050
-
4051
-
4052
-    /**
4053
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4054
-     *
4055
-     * @param                            mixed      array | string    $op_and_value
4056
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4057
-     * @throws EE_Error
4058
-     * @return string
4059
-     */
4060
-    private function _construct_op_and_value($op_and_value, $field_obj)
4061
-    {
4062
-        if (is_array($op_and_value)) {
4063
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4064
-            if (! $operator) {
4065
-                $php_array_like_string = array();
4066
-                foreach ($op_and_value as $key => $value) {
4067
-                    $php_array_like_string[] = "$key=>$value";
4068
-                }
4069
-                throw new EE_Error(
4070
-                    sprintf(
4071
-                        __(
4072
-                            "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))",
4073
-                            "event_espresso"
4074
-                        ),
4075
-                        implode(",", $php_array_like_string)
4076
-                    )
4077
-                );
4078
-            }
4079
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4080
-        } else {
4081
-            $operator = '=';
4082
-            $value = $op_and_value;
4083
-        }
4084
-        //check to see if the value is actually another field
4085
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4086
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4087
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4088
-            //in this case, the value should be an array, or at least a comma-separated list
4089
-            //it will need to handle a little differently
4090
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4091
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4092
-            return $operator . SP . $cleaned_value;
4093
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4094
-            //the value should be an array with count of two.
4095
-            if (count($value) !== 2) {
4096
-                throw new EE_Error(
4097
-                    sprintf(
4098
-                        __(
4099
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4100
-                            'event_espresso'
4101
-                        ),
4102
-                        "BETWEEN"
4103
-                    )
4104
-                );
4105
-            }
4106
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4107
-            return $operator . SP . $cleaned_value;
4108
-        } elseif (in_array($operator, $this->_null_style_operators)) {
4109
-            if ($value !== null) {
4110
-                throw new EE_Error(
4111
-                    sprintf(
4112
-                        __(
4113
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4114
-                            "event_espresso"
4115
-                        ),
4116
-                        $value,
4117
-                        $operator
4118
-                    )
4119
-                );
4120
-            }
4121
-            return $operator;
4122
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
4123
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4124
-            //remove other junk. So just treat it as a string.
4125
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4126
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4127
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4128
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4129
-            throw new EE_Error(
4130
-                sprintf(
4131
-                    __(
4132
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4133
-                        'event_espresso'
4134
-                    ),
4135
-                    $operator,
4136
-                    $operator
4137
-                )
4138
-            );
4139
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4140
-            throw new EE_Error(
4141
-                sprintf(
4142
-                    __(
4143
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4144
-                        'event_espresso'
4145
-                    ),
4146
-                    $operator,
4147
-                    $operator
4148
-                )
4149
-            );
4150
-        } else {
4151
-            throw new EE_Error(
4152
-                sprintf(
4153
-                    __(
4154
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4155
-                        "event_espresso"
4156
-                    ),
4157
-                    http_build_query($op_and_value)
4158
-                )
4159
-            );
4160
-        }
4161
-    }
4162
-
4163
-
4164
-
4165
-    /**
4166
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4167
-     *
4168
-     * @param array                      $values
4169
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4170
-     *                                              '%s'
4171
-     * @return string
4172
-     * @throws \EE_Error
4173
-     */
4174
-    public function _construct_between_value($values, $field_obj)
4175
-    {
4176
-        $cleaned_values = array();
4177
-        foreach ($values as $value) {
4178
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4179
-        }
4180
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4181
-    }
4182
-
4183
-
4184
-
4185
-    /**
4186
-     * Takes an array or a comma-separated list of $values and cleans them
4187
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4188
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4189
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4190
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4191
-     *
4192
-     * @param mixed                      $values    array or comma-separated string
4193
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4194
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4195
-     * @throws \EE_Error
4196
-     */
4197
-    public function _construct_in_value($values, $field_obj)
4198
-    {
4199
-        //check if the value is a CSV list
4200
-        if (is_string($values)) {
4201
-            //in which case, turn it into an array
4202
-            $values = explode(",", $values);
4203
-        }
4204
-        $cleaned_values = array();
4205
-        foreach ($values as $value) {
4206
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4207
-        }
4208
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4209
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4210
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4211
-        if (empty($cleaned_values)) {
4212
-            $all_fields = $this->field_settings();
4213
-            $a_field = array_shift($all_fields);
4214
-            $main_table = $this->_get_main_table();
4215
-            $cleaned_values[] = "SELECT "
4216
-                                . $a_field->get_table_column()
4217
-                                . " FROM "
4218
-                                . $main_table->get_table_name()
4219
-                                . " WHERE FALSE";
4220
-        }
4221
-        return "(" . implode(",", $cleaned_values) . ")";
4222
-    }
4223
-
4224
-
4225
-
4226
-    /**
4227
-     * @param mixed                      $value
4228
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4229
-     * @throws EE_Error
4230
-     * @return false|null|string
4231
-     */
4232
-    private function _wpdb_prepare_using_field($value, $field_obj)
4233
-    {
4234
-        /** @type WPDB $wpdb */
4235
-        global $wpdb;
4236
-        if ($field_obj instanceof EE_Model_Field_Base) {
4237
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4238
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4239
-        } else {//$field_obj should really just be a data type
4240
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4241
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4242
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4243
-            }
4244
-            return $wpdb->prepare($field_obj, $value);
4245
-        }
4246
-    }
4247
-
4248
-
4249
-
4250
-    /**
4251
-     * Takes the input parameter and finds the model field that it indicates.
4252
-     *
4253
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4254
-     * @throws EE_Error
4255
-     * @return EE_Model_Field_Base
4256
-     */
4257
-    protected function _deduce_field_from_query_param($query_param_name)
4258
-    {
4259
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4260
-        //which will help us find the database table and column
4261
-        $query_param_parts = explode(".", $query_param_name);
4262
-        if (empty($query_param_parts)) {
4263
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4264
-                'event_espresso'), $query_param_name));
4265
-        }
4266
-        $number_of_parts = count($query_param_parts);
4267
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4268
-        if ($number_of_parts === 1) {
4269
-            $field_name = $last_query_param_part;
4270
-            $model_obj = $this;
4271
-        } else {// $number_of_parts >= 2
4272
-            //the last part is the column name, and there are only 2parts. therefore...
4273
-            $field_name = $last_query_param_part;
4274
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4275
-        }
4276
-        try {
4277
-            return $model_obj->field_settings_for($field_name);
4278
-        } catch (EE_Error $e) {
4279
-            return null;
4280
-        }
4281
-    }
4282
-
4283
-
4284
-
4285
-    /**
4286
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4287
-     * alias and column which corresponds to it
4288
-     *
4289
-     * @param string $field_name
4290
-     * @throws EE_Error
4291
-     * @return string
4292
-     */
4293
-    public function _get_qualified_column_for_field($field_name)
4294
-    {
4295
-        $all_fields = $this->field_settings();
4296
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4297
-        if ($field) {
4298
-            return $field->get_qualified_column();
4299
-        } else {
4300
-            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.",
4301
-                'event_espresso'), $field_name, get_class($this)));
4302
-        }
4303
-    }
4304
-
4305
-
4306
-
4307
-    /**
4308
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4309
-     * Example usage:
4310
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4311
-     *      array(),
4312
-     *      ARRAY_A,
4313
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4314
-     *  );
4315
-     * is equivalent to
4316
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4317
-     * and
4318
-     *  EEM_Event::instance()->get_all_wpdb_results(
4319
-     *      array(
4320
-     *          array(
4321
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4322
-     *          ),
4323
-     *          ARRAY_A,
4324
-     *          implode(
4325
-     *              ', ',
4326
-     *              array_merge(
4327
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4328
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4329
-     *              )
4330
-     *          )
4331
-     *      )
4332
-     *  );
4333
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4334
-     *
4335
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4336
-     *                                            and the one whose fields you are selecting for example: when querying
4337
-     *                                            tickets model and selecting fields from the tickets model you would
4338
-     *                                            leave this parameter empty, because no models are needed to join
4339
-     *                                            between the queried model and the selected one. Likewise when
4340
-     *                                            querying the datetime model and selecting fields from the tickets
4341
-     *                                            model, it would also be left empty, because there is a direct
4342
-     *                                            relation from datetimes to tickets, so no model is needed to join
4343
-     *                                            them together. However, when querying from the event model and
4344
-     *                                            selecting fields from the ticket model, you should provide the string
4345
-     *                                            'Datetime', indicating that the event model must first join to the
4346
-     *                                            datetime model in order to find its relation to ticket model.
4347
-     *                                            Also, when querying from the venue model and selecting fields from
4348
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4349
-     *                                            indicating you need to join the venue model to the event model,
4350
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4351
-     *                                            This string is used to deduce the prefix that gets added onto the
4352
-     *                                            models' tables qualified columns
4353
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4354
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4355
-     *                                            qualified column names
4356
-     * @return array|string
4357
-     */
4358
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4359
-    {
4360
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4361
-        $qualified_columns = array();
4362
-        foreach ($this->field_settings() as $field_name => $field) {
4363
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4364
-        }
4365
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4366
-    }
4367
-
4368
-
4369
-
4370
-    /**
4371
-     * constructs the select use on special limit joins
4372
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4373
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4374
-     * (as that is typically where the limits would be set).
4375
-     *
4376
-     * @param  string       $table_alias The table the select is being built for
4377
-     * @param  mixed|string $limit       The limit for this select
4378
-     * @return string                The final select join element for the query.
4379
-     */
4380
-    public function _construct_limit_join_select($table_alias, $limit)
4381
-    {
4382
-        $SQL = '';
4383
-        foreach ($this->_tables as $table_obj) {
4384
-            if ($table_obj instanceof EE_Primary_Table) {
4385
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4386
-                    ? $table_obj->get_select_join_limit($limit)
4387
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4388
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4389
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4390
-                    ? $table_obj->get_select_join_limit_join($limit)
4391
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4392
-            }
4393
-        }
4394
-        return $SQL;
4395
-    }
4396
-
4397
-
4398
-
4399
-    /**
4400
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4401
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4402
-     *
4403
-     * @return string SQL
4404
-     * @throws \EE_Error
4405
-     */
4406
-    public function _construct_internal_join()
4407
-    {
4408
-        $SQL = $this->_get_main_table()->get_table_sql();
4409
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4410
-        return $SQL;
4411
-    }
4412
-
4413
-
4414
-
4415
-    /**
4416
-     * Constructs the SQL for joining all the tables on this model.
4417
-     * Normally $alias should be the primary table's alias, but in cases where
4418
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4419
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4420
-     * alias, this will construct SQL like:
4421
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4422
-     * With $alias being a secondary table's alias, this will construct SQL like:
4423
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4424
-     *
4425
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4426
-     * @return string
4427
-     */
4428
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4429
-    {
4430
-        $SQL = '';
4431
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4432
-        foreach ($this->_tables as $table_obj) {
4433
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4434
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4435
-                    //so we're joining to this table, meaning the table is already in
4436
-                    //the FROM statement, BUT the primary table isn't. So we want
4437
-                    //to add the inverse join sql
4438
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4439
-                } else {
4440
-                    //just add a regular JOIN to this table from the primary table
4441
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4442
-                }
4443
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4444
-        }
4445
-        return $SQL;
4446
-    }
4447
-
4448
-
4449
-
4450
-    /**
4451
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4452
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4453
-     * their data type (eg, '%s', '%d', etc)
4454
-     *
4455
-     * @return array
4456
-     */
4457
-    public function _get_data_types()
4458
-    {
4459
-        $data_types = array();
4460
-        foreach ($this->field_settings() as $field_obj) {
4461
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4462
-            /** @var $field_obj EE_Model_Field_Base */
4463
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4464
-        }
4465
-        return $data_types;
4466
-    }
4467
-
4468
-
4469
-
4470
-    /**
4471
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4472
-     *
4473
-     * @param string $model_name
4474
-     * @throws EE_Error
4475
-     * @return EEM_Base
4476
-     */
4477
-    public function get_related_model_obj($model_name)
4478
-    {
4479
-        $model_classname = "EEM_" . $model_name;
4480
-        if (! class_exists($model_classname)) {
4481
-            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",
4482
-                'event_espresso'), $model_name, $model_classname));
4483
-        }
4484
-        return call_user_func($model_classname . "::instance");
4485
-    }
4486
-
4487
-
4488
-
4489
-    /**
4490
-     * Returns the array of EE_ModelRelations for this model.
4491
-     *
4492
-     * @return EE_Model_Relation_Base[]
4493
-     */
4494
-    public function relation_settings()
4495
-    {
4496
-        return $this->_model_relations;
4497
-    }
4498
-
4499
-
4500
-
4501
-    /**
4502
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4503
-     * because without THOSE models, this model probably doesn't have much purpose.
4504
-     * (Eg, without an event, datetimes have little purpose.)
4505
-     *
4506
-     * @return EE_Belongs_To_Relation[]
4507
-     */
4508
-    public function belongs_to_relations()
4509
-    {
4510
-        $belongs_to_relations = array();
4511
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4512
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4513
-                $belongs_to_relations[$model_name] = $relation_obj;
4514
-            }
4515
-        }
4516
-        return $belongs_to_relations;
4517
-    }
4518
-
4519
-
4520
-
4521
-    /**
4522
-     * Returns the specified EE_Model_Relation, or throws an exception
4523
-     *
4524
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4525
-     * @throws EE_Error
4526
-     * @return EE_Model_Relation_Base
4527
-     */
4528
-    public function related_settings_for($relation_name)
4529
-    {
4530
-        $relatedModels = $this->relation_settings();
4531
-        if (! array_key_exists($relation_name, $relatedModels)) {
4532
-            throw new EE_Error(
4533
-                sprintf(
4534
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4535
-                        'event_espresso'),
4536
-                    $relation_name,
4537
-                    $this->_get_class_name(),
4538
-                    implode(', ', array_keys($relatedModels))
4539
-                )
4540
-            );
4541
-        }
4542
-        return $relatedModels[$relation_name];
4543
-    }
4544
-
4545
-
4546
-
4547
-    /**
4548
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4549
-     * fields
4550
-     *
4551
-     * @param string $fieldName
4552
-     * @throws EE_Error
4553
-     * @return EE_Model_Field_Base
4554
-     */
4555
-    public function field_settings_for($fieldName)
4556
-    {
4557
-        $fieldSettings = $this->field_settings(true);
4558
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4559
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4560
-                get_class($this)));
4561
-        }
4562
-        return $fieldSettings[$fieldName];
4563
-    }
4564
-
4565
-
4566
-
4567
-    /**
4568
-     * Checks if this field exists on this model
4569
-     *
4570
-     * @param string $fieldName a key in the model's _field_settings array
4571
-     * @return boolean
4572
-     */
4573
-    public function has_field($fieldName)
4574
-    {
4575
-        $fieldSettings = $this->field_settings(true);
4576
-        if (isset($fieldSettings[$fieldName])) {
4577
-            return true;
4578
-        } else {
4579
-            return false;
4580
-        }
4581
-    }
4582
-
4583
-
4584
-
4585
-    /**
4586
-     * Returns whether or not this model has a relation to the specified model
4587
-     *
4588
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4589
-     * @return boolean
4590
-     */
4591
-    public function has_relation($relation_name)
4592
-    {
4593
-        $relations = $this->relation_settings();
4594
-        if (isset($relations[$relation_name])) {
4595
-            return true;
4596
-        } else {
4597
-            return false;
4598
-        }
4599
-    }
4600
-
4601
-
4602
-
4603
-    /**
4604
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4605
-     * Eg, on EE_Answer that would be ANS_ID field object
4606
-     *
4607
-     * @param $field_obj
4608
-     * @return boolean
4609
-     */
4610
-    public function is_primary_key_field($field_obj)
4611
-    {
4612
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4613
-    }
4614
-
4615
-
4616
-
4617
-    /**
4618
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4619
-     * Eg, on EE_Answer that would be ANS_ID field object
4620
-     *
4621
-     * @return EE_Model_Field_Base
4622
-     * @throws EE_Error
4623
-     */
4624
-    public function get_primary_key_field()
4625
-    {
4626
-        if ($this->_primary_key_field === null) {
4627
-            foreach ($this->field_settings(true) as $field_obj) {
4628
-                if ($this->is_primary_key_field($field_obj)) {
4629
-                    $this->_primary_key_field = $field_obj;
4630
-                    break;
4631
-                }
4632
-            }
4633
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4634
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4635
-                    get_class($this)));
4636
-            }
4637
-        }
4638
-        return $this->_primary_key_field;
4639
-    }
4640
-
4641
-
4642
-
4643
-    /**
4644
-     * Returns whether or not not there is a primary key on this model.
4645
-     * Internally does some caching.
4646
-     *
4647
-     * @return boolean
4648
-     */
4649
-    public function has_primary_key_field()
4650
-    {
4651
-        if ($this->_has_primary_key_field === null) {
4652
-            try {
4653
-                $this->get_primary_key_field();
4654
-                $this->_has_primary_key_field = true;
4655
-            } catch (EE_Error $e) {
4656
-                $this->_has_primary_key_field = false;
4657
-            }
4658
-        }
4659
-        return $this->_has_primary_key_field;
4660
-    }
4661
-
4662
-
4663
-
4664
-    /**
4665
-     * Finds the first field of type $field_class_name.
4666
-     *
4667
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4668
-     *                                 EE_Foreign_Key_Field, etc
4669
-     * @return EE_Model_Field_Base or null if none is found
4670
-     */
4671
-    public function get_a_field_of_type($field_class_name)
4672
-    {
4673
-        foreach ($this->field_settings() as $field) {
4674
-            if ($field instanceof $field_class_name) {
4675
-                return $field;
4676
-            }
4677
-        }
4678
-        return null;
4679
-    }
4680
-
4681
-
4682
-
4683
-    /**
4684
-     * Gets a foreign key field pointing to model.
4685
-     *
4686
-     * @param string $model_name eg Event, Registration, not EEM_Event
4687
-     * @return EE_Foreign_Key_Field_Base
4688
-     * @throws EE_Error
4689
-     */
4690
-    public function get_foreign_key_to($model_name)
4691
-    {
4692
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4693
-            foreach ($this->field_settings() as $field) {
4694
-                if (
4695
-                    $field instanceof EE_Foreign_Key_Field_Base
4696
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4697
-                ) {
4698
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4699
-                    break;
4700
-                }
4701
-            }
4702
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4703
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4704
-                    'event_espresso'), $model_name, get_class($this)));
4705
-            }
4706
-        }
4707
-        return $this->_cache_foreign_key_to_fields[$model_name];
4708
-    }
4709
-
4710
-
4711
-
4712
-    /**
4713
-     * Gets the actual table for the table alias
4714
-     *
4715
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4716
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4717
-     *                            Either one works
4718
-     * @return EE_Table_Base
4719
-     */
4720
-    public function get_table_for_alias($table_alias)
4721
-    {
4722
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4723
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4724
-    }
4725
-
4726
-
4727
-
4728
-    /**
4729
-     * Returns a flat array of all field son this model, instead of organizing them
4730
-     * by table_alias as they are in the constructor.
4731
-     *
4732
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4733
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4734
-     */
4735
-    public function field_settings($include_db_only_fields = false)
4736
-    {
4737
-        if ($include_db_only_fields) {
4738
-            if ($this->_cached_fields === null) {
4739
-                $this->_cached_fields = array();
4740
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4741
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4742
-                        $this->_cached_fields[$field_name] = $field_obj;
4743
-                    }
4744
-                }
4745
-            }
4746
-            return $this->_cached_fields;
4747
-        } else {
4748
-            if ($this->_cached_fields_non_db_only === null) {
4749
-                $this->_cached_fields_non_db_only = array();
4750
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4751
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4752
-                        /** @var $field_obj EE_Model_Field_Base */
4753
-                        if (! $field_obj->is_db_only_field()) {
4754
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4755
-                        }
4756
-                    }
4757
-                }
4758
-            }
4759
-            return $this->_cached_fields_non_db_only;
4760
-        }
4761
-    }
4762
-
4763
-
4764
-
4765
-    /**
4766
-     *        cycle though array of attendees and create objects out of each item
4767
-     *
4768
-     * @access        private
4769
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4770
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4771
-     *                           numerically indexed)
4772
-     * @throws \EE_Error
4773
-     */
4774
-    protected function _create_objects($rows = array())
4775
-    {
4776
-        $array_of_objects = array();
4777
-        if (empty($rows)) {
4778
-            return array();
4779
-        }
4780
-        $count_if_model_has_no_primary_key = 0;
4781
-        $has_primary_key = $this->has_primary_key_field();
4782
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4783
-        foreach ((array)$rows as $row) {
4784
-            if (empty($row)) {
4785
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4786
-                return array();
4787
-            }
4788
-            //check if we've already set this object in the results array,
4789
-            //in which case there's no need to process it further (again)
4790
-            if ($has_primary_key) {
4791
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4792
-                    $row,
4793
-                    $primary_key_field->get_qualified_column(),
4794
-                    $primary_key_field->get_table_column()
4795
-                );
4796
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4797
-                    continue;
4798
-                }
4799
-            }
4800
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4801
-            if (! $classInstance) {
4802
-                throw new EE_Error(
4803
-                    sprintf(
4804
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4805
-                        $this->get_this_model_name(),
4806
-                        http_build_query($row)
4807
-                    )
4808
-                );
4809
-            }
4810
-            //set the timezone on the instantiated objects
4811
-            $classInstance->set_timezone($this->_timezone);
4812
-            //make sure if there is any timezone setting present that we set the timezone for the object
4813
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4814
-            $array_of_objects[$key] = $classInstance;
4815
-            //also, for all the relations of type BelongsTo, see if we can cache
4816
-            //those related models
4817
-            //(we could do this for other relations too, but if there are conditions
4818
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4819
-            //so it requires a little more thought than just caching them immediately...)
4820
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4821
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4822
-                    //check if this model's INFO is present. If so, cache it on the model
4823
-                    $other_model = $relation_obj->get_other_model();
4824
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4825
-                    //if we managed to make a model object from the results, cache it on the main model object
4826
-                    if ($other_model_obj_maybe) {
4827
-                        //set timezone on these other model objects if they are present
4828
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4829
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4830
-                    }
4831
-                }
4832
-            }
4833
-        }
4834
-        return $array_of_objects;
4835
-    }
4836
-
4837
-
4838
-
4839
-    /**
4840
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4841
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4842
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4843
-     * object (as set in the model_field!).
4844
-     *
4845
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4846
-     */
4847
-    public function create_default_object()
4848
-    {
4849
-        $this_model_fields_and_values = array();
4850
-        //setup the row using default values;
4851
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4852
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4853
-        }
4854
-        $className = $this->_get_class_name();
4855
-        $classInstance = EE_Registry::instance()
4856
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4857
-        return $classInstance;
4858
-    }
4859
-
4860
-
4861
-
4862
-    /**
4863
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4864
-     *                             or an stdClass where each property is the name of a column,
4865
-     * @return EE_Base_Class
4866
-     * @throws \EE_Error
4867
-     */
4868
-    public function instantiate_class_from_array_or_object($cols_n_values)
4869
-    {
4870
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4871
-            $cols_n_values = get_object_vars($cols_n_values);
4872
-        }
4873
-        $primary_key = null;
4874
-        //make sure the array only has keys that are fields/columns on this model
4875
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4876
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4877
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4878
-        }
4879
-        $className = $this->_get_class_name();
4880
-        //check we actually found results that we can use to build our model object
4881
-        //if not, return null
4882
-        if ($this->has_primary_key_field()) {
4883
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4884
-                return null;
4885
-            }
4886
-        } else if ($this->unique_indexes()) {
4887
-            $first_column = reset($this_model_fields_n_values);
4888
-            if (empty($first_column)) {
4889
-                return null;
4890
-            }
4891
-        }
4892
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4893
-        if ($primary_key) {
4894
-            $classInstance = $this->get_from_entity_map($primary_key);
4895
-            if (! $classInstance) {
4896
-                $classInstance = EE_Registry::instance()
4897
-                                            ->load_class($className,
4898
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4899
-                // add this new object to the entity map
4900
-                $classInstance = $this->add_to_entity_map($classInstance);
4901
-            }
4902
-        } else {
4903
-            $classInstance = EE_Registry::instance()
4904
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4905
-                                            true, false);
4906
-        }
4907
-        //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.
4908
-        $this->set_timezone($classInstance->get_timezone());
4909
-        return $classInstance;
4910
-    }
4911
-
4912
-
4913
-
4914
-    /**
4915
-     * Gets the model object from the  entity map if it exists
4916
-     *
4917
-     * @param int|string $id the ID of the model object
4918
-     * @return EE_Base_Class
4919
-     */
4920
-    public function get_from_entity_map($id)
4921
-    {
4922
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4923
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4924
-    }
4925
-
4926
-
4927
-
4928
-    /**
4929
-     * add_to_entity_map
4930
-     * Adds the object to the model's entity mappings
4931
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4932
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4933
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4934
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4935
-     *        then this method should be called immediately after the update query
4936
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4937
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4938
-     *
4939
-     * @param    EE_Base_Class $object
4940
-     * @throws EE_Error
4941
-     * @return \EE_Base_Class
4942
-     */
4943
-    public function add_to_entity_map(EE_Base_Class $object)
4944
-    {
4945
-        $className = $this->_get_class_name();
4946
-        if (! $object instanceof $className) {
4947
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4948
-                is_object($object) ? get_class($object) : $object, $className));
4949
-        }
4950
-        /** @var $object EE_Base_Class */
4951
-        if (! $object->ID()) {
4952
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4953
-                "event_espresso"), get_class($this)));
4954
-        }
4955
-        // double check it's not already there
4956
-        $classInstance = $this->get_from_entity_map($object->ID());
4957
-        if ($classInstance) {
4958
-            return $classInstance;
4959
-        } else {
4960
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4961
-            return $object;
4962
-        }
4963
-    }
4964
-
4965
-
4966
-
4967
-    /**
4968
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4969
-     * if no identifier is provided, then the entire entity map is emptied
4970
-     *
4971
-     * @param int|string $id the ID of the model object
4972
-     * @return boolean
4973
-     */
4974
-    public function clear_entity_map($id = null)
4975
-    {
4976
-        if (empty($id)) {
4977
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4978
-            return true;
4979
-        }
4980
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4981
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4982
-            return true;
4983
-        }
4984
-        return false;
4985
-    }
4986
-
4987
-
4988
-
4989
-    /**
4990
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4991
-     * Given an array where keys are column (or column alias) names and values,
4992
-     * returns an array of their corresponding field names and database values
4993
-     *
4994
-     * @param array $cols_n_values
4995
-     * @return array
4996
-     */
4997
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4998
-    {
4999
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5000
-    }
5001
-
5002
-
5003
-
5004
-    /**
5005
-     * _deduce_fields_n_values_from_cols_n_values
5006
-     * Given an array where keys are column (or column alias) names and values,
5007
-     * returns an array of their corresponding field names and database values
5008
-     *
5009
-     * @param string $cols_n_values
5010
-     * @return array
5011
-     */
5012
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5013
-    {
5014
-        $this_model_fields_n_values = array();
5015
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5016
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5017
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5018
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5019
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5020
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5021
-                    if (! $field_obj->is_db_only_field()) {
5022
-                        //prepare field as if its coming from db
5023
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5024
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5025
-                    }
5026
-                }
5027
-            } else {
5028
-                //the table's rows existed. Use their values
5029
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5030
-                    if (! $field_obj->is_db_only_field()) {
5031
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5032
-                            $cols_n_values, $field_obj->get_qualified_column(),
5033
-                            $field_obj->get_table_column()
5034
-                        );
5035
-                    }
5036
-                }
5037
-            }
5038
-        }
5039
-        return $this_model_fields_n_values;
5040
-    }
5041
-
5042
-
5043
-
5044
-    /**
5045
-     * @param $cols_n_values
5046
-     * @param $qualified_column
5047
-     * @param $regular_column
5048
-     * @return null
5049
-     */
5050
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5051
-    {
5052
-        $value = null;
5053
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5054
-        //does the field on the model relate to this column retrieved from the db?
5055
-        //or is it a db-only field? (not relating to the model)
5056
-        if (isset($cols_n_values[$qualified_column])) {
5057
-            $value = $cols_n_values[$qualified_column];
5058
-        } elseif (isset($cols_n_values[$regular_column])) {
5059
-            $value = $cols_n_values[$regular_column];
5060
-        }
5061
-        return $value;
5062
-    }
5063
-
5064
-
5065
-
5066
-    /**
5067
-     * refresh_entity_map_from_db
5068
-     * Makes sure the model object in the entity map at $id assumes the values
5069
-     * of the database (opposite of EE_base_Class::save())
5070
-     *
5071
-     * @param int|string $id
5072
-     * @return EE_Base_Class
5073
-     * @throws \EE_Error
5074
-     */
5075
-    public function refresh_entity_map_from_db($id)
5076
-    {
5077
-        $obj_in_map = $this->get_from_entity_map($id);
5078
-        if ($obj_in_map) {
5079
-            $wpdb_results = $this->_get_all_wpdb_results(
5080
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5081
-            );
5082
-            if ($wpdb_results && is_array($wpdb_results)) {
5083
-                $one_row = reset($wpdb_results);
5084
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5085
-                    $obj_in_map->set_from_db($field_name, $db_value);
5086
-                }
5087
-                //clear the cache of related model objects
5088
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5089
-                    $obj_in_map->clear_cache($relation_name, null, true);
5090
-                }
5091
-            }
5092
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5093
-            return $obj_in_map;
5094
-        } else {
5095
-            return $this->get_one_by_ID($id);
5096
-        }
5097
-    }
5098
-
5099
-
5100
-
5101
-    /**
5102
-     * refresh_entity_map_with
5103
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5104
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5105
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5106
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5107
-     *
5108
-     * @param int|string    $id
5109
-     * @param EE_Base_Class $replacing_model_obj
5110
-     * @return \EE_Base_Class
5111
-     * @throws \EE_Error
5112
-     */
5113
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5114
-    {
5115
-        $obj_in_map = $this->get_from_entity_map($id);
5116
-        if ($obj_in_map) {
5117
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5118
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5119
-                    $obj_in_map->set($field_name, $value);
5120
-                }
5121
-                //make the model object in the entity map's cache match the $replacing_model_obj
5122
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5123
-                    $obj_in_map->clear_cache($relation_name, null, true);
5124
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5125
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5126
-                    }
5127
-                }
5128
-            }
5129
-            return $obj_in_map;
5130
-        } else {
5131
-            $this->add_to_entity_map($replacing_model_obj);
5132
-            return $replacing_model_obj;
5133
-        }
5134
-    }
5135
-
5136
-
5137
-
5138
-    /**
5139
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5140
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5141
-     * require_once($this->_getClassName().".class.php");
5142
-     *
5143
-     * @return string
5144
-     */
5145
-    private function _get_class_name()
5146
-    {
5147
-        return "EE_" . $this->get_this_model_name();
5148
-    }
5149
-
5150
-
5151
-
5152
-    /**
5153
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5154
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5155
-     * it would be 'Events'.
5156
-     *
5157
-     * @param int $quantity
5158
-     * @return string
5159
-     */
5160
-    public function item_name($quantity = 1)
5161
-    {
5162
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5163
-    }
5164
-
5165
-
5166
-
5167
-    /**
5168
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5169
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5170
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5171
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5172
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5173
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5174
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5175
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5176
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5177
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5178
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5179
-     *        return $previousReturnValue.$returnString;
5180
-     * }
5181
-     * require('EEM_Answer.model.php');
5182
-     * $answer=EEM_Answer::instance();
5183
-     * echo $answer->my_callback('monkeys',100);
5184
-     * //will output "you called my_callback! and passed args:monkeys,100"
5185
-     *
5186
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5187
-     * @param array  $args       array of original arguments passed to the function
5188
-     * @throws EE_Error
5189
-     * @return mixed whatever the plugin which calls add_filter decides
5190
-     */
5191
-    public function __call($methodName, $args)
5192
-    {
5193
-        $className = get_class($this);
5194
-        $tagName = "FHEE__{$className}__{$methodName}";
5195
-        if (! has_filter($tagName)) {
5196
-            throw new EE_Error(
5197
-                sprintf(
5198
-                    __('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 );',
5199
-                        'event_espresso'),
5200
-                    $methodName,
5201
-                    $className,
5202
-                    $tagName,
5203
-                    '<br />'
5204
-                )
5205
-            );
5206
-        }
5207
-        return apply_filters($tagName, null, $this, $args);
5208
-    }
5209
-
5210
-
5211
-
5212
-    /**
5213
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5214
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5215
-     *
5216
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5217
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5218
-     *                                                       the object's class name
5219
-     *                                                       or object's ID
5220
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5221
-     *                                                       exists in the database. If it does not, we add it
5222
-     * @throws EE_Error
5223
-     * @return EE_Base_Class
5224
-     */
5225
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5226
-    {
5227
-        $className = $this->_get_class_name();
5228
-        if ($base_class_obj_or_id instanceof $className) {
5229
-            $model_object = $base_class_obj_or_id;
5230
-        } else {
5231
-            $primary_key_field = $this->get_primary_key_field();
5232
-            if (
5233
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5234
-                && (
5235
-                    is_int($base_class_obj_or_id)
5236
-                    || is_string($base_class_obj_or_id)
5237
-                )
5238
-            ) {
5239
-                // assume it's an ID.
5240
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5241
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5242
-            } else if (
5243
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5244
-                && is_string($base_class_obj_or_id)
5245
-            ) {
5246
-                // assume its a string representation of the object
5247
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5248
-            } else {
5249
-                throw new EE_Error(
5250
-                    sprintf(
5251
-                        __(
5252
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5253
-                            'event_espresso'
5254
-                        ),
5255
-                        $base_class_obj_or_id,
5256
-                        $this->_get_class_name(),
5257
-                        print_r($base_class_obj_or_id, true)
5258
-                    )
5259
-                );
5260
-            }
5261
-        }
5262
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5263
-            $model_object->save();
5264
-        }
5265
-        return $model_object;
5266
-    }
5267
-
5268
-
5269
-
5270
-    /**
5271
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5272
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5273
-     * returns it ID.
5274
-     *
5275
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5276
-     * @return int|string depending on the type of this model object's ID
5277
-     * @throws EE_Error
5278
-     */
5279
-    public function ensure_is_ID($base_class_obj_or_id)
5280
-    {
5281
-        $className = $this->_get_class_name();
5282
-        if ($base_class_obj_or_id instanceof $className) {
5283
-            /** @var $base_class_obj_or_id EE_Base_Class */
5284
-            $id = $base_class_obj_or_id->ID();
5285
-        } elseif (is_int($base_class_obj_or_id)) {
5286
-            //assume it's an ID
5287
-            $id = $base_class_obj_or_id;
5288
-        } elseif (is_string($base_class_obj_or_id)) {
5289
-            //assume its a string representation of the object
5290
-            $id = $base_class_obj_or_id;
5291
-        } else {
5292
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5293
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5294
-                print_r($base_class_obj_or_id, true)));
5295
-        }
5296
-        return $id;
5297
-    }
5298
-
5299
-
5300
-
5301
-    /**
5302
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5303
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5304
-     * been sanitized and converted into the appropriate domain.
5305
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5306
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5307
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5308
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5309
-     * $EVT = EEM_Event::instance(); $old_setting =
5310
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5311
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5312
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5313
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5314
-     *
5315
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5316
-     * @return void
5317
-     */
5318
-    public function assume_values_already_prepared_by_model_object(
5319
-        $values_already_prepared = self::not_prepared_by_model_object
5320
-    ) {
5321
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5322
-    }
5323
-
5324
-
5325
-
5326
-    /**
5327
-     * Read comments for assume_values_already_prepared_by_model_object()
5328
-     *
5329
-     * @return int
5330
-     */
5331
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5332
-    {
5333
-        return $this->_values_already_prepared_by_model_object;
5334
-    }
5335
-
5336
-
5337
-
5338
-    /**
5339
-     * Gets all the indexes on this model
5340
-     *
5341
-     * @return EE_Index[]
5342
-     */
5343
-    public function indexes()
5344
-    {
5345
-        return $this->_indexes;
5346
-    }
5347
-
5348
-
5349
-
5350
-    /**
5351
-     * Gets all the Unique Indexes on this model
5352
-     *
5353
-     * @return EE_Unique_Index[]
5354
-     */
5355
-    public function unique_indexes()
5356
-    {
5357
-        $unique_indexes = array();
5358
-        foreach ($this->_indexes as $name => $index) {
5359
-            if ($index instanceof EE_Unique_Index) {
5360
-                $unique_indexes [$name] = $index;
5361
-            }
5362
-        }
5363
-        return $unique_indexes;
5364
-    }
5365
-
5366
-
5367
-
5368
-    /**
5369
-     * Gets all the fields which, when combined, make the primary key.
5370
-     * This is usually just an array with 1 element (the primary key), but in cases
5371
-     * where there is no primary key, it's a combination of fields as defined
5372
-     * on a primary index
5373
-     *
5374
-     * @return EE_Model_Field_Base[] indexed by the field's name
5375
-     * @throws \EE_Error
5376
-     */
5377
-    public function get_combined_primary_key_fields()
5378
-    {
5379
-        foreach ($this->indexes() as $index) {
5380
-            if ($index instanceof EE_Primary_Key_Index) {
5381
-                return $index->fields();
5382
-            }
5383
-        }
5384
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5385
-    }
5386
-
5387
-
5388
-
5389
-    /**
5390
-     * Used to build a primary key string (when the model has no primary key),
5391
-     * which can be used a unique string to identify this model object.
5392
-     *
5393
-     * @param array $cols_n_values keys are field names, values are their values
5394
-     * @return string
5395
-     * @throws \EE_Error
5396
-     */
5397
-    public function get_index_primary_key_string($cols_n_values)
5398
-    {
5399
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5400
-            $this->get_combined_primary_key_fields());
5401
-        return http_build_query($cols_n_values_for_primary_key_index);
5402
-    }
5403
-
5404
-
5405
-
5406
-    /**
5407
-     * Gets the field values from the primary key string
5408
-     *
5409
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5410
-     * @param string $index_primary_key_string
5411
-     * @return null|array
5412
-     * @throws \EE_Error
5413
-     */
5414
-    public function parse_index_primary_key_string($index_primary_key_string)
5415
-    {
5416
-        $key_fields = $this->get_combined_primary_key_fields();
5417
-        //check all of them are in the $id
5418
-        $key_vals_in_combined_pk = array();
5419
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5420
-        foreach ($key_fields as $key_field_name => $field_obj) {
5421
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5422
-                return null;
5423
-            }
5424
-        }
5425
-        return $key_vals_in_combined_pk;
5426
-    }
5427
-
5428
-
5429
-
5430
-    /**
5431
-     * verifies that an array of key-value pairs for model fields has a key
5432
-     * for each field comprising the primary key index
5433
-     *
5434
-     * @param array $key_vals
5435
-     * @return boolean
5436
-     * @throws \EE_Error
5437
-     */
5438
-    public function has_all_combined_primary_key_fields($key_vals)
5439
-    {
5440
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5441
-        foreach ($keys_it_should_have as $key) {
5442
-            if (! isset($key_vals[$key])) {
5443
-                return false;
5444
-            }
5445
-        }
5446
-        return true;
5447
-    }
5448
-
5449
-
5450
-
5451
-    /**
5452
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5453
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5454
-     *
5455
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5456
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5457
-     * @throws EE_Error
5458
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5459
-     *                                                              indexed)
5460
-     */
5461
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5462
-    {
5463
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5464
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5465
-        } elseif (is_array($model_object_or_attributes_array)) {
5466
-            $attributes_array = $model_object_or_attributes_array;
5467
-        } else {
5468
-            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",
5469
-                "event_espresso"), $model_object_or_attributes_array));
5470
-        }
5471
-        //even copies obviously won't have the same ID, so remove the primary key
5472
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5473
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5474
-            unset($attributes_array[$this->primary_key_name()]);
5475
-        }
5476
-        if (isset($query_params[0])) {
5477
-            $query_params[0] = array_merge($attributes_array, $query_params);
5478
-        } else {
5479
-            $query_params[0] = $attributes_array;
5480
-        }
5481
-        return $this->get_all($query_params);
5482
-    }
5483
-
5484
-
5485
-
5486
-    /**
5487
-     * Gets the first copy we find. See get_all_copies for more details
5488
-     *
5489
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5490
-     * @param array $query_params
5491
-     * @return EE_Base_Class
5492
-     * @throws \EE_Error
5493
-     */
5494
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5495
-    {
5496
-        if (! is_array($query_params)) {
5497
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5498
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5499
-                    gettype($query_params)), '4.6.0');
5500
-            $query_params = array();
5501
-        }
5502
-        $query_params['limit'] = 1;
5503
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5504
-        if (is_array($copies)) {
5505
-            return array_shift($copies);
5506
-        } else {
5507
-            return null;
5508
-        }
5509
-    }
5510
-
5511
-
5512
-
5513
-    /**
5514
-     * Updates the item with the specified id. Ignores default query parameters because
5515
-     * we have specified the ID, and its assumed we KNOW what we're doing
5516
-     *
5517
-     * @param array      $fields_n_values keys are field names, values are their new values
5518
-     * @param int|string $id              the value of the primary key to update
5519
-     * @return int number of rows updated
5520
-     * @throws \EE_Error
5521
-     */
5522
-    public function update_by_ID($fields_n_values, $id)
5523
-    {
5524
-        $query_params = array(
5525
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5526
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5527
-        );
5528
-        return $this->update($fields_n_values, $query_params);
5529
-    }
5530
-
5531
-
5532
-
5533
-    /**
5534
-     * Changes an operator which was supplied to the models into one usable in SQL
5535
-     *
5536
-     * @param string $operator_supplied
5537
-     * @return string an operator which can be used in SQL
5538
-     * @throws EE_Error
5539
-     */
5540
-    private function _prepare_operator_for_sql($operator_supplied)
5541
-    {
5542
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5543
-            : null;
5544
-        if ($sql_operator) {
5545
-            return $sql_operator;
5546
-        } else {
5547
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5548
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5549
-        }
5550
-    }
5551
-
5552
-
5553
-
5554
-    /**
5555
-     * Gets an array where keys are the primary keys and values are their 'names'
5556
-     * (as determined by the model object's name() function, which is often overridden)
5557
-     *
5558
-     * @param array $query_params like get_all's
5559
-     * @return string[]
5560
-     * @throws \EE_Error
5561
-     */
5562
-    public function get_all_names($query_params = array())
5563
-    {
5564
-        $objs = $this->get_all($query_params);
5565
-        $names = array();
5566
-        foreach ($objs as $obj) {
5567
-            $names[$obj->ID()] = $obj->name();
5568
-        }
5569
-        return $names;
5570
-    }
5571
-
5572
-
5573
-
5574
-    /**
5575
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5576
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5577
-     * this is duplicated effort and reduces efficiency) you would be better to use
5578
-     * array_keys() on $model_objects.
5579
-     *
5580
-     * @param \EE_Base_Class[] $model_objects
5581
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5582
-     *                                               in the returned array
5583
-     * @return array
5584
-     * @throws \EE_Error
5585
-     */
5586
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5587
-    {
5588
-        if (! $this->has_primary_key_field()) {
5589
-            if (WP_DEBUG) {
5590
-                EE_Error::add_error(
5591
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5592
-                    __FILE__,
5593
-                    __FUNCTION__,
5594
-                    __LINE__
5595
-                );
5596
-            }
5597
-        }
5598
-        $IDs = array();
5599
-        foreach ($model_objects as $model_object) {
5600
-            $id = $model_object->ID();
5601
-            if (! $id) {
5602
-                if ($filter_out_empty_ids) {
5603
-                    continue;
5604
-                }
5605
-                if (WP_DEBUG) {
5606
-                    EE_Error::add_error(
5607
-                        __(
5608
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5609
-                            'event_espresso'
5610
-                        ),
5611
-                        __FILE__,
5612
-                        __FUNCTION__,
5613
-                        __LINE__
5614
-                    );
5615
-                }
5616
-            }
5617
-            $IDs[] = $id;
5618
-        }
5619
-        return $IDs;
5620
-    }
5621
-
5622
-
5623
-
5624
-    /**
5625
-     * Returns the string used in capabilities relating to this model. If there
5626
-     * are no capabilities that relate to this model returns false
5627
-     *
5628
-     * @return string|false
5629
-     */
5630
-    public function cap_slug()
5631
-    {
5632
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5633
-    }
5634
-
5635
-
5636
-
5637
-    /**
5638
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5639
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5640
-     * only returns the cap restrictions array in that context (ie, the array
5641
-     * at that key)
5642
-     *
5643
-     * @param string $context
5644
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5645
-     * @throws \EE_Error
5646
-     */
5647
-    public function cap_restrictions($context = EEM_Base::caps_read)
5648
-    {
5649
-        EEM_Base::verify_is_valid_cap_context($context);
5650
-        //check if we ought to run the restriction generator first
5651
-        if (
5652
-            isset($this->_cap_restriction_generators[$context])
5653
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5654
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5655
-        ) {
5656
-            $this->_cap_restrictions[$context] = array_merge(
5657
-                $this->_cap_restrictions[$context],
5658
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5659
-            );
5660
-        }
5661
-        //and make sure we've finalized the construction of each restriction
5662
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5663
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5664
-                $where_conditions_obj->_finalize_construct($this);
5665
-            }
5666
-        }
5667
-        return $this->_cap_restrictions[$context];
5668
-    }
5669
-
5670
-
5671
-
5672
-    /**
5673
-     * Indicating whether or not this model thinks its a wp core model
5674
-     *
5675
-     * @return boolean
5676
-     */
5677
-    public function is_wp_core_model()
5678
-    {
5679
-        return $this->_wp_core_model;
5680
-    }
5681
-
5682
-
5683
-
5684
-    /**
5685
-     * Gets all the caps that are missing which impose a restriction on
5686
-     * queries made in this context
5687
-     *
5688
-     * @param string $context one of EEM_Base::caps_ constants
5689
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5690
-     * @throws \EE_Error
5691
-     */
5692
-    public function caps_missing($context = EEM_Base::caps_read)
5693
-    {
5694
-        $missing_caps = array();
5695
-        $cap_restrictions = $this->cap_restrictions($context);
5696
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5697
-            if (! EE_Capabilities::instance()
5698
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5699
-            ) {
5700
-                $missing_caps[$cap] = $restriction_if_no_cap;
5701
-            }
5702
-        }
5703
-        return $missing_caps;
5704
-    }
5705
-
5706
-
5707
-
5708
-    /**
5709
-     * Gets the mapping from capability contexts to action strings used in capability names
5710
-     *
5711
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5712
-     * one of 'read', 'edit', or 'delete'
5713
-     */
5714
-    public function cap_contexts_to_cap_action_map()
5715
-    {
5716
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5717
-            $this);
5718
-    }
5719
-
5720
-
5721
-
5722
-    /**
5723
-     * Gets the action string for the specified capability context
5724
-     *
5725
-     * @param string $context
5726
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5727
-     * @throws \EE_Error
5728
-     */
5729
-    public function cap_action_for_context($context)
5730
-    {
5731
-        $mapping = $this->cap_contexts_to_cap_action_map();
5732
-        if (isset($mapping[$context])) {
5733
-            return $mapping[$context];
5734
-        }
5735
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5736
-            return $action;
5737
-        }
5738
-        throw new EE_Error(
5739
-            sprintf(
5740
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5741
-                $context,
5742
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5743
-            )
5744
-        );
5745
-    }
5746
-
5747
-
5748
-
5749
-    /**
5750
-     * Returns all the capability contexts which are valid when querying models
5751
-     *
5752
-     * @return array
5753
-     */
5754
-    public static function valid_cap_contexts()
5755
-    {
5756
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5757
-            self::caps_read,
5758
-            self::caps_read_admin,
5759
-            self::caps_edit,
5760
-            self::caps_delete,
5761
-        ));
5762
-    }
5763
-
5764
-
5765
-
5766
-    /**
5767
-     * Returns all valid options for 'default_where_conditions'
5768
-     *
5769
-     * @return array
5770
-     */
5771
-    public static function valid_default_where_conditions()
5772
-    {
5773
-        return array(
5774
-            EEM_Base::default_where_conditions_all,
5775
-            EEM_Base::default_where_conditions_this_only,
5776
-            EEM_Base::default_where_conditions_others_only,
5777
-            EEM_Base::default_where_conditions_minimum_all,
5778
-            EEM_Base::default_where_conditions_minimum_others,
5779
-            EEM_Base::default_where_conditions_none
5780
-        );
5781
-    }
5782
-
5783
-    // public static function default_where_conditions_full
5784
-    /**
5785
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5786
-     *
5787
-     * @param string $context
5788
-     * @return bool
5789
-     * @throws \EE_Error
5790
-     */
5791
-    static public function verify_is_valid_cap_context($context)
5792
-    {
5793
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5794
-        if (in_array($context, $valid_cap_contexts)) {
5795
-            return true;
5796
-        } else {
5797
-            throw new EE_Error(
5798
-                sprintf(
5799
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5800
-                        'event_espresso'),
5801
-                    $context,
5802
-                    'EEM_Base',
5803
-                    implode(',', $valid_cap_contexts)
5804
-                )
5805
-            );
5806
-        }
5807
-    }
5808
-
5809
-
5810
-
5811
-    /**
5812
-     * Clears all the models field caches. This is only useful when a sub-class
5813
-     * might have added a field or something and these caches might be invalidated
5814
-     */
5815
-    protected function _invalidate_field_caches()
5816
-    {
5817
-        $this->_cache_foreign_key_to_fields = array();
5818
-        $this->_cached_fields = null;
5819
-        $this->_cached_fields_non_db_only = null;
5820
-    }
5821
-
5822
-
5823
-
5824
-    /**
5825
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5826
-     * (eg "and", "or", "not").
5827
-     *
5828
-     * @return array
5829
-     */
5830
-    public function logic_query_param_keys()
5831
-    {
5832
-        return $this->_logic_query_param_keys;
5833
-    }
5834
-
5835
-
5836
-
5837
-    /**
5838
-     * Determines whether or not the where query param array key is for a logic query param.
5839
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5840
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5841
-     *
5842
-     * @param $query_param_key
5843
-     * @return bool
5844
-     */
5845
-    public function is_logic_query_param_key($query_param_key)
5846
-    {
5847
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5848
-            if ($query_param_key === $logic_query_param_key
5849
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5850
-            ) {
5851
-                return true;
5852
-            }
5853
-        }
5854
-        return false;
5855
-    }
3615
+		}
3616
+		return $null_friendly_where_conditions;
3617
+	}
3618
+
3619
+
3620
+
3621
+	/**
3622
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3623
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3624
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3625
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3626
+	 *
3627
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3628
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3629
+	 */
3630
+	private function _get_default_where_conditions($model_relation_path = null)
3631
+	{
3632
+		if ($this->_ignore_where_strategy) {
3633
+			return array();
3634
+		}
3635
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3636
+	}
3637
+
3638
+
3639
+
3640
+	/**
3641
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3642
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3643
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3644
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3645
+	 * Similar to _get_default_where_conditions
3646
+	 *
3647
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3648
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3649
+	 */
3650
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3651
+	{
3652
+		if ($this->_ignore_where_strategy) {
3653
+			return array();
3654
+		}
3655
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3656
+	}
3657
+
3658
+
3659
+
3660
+	/**
3661
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3662
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3663
+	 *
3664
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3665
+	 * @return string
3666
+	 * @throws \EE_Error
3667
+	 */
3668
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3669
+	{
3670
+		$selects = $this->_get_columns_to_select_for_this_model();
3671
+		foreach (
3672
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3673
+			$name_of_other_model_included
3674
+		) {
3675
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3676
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3677
+			foreach ($other_model_selects as $key => $value) {
3678
+				$selects[] = $value;
3679
+			}
3680
+		}
3681
+		return implode(", ", $selects);
3682
+	}
3683
+
3684
+
3685
+
3686
+	/**
3687
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3688
+	 * So that's going to be the columns for all the fields on the model
3689
+	 *
3690
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3691
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3692
+	 */
3693
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3694
+	{
3695
+		$fields = $this->field_settings();
3696
+		$selects = array();
3697
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3698
+			$this->get_this_model_name());
3699
+		foreach ($fields as $field_obj) {
3700
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3701
+						 . $field_obj->get_table_alias()
3702
+						 . "."
3703
+						 . $field_obj->get_table_column()
3704
+						 . " AS '"
3705
+						 . $table_alias_with_model_relation_chain_prefix
3706
+						 . $field_obj->get_table_alias()
3707
+						 . "."
3708
+						 . $field_obj->get_table_column()
3709
+						 . "'";
3710
+		}
3711
+		//make sure we are also getting the PKs of each table
3712
+		$tables = $this->get_tables();
3713
+		if (count($tables) > 1) {
3714
+			foreach ($tables as $table_obj) {
3715
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3716
+									   . $table_obj->get_fully_qualified_pk_column();
3717
+				if (! in_array($qualified_pk_column, $selects)) {
3718
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3719
+				}
3720
+			}
3721
+		}
3722
+		return $selects;
3723
+	}
3724
+
3725
+
3726
+
3727
+	/**
3728
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3729
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3730
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3731
+	 * SQL for joining, and the data types
3732
+	 *
3733
+	 * @param null|string                 $original_query_param
3734
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3735
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3736
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3737
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3738
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3739
+	 *                                                          or 'Registration's
3740
+	 * @param string                      $original_query_param what it originally was (eg
3741
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3742
+	 *                                                          matches $query_param
3743
+	 * @throws EE_Error
3744
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3745
+	 */
3746
+	private function _extract_related_model_info_from_query_param(
3747
+		$query_param,
3748
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3749
+		$query_param_type,
3750
+		$original_query_param = null
3751
+	) {
3752
+		if ($original_query_param === null) {
3753
+			$original_query_param = $query_param;
3754
+		}
3755
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3756
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3757
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3758
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3759
+		//check to see if we have a field on this model
3760
+		$this_model_fields = $this->field_settings(true);
3761
+		if (array_key_exists($query_param, $this_model_fields)) {
3762
+			if ($allow_fields) {
3763
+				return;
3764
+			} else {
3765
+				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",
3766
+					"event_espresso"),
3767
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3768
+			}
3769
+		} //check if this is a special logic query param
3770
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3771
+			if ($allow_logic_query_params) {
3772
+				return;
3773
+			} else {
3774
+				throw new EE_Error(
3775
+					sprintf(
3776
+						__('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',
3777
+							'event_espresso'),
3778
+						implode('", "', $this->_logic_query_param_keys),
3779
+						$query_param,
3780
+						get_class($this),
3781
+						'<br />',
3782
+						"\t"
3783
+						. ' $passed_in_query_info = <pre>'
3784
+						. print_r($passed_in_query_info, true)
3785
+						. '</pre>'
3786
+						. "\n\t"
3787
+						. ' $query_param_type = '
3788
+						. $query_param_type
3789
+						. "\n\t"
3790
+						. ' $original_query_param = '
3791
+						. $original_query_param
3792
+					)
3793
+				);
3794
+			}
3795
+		} //check if it's a custom selection
3796
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3797
+			return;
3798
+		}
3799
+		//check if has a model name at the beginning
3800
+		//and
3801
+		//check if it's a field on a related model
3802
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3803
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3804
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3805
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3806
+				if ($query_param === '') {
3807
+					//nothing left to $query_param
3808
+					//we should actually end in a field name, not a model like this!
3809
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3810
+						"event_espresso"),
3811
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3812
+				} else {
3813
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3814
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3815
+						$passed_in_query_info, $query_param_type, $original_query_param);
3816
+					return;
3817
+				}
3818
+			} elseif ($query_param === $valid_related_model_name) {
3819
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3820
+				return;
3821
+			}
3822
+		}
3823
+		//ok so $query_param didn't start with a model name
3824
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3825
+		//it's wack, that's what it is
3826
+		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",
3827
+			"event_espresso"),
3828
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3829
+	}
3830
+
3831
+
3832
+
3833
+	/**
3834
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3835
+	 * and store it on $passed_in_query_info
3836
+	 *
3837
+	 * @param string                      $model_name
3838
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3839
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3840
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3841
+	 *                                                          and are adding a join to 'Payment' with the original
3842
+	 *                                                          query param key
3843
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3844
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3845
+	 *                                                          Payment wants to add default query params so that it
3846
+	 *                                                          will know what models to prepend onto its default query
3847
+	 *                                                          params or in case it wants to rename tables (in case
3848
+	 *                                                          there are multiple joins to the same table)
3849
+	 * @return void
3850
+	 * @throws \EE_Error
3851
+	 */
3852
+	private function _add_join_to_model(
3853
+		$model_name,
3854
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3855
+		$original_query_param
3856
+	) {
3857
+		$relation_obj = $this->related_settings_for($model_name);
3858
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3859
+		//check if the relation is HABTM, because then we're essentially doing two joins
3860
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3861
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3862
+			$join_model_obj = $relation_obj->get_join_model();
3863
+			//replace the model specified with the join model for this relation chain, whi
3864
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3865
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3866
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3867
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3868
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3869
+			$passed_in_query_info->merge($new_query_info);
3870
+		}
3871
+		//now just join to the other table pointed to by the relation object, and add its data types
3872
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3873
+			array($model_relation_chain => $model_name),
3874
+			$relation_obj->get_join_statement($model_relation_chain));
3875
+		$passed_in_query_info->merge($new_query_info);
3876
+	}
3877
+
3878
+
3879
+
3880
+	/**
3881
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3882
+	 *
3883
+	 * @param array $where_params like EEM_Base::get_all
3884
+	 * @return string of SQL
3885
+	 * @throws \EE_Error
3886
+	 */
3887
+	private function _construct_where_clause($where_params)
3888
+	{
3889
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3890
+		if ($SQL) {
3891
+			return " WHERE " . $SQL;
3892
+		} else {
3893
+			return '';
3894
+		}
3895
+	}
3896
+
3897
+
3898
+
3899
+	/**
3900
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3901
+	 * and should be passed HAVING parameters, not WHERE parameters
3902
+	 *
3903
+	 * @param array $having_params
3904
+	 * @return string
3905
+	 * @throws \EE_Error
3906
+	 */
3907
+	private function _construct_having_clause($having_params)
3908
+	{
3909
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3910
+		if ($SQL) {
3911
+			return " HAVING " . $SQL;
3912
+		} else {
3913
+			return '';
3914
+		}
3915
+	}
3916
+
3917
+
3918
+
3919
+	/**
3920
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3921
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3922
+	 * EEM_Attendee.
3923
+	 *
3924
+	 * @param string $field_name
3925
+	 * @param string $model_name
3926
+	 * @return EE_Model_Field_Base
3927
+	 * @throws EE_Error
3928
+	 */
3929
+	protected function _get_field_on_model($field_name, $model_name)
3930
+	{
3931
+		$model_class = 'EEM_' . $model_name;
3932
+		$model_filepath = $model_class . ".model.php";
3933
+		if (is_readable($model_filepath)) {
3934
+			require_once($model_filepath);
3935
+			$model_instance = call_user_func($model_name . "::instance");
3936
+			/* @var $model_instance EEM_Base */
3937
+			return $model_instance->field_settings_for($field_name);
3938
+		} else {
3939
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3940
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3941
+		}
3942
+	}
3943
+
3944
+
3945
+
3946
+	/**
3947
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3948
+	 * Event_Meta.meta_value = 'foo'))"
3949
+	 *
3950
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3951
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3952
+	 * @throws EE_Error
3953
+	 * @return string of SQL
3954
+	 */
3955
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3956
+	{
3957
+		$where_clauses = array();
3958
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3959
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3960
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3961
+				switch ($query_param) {
3962
+					case 'not':
3963
+					case 'NOT':
3964
+						$where_clauses[] = "! ("
3965
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3966
+								$glue)
3967
+										   . ")";
3968
+						break;
3969
+					case 'and':
3970
+					case 'AND':
3971
+						$where_clauses[] = " ("
3972
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3973
+								' AND ')
3974
+										   . ")";
3975
+						break;
3976
+					case 'or':
3977
+					case 'OR':
3978
+						$where_clauses[] = " ("
3979
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3980
+								' OR ')
3981
+										   . ")";
3982
+						break;
3983
+				}
3984
+			} else {
3985
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3986
+				//if it's not a normal field, maybe it's a custom selection?
3987
+				if (! $field_obj) {
3988
+					if (isset($this->_custom_selections[$query_param][1])) {
3989
+						$field_obj = $this->_custom_selections[$query_param][1];
3990
+					} else {
3991
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3992
+							"event_espresso"), $query_param));
3993
+					}
3994
+				}
3995
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3996
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3997
+			}
3998
+		}
3999
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4000
+	}
4001
+
4002
+
4003
+
4004
+	/**
4005
+	 * Takes the input parameter and extract the table name (alias) and column name
4006
+	 *
4007
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4008
+	 * @throws EE_Error
4009
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4010
+	 */
4011
+	private function _deduce_column_name_from_query_param($query_param)
4012
+	{
4013
+		$field = $this->_deduce_field_from_query_param($query_param);
4014
+		if ($field) {
4015
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4016
+				$query_param);
4017
+			return $table_alias_prefix . $field->get_qualified_column();
4018
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4019
+			//maybe it's custom selection item?
4020
+			//if so, just use it as the "column name"
4021
+			return $query_param;
4022
+		} else {
4023
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4024
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4025
+		}
4026
+	}
4027
+
4028
+
4029
+
4030
+	/**
4031
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4032
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4033
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4034
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4035
+	 *
4036
+	 * @param string $condition_query_param_key
4037
+	 * @return string
4038
+	 */
4039
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4040
+	{
4041
+		$pos_of_star = strpos($condition_query_param_key, '*');
4042
+		if ($pos_of_star === false) {
4043
+			return $condition_query_param_key;
4044
+		} else {
4045
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4046
+			return $condition_query_param_sans_star;
4047
+		}
4048
+	}
4049
+
4050
+
4051
+
4052
+	/**
4053
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4054
+	 *
4055
+	 * @param                            mixed      array | string    $op_and_value
4056
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4057
+	 * @throws EE_Error
4058
+	 * @return string
4059
+	 */
4060
+	private function _construct_op_and_value($op_and_value, $field_obj)
4061
+	{
4062
+		if (is_array($op_and_value)) {
4063
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4064
+			if (! $operator) {
4065
+				$php_array_like_string = array();
4066
+				foreach ($op_and_value as $key => $value) {
4067
+					$php_array_like_string[] = "$key=>$value";
4068
+				}
4069
+				throw new EE_Error(
4070
+					sprintf(
4071
+						__(
4072
+							"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))",
4073
+							"event_espresso"
4074
+						),
4075
+						implode(",", $php_array_like_string)
4076
+					)
4077
+				);
4078
+			}
4079
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4080
+		} else {
4081
+			$operator = '=';
4082
+			$value = $op_and_value;
4083
+		}
4084
+		//check to see if the value is actually another field
4085
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4086
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4087
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4088
+			//in this case, the value should be an array, or at least a comma-separated list
4089
+			//it will need to handle a little differently
4090
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4091
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4092
+			return $operator . SP . $cleaned_value;
4093
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4094
+			//the value should be an array with count of two.
4095
+			if (count($value) !== 2) {
4096
+				throw new EE_Error(
4097
+					sprintf(
4098
+						__(
4099
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4100
+							'event_espresso'
4101
+						),
4102
+						"BETWEEN"
4103
+					)
4104
+				);
4105
+			}
4106
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4107
+			return $operator . SP . $cleaned_value;
4108
+		} elseif (in_array($operator, $this->_null_style_operators)) {
4109
+			if ($value !== null) {
4110
+				throw new EE_Error(
4111
+					sprintf(
4112
+						__(
4113
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4114
+							"event_espresso"
4115
+						),
4116
+						$value,
4117
+						$operator
4118
+					)
4119
+				);
4120
+			}
4121
+			return $operator;
4122
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
4123
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4124
+			//remove other junk. So just treat it as a string.
4125
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4126
+		} elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4127
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4128
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4129
+			throw new EE_Error(
4130
+				sprintf(
4131
+					__(
4132
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4133
+						'event_espresso'
4134
+					),
4135
+					$operator,
4136
+					$operator
4137
+				)
4138
+			);
4139
+		} elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4140
+			throw new EE_Error(
4141
+				sprintf(
4142
+					__(
4143
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4144
+						'event_espresso'
4145
+					),
4146
+					$operator,
4147
+					$operator
4148
+				)
4149
+			);
4150
+		} else {
4151
+			throw new EE_Error(
4152
+				sprintf(
4153
+					__(
4154
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4155
+						"event_espresso"
4156
+					),
4157
+					http_build_query($op_and_value)
4158
+				)
4159
+			);
4160
+		}
4161
+	}
4162
+
4163
+
4164
+
4165
+	/**
4166
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4167
+	 *
4168
+	 * @param array                      $values
4169
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4170
+	 *                                              '%s'
4171
+	 * @return string
4172
+	 * @throws \EE_Error
4173
+	 */
4174
+	public function _construct_between_value($values, $field_obj)
4175
+	{
4176
+		$cleaned_values = array();
4177
+		foreach ($values as $value) {
4178
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4179
+		}
4180
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4181
+	}
4182
+
4183
+
4184
+
4185
+	/**
4186
+	 * Takes an array or a comma-separated list of $values and cleans them
4187
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4188
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4189
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4190
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4191
+	 *
4192
+	 * @param mixed                      $values    array or comma-separated string
4193
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4194
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4195
+	 * @throws \EE_Error
4196
+	 */
4197
+	public function _construct_in_value($values, $field_obj)
4198
+	{
4199
+		//check if the value is a CSV list
4200
+		if (is_string($values)) {
4201
+			//in which case, turn it into an array
4202
+			$values = explode(",", $values);
4203
+		}
4204
+		$cleaned_values = array();
4205
+		foreach ($values as $value) {
4206
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4207
+		}
4208
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4209
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4210
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4211
+		if (empty($cleaned_values)) {
4212
+			$all_fields = $this->field_settings();
4213
+			$a_field = array_shift($all_fields);
4214
+			$main_table = $this->_get_main_table();
4215
+			$cleaned_values[] = "SELECT "
4216
+								. $a_field->get_table_column()
4217
+								. " FROM "
4218
+								. $main_table->get_table_name()
4219
+								. " WHERE FALSE";
4220
+		}
4221
+		return "(" . implode(",", $cleaned_values) . ")";
4222
+	}
4223
+
4224
+
4225
+
4226
+	/**
4227
+	 * @param mixed                      $value
4228
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4229
+	 * @throws EE_Error
4230
+	 * @return false|null|string
4231
+	 */
4232
+	private function _wpdb_prepare_using_field($value, $field_obj)
4233
+	{
4234
+		/** @type WPDB $wpdb */
4235
+		global $wpdb;
4236
+		if ($field_obj instanceof EE_Model_Field_Base) {
4237
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4238
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4239
+		} else {//$field_obj should really just be a data type
4240
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4241
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4242
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4243
+			}
4244
+			return $wpdb->prepare($field_obj, $value);
4245
+		}
4246
+	}
4247
+
4248
+
4249
+
4250
+	/**
4251
+	 * Takes the input parameter and finds the model field that it indicates.
4252
+	 *
4253
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4254
+	 * @throws EE_Error
4255
+	 * @return EE_Model_Field_Base
4256
+	 */
4257
+	protected function _deduce_field_from_query_param($query_param_name)
4258
+	{
4259
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4260
+		//which will help us find the database table and column
4261
+		$query_param_parts = explode(".", $query_param_name);
4262
+		if (empty($query_param_parts)) {
4263
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4264
+				'event_espresso'), $query_param_name));
4265
+		}
4266
+		$number_of_parts = count($query_param_parts);
4267
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4268
+		if ($number_of_parts === 1) {
4269
+			$field_name = $last_query_param_part;
4270
+			$model_obj = $this;
4271
+		} else {// $number_of_parts >= 2
4272
+			//the last part is the column name, and there are only 2parts. therefore...
4273
+			$field_name = $last_query_param_part;
4274
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4275
+		}
4276
+		try {
4277
+			return $model_obj->field_settings_for($field_name);
4278
+		} catch (EE_Error $e) {
4279
+			return null;
4280
+		}
4281
+	}
4282
+
4283
+
4284
+
4285
+	/**
4286
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4287
+	 * alias and column which corresponds to it
4288
+	 *
4289
+	 * @param string $field_name
4290
+	 * @throws EE_Error
4291
+	 * @return string
4292
+	 */
4293
+	public function _get_qualified_column_for_field($field_name)
4294
+	{
4295
+		$all_fields = $this->field_settings();
4296
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4297
+		if ($field) {
4298
+			return $field->get_qualified_column();
4299
+		} else {
4300
+			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.",
4301
+				'event_espresso'), $field_name, get_class($this)));
4302
+		}
4303
+	}
4304
+
4305
+
4306
+
4307
+	/**
4308
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4309
+	 * Example usage:
4310
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4311
+	 *      array(),
4312
+	 *      ARRAY_A,
4313
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4314
+	 *  );
4315
+	 * is equivalent to
4316
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4317
+	 * and
4318
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4319
+	 *      array(
4320
+	 *          array(
4321
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4322
+	 *          ),
4323
+	 *          ARRAY_A,
4324
+	 *          implode(
4325
+	 *              ', ',
4326
+	 *              array_merge(
4327
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4328
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4329
+	 *              )
4330
+	 *          )
4331
+	 *      )
4332
+	 *  );
4333
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4334
+	 *
4335
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4336
+	 *                                            and the one whose fields you are selecting for example: when querying
4337
+	 *                                            tickets model and selecting fields from the tickets model you would
4338
+	 *                                            leave this parameter empty, because no models are needed to join
4339
+	 *                                            between the queried model and the selected one. Likewise when
4340
+	 *                                            querying the datetime model and selecting fields from the tickets
4341
+	 *                                            model, it would also be left empty, because there is a direct
4342
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4343
+	 *                                            them together. However, when querying from the event model and
4344
+	 *                                            selecting fields from the ticket model, you should provide the string
4345
+	 *                                            'Datetime', indicating that the event model must first join to the
4346
+	 *                                            datetime model in order to find its relation to ticket model.
4347
+	 *                                            Also, when querying from the venue model and selecting fields from
4348
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4349
+	 *                                            indicating you need to join the venue model to the event model,
4350
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4351
+	 *                                            This string is used to deduce the prefix that gets added onto the
4352
+	 *                                            models' tables qualified columns
4353
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4354
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4355
+	 *                                            qualified column names
4356
+	 * @return array|string
4357
+	 */
4358
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4359
+	{
4360
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4361
+		$qualified_columns = array();
4362
+		foreach ($this->field_settings() as $field_name => $field) {
4363
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4364
+		}
4365
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4366
+	}
4367
+
4368
+
4369
+
4370
+	/**
4371
+	 * constructs the select use on special limit joins
4372
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4373
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4374
+	 * (as that is typically where the limits would be set).
4375
+	 *
4376
+	 * @param  string       $table_alias The table the select is being built for
4377
+	 * @param  mixed|string $limit       The limit for this select
4378
+	 * @return string                The final select join element for the query.
4379
+	 */
4380
+	public function _construct_limit_join_select($table_alias, $limit)
4381
+	{
4382
+		$SQL = '';
4383
+		foreach ($this->_tables as $table_obj) {
4384
+			if ($table_obj instanceof EE_Primary_Table) {
4385
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4386
+					? $table_obj->get_select_join_limit($limit)
4387
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4388
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4389
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4390
+					? $table_obj->get_select_join_limit_join($limit)
4391
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4392
+			}
4393
+		}
4394
+		return $SQL;
4395
+	}
4396
+
4397
+
4398
+
4399
+	/**
4400
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4401
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4402
+	 *
4403
+	 * @return string SQL
4404
+	 * @throws \EE_Error
4405
+	 */
4406
+	public function _construct_internal_join()
4407
+	{
4408
+		$SQL = $this->_get_main_table()->get_table_sql();
4409
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4410
+		return $SQL;
4411
+	}
4412
+
4413
+
4414
+
4415
+	/**
4416
+	 * Constructs the SQL for joining all the tables on this model.
4417
+	 * Normally $alias should be the primary table's alias, but in cases where
4418
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4419
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4420
+	 * alias, this will construct SQL like:
4421
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4422
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4423
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4424
+	 *
4425
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4426
+	 * @return string
4427
+	 */
4428
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4429
+	{
4430
+		$SQL = '';
4431
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4432
+		foreach ($this->_tables as $table_obj) {
4433
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4434
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4435
+					//so we're joining to this table, meaning the table is already in
4436
+					//the FROM statement, BUT the primary table isn't. So we want
4437
+					//to add the inverse join sql
4438
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4439
+				} else {
4440
+					//just add a regular JOIN to this table from the primary table
4441
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4442
+				}
4443
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4444
+		}
4445
+		return $SQL;
4446
+	}
4447
+
4448
+
4449
+
4450
+	/**
4451
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4452
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4453
+	 * their data type (eg, '%s', '%d', etc)
4454
+	 *
4455
+	 * @return array
4456
+	 */
4457
+	public function _get_data_types()
4458
+	{
4459
+		$data_types = array();
4460
+		foreach ($this->field_settings() as $field_obj) {
4461
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4462
+			/** @var $field_obj EE_Model_Field_Base */
4463
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4464
+		}
4465
+		return $data_types;
4466
+	}
4467
+
4468
+
4469
+
4470
+	/**
4471
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4472
+	 *
4473
+	 * @param string $model_name
4474
+	 * @throws EE_Error
4475
+	 * @return EEM_Base
4476
+	 */
4477
+	public function get_related_model_obj($model_name)
4478
+	{
4479
+		$model_classname = "EEM_" . $model_name;
4480
+		if (! class_exists($model_classname)) {
4481
+			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",
4482
+				'event_espresso'), $model_name, $model_classname));
4483
+		}
4484
+		return call_user_func($model_classname . "::instance");
4485
+	}
4486
+
4487
+
4488
+
4489
+	/**
4490
+	 * Returns the array of EE_ModelRelations for this model.
4491
+	 *
4492
+	 * @return EE_Model_Relation_Base[]
4493
+	 */
4494
+	public function relation_settings()
4495
+	{
4496
+		return $this->_model_relations;
4497
+	}
4498
+
4499
+
4500
+
4501
+	/**
4502
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4503
+	 * because without THOSE models, this model probably doesn't have much purpose.
4504
+	 * (Eg, without an event, datetimes have little purpose.)
4505
+	 *
4506
+	 * @return EE_Belongs_To_Relation[]
4507
+	 */
4508
+	public function belongs_to_relations()
4509
+	{
4510
+		$belongs_to_relations = array();
4511
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4512
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4513
+				$belongs_to_relations[$model_name] = $relation_obj;
4514
+			}
4515
+		}
4516
+		return $belongs_to_relations;
4517
+	}
4518
+
4519
+
4520
+
4521
+	/**
4522
+	 * Returns the specified EE_Model_Relation, or throws an exception
4523
+	 *
4524
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4525
+	 * @throws EE_Error
4526
+	 * @return EE_Model_Relation_Base
4527
+	 */
4528
+	public function related_settings_for($relation_name)
4529
+	{
4530
+		$relatedModels = $this->relation_settings();
4531
+		if (! array_key_exists($relation_name, $relatedModels)) {
4532
+			throw new EE_Error(
4533
+				sprintf(
4534
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4535
+						'event_espresso'),
4536
+					$relation_name,
4537
+					$this->_get_class_name(),
4538
+					implode(', ', array_keys($relatedModels))
4539
+				)
4540
+			);
4541
+		}
4542
+		return $relatedModels[$relation_name];
4543
+	}
4544
+
4545
+
4546
+
4547
+	/**
4548
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4549
+	 * fields
4550
+	 *
4551
+	 * @param string $fieldName
4552
+	 * @throws EE_Error
4553
+	 * @return EE_Model_Field_Base
4554
+	 */
4555
+	public function field_settings_for($fieldName)
4556
+	{
4557
+		$fieldSettings = $this->field_settings(true);
4558
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4559
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4560
+				get_class($this)));
4561
+		}
4562
+		return $fieldSettings[$fieldName];
4563
+	}
4564
+
4565
+
4566
+
4567
+	/**
4568
+	 * Checks if this field exists on this model
4569
+	 *
4570
+	 * @param string $fieldName a key in the model's _field_settings array
4571
+	 * @return boolean
4572
+	 */
4573
+	public function has_field($fieldName)
4574
+	{
4575
+		$fieldSettings = $this->field_settings(true);
4576
+		if (isset($fieldSettings[$fieldName])) {
4577
+			return true;
4578
+		} else {
4579
+			return false;
4580
+		}
4581
+	}
4582
+
4583
+
4584
+
4585
+	/**
4586
+	 * Returns whether or not this model has a relation to the specified model
4587
+	 *
4588
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4589
+	 * @return boolean
4590
+	 */
4591
+	public function has_relation($relation_name)
4592
+	{
4593
+		$relations = $this->relation_settings();
4594
+		if (isset($relations[$relation_name])) {
4595
+			return true;
4596
+		} else {
4597
+			return false;
4598
+		}
4599
+	}
4600
+
4601
+
4602
+
4603
+	/**
4604
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4605
+	 * Eg, on EE_Answer that would be ANS_ID field object
4606
+	 *
4607
+	 * @param $field_obj
4608
+	 * @return boolean
4609
+	 */
4610
+	public function is_primary_key_field($field_obj)
4611
+	{
4612
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4613
+	}
4614
+
4615
+
4616
+
4617
+	/**
4618
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4619
+	 * Eg, on EE_Answer that would be ANS_ID field object
4620
+	 *
4621
+	 * @return EE_Model_Field_Base
4622
+	 * @throws EE_Error
4623
+	 */
4624
+	public function get_primary_key_field()
4625
+	{
4626
+		if ($this->_primary_key_field === null) {
4627
+			foreach ($this->field_settings(true) as $field_obj) {
4628
+				if ($this->is_primary_key_field($field_obj)) {
4629
+					$this->_primary_key_field = $field_obj;
4630
+					break;
4631
+				}
4632
+			}
4633
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4634
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4635
+					get_class($this)));
4636
+			}
4637
+		}
4638
+		return $this->_primary_key_field;
4639
+	}
4640
+
4641
+
4642
+
4643
+	/**
4644
+	 * Returns whether or not not there is a primary key on this model.
4645
+	 * Internally does some caching.
4646
+	 *
4647
+	 * @return boolean
4648
+	 */
4649
+	public function has_primary_key_field()
4650
+	{
4651
+		if ($this->_has_primary_key_field === null) {
4652
+			try {
4653
+				$this->get_primary_key_field();
4654
+				$this->_has_primary_key_field = true;
4655
+			} catch (EE_Error $e) {
4656
+				$this->_has_primary_key_field = false;
4657
+			}
4658
+		}
4659
+		return $this->_has_primary_key_field;
4660
+	}
4661
+
4662
+
4663
+
4664
+	/**
4665
+	 * Finds the first field of type $field_class_name.
4666
+	 *
4667
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4668
+	 *                                 EE_Foreign_Key_Field, etc
4669
+	 * @return EE_Model_Field_Base or null if none is found
4670
+	 */
4671
+	public function get_a_field_of_type($field_class_name)
4672
+	{
4673
+		foreach ($this->field_settings() as $field) {
4674
+			if ($field instanceof $field_class_name) {
4675
+				return $field;
4676
+			}
4677
+		}
4678
+		return null;
4679
+	}
4680
+
4681
+
4682
+
4683
+	/**
4684
+	 * Gets a foreign key field pointing to model.
4685
+	 *
4686
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4687
+	 * @return EE_Foreign_Key_Field_Base
4688
+	 * @throws EE_Error
4689
+	 */
4690
+	public function get_foreign_key_to($model_name)
4691
+	{
4692
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4693
+			foreach ($this->field_settings() as $field) {
4694
+				if (
4695
+					$field instanceof EE_Foreign_Key_Field_Base
4696
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4697
+				) {
4698
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4699
+					break;
4700
+				}
4701
+			}
4702
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4703
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4704
+					'event_espresso'), $model_name, get_class($this)));
4705
+			}
4706
+		}
4707
+		return $this->_cache_foreign_key_to_fields[$model_name];
4708
+	}
4709
+
4710
+
4711
+
4712
+	/**
4713
+	 * Gets the actual table for the table alias
4714
+	 *
4715
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4716
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4717
+	 *                            Either one works
4718
+	 * @return EE_Table_Base
4719
+	 */
4720
+	public function get_table_for_alias($table_alias)
4721
+	{
4722
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4723
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4724
+	}
4725
+
4726
+
4727
+
4728
+	/**
4729
+	 * Returns a flat array of all field son this model, instead of organizing them
4730
+	 * by table_alias as they are in the constructor.
4731
+	 *
4732
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4733
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4734
+	 */
4735
+	public function field_settings($include_db_only_fields = false)
4736
+	{
4737
+		if ($include_db_only_fields) {
4738
+			if ($this->_cached_fields === null) {
4739
+				$this->_cached_fields = array();
4740
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4741
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4742
+						$this->_cached_fields[$field_name] = $field_obj;
4743
+					}
4744
+				}
4745
+			}
4746
+			return $this->_cached_fields;
4747
+		} else {
4748
+			if ($this->_cached_fields_non_db_only === null) {
4749
+				$this->_cached_fields_non_db_only = array();
4750
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4751
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4752
+						/** @var $field_obj EE_Model_Field_Base */
4753
+						if (! $field_obj->is_db_only_field()) {
4754
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4755
+						}
4756
+					}
4757
+				}
4758
+			}
4759
+			return $this->_cached_fields_non_db_only;
4760
+		}
4761
+	}
4762
+
4763
+
4764
+
4765
+	/**
4766
+	 *        cycle though array of attendees and create objects out of each item
4767
+	 *
4768
+	 * @access        private
4769
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4770
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4771
+	 *                           numerically indexed)
4772
+	 * @throws \EE_Error
4773
+	 */
4774
+	protected function _create_objects($rows = array())
4775
+	{
4776
+		$array_of_objects = array();
4777
+		if (empty($rows)) {
4778
+			return array();
4779
+		}
4780
+		$count_if_model_has_no_primary_key = 0;
4781
+		$has_primary_key = $this->has_primary_key_field();
4782
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4783
+		foreach ((array)$rows as $row) {
4784
+			if (empty($row)) {
4785
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4786
+				return array();
4787
+			}
4788
+			//check if we've already set this object in the results array,
4789
+			//in which case there's no need to process it further (again)
4790
+			if ($has_primary_key) {
4791
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4792
+					$row,
4793
+					$primary_key_field->get_qualified_column(),
4794
+					$primary_key_field->get_table_column()
4795
+				);
4796
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4797
+					continue;
4798
+				}
4799
+			}
4800
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4801
+			if (! $classInstance) {
4802
+				throw new EE_Error(
4803
+					sprintf(
4804
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4805
+						$this->get_this_model_name(),
4806
+						http_build_query($row)
4807
+					)
4808
+				);
4809
+			}
4810
+			//set the timezone on the instantiated objects
4811
+			$classInstance->set_timezone($this->_timezone);
4812
+			//make sure if there is any timezone setting present that we set the timezone for the object
4813
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4814
+			$array_of_objects[$key] = $classInstance;
4815
+			//also, for all the relations of type BelongsTo, see if we can cache
4816
+			//those related models
4817
+			//(we could do this for other relations too, but if there are conditions
4818
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4819
+			//so it requires a little more thought than just caching them immediately...)
4820
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4821
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4822
+					//check if this model's INFO is present. If so, cache it on the model
4823
+					$other_model = $relation_obj->get_other_model();
4824
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4825
+					//if we managed to make a model object from the results, cache it on the main model object
4826
+					if ($other_model_obj_maybe) {
4827
+						//set timezone on these other model objects if they are present
4828
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4829
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4830
+					}
4831
+				}
4832
+			}
4833
+		}
4834
+		return $array_of_objects;
4835
+	}
4836
+
4837
+
4838
+
4839
+	/**
4840
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4841
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4842
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4843
+	 * object (as set in the model_field!).
4844
+	 *
4845
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4846
+	 */
4847
+	public function create_default_object()
4848
+	{
4849
+		$this_model_fields_and_values = array();
4850
+		//setup the row using default values;
4851
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4852
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4853
+		}
4854
+		$className = $this->_get_class_name();
4855
+		$classInstance = EE_Registry::instance()
4856
+									->load_class($className, array($this_model_fields_and_values), false, false);
4857
+		return $classInstance;
4858
+	}
4859
+
4860
+
4861
+
4862
+	/**
4863
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4864
+	 *                             or an stdClass where each property is the name of a column,
4865
+	 * @return EE_Base_Class
4866
+	 * @throws \EE_Error
4867
+	 */
4868
+	public function instantiate_class_from_array_or_object($cols_n_values)
4869
+	{
4870
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4871
+			$cols_n_values = get_object_vars($cols_n_values);
4872
+		}
4873
+		$primary_key = null;
4874
+		//make sure the array only has keys that are fields/columns on this model
4875
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4876
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4877
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4878
+		}
4879
+		$className = $this->_get_class_name();
4880
+		//check we actually found results that we can use to build our model object
4881
+		//if not, return null
4882
+		if ($this->has_primary_key_field()) {
4883
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4884
+				return null;
4885
+			}
4886
+		} else if ($this->unique_indexes()) {
4887
+			$first_column = reset($this_model_fields_n_values);
4888
+			if (empty($first_column)) {
4889
+				return null;
4890
+			}
4891
+		}
4892
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4893
+		if ($primary_key) {
4894
+			$classInstance = $this->get_from_entity_map($primary_key);
4895
+			if (! $classInstance) {
4896
+				$classInstance = EE_Registry::instance()
4897
+											->load_class($className,
4898
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4899
+				// add this new object to the entity map
4900
+				$classInstance = $this->add_to_entity_map($classInstance);
4901
+			}
4902
+		} else {
4903
+			$classInstance = EE_Registry::instance()
4904
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4905
+											true, false);
4906
+		}
4907
+		//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.
4908
+		$this->set_timezone($classInstance->get_timezone());
4909
+		return $classInstance;
4910
+	}
4911
+
4912
+
4913
+
4914
+	/**
4915
+	 * Gets the model object from the  entity map if it exists
4916
+	 *
4917
+	 * @param int|string $id the ID of the model object
4918
+	 * @return EE_Base_Class
4919
+	 */
4920
+	public function get_from_entity_map($id)
4921
+	{
4922
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4923
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4924
+	}
4925
+
4926
+
4927
+
4928
+	/**
4929
+	 * add_to_entity_map
4930
+	 * Adds the object to the model's entity mappings
4931
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4932
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4933
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4934
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4935
+	 *        then this method should be called immediately after the update query
4936
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4937
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4938
+	 *
4939
+	 * @param    EE_Base_Class $object
4940
+	 * @throws EE_Error
4941
+	 * @return \EE_Base_Class
4942
+	 */
4943
+	public function add_to_entity_map(EE_Base_Class $object)
4944
+	{
4945
+		$className = $this->_get_class_name();
4946
+		if (! $object instanceof $className) {
4947
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4948
+				is_object($object) ? get_class($object) : $object, $className));
4949
+		}
4950
+		/** @var $object EE_Base_Class */
4951
+		if (! $object->ID()) {
4952
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4953
+				"event_espresso"), get_class($this)));
4954
+		}
4955
+		// double check it's not already there
4956
+		$classInstance = $this->get_from_entity_map($object->ID());
4957
+		if ($classInstance) {
4958
+			return $classInstance;
4959
+		} else {
4960
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4961
+			return $object;
4962
+		}
4963
+	}
4964
+
4965
+
4966
+
4967
+	/**
4968
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4969
+	 * if no identifier is provided, then the entire entity map is emptied
4970
+	 *
4971
+	 * @param int|string $id the ID of the model object
4972
+	 * @return boolean
4973
+	 */
4974
+	public function clear_entity_map($id = null)
4975
+	{
4976
+		if (empty($id)) {
4977
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4978
+			return true;
4979
+		}
4980
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4981
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4982
+			return true;
4983
+		}
4984
+		return false;
4985
+	}
4986
+
4987
+
4988
+
4989
+	/**
4990
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4991
+	 * Given an array where keys are column (or column alias) names and values,
4992
+	 * returns an array of their corresponding field names and database values
4993
+	 *
4994
+	 * @param array $cols_n_values
4995
+	 * @return array
4996
+	 */
4997
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4998
+	{
4999
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5000
+	}
5001
+
5002
+
5003
+
5004
+	/**
5005
+	 * _deduce_fields_n_values_from_cols_n_values
5006
+	 * Given an array where keys are column (or column alias) names and values,
5007
+	 * returns an array of their corresponding field names and database values
5008
+	 *
5009
+	 * @param string $cols_n_values
5010
+	 * @return array
5011
+	 */
5012
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5013
+	{
5014
+		$this_model_fields_n_values = array();
5015
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5016
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5017
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5018
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5019
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5020
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5021
+					if (! $field_obj->is_db_only_field()) {
5022
+						//prepare field as if its coming from db
5023
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5024
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5025
+					}
5026
+				}
5027
+			} else {
5028
+				//the table's rows existed. Use their values
5029
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5030
+					if (! $field_obj->is_db_only_field()) {
5031
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5032
+							$cols_n_values, $field_obj->get_qualified_column(),
5033
+							$field_obj->get_table_column()
5034
+						);
5035
+					}
5036
+				}
5037
+			}
5038
+		}
5039
+		return $this_model_fields_n_values;
5040
+	}
5041
+
5042
+
5043
+
5044
+	/**
5045
+	 * @param $cols_n_values
5046
+	 * @param $qualified_column
5047
+	 * @param $regular_column
5048
+	 * @return null
5049
+	 */
5050
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5051
+	{
5052
+		$value = null;
5053
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5054
+		//does the field on the model relate to this column retrieved from the db?
5055
+		//or is it a db-only field? (not relating to the model)
5056
+		if (isset($cols_n_values[$qualified_column])) {
5057
+			$value = $cols_n_values[$qualified_column];
5058
+		} elseif (isset($cols_n_values[$regular_column])) {
5059
+			$value = $cols_n_values[$regular_column];
5060
+		}
5061
+		return $value;
5062
+	}
5063
+
5064
+
5065
+
5066
+	/**
5067
+	 * refresh_entity_map_from_db
5068
+	 * Makes sure the model object in the entity map at $id assumes the values
5069
+	 * of the database (opposite of EE_base_Class::save())
5070
+	 *
5071
+	 * @param int|string $id
5072
+	 * @return EE_Base_Class
5073
+	 * @throws \EE_Error
5074
+	 */
5075
+	public function refresh_entity_map_from_db($id)
5076
+	{
5077
+		$obj_in_map = $this->get_from_entity_map($id);
5078
+		if ($obj_in_map) {
5079
+			$wpdb_results = $this->_get_all_wpdb_results(
5080
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5081
+			);
5082
+			if ($wpdb_results && is_array($wpdb_results)) {
5083
+				$one_row = reset($wpdb_results);
5084
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5085
+					$obj_in_map->set_from_db($field_name, $db_value);
5086
+				}
5087
+				//clear the cache of related model objects
5088
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5089
+					$obj_in_map->clear_cache($relation_name, null, true);
5090
+				}
5091
+			}
5092
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5093
+			return $obj_in_map;
5094
+		} else {
5095
+			return $this->get_one_by_ID($id);
5096
+		}
5097
+	}
5098
+
5099
+
5100
+
5101
+	/**
5102
+	 * refresh_entity_map_with
5103
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5104
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5105
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5106
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5107
+	 *
5108
+	 * @param int|string    $id
5109
+	 * @param EE_Base_Class $replacing_model_obj
5110
+	 * @return \EE_Base_Class
5111
+	 * @throws \EE_Error
5112
+	 */
5113
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5114
+	{
5115
+		$obj_in_map = $this->get_from_entity_map($id);
5116
+		if ($obj_in_map) {
5117
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5118
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5119
+					$obj_in_map->set($field_name, $value);
5120
+				}
5121
+				//make the model object in the entity map's cache match the $replacing_model_obj
5122
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5123
+					$obj_in_map->clear_cache($relation_name, null, true);
5124
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5125
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5126
+					}
5127
+				}
5128
+			}
5129
+			return $obj_in_map;
5130
+		} else {
5131
+			$this->add_to_entity_map($replacing_model_obj);
5132
+			return $replacing_model_obj;
5133
+		}
5134
+	}
5135
+
5136
+
5137
+
5138
+	/**
5139
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5140
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5141
+	 * require_once($this->_getClassName().".class.php");
5142
+	 *
5143
+	 * @return string
5144
+	 */
5145
+	private function _get_class_name()
5146
+	{
5147
+		return "EE_" . $this->get_this_model_name();
5148
+	}
5149
+
5150
+
5151
+
5152
+	/**
5153
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5154
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5155
+	 * it would be 'Events'.
5156
+	 *
5157
+	 * @param int $quantity
5158
+	 * @return string
5159
+	 */
5160
+	public function item_name($quantity = 1)
5161
+	{
5162
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5163
+	}
5164
+
5165
+
5166
+
5167
+	/**
5168
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5169
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5170
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5171
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5172
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5173
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5174
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5175
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5176
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5177
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5178
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5179
+	 *        return $previousReturnValue.$returnString;
5180
+	 * }
5181
+	 * require('EEM_Answer.model.php');
5182
+	 * $answer=EEM_Answer::instance();
5183
+	 * echo $answer->my_callback('monkeys',100);
5184
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5185
+	 *
5186
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5187
+	 * @param array  $args       array of original arguments passed to the function
5188
+	 * @throws EE_Error
5189
+	 * @return mixed whatever the plugin which calls add_filter decides
5190
+	 */
5191
+	public function __call($methodName, $args)
5192
+	{
5193
+		$className = get_class($this);
5194
+		$tagName = "FHEE__{$className}__{$methodName}";
5195
+		if (! has_filter($tagName)) {
5196
+			throw new EE_Error(
5197
+				sprintf(
5198
+					__('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 );',
5199
+						'event_espresso'),
5200
+					$methodName,
5201
+					$className,
5202
+					$tagName,
5203
+					'<br />'
5204
+				)
5205
+			);
5206
+		}
5207
+		return apply_filters($tagName, null, $this, $args);
5208
+	}
5209
+
5210
+
5211
+
5212
+	/**
5213
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5214
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5215
+	 *
5216
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5217
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5218
+	 *                                                       the object's class name
5219
+	 *                                                       or object's ID
5220
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5221
+	 *                                                       exists in the database. If it does not, we add it
5222
+	 * @throws EE_Error
5223
+	 * @return EE_Base_Class
5224
+	 */
5225
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5226
+	{
5227
+		$className = $this->_get_class_name();
5228
+		if ($base_class_obj_or_id instanceof $className) {
5229
+			$model_object = $base_class_obj_or_id;
5230
+		} else {
5231
+			$primary_key_field = $this->get_primary_key_field();
5232
+			if (
5233
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5234
+				&& (
5235
+					is_int($base_class_obj_or_id)
5236
+					|| is_string($base_class_obj_or_id)
5237
+				)
5238
+			) {
5239
+				// assume it's an ID.
5240
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5241
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5242
+			} else if (
5243
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5244
+				&& is_string($base_class_obj_or_id)
5245
+			) {
5246
+				// assume its a string representation of the object
5247
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5248
+			} else {
5249
+				throw new EE_Error(
5250
+					sprintf(
5251
+						__(
5252
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5253
+							'event_espresso'
5254
+						),
5255
+						$base_class_obj_or_id,
5256
+						$this->_get_class_name(),
5257
+						print_r($base_class_obj_or_id, true)
5258
+					)
5259
+				);
5260
+			}
5261
+		}
5262
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5263
+			$model_object->save();
5264
+		}
5265
+		return $model_object;
5266
+	}
5267
+
5268
+
5269
+
5270
+	/**
5271
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5272
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5273
+	 * returns it ID.
5274
+	 *
5275
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5276
+	 * @return int|string depending on the type of this model object's ID
5277
+	 * @throws EE_Error
5278
+	 */
5279
+	public function ensure_is_ID($base_class_obj_or_id)
5280
+	{
5281
+		$className = $this->_get_class_name();
5282
+		if ($base_class_obj_or_id instanceof $className) {
5283
+			/** @var $base_class_obj_or_id EE_Base_Class */
5284
+			$id = $base_class_obj_or_id->ID();
5285
+		} elseif (is_int($base_class_obj_or_id)) {
5286
+			//assume it's an ID
5287
+			$id = $base_class_obj_or_id;
5288
+		} elseif (is_string($base_class_obj_or_id)) {
5289
+			//assume its a string representation of the object
5290
+			$id = $base_class_obj_or_id;
5291
+		} else {
5292
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5293
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5294
+				print_r($base_class_obj_or_id, true)));
5295
+		}
5296
+		return $id;
5297
+	}
5298
+
5299
+
5300
+
5301
+	/**
5302
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5303
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5304
+	 * been sanitized and converted into the appropriate domain.
5305
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5306
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5307
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5308
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5309
+	 * $EVT = EEM_Event::instance(); $old_setting =
5310
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5311
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5312
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5313
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5314
+	 *
5315
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5316
+	 * @return void
5317
+	 */
5318
+	public function assume_values_already_prepared_by_model_object(
5319
+		$values_already_prepared = self::not_prepared_by_model_object
5320
+	) {
5321
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5322
+	}
5323
+
5324
+
5325
+
5326
+	/**
5327
+	 * Read comments for assume_values_already_prepared_by_model_object()
5328
+	 *
5329
+	 * @return int
5330
+	 */
5331
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5332
+	{
5333
+		return $this->_values_already_prepared_by_model_object;
5334
+	}
5335
+
5336
+
5337
+
5338
+	/**
5339
+	 * Gets all the indexes on this model
5340
+	 *
5341
+	 * @return EE_Index[]
5342
+	 */
5343
+	public function indexes()
5344
+	{
5345
+		return $this->_indexes;
5346
+	}
5347
+
5348
+
5349
+
5350
+	/**
5351
+	 * Gets all the Unique Indexes on this model
5352
+	 *
5353
+	 * @return EE_Unique_Index[]
5354
+	 */
5355
+	public function unique_indexes()
5356
+	{
5357
+		$unique_indexes = array();
5358
+		foreach ($this->_indexes as $name => $index) {
5359
+			if ($index instanceof EE_Unique_Index) {
5360
+				$unique_indexes [$name] = $index;
5361
+			}
5362
+		}
5363
+		return $unique_indexes;
5364
+	}
5365
+
5366
+
5367
+
5368
+	/**
5369
+	 * Gets all the fields which, when combined, make the primary key.
5370
+	 * This is usually just an array with 1 element (the primary key), but in cases
5371
+	 * where there is no primary key, it's a combination of fields as defined
5372
+	 * on a primary index
5373
+	 *
5374
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5375
+	 * @throws \EE_Error
5376
+	 */
5377
+	public function get_combined_primary_key_fields()
5378
+	{
5379
+		foreach ($this->indexes() as $index) {
5380
+			if ($index instanceof EE_Primary_Key_Index) {
5381
+				return $index->fields();
5382
+			}
5383
+		}
5384
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5385
+	}
5386
+
5387
+
5388
+
5389
+	/**
5390
+	 * Used to build a primary key string (when the model has no primary key),
5391
+	 * which can be used a unique string to identify this model object.
5392
+	 *
5393
+	 * @param array $cols_n_values keys are field names, values are their values
5394
+	 * @return string
5395
+	 * @throws \EE_Error
5396
+	 */
5397
+	public function get_index_primary_key_string($cols_n_values)
5398
+	{
5399
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5400
+			$this->get_combined_primary_key_fields());
5401
+		return http_build_query($cols_n_values_for_primary_key_index);
5402
+	}
5403
+
5404
+
5405
+
5406
+	/**
5407
+	 * Gets the field values from the primary key string
5408
+	 *
5409
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5410
+	 * @param string $index_primary_key_string
5411
+	 * @return null|array
5412
+	 * @throws \EE_Error
5413
+	 */
5414
+	public function parse_index_primary_key_string($index_primary_key_string)
5415
+	{
5416
+		$key_fields = $this->get_combined_primary_key_fields();
5417
+		//check all of them are in the $id
5418
+		$key_vals_in_combined_pk = array();
5419
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5420
+		foreach ($key_fields as $key_field_name => $field_obj) {
5421
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5422
+				return null;
5423
+			}
5424
+		}
5425
+		return $key_vals_in_combined_pk;
5426
+	}
5427
+
5428
+
5429
+
5430
+	/**
5431
+	 * verifies that an array of key-value pairs for model fields has a key
5432
+	 * for each field comprising the primary key index
5433
+	 *
5434
+	 * @param array $key_vals
5435
+	 * @return boolean
5436
+	 * @throws \EE_Error
5437
+	 */
5438
+	public function has_all_combined_primary_key_fields($key_vals)
5439
+	{
5440
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5441
+		foreach ($keys_it_should_have as $key) {
5442
+			if (! isset($key_vals[$key])) {
5443
+				return false;
5444
+			}
5445
+		}
5446
+		return true;
5447
+	}
5448
+
5449
+
5450
+
5451
+	/**
5452
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5453
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5454
+	 *
5455
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5456
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5457
+	 * @throws EE_Error
5458
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5459
+	 *                                                              indexed)
5460
+	 */
5461
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5462
+	{
5463
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5464
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5465
+		} elseif (is_array($model_object_or_attributes_array)) {
5466
+			$attributes_array = $model_object_or_attributes_array;
5467
+		} else {
5468
+			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",
5469
+				"event_espresso"), $model_object_or_attributes_array));
5470
+		}
5471
+		//even copies obviously won't have the same ID, so remove the primary key
5472
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5473
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5474
+			unset($attributes_array[$this->primary_key_name()]);
5475
+		}
5476
+		if (isset($query_params[0])) {
5477
+			$query_params[0] = array_merge($attributes_array, $query_params);
5478
+		} else {
5479
+			$query_params[0] = $attributes_array;
5480
+		}
5481
+		return $this->get_all($query_params);
5482
+	}
5483
+
5484
+
5485
+
5486
+	/**
5487
+	 * Gets the first copy we find. See get_all_copies for more details
5488
+	 *
5489
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5490
+	 * @param array $query_params
5491
+	 * @return EE_Base_Class
5492
+	 * @throws \EE_Error
5493
+	 */
5494
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5495
+	{
5496
+		if (! is_array($query_params)) {
5497
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5498
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5499
+					gettype($query_params)), '4.6.0');
5500
+			$query_params = array();
5501
+		}
5502
+		$query_params['limit'] = 1;
5503
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5504
+		if (is_array($copies)) {
5505
+			return array_shift($copies);
5506
+		} else {
5507
+			return null;
5508
+		}
5509
+	}
5510
+
5511
+
5512
+
5513
+	/**
5514
+	 * Updates the item with the specified id. Ignores default query parameters because
5515
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5516
+	 *
5517
+	 * @param array      $fields_n_values keys are field names, values are their new values
5518
+	 * @param int|string $id              the value of the primary key to update
5519
+	 * @return int number of rows updated
5520
+	 * @throws \EE_Error
5521
+	 */
5522
+	public function update_by_ID($fields_n_values, $id)
5523
+	{
5524
+		$query_params = array(
5525
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5526
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5527
+		);
5528
+		return $this->update($fields_n_values, $query_params);
5529
+	}
5530
+
5531
+
5532
+
5533
+	/**
5534
+	 * Changes an operator which was supplied to the models into one usable in SQL
5535
+	 *
5536
+	 * @param string $operator_supplied
5537
+	 * @return string an operator which can be used in SQL
5538
+	 * @throws EE_Error
5539
+	 */
5540
+	private function _prepare_operator_for_sql($operator_supplied)
5541
+	{
5542
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5543
+			: null;
5544
+		if ($sql_operator) {
5545
+			return $sql_operator;
5546
+		} else {
5547
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5548
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5549
+		}
5550
+	}
5551
+
5552
+
5553
+
5554
+	/**
5555
+	 * Gets an array where keys are the primary keys and values are their 'names'
5556
+	 * (as determined by the model object's name() function, which is often overridden)
5557
+	 *
5558
+	 * @param array $query_params like get_all's
5559
+	 * @return string[]
5560
+	 * @throws \EE_Error
5561
+	 */
5562
+	public function get_all_names($query_params = array())
5563
+	{
5564
+		$objs = $this->get_all($query_params);
5565
+		$names = array();
5566
+		foreach ($objs as $obj) {
5567
+			$names[$obj->ID()] = $obj->name();
5568
+		}
5569
+		return $names;
5570
+	}
5571
+
5572
+
5573
+
5574
+	/**
5575
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5576
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5577
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5578
+	 * array_keys() on $model_objects.
5579
+	 *
5580
+	 * @param \EE_Base_Class[] $model_objects
5581
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5582
+	 *                                               in the returned array
5583
+	 * @return array
5584
+	 * @throws \EE_Error
5585
+	 */
5586
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5587
+	{
5588
+		if (! $this->has_primary_key_field()) {
5589
+			if (WP_DEBUG) {
5590
+				EE_Error::add_error(
5591
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5592
+					__FILE__,
5593
+					__FUNCTION__,
5594
+					__LINE__
5595
+				);
5596
+			}
5597
+		}
5598
+		$IDs = array();
5599
+		foreach ($model_objects as $model_object) {
5600
+			$id = $model_object->ID();
5601
+			if (! $id) {
5602
+				if ($filter_out_empty_ids) {
5603
+					continue;
5604
+				}
5605
+				if (WP_DEBUG) {
5606
+					EE_Error::add_error(
5607
+						__(
5608
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5609
+							'event_espresso'
5610
+						),
5611
+						__FILE__,
5612
+						__FUNCTION__,
5613
+						__LINE__
5614
+					);
5615
+				}
5616
+			}
5617
+			$IDs[] = $id;
5618
+		}
5619
+		return $IDs;
5620
+	}
5621
+
5622
+
5623
+
5624
+	/**
5625
+	 * Returns the string used in capabilities relating to this model. If there
5626
+	 * are no capabilities that relate to this model returns false
5627
+	 *
5628
+	 * @return string|false
5629
+	 */
5630
+	public function cap_slug()
5631
+	{
5632
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5633
+	}
5634
+
5635
+
5636
+
5637
+	/**
5638
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5639
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5640
+	 * only returns the cap restrictions array in that context (ie, the array
5641
+	 * at that key)
5642
+	 *
5643
+	 * @param string $context
5644
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5645
+	 * @throws \EE_Error
5646
+	 */
5647
+	public function cap_restrictions($context = EEM_Base::caps_read)
5648
+	{
5649
+		EEM_Base::verify_is_valid_cap_context($context);
5650
+		//check if we ought to run the restriction generator first
5651
+		if (
5652
+			isset($this->_cap_restriction_generators[$context])
5653
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5654
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5655
+		) {
5656
+			$this->_cap_restrictions[$context] = array_merge(
5657
+				$this->_cap_restrictions[$context],
5658
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5659
+			);
5660
+		}
5661
+		//and make sure we've finalized the construction of each restriction
5662
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5663
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5664
+				$where_conditions_obj->_finalize_construct($this);
5665
+			}
5666
+		}
5667
+		return $this->_cap_restrictions[$context];
5668
+	}
5669
+
5670
+
5671
+
5672
+	/**
5673
+	 * Indicating whether or not this model thinks its a wp core model
5674
+	 *
5675
+	 * @return boolean
5676
+	 */
5677
+	public function is_wp_core_model()
5678
+	{
5679
+		return $this->_wp_core_model;
5680
+	}
5681
+
5682
+
5683
+
5684
+	/**
5685
+	 * Gets all the caps that are missing which impose a restriction on
5686
+	 * queries made in this context
5687
+	 *
5688
+	 * @param string $context one of EEM_Base::caps_ constants
5689
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5690
+	 * @throws \EE_Error
5691
+	 */
5692
+	public function caps_missing($context = EEM_Base::caps_read)
5693
+	{
5694
+		$missing_caps = array();
5695
+		$cap_restrictions = $this->cap_restrictions($context);
5696
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5697
+			if (! EE_Capabilities::instance()
5698
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5699
+			) {
5700
+				$missing_caps[$cap] = $restriction_if_no_cap;
5701
+			}
5702
+		}
5703
+		return $missing_caps;
5704
+	}
5705
+
5706
+
5707
+
5708
+	/**
5709
+	 * Gets the mapping from capability contexts to action strings used in capability names
5710
+	 *
5711
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5712
+	 * one of 'read', 'edit', or 'delete'
5713
+	 */
5714
+	public function cap_contexts_to_cap_action_map()
5715
+	{
5716
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5717
+			$this);
5718
+	}
5719
+
5720
+
5721
+
5722
+	/**
5723
+	 * Gets the action string for the specified capability context
5724
+	 *
5725
+	 * @param string $context
5726
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5727
+	 * @throws \EE_Error
5728
+	 */
5729
+	public function cap_action_for_context($context)
5730
+	{
5731
+		$mapping = $this->cap_contexts_to_cap_action_map();
5732
+		if (isset($mapping[$context])) {
5733
+			return $mapping[$context];
5734
+		}
5735
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5736
+			return $action;
5737
+		}
5738
+		throw new EE_Error(
5739
+			sprintf(
5740
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5741
+				$context,
5742
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5743
+			)
5744
+		);
5745
+	}
5746
+
5747
+
5748
+
5749
+	/**
5750
+	 * Returns all the capability contexts which are valid when querying models
5751
+	 *
5752
+	 * @return array
5753
+	 */
5754
+	public static function valid_cap_contexts()
5755
+	{
5756
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5757
+			self::caps_read,
5758
+			self::caps_read_admin,
5759
+			self::caps_edit,
5760
+			self::caps_delete,
5761
+		));
5762
+	}
5763
+
5764
+
5765
+
5766
+	/**
5767
+	 * Returns all valid options for 'default_where_conditions'
5768
+	 *
5769
+	 * @return array
5770
+	 */
5771
+	public static function valid_default_where_conditions()
5772
+	{
5773
+		return array(
5774
+			EEM_Base::default_where_conditions_all,
5775
+			EEM_Base::default_where_conditions_this_only,
5776
+			EEM_Base::default_where_conditions_others_only,
5777
+			EEM_Base::default_where_conditions_minimum_all,
5778
+			EEM_Base::default_where_conditions_minimum_others,
5779
+			EEM_Base::default_where_conditions_none
5780
+		);
5781
+	}
5782
+
5783
+	// public static function default_where_conditions_full
5784
+	/**
5785
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5786
+	 *
5787
+	 * @param string $context
5788
+	 * @return bool
5789
+	 * @throws \EE_Error
5790
+	 */
5791
+	static public function verify_is_valid_cap_context($context)
5792
+	{
5793
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5794
+		if (in_array($context, $valid_cap_contexts)) {
5795
+			return true;
5796
+		} else {
5797
+			throw new EE_Error(
5798
+				sprintf(
5799
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5800
+						'event_espresso'),
5801
+					$context,
5802
+					'EEM_Base',
5803
+					implode(',', $valid_cap_contexts)
5804
+				)
5805
+			);
5806
+		}
5807
+	}
5808
+
5809
+
5810
+
5811
+	/**
5812
+	 * Clears all the models field caches. This is only useful when a sub-class
5813
+	 * might have added a field or something and these caches might be invalidated
5814
+	 */
5815
+	protected function _invalidate_field_caches()
5816
+	{
5817
+		$this->_cache_foreign_key_to_fields = array();
5818
+		$this->_cached_fields = null;
5819
+		$this->_cached_fields_non_db_only = null;
5820
+	}
5821
+
5822
+
5823
+
5824
+	/**
5825
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5826
+	 * (eg "and", "or", "not").
5827
+	 *
5828
+	 * @return array
5829
+	 */
5830
+	public function logic_query_param_keys()
5831
+	{
5832
+		return $this->_logic_query_param_keys;
5833
+	}
5834
+
5835
+
5836
+
5837
+	/**
5838
+	 * Determines whether or not the where query param array key is for a logic query param.
5839
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5840
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5841
+	 *
5842
+	 * @param $query_param_key
5843
+	 * @return bool
5844
+	 */
5845
+	public function is_logic_query_param_key($query_param_key)
5846
+	{
5847
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5848
+			if ($query_param_key === $logic_query_param_key
5849
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5850
+			) {
5851
+				return true;
5852
+			}
5853
+		}
5854
+		return false;
5855
+	}
5856 5856
 
5857 5857
 
5858 5858
 
Please login to merge, or discard this patch.