Completed
Branch FET-10857-model-field-factory (305899)
by
unknown
57:17 queued 45:28
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/EE_Error.core.php 1 patch
Indentation   +1090 added lines, -1090 removed lines patch added patch discarded remove patch
@@ -5,8 +5,8 @@  discard block
 block discarded – undo
5 5
 // if you're a dev and want to receive all errors via email
6 6
 // add this to your wp-config.php: define( 'EE_ERROR_EMAILS', TRUE );
7 7
 if (defined('WP_DEBUG') && WP_DEBUG === true && defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS === true) {
8
-    set_error_handler(array('EE_Error', 'error_handler'));
9
-    register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
8
+	set_error_handler(array('EE_Error', 'error_handler'));
9
+	register_shutdown_function(array('EE_Error', 'fatal_error_handler'));
10 10
 }
11 11
 
12 12
 
@@ -23,259 +23,259 @@  discard block
 block discarded – undo
23 23
 {
24 24
 
25 25
 
26
-    /**
27
-     *    name of the file to log exceptions to
28
-     *
29
-     * @var string
30
-     */
31
-    private static $_exception_log_file = 'espresso_error_log.txt';
32
-
33
-    /**
34
-     *    stores details for all exception
35
-     *
36
-     * @var array
37
-     */
38
-    private static $_all_exceptions = array();
39
-
40
-    /**
41
-     *    tracks number of errors
42
-     *
43
-     * @var int
44
-     */
45
-    private static $_error_count = 0;
46
-
47
-    /**
48
-     *    has shutdown action been added ?
49
-     *
50
-     * @var array $_espresso_notices
51
-     */
52
-    private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
53
-
54
-
55
-
56
-    /**
57
-     * @override default exception handling
58
-     * @param string         $message
59
-     * @param int            $code
60
-     * @param Exception|null $previous
61
-     */
62
-    public function __construct($message, $code = 0, Exception $previous = null)
63
-    {
64
-        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
65
-            parent::__construct($message, $code);
66
-        } else {
67
-            parent::__construct($message, $code, $previous);
68
-        }
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     *    error_handler
75
-     *
76
-     * @param $code
77
-     * @param $message
78
-     * @param $file
79
-     * @param $line
80
-     * @return void
81
-     */
82
-    public static function error_handler($code, $message, $file, $line)
83
-    {
84
-        $type = EE_Error::error_type($code);
85
-        $site = site_url();
86
-        switch ($site) {
87
-            case 'http://ee4.eventespresso.com/' :
88
-            case 'http://ee4decaf.eventespresso.com/' :
89
-            case 'http://ee4hf.eventespresso.com/' :
90
-            case 'http://ee4a.eventespresso.com/' :
91
-            case 'http://ee4ad.eventespresso.com/' :
92
-            case 'http://ee4b.eventespresso.com/' :
93
-            case 'http://ee4bd.eventespresso.com/' :
94
-            case 'http://ee4d.eventespresso.com/' :
95
-            case 'http://ee4dd.eventespresso.com/' :
96
-                $to = '[email protected]';
97
-                break;
98
-            default :
99
-                $to = get_option('admin_email');
100
-        }
101
-        $subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
102
-        $msg = EE_Error::_format_error($type, $message, $file, $line);
103
-        if (function_exists('wp_mail')) {
104
-            add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
105
-            wp_mail($to, $subject, $msg);
106
-        }
107
-        echo '<div id="message" class="espresso-notices error"><p>';
108
-        echo $type . ': ' . $message . '<br />' . $file . ' line ' . $line;
109
-        echo '<br /></p></div>';
110
-    }
111
-
112
-
113
-
114
-    /**
115
-     * error_type
116
-     * http://www.php.net/manual/en/errorfunc.constants.php#109430
117
-     *
118
-     * @param $code
119
-     * @return string
120
-     */
121
-    public static function error_type($code)
122
-    {
123
-        switch ($code) {
124
-            case E_ERROR: // 1 //
125
-                return 'E_ERROR';
126
-            case E_WARNING: // 2 //
127
-                return 'E_WARNING';
128
-            case E_PARSE: // 4 //
129
-                return 'E_PARSE';
130
-            case E_NOTICE: // 8 //
131
-                return 'E_NOTICE';
132
-            case E_CORE_ERROR: // 16 //
133
-                return 'E_CORE_ERROR';
134
-            case E_CORE_WARNING: // 32 //
135
-                return 'E_CORE_WARNING';
136
-            case E_COMPILE_ERROR: // 64 //
137
-                return 'E_COMPILE_ERROR';
138
-            case E_COMPILE_WARNING: // 128 //
139
-                return 'E_COMPILE_WARNING';
140
-            case E_USER_ERROR: // 256 //
141
-                return 'E_USER_ERROR';
142
-            case E_USER_WARNING: // 512 //
143
-                return 'E_USER_WARNING';
144
-            case E_USER_NOTICE: // 1024 //
145
-                return 'E_USER_NOTICE';
146
-            case E_STRICT: // 2048 //
147
-                return 'E_STRICT';
148
-            case E_RECOVERABLE_ERROR: // 4096 //
149
-                return 'E_RECOVERABLE_ERROR';
150
-            case E_DEPRECATED: // 8192 //
151
-                return 'E_DEPRECATED';
152
-            case E_USER_DEPRECATED: // 16384 //
153
-                return 'E_USER_DEPRECATED';
154
-            case E_ALL: // 16384 //
155
-                return 'E_ALL';
156
-        }
157
-        return '';
158
-    }
159
-
160
-
161
-
162
-    /**
163
-     *    fatal_error_handler
164
-     *
165
-     * @return void
166
-     */
167
-    public static function fatal_error_handler()
168
-    {
169
-        $last_error = error_get_last();
170
-        if ($last_error['type'] === E_ERROR) {
171
-            EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
172
-        }
173
-    }
174
-
175
-
176
-
177
-    /**
178
-     * _format_error
179
-     *
180
-     * @param $code
181
-     * @param $message
182
-     * @param $file
183
-     * @param $line
184
-     * @return string
185
-     */
186
-    private static function _format_error($code, $message, $file, $line)
187
-    {
188
-        $html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
189
-        $html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
190
-        $html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
191
-        $html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
192
-        $html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
193
-        $html .= '</tbody></table>';
194
-        return $html;
195
-    }
196
-
197
-
198
-
199
-    /**
200
-     * set_content_type
201
-     *
202
-     * @param $content_type
203
-     * @return string
204
-     */
205
-    public static function set_content_type($content_type)
206
-    {
207
-        return 'text/html';
208
-    }
209
-
210
-
211
-
212
-    /**
213
-     * @return void
214
-     * @throws EE_Error
215
-     * @throws ReflectionException
216
-     */
217
-    public function get_error()
218
-    {
219
-        if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
220
-            throw $this;
221
-        }
222
-        // get separate user and developer messages if they exist
223
-        $msg = explode('||', $this->getMessage());
224
-        $user_msg = $msg[0];
225
-        $dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
226
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
227
-        // add details to _all_exceptions array
228
-        $x_time = time();
229
-        self::$_all_exceptions[$x_time]['name'] = get_class($this);
230
-        self::$_all_exceptions[$x_time]['file'] = $this->getFile();
231
-        self::$_all_exceptions[$x_time]['line'] = $this->getLine();
232
-        self::$_all_exceptions[$x_time]['msg'] = $msg;
233
-        self::$_all_exceptions[$x_time]['code'] = $this->getCode();
234
-        self::$_all_exceptions[$x_time]['trace'] = $this->getTrace();
235
-        self::$_all_exceptions[$x_time]['string'] = $this->getTraceAsString();
236
-        self::$_error_count++;
237
-        //add_action( 'shutdown', array( $this, 'display_errors' ));
238
-        $this->display_errors();
239
-    }
240
-
241
-
242
-
243
-    /**
244
-     *    has_error
245
-     *
246
-     * @param bool   $check_stored
247
-     * @param string $type_to_check
248
-     * @return bool
249
-     */
250
-    public static function has_error($check_stored = false, $type_to_check = 'errors')
251
-    {
252
-        $has_error = isset(self::$_espresso_notices[$type_to_check])
253
-                     && ! empty(self::$_espresso_notices[$type_to_check])
254
-            ? true
255
-            : false;
256
-        if ($check_stored && ! $has_error) {
257
-            $notices = (array)get_option('ee_notices', array());
258
-            foreach ($notices as $type => $notice) {
259
-                if ($type === $type_to_check && $notice) {
260
-                    return true;
261
-                }
262
-            }
263
-        }
264
-        return $has_error;
265
-    }
266
-
267
-
268
-
269
-    /**
270
-     *    display_errors
271
-     *
272
-     * @echo   string
273
-     * @throws \ReflectionException
274
-     */
275
-    public function display_errors()
276
-    {
277
-        $trace_details = '';
278
-        $output = '
26
+	/**
27
+	 *    name of the file to log exceptions to
28
+	 *
29
+	 * @var string
30
+	 */
31
+	private static $_exception_log_file = 'espresso_error_log.txt';
32
+
33
+	/**
34
+	 *    stores details for all exception
35
+	 *
36
+	 * @var array
37
+	 */
38
+	private static $_all_exceptions = array();
39
+
40
+	/**
41
+	 *    tracks number of errors
42
+	 *
43
+	 * @var int
44
+	 */
45
+	private static $_error_count = 0;
46
+
47
+	/**
48
+	 *    has shutdown action been added ?
49
+	 *
50
+	 * @var array $_espresso_notices
51
+	 */
52
+	private static $_espresso_notices = array('success' => false, 'errors' => false, 'attention' => false);
53
+
54
+
55
+
56
+	/**
57
+	 * @override default exception handling
58
+	 * @param string         $message
59
+	 * @param int            $code
60
+	 * @param Exception|null $previous
61
+	 */
62
+	public function __construct($message, $code = 0, Exception $previous = null)
63
+	{
64
+		if (version_compare(PHP_VERSION, '5.3.0', '<')) {
65
+			parent::__construct($message, $code);
66
+		} else {
67
+			parent::__construct($message, $code, $previous);
68
+		}
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 *    error_handler
75
+	 *
76
+	 * @param $code
77
+	 * @param $message
78
+	 * @param $file
79
+	 * @param $line
80
+	 * @return void
81
+	 */
82
+	public static function error_handler($code, $message, $file, $line)
83
+	{
84
+		$type = EE_Error::error_type($code);
85
+		$site = site_url();
86
+		switch ($site) {
87
+			case 'http://ee4.eventespresso.com/' :
88
+			case 'http://ee4decaf.eventespresso.com/' :
89
+			case 'http://ee4hf.eventespresso.com/' :
90
+			case 'http://ee4a.eventespresso.com/' :
91
+			case 'http://ee4ad.eventespresso.com/' :
92
+			case 'http://ee4b.eventespresso.com/' :
93
+			case 'http://ee4bd.eventespresso.com/' :
94
+			case 'http://ee4d.eventespresso.com/' :
95
+			case 'http://ee4dd.eventespresso.com/' :
96
+				$to = '[email protected]';
97
+				break;
98
+			default :
99
+				$to = get_option('admin_email');
100
+		}
101
+		$subject = $type . ' ' . $message . ' in ' . EVENT_ESPRESSO_VERSION . ' on ' . site_url();
102
+		$msg = EE_Error::_format_error($type, $message, $file, $line);
103
+		if (function_exists('wp_mail')) {
104
+			add_filter('wp_mail_content_type', array('EE_Error', 'set_content_type'));
105
+			wp_mail($to, $subject, $msg);
106
+		}
107
+		echo '<div id="message" class="espresso-notices error"><p>';
108
+		echo $type . ': ' . $message . '<br />' . $file . ' line ' . $line;
109
+		echo '<br /></p></div>';
110
+	}
111
+
112
+
113
+
114
+	/**
115
+	 * error_type
116
+	 * http://www.php.net/manual/en/errorfunc.constants.php#109430
117
+	 *
118
+	 * @param $code
119
+	 * @return string
120
+	 */
121
+	public static function error_type($code)
122
+	{
123
+		switch ($code) {
124
+			case E_ERROR: // 1 //
125
+				return 'E_ERROR';
126
+			case E_WARNING: // 2 //
127
+				return 'E_WARNING';
128
+			case E_PARSE: // 4 //
129
+				return 'E_PARSE';
130
+			case E_NOTICE: // 8 //
131
+				return 'E_NOTICE';
132
+			case E_CORE_ERROR: // 16 //
133
+				return 'E_CORE_ERROR';
134
+			case E_CORE_WARNING: // 32 //
135
+				return 'E_CORE_WARNING';
136
+			case E_COMPILE_ERROR: // 64 //
137
+				return 'E_COMPILE_ERROR';
138
+			case E_COMPILE_WARNING: // 128 //
139
+				return 'E_COMPILE_WARNING';
140
+			case E_USER_ERROR: // 256 //
141
+				return 'E_USER_ERROR';
142
+			case E_USER_WARNING: // 512 //
143
+				return 'E_USER_WARNING';
144
+			case E_USER_NOTICE: // 1024 //
145
+				return 'E_USER_NOTICE';
146
+			case E_STRICT: // 2048 //
147
+				return 'E_STRICT';
148
+			case E_RECOVERABLE_ERROR: // 4096 //
149
+				return 'E_RECOVERABLE_ERROR';
150
+			case E_DEPRECATED: // 8192 //
151
+				return 'E_DEPRECATED';
152
+			case E_USER_DEPRECATED: // 16384 //
153
+				return 'E_USER_DEPRECATED';
154
+			case E_ALL: // 16384 //
155
+				return 'E_ALL';
156
+		}
157
+		return '';
158
+	}
159
+
160
+
161
+
162
+	/**
163
+	 *    fatal_error_handler
164
+	 *
165
+	 * @return void
166
+	 */
167
+	public static function fatal_error_handler()
168
+	{
169
+		$last_error = error_get_last();
170
+		if ($last_error['type'] === E_ERROR) {
171
+			EE_Error::error_handler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
172
+		}
173
+	}
174
+
175
+
176
+
177
+	/**
178
+	 * _format_error
179
+	 *
180
+	 * @param $code
181
+	 * @param $message
182
+	 * @param $file
183
+	 * @param $line
184
+	 * @return string
185
+	 */
186
+	private static function _format_error($code, $message, $file, $line)
187
+	{
188
+		$html = "<table cellpadding='5'><thead bgcolor='#f8f8f8'><th>Item</th><th align='left'>Details</th></thead><tbody>";
189
+		$html .= "<tr valign='top'><td><b>Code</b></td><td>$code</td></tr>";
190
+		$html .= "<tr valign='top'><td><b>Error</b></td><td>$message</td></tr>";
191
+		$html .= "<tr valign='top'><td><b>File</b></td><td>$file</td></tr>";
192
+		$html .= "<tr valign='top'><td><b>Line</b></td><td>$line</td></tr>";
193
+		$html .= '</tbody></table>';
194
+		return $html;
195
+	}
196
+
197
+
198
+
199
+	/**
200
+	 * set_content_type
201
+	 *
202
+	 * @param $content_type
203
+	 * @return string
204
+	 */
205
+	public static function set_content_type($content_type)
206
+	{
207
+		return 'text/html';
208
+	}
209
+
210
+
211
+
212
+	/**
213
+	 * @return void
214
+	 * @throws EE_Error
215
+	 * @throws ReflectionException
216
+	 */
217
+	public function get_error()
218
+	{
219
+		if (apply_filters('FHEE__EE_Error__get_error__show_normal_exceptions', false)) {
220
+			throw $this;
221
+		}
222
+		// get separate user and developer messages if they exist
223
+		$msg = explode('||', $this->getMessage());
224
+		$user_msg = $msg[0];
225
+		$dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
226
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
227
+		// add details to _all_exceptions array
228
+		$x_time = time();
229
+		self::$_all_exceptions[$x_time]['name'] = get_class($this);
230
+		self::$_all_exceptions[$x_time]['file'] = $this->getFile();
231
+		self::$_all_exceptions[$x_time]['line'] = $this->getLine();
232
+		self::$_all_exceptions[$x_time]['msg'] = $msg;
233
+		self::$_all_exceptions[$x_time]['code'] = $this->getCode();
234
+		self::$_all_exceptions[$x_time]['trace'] = $this->getTrace();
235
+		self::$_all_exceptions[$x_time]['string'] = $this->getTraceAsString();
236
+		self::$_error_count++;
237
+		//add_action( 'shutdown', array( $this, 'display_errors' ));
238
+		$this->display_errors();
239
+	}
240
+
241
+
242
+
243
+	/**
244
+	 *    has_error
245
+	 *
246
+	 * @param bool   $check_stored
247
+	 * @param string $type_to_check
248
+	 * @return bool
249
+	 */
250
+	public static function has_error($check_stored = false, $type_to_check = 'errors')
251
+	{
252
+		$has_error = isset(self::$_espresso_notices[$type_to_check])
253
+					 && ! empty(self::$_espresso_notices[$type_to_check])
254
+			? true
255
+			: false;
256
+		if ($check_stored && ! $has_error) {
257
+			$notices = (array)get_option('ee_notices', array());
258
+			foreach ($notices as $type => $notice) {
259
+				if ($type === $type_to_check && $notice) {
260
+					return true;
261
+				}
262
+			}
263
+		}
264
+		return $has_error;
265
+	}
266
+
267
+
268
+
269
+	/**
270
+	 *    display_errors
271
+	 *
272
+	 * @echo   string
273
+	 * @throws \ReflectionException
274
+	 */
275
+	public function display_errors()
276
+	{
277
+		$trace_details = '';
278
+		$output = '
279 279
 <style type="text/css">
280 280
 	#ee-error-message {
281 281
 		max-width:90% !important;
@@ -331,19 +331,19 @@  discard block
 block discarded – undo
331 331
 	}
332 332
 </style>
333 333
 <div id="ee-error-message" class="error">';
334
-        if (! WP_DEBUG) {
335
-            $output .= '
334
+		if (! WP_DEBUG) {
335
+			$output .= '
336 336
 	<p>';
337
-        }
338
-        // cycle thru errors
339
-        foreach (self::$_all_exceptions as $time => $ex) {
340
-            $error_code = '';
341
-            // process trace info
342
-            if (empty($ex['trace'])) {
343
-                $trace_details .= __('Sorry, but no trace information was available for this exception.',
344
-                    'event_espresso');
345
-            } else {
346
-                $trace_details .= '
337
+		}
338
+		// cycle thru errors
339
+		foreach (self::$_all_exceptions as $time => $ex) {
340
+			$error_code = '';
341
+			// process trace info
342
+			if (empty($ex['trace'])) {
343
+				$trace_details .= __('Sorry, but no trace information was available for this exception.',
344
+					'event_espresso');
345
+			} else {
346
+				$trace_details .= '
347 347
 			<div id="ee-trace-details">
348 348
 			<table width="100%" border="0" cellpadding="5" cellspacing="0">
349 349
 				<tr>
@@ -353,38 +353,38 @@  discard block
 block discarded – undo
353 353
 					<th scope="col" align="left">Class</th>
354 354
 					<th scope="col" align="left">Method( arguments )</th>
355 355
 				</tr>';
356
-                $last_on_stack = count($ex['trace']) - 1;
357
-                // reverse array so that stack is in proper chronological order
358
-                $sorted_trace = array_reverse($ex['trace']);
359
-                foreach ($sorted_trace as $nmbr => $trace) {
360
-                    $file = isset($trace['file']) ? $trace['file'] : '';
361
-                    $class = isset($trace['class']) ? $trace['class'] : '';
362
-                    $type = isset($trace['type']) ? $trace['type'] : '';
363
-                    $function = isset($trace['function']) ? $trace['function'] : '';
364
-                    $args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
365
-                    $line = isset($trace['line']) ? $trace['line'] : '';
366
-                    $zebra = ($nmbr % 2) ? ' odd' : '';
367
-                    if (empty($file) && ! empty($class)) {
368
-                        $a = new ReflectionClass($class);
369
-                        $file = $a->getFileName();
370
-                        if (empty($line) && ! empty($function)) {
371
-                            $b = new ReflectionMethod($class, $function);
372
-                            $line = $b->getStartLine();
373
-                        }
374
-                    }
375
-                    if ($nmbr === $last_on_stack) {
376
-                        $file = $ex['file'] !== '' ? $ex['file'] : $file;
377
-                        $line = $ex['line'] !== '' ? $ex['line'] : $line;
378
-                        $error_code = self::generate_error_code($file, $trace['function'], $line);
379
-                    }
380
-                    $nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
381
-                    $line_dsply = ! empty($line) ? $line : '&nbsp;';
382
-                    $file_dsply = ! empty($file) ? $file : '&nbsp;';
383
-                    $class_dsply = ! empty($class) ? $class : '&nbsp;';
384
-                    $type_dsply = ! empty($type) ? $type : '&nbsp;';
385
-                    $function_dsply = ! empty($function) ? $function : '&nbsp;';
386
-                    $args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
387
-                    $trace_details .= '
356
+				$last_on_stack = count($ex['trace']) - 1;
357
+				// reverse array so that stack is in proper chronological order
358
+				$sorted_trace = array_reverse($ex['trace']);
359
+				foreach ($sorted_trace as $nmbr => $trace) {
360
+					$file = isset($trace['file']) ? $trace['file'] : '';
361
+					$class = isset($trace['class']) ? $trace['class'] : '';
362
+					$type = isset($trace['type']) ? $trace['type'] : '';
363
+					$function = isset($trace['function']) ? $trace['function'] : '';
364
+					$args = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
365
+					$line = isset($trace['line']) ? $trace['line'] : '';
366
+					$zebra = ($nmbr % 2) ? ' odd' : '';
367
+					if (empty($file) && ! empty($class)) {
368
+						$a = new ReflectionClass($class);
369
+						$file = $a->getFileName();
370
+						if (empty($line) && ! empty($function)) {
371
+							$b = new ReflectionMethod($class, $function);
372
+							$line = $b->getStartLine();
373
+						}
374
+					}
375
+					if ($nmbr === $last_on_stack) {
376
+						$file = $ex['file'] !== '' ? $ex['file'] : $file;
377
+						$line = $ex['line'] !== '' ? $ex['line'] : $line;
378
+						$error_code = self::generate_error_code($file, $trace['function'], $line);
379
+					}
380
+					$nmbr_dsply = ! empty($nmbr) ? $nmbr : '&nbsp;';
381
+					$line_dsply = ! empty($line) ? $line : '&nbsp;';
382
+					$file_dsply = ! empty($file) ? $file : '&nbsp;';
383
+					$class_dsply = ! empty($class) ? $class : '&nbsp;';
384
+					$type_dsply = ! empty($type) ? $type : '&nbsp;';
385
+					$function_dsply = ! empty($function) ? $function : '&nbsp;';
386
+					$args_dsply = ! empty($args) ? '( ' . $args . ' )' : '';
387
+					$trace_details .= '
388 388
 					<tr>
389 389
 						<td align="right" class="' . $zebra . '">' . $nmbr_dsply . '</td>
390 390
 						<td align="right" class="' . $zebra . '">' . $line_dsply . '</td>
@@ -392,674 +392,674 @@  discard block
 block discarded – undo
392 392
 						<td align="left" class="' . $zebra . '">' . $class_dsply . '</td>
393 393
 						<td align="left" class="' . $zebra . '">' . $type_dsply . $function_dsply . $args_dsply . '</td>
394 394
 					</tr>';
395
-                }
396
-                $trace_details .= '
395
+				}
396
+				$trace_details .= '
397 397
 			 </table>
398 398
 			</div>';
399
-            }
400
-            $ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
401
-            // add generic non-identifying messages for non-privileged users
402
-            if (! WP_DEBUG) {
403
-                $output .= '<span class="ee-error-user-msg-spn">'
404
-                           . trim($ex['msg'])
405
-                           . '</span> &nbsp; <sup>'
406
-                           . $ex['code']
407
-                           . '</sup><br />';
408
-            } else {
409
-                // or helpful developer messages if debugging is on
410
-                $output .= '
399
+			}
400
+			$ex['code'] = $ex['code'] ? $ex['code'] : $error_code;
401
+			// add generic non-identifying messages for non-privileged users
402
+			if (! WP_DEBUG) {
403
+				$output .= '<span class="ee-error-user-msg-spn">'
404
+						   . trim($ex['msg'])
405
+						   . '</span> &nbsp; <sup>'
406
+						   . $ex['code']
407
+						   . '</sup><br />';
408
+			} else {
409
+				// or helpful developer messages if debugging is on
410
+				$output .= '
411 411
 		<div class="ee-error-dev-msg-dv">
412 412
 			<p class="ee-error-dev-msg-pg">
413 413
 				<strong class="ee-error-dev-msg-str">An '
414
-                           . $ex['name']
415
-                           . ' exception was thrown!</strong>  &nbsp; <span>code: '
416
-                           . $ex['code']
417
-                           . '</span><br />
414
+						   . $ex['name']
415
+						   . ' exception was thrown!</strong>  &nbsp; <span>code: '
416
+						   . $ex['code']
417
+						   . '</span><br />
418 418
 				<span class="big-text">"'
419
-                           . trim($ex['msg'])
420
-                           . '"</span><br/>
419
+						   . trim($ex['msg'])
420
+						   . '"</span><br/>
421 421
 				<a id="display-ee-error-trace-'
422
-                           . self::$_error_count
423
-                           . $time
424
-                           . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
425
-                           . self::$_error_count
426
-                           . $time
427
-                           . '">
422
+						   . self::$_error_count
423
+						   . $time
424
+						   . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-'
425
+						   . self::$_error_count
426
+						   . $time
427
+						   . '">
428 428
 					'
429
-                           . __('click to view backtrace and class/method details', 'event_espresso')
430
-                           . '
429
+						   . __('click to view backtrace and class/method details', 'event_espresso')
430
+						   . '
431 431
 				</a><br />
432 432
 				<span class="small-text lt-grey-text">'
433
-                           . $ex['file']
434
-                           . ' &nbsp; ( line no: '
435
-                           . $ex['line']
436
-                           . ' )</span>
433
+						   . $ex['file']
434
+						   . ' &nbsp; ( line no: '
435
+						   . $ex['line']
436
+						   . ' )</span>
437 437
 			</p>
438 438
 			<div id="ee-error-trace-'
439
-                           . self::$_error_count
440
-                           . $time
441
-                           . '-dv" class="ee-error-trace-dv" style="display: none;">
439
+						   . self::$_error_count
440
+						   . $time
441
+						   . '-dv" class="ee-error-trace-dv" style="display: none;">
442 442
 				'
443
-                           . $trace_details;
444
-                if (! empty($class)) {
445
-                    $output .= '
443
+						   . $trace_details;
444
+				if (! empty($class)) {
445
+					$output .= '
446 446
 				<div style="padding:3px; margin:0 0 1em; border:1px solid #666; background:#fff; border-radius:3px;">
447 447
 					<div style="padding:1em 2em; border:1px solid #666; background:#f9f9f9;">
448 448
 						<h3>Class Details</h3>';
449
-                    $a = new ReflectionClass($class);
450
-                    $output .= '
449
+					$a = new ReflectionClass($class);
450
+					$output .= '
451 451
 						<pre>' . $a . '</pre>
452 452
 					</div>
453 453
 				</div>';
454
-                }
455
-                $output .= '
454
+				}
455
+				$output .= '
456 456
 			</div>
457 457
 		</div>
458 458
 		<br />';
459
-            }
460
-            $this->write_to_error_log($time, $ex);
461
-        }
462
-        // remove last linebreak
463
-        $output = substr($output, 0, -6);
464
-        if (! WP_DEBUG) {
465
-            $output .= '
459
+			}
460
+			$this->write_to_error_log($time, $ex);
461
+		}
462
+		// remove last linebreak
463
+		$output = substr($output, 0, -6);
464
+		if (! WP_DEBUG) {
465
+			$output .= '
466 466
 	</p>';
467
-        }
468
-        $output .= '
467
+		}
468
+		$output .= '
469 469
 </div>';
470
-        $output .= self::_print_scripts(true);
471
-        if (defined('DOING_AJAX')) {
472
-            echo wp_json_encode(array('error' => $output));
473
-            exit();
474
-        }
475
-        echo $output;
476
-        die();
477
-    }
478
-
479
-
480
-
481
-    /**
482
-     *    generate string from exception trace args
483
-     *
484
-     * @param array $arguments
485
-     * @param bool  $array
486
-     * @return string
487
-     */
488
-    private function _convert_args_to_string($arguments = array(), $array = false)
489
-    {
490
-        $arg_string = '';
491
-        if (! empty($arguments)) {
492
-            $args = array();
493
-            foreach ($arguments as $arg) {
494
-                if (! empty($arg)) {
495
-                    if (is_string($arg)) {
496
-                        $args[] = " '" . $arg . "'";
497
-                    } elseif (is_array($arg)) {
498
-                        $args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
499
-                    } elseif ($arg === null) {
500
-                        $args[] = ' NULL';
501
-                    } elseif (is_bool($arg)) {
502
-                        $args[] = ($arg) ? ' TRUE' : ' FALSE';
503
-                    } elseif (is_object($arg)) {
504
-                        $args[] = ' OBJECT ' . get_class($arg);
505
-                    } elseif (is_resource($arg)) {
506
-                        $args[] = get_resource_type($arg);
507
-                    } else {
508
-                        $args[] = $arg;
509
-                    }
510
-                }
511
-            }
512
-            $arg_string = implode(', ', $args);
513
-        }
514
-        if ($array) {
515
-            $arg_string .= ' )';
516
-        }
517
-        return $arg_string;
518
-    }
519
-
520
-
521
-
522
-    /**
523
-     *    add error message
524
-     *
525
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
526
-     *                            separate messages for user || dev
527
-     * @param        string $file the file that the error occurred in - just use __FILE__
528
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
529
-     * @param        string $line the line number where the error occurred - just use __LINE__
530
-     * @return        void
531
-     */
532
-    public static function add_error($msg = null, $file = null, $func = null, $line = null)
533
-    {
534
-        self::_add_notice('errors', $msg, $file, $func, $line);
535
-        self::$_error_count++;
536
-    }
537
-
538
-
539
-
540
-    /**
541
-     * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
542
-     * adds an error
543
-     *
544
-     * @param string $msg
545
-     * @param string $file
546
-     * @param string $func
547
-     * @param string $line
548
-     * @throws EE_Error
549
-     */
550
-    public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
551
-    {
552
-        if (WP_DEBUG) {
553
-            throw new EE_Error($msg);
554
-        }
555
-        EE_Error::add_error($msg, $file, $func, $line);
556
-    }
557
-
558
-
559
-
560
-    /**
561
-     *    add success message
562
-     *
563
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
564
-     *                            separate messages for user || dev
565
-     * @param        string $file the file that the error occurred in - just use __FILE__
566
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
567
-     * @param        string $line the line number where the error occurred - just use __LINE__
568
-     * @return        void
569
-     */
570
-    public static function add_success($msg = null, $file = null, $func = null, $line = null)
571
-    {
572
-        self::_add_notice('success', $msg, $file, $func, $line);
573
-    }
574
-
575
-
576
-
577
-    /**
578
-     *    add attention message
579
-     *
580
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
581
-     *                            separate messages for user || dev
582
-     * @param        string $file the file that the error occurred in - just use __FILE__
583
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
584
-     * @param        string $line the line number where the error occurred - just use __LINE__
585
-     * @return        void
586
-     */
587
-    public static function add_attention($msg = null, $file = null, $func = null, $line = null)
588
-    {
589
-        self::_add_notice('attention', $msg, $file, $func, $line);
590
-    }
591
-
592
-
593
-
594
-    /**
595
-     *    add success message
596
-     *
597
-     * @param        string $type whether the message is for a success or error notification
598
-     * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
599
-     *                            separate messages for user || dev
600
-     * @param        string $file the file that the error occurred in - just use __FILE__
601
-     * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
602
-     * @param        string $line the line number where the error occurred - just use __LINE__
603
-     * @return        void
604
-     */
605
-    private static function _add_notice($type = 'success', $msg = null, $file = null, $func = null, $line = null)
606
-    {
607
-        if (empty($msg)) {
608
-            EE_Error::doing_it_wrong(
609
-                'EE_Error::add_' . $type . '()',
610
-                sprintf(
611
-                    __('Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
612
-                        'event_espresso'),
613
-                    $type,
614
-                    $file,
615
-                    $line
616
-                ),
617
-                EVENT_ESPRESSO_VERSION
618
-            );
619
-        }
620
-        if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
621
-            EE_Error::doing_it_wrong(
622
-                'EE_Error::add_error()',
623
-                __('You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
624
-                    'event_espresso'),
625
-                EVENT_ESPRESSO_VERSION
626
-            );
627
-        }
628
-        // get separate user and developer messages if they exist
629
-        $msg = explode('||', $msg);
630
-        $user_msg = $msg[0];
631
-        $dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
632
-        /**
633
-         * Do an action so other code can be triggered when a notice is created
634
-         *
635
-         * @param string $type     can be 'errors', 'attention', or 'success'
636
-         * @param string $user_msg message displayed to user when WP_DEBUG is off
637
-         * @param string $user_msg message displayed to user when WP_DEBUG is on
638
-         * @param string $file     file where error was generated
639
-         * @param string $func     function where error was generated
640
-         * @param string $line     line where error was generated
641
-         */
642
-        do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
643
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
644
-        // add notice if message exists
645
-        if (! empty($msg)) {
646
-            // get error code
647
-            $notice_code = EE_Error::generate_error_code($file, $func, $line);
648
-            if (WP_DEBUG && $type === 'errors') {
649
-                $msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
650
-            }
651
-            // add notice. Index by code if it's not blank
652
-            if ($notice_code) {
653
-                self::$_espresso_notices[$type][$notice_code] = $msg;
654
-            } else {
655
-                self::$_espresso_notices[$type][] = $msg;
656
-            }
657
-            add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
658
-        }
659
-    }
660
-
661
-
662
-
663
-    /**
664
-     *    in some case it may be necessary to overwrite the existing success messages
665
-     *
666
-     * @return        void
667
-     */
668
-    public static function overwrite_success()
669
-    {
670
-        self::$_espresso_notices['success'] = false;
671
-    }
672
-
673
-
674
-
675
-    /**
676
-     *    in some case it may be necessary to overwrite the existing attention messages
677
-     *
678
-     * @return        void
679
-     */
680
-    public static function overwrite_attention()
681
-    {
682
-        self::$_espresso_notices['attention'] = false;
683
-    }
684
-
685
-
686
-
687
-    /**
688
-     *    in some case it may be necessary to overwrite the existing error messages
689
-     *
690
-     * @return        void
691
-     */
692
-    public static function overwrite_errors()
693
-    {
694
-        self::$_espresso_notices['errors'] = false;
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     *    reset_notices
701
-     *
702
-     * @return void
703
-     */
704
-    public static function reset_notices()
705
-    {
706
-        self::$_espresso_notices['success'] = false;
707
-        self::$_espresso_notices['attention'] = false;
708
-        self::$_espresso_notices['errors'] = false;
709
-    }
710
-
711
-
712
-
713
-    /**
714
-     *    has_errors
715
-     *
716
-     * @return int
717
-     */
718
-    public static function has_notices()
719
-    {
720
-        $has_notices = 0;
721
-        // check for success messages
722
-        $has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success']) ? 3
723
-            : $has_notices;
724
-        // check for attention messages
725
-        $has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention']) ? 2
726
-            : $has_notices;
727
-        // check for error messages
728
-        $has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors']) ? 1
729
-            : $has_notices;
730
-        return $has_notices;
731
-    }
732
-
733
-
734
-
735
-    /**
736
-     * This simply returns non formatted error notices as they were sent into the EE_Error object.
737
-     *
738
-     * @since 4.9.0
739
-     * @return array
740
-     */
741
-    public static function get_vanilla_notices()
742
-    {
743
-        return array(
744
-            'success'   => isset(self::$_espresso_notices['success']) ? self::$_espresso_notices['success'] : array(),
745
-            'attention' => isset(self::$_espresso_notices['attention']) ? self::$_espresso_notices['attention']
746
-                : array(),
747
-            'errors'    => isset(self::$_espresso_notices['errors']) ? self::$_espresso_notices['errors'] : array(),
748
-        );
749
-    }
750
-
751
-
752
-
753
-    /**
754
-     *    compile all error or success messages into one string
755
-     *
756
-     * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
757
-     * @param        boolean $format_output     whether or not to format the messages for display in the WP admin
758
-     * @param        boolean $save_to_transient whether or not to save notices to the db for retrieval on next request
759
-     *                                          - ONLY do this just before redirecting
760
-     * @param        boolean $remove_empty      whether or not to unset empty messages
761
-     * @return        array
762
-     */
763
-    public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
764
-    {
765
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
766
-        $success_messages = '';
767
-        $attention_messages = '';
768
-        $error_messages = '';
769
-        $print_scripts = false;
770
-        // either save notices to the db
771
-        if ($save_to_transient) {
772
-            update_option('ee_notices', self::$_espresso_notices);
773
-            return array();
774
-        }
775
-        // grab any notices that have been previously saved
776
-        if ($notices = get_option('ee_notices', false)) {
777
-            foreach ($notices as $type => $notice) {
778
-                if (is_array($notice) && ! empty($notice)) {
779
-                    // make sure that existing notice type is an array
780
-                    self::$_espresso_notices[$type] = is_array(self::$_espresso_notices[$type])
781
-                                                      && ! empty(self::$_espresso_notices[$type])
782
-                        ? self::$_espresso_notices[$type] : array();
783
-                    // merge stored notices with any newly created ones
784
-                    self::$_espresso_notices[$type] = array_merge(self::$_espresso_notices[$type], $notice);
785
-                    $print_scripts = true;
786
-                }
787
-            }
788
-            // now clear any stored notices
789
-            update_option('ee_notices', false);
790
-        }
791
-        // check for success messages
792
-        if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
793
-            // combine messages
794
-            $success_messages .= implode(self::$_espresso_notices['success'], '<br /><br />');
795
-            $print_scripts = true;
796
-        }
797
-        // check for attention messages
798
-        if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
799
-            // combine messages
800
-            $attention_messages .= implode(self::$_espresso_notices['attention'], '<br /><br />');
801
-            $print_scripts = true;
802
-        }
803
-        // check for error messages
804
-        if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
805
-            $error_messages .= count(self::$_espresso_notices['errors']) > 1
806
-                ? __('The following errors have occurred:<br />', 'event_espresso')
807
-                : __('An error has occurred:<br />', 'event_espresso');
808
-            // combine messages
809
-            $error_messages .= implode(self::$_espresso_notices['errors'], '<br /><br />');
810
-            $print_scripts = true;
811
-        }
812
-        if ($format_output) {
813
-            $notices = '<div id="espresso-notices">';
814
-            $close = is_admin() ? ''
815
-                : '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"></span></a>';
816
-            if ($success_messages !== '') {
817
-                $css_id = is_admin() ? 'message' : 'espresso-notices-success';
818
-                $css_class = is_admin() ? 'updated fade' : 'success fade-away';
819
-                //showMessage( $success_messages );
820
-                $notices .= '<div id="'
821
-                            . $css_id
822
-                            . '" class="espresso-notices '
823
-                            . $css_class
824
-                            . '" style="display:none;"><p>'
825
-                            . $success_messages
826
-                            . '</p>'
827
-                            . $close
828
-                            . '</div>';
829
-            }
830
-            if ($attention_messages !== '') {
831
-                $css_id = is_admin() ? 'message' : 'espresso-notices-attention';
832
-                $css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
833
-                //showMessage( $error_messages, TRUE );
834
-                $notices .= '<div id="'
835
-                            . $css_id
836
-                            . '" class="espresso-notices '
837
-                            . $css_class
838
-                            . '" style="display:none;"><p>'
839
-                            . $attention_messages
840
-                            . '</p>'
841
-                            . $close
842
-                            . '</div>';
843
-            }
844
-            if ($error_messages !== '') {
845
-                $css_id = is_admin() ? 'message' : 'espresso-notices-error';
846
-                $css_class = is_admin() ? 'error' : 'error fade-away';
847
-                //showMessage( $error_messages, TRUE );
848
-                $notices .= '<div id="'
849
-                            . $css_id
850
-                            . '" class="espresso-notices '
851
-                            . $css_class
852
-                            . '" style="display:none;"><p>'
853
-                            . $error_messages
854
-                            . '</p>'
855
-                            . $close
856
-                            . '</div>';
857
-            }
858
-            $notices .= '</div>';
859
-        } else {
860
-            $notices = array(
861
-                'success'   => $success_messages,
862
-                'attention' => $attention_messages,
863
-                'errors'    => $error_messages,
864
-            );
865
-            if ($remove_empty) {
866
-                // remove empty notices
867
-                foreach ($notices as $type => $notice) {
868
-                    if (empty($notice)) {
869
-                        unset($notices[$type]);
870
-                    }
871
-                }
872
-            }
873
-        }
874
-        if ($print_scripts) {
875
-            self::_print_scripts();
876
-        }
877
-        return $notices;
878
-    }
879
-
880
-
881
-
882
-    /**
883
-     *    add_persistent_admin_notice
884
-     *
885
-     * @param        string $pan_name     the name, or key of the Persistent Admin Notice to be stored
886
-     * @param        string $pan_message  the message to be stored persistently until dismissed
887
-     * @param bool          $force_update allows one to enforce the reappearance of a persistent message.
888
-     * @return        void
889
-     */
890
-    public static function add_persistent_admin_notice($pan_name = '', $pan_message, $force_update = false)
891
-    {
892
-        if (! empty($pan_name) && ! empty($pan_message)) {
893
-            $persistent_admin_notices = get_option('ee_pers_admin_notices', array());
894
-            //maybe initialize persistent_admin_notices
895
-            if (empty($persistent_admin_notices)) {
896
-                add_option('ee_pers_admin_notices', array(), '', 'no');
897
-            }
898
-            $pan_name = sanitize_key($pan_name);
899
-            if (! array_key_exists($pan_name, $persistent_admin_notices) || $force_update) {
900
-                $persistent_admin_notices[$pan_name] = $pan_message;
901
-                update_option('ee_pers_admin_notices', $persistent_admin_notices);
902
-            }
903
-        }
904
-    }
905
-
906
-
907
-
908
-    /**
909
-     *    dismiss_persistent_admin_notice
910
-     *
911
-     * @param        string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
912
-     * @param bool          $purge
913
-     * @param bool          $return_immediately
914
-     * @return        void
915
-     */
916
-    public static function dismiss_persistent_admin_notice($pan_name = '', $purge = false, $return_immediately = false)
917
-    {
918
-        $pan_name = EE_Registry::instance()->REQ->is_set('ee_nag_notice')
919
-            ? EE_Registry::instance()->REQ->get('ee_nag_notice') : $pan_name;
920
-        if (! empty($pan_name)) {
921
-            $persistent_admin_notices = get_option('ee_pers_admin_notices', array());
922
-            // check if notice we wish to dismiss is actually in the $persistent_admin_notices array
923
-            if (is_array($persistent_admin_notices) && isset($persistent_admin_notices[$pan_name])) {
924
-                // completely delete nag notice, or just NULL message so that it can NOT be added again ?
925
-                if ($purge) {
926
-                    unset($persistent_admin_notices[$pan_name]);
927
-                } else {
928
-                    $persistent_admin_notices[$pan_name] = null;
929
-                }
930
-                if (update_option('ee_pers_admin_notices', $persistent_admin_notices) === false) {
931
-                    EE_Error::add_error(sprintf(__('The persistent admin notice for "%s" could not be deleted.',
932
-                        'event_espresso'), $pan_name), __FILE__, __FUNCTION__, __LINE__);
933
-                }
934
-            }
935
-        }
936
-        if ($return_immediately) {
937
-            return;
938
-        }
939
-        if (EE_Registry::instance()->REQ->ajax) {
940
-            // grab any notices and concatenate into string
941
-            echo wp_json_encode(array('errors' => implode('<br />', EE_Error::get_notices(false))));
942
-            exit();
943
-        }
944
-        // save errors to a transient to be displayed on next request (after redirect)
945
-        EE_Error::get_notices(false, true);
946
-        $return_url = EE_Registry::instance()->REQ->is_set('return_url')
947
-            ? EE_Registry::instance()->REQ->get('return_url') : '';
948
-        wp_safe_redirect(urldecode($return_url));
949
-    }
950
-
951
-
952
-
953
-    /**
954
-     * display_persistent_admin_notices
955
-     *
956
-     * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
957
-     * @param  string $pan_message the message to be stored persistently until dismissed
958
-     * @param  string $return_url  URL to go back to after nag notice is dismissed
959
-     * @return string
960
-     */
961
-    public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
962
-    {
963
-        if (! empty($pan_name) && ! empty($pan_message)) {
964
-            $args = array(
965
-                'nag_notice'    => $pan_name,
966
-                'return_url'    => urlencode($return_url),
967
-                'ajax_url'      => WP_AJAX_URL,
968
-                'unknown_error' => esc_html__(
969
-                    'An unknown error has occurred on the server while attempting to dismiss this notice.',
970
-                    'event_espresso'
971
-                ),
972
-            );
973
-            EE_Registry::$i18n_js_strings = array_merge(
974
-                EE_Registry::$i18n_js_strings,
975
-                array('ee_dismiss' => $args)
976
-            );
977
-            return '
470
+		$output .= self::_print_scripts(true);
471
+		if (defined('DOING_AJAX')) {
472
+			echo wp_json_encode(array('error' => $output));
473
+			exit();
474
+		}
475
+		echo $output;
476
+		die();
477
+	}
478
+
479
+
480
+
481
+	/**
482
+	 *    generate string from exception trace args
483
+	 *
484
+	 * @param array $arguments
485
+	 * @param bool  $array
486
+	 * @return string
487
+	 */
488
+	private function _convert_args_to_string($arguments = array(), $array = false)
489
+	{
490
+		$arg_string = '';
491
+		if (! empty($arguments)) {
492
+			$args = array();
493
+			foreach ($arguments as $arg) {
494
+				if (! empty($arg)) {
495
+					if (is_string($arg)) {
496
+						$args[] = " '" . $arg . "'";
497
+					} elseif (is_array($arg)) {
498
+						$args[] = 'ARRAY(' . $this->_convert_args_to_string($arg, true);
499
+					} elseif ($arg === null) {
500
+						$args[] = ' NULL';
501
+					} elseif (is_bool($arg)) {
502
+						$args[] = ($arg) ? ' TRUE' : ' FALSE';
503
+					} elseif (is_object($arg)) {
504
+						$args[] = ' OBJECT ' . get_class($arg);
505
+					} elseif (is_resource($arg)) {
506
+						$args[] = get_resource_type($arg);
507
+					} else {
508
+						$args[] = $arg;
509
+					}
510
+				}
511
+			}
512
+			$arg_string = implode(', ', $args);
513
+		}
514
+		if ($array) {
515
+			$arg_string .= ' )';
516
+		}
517
+		return $arg_string;
518
+	}
519
+
520
+
521
+
522
+	/**
523
+	 *    add error message
524
+	 *
525
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
526
+	 *                            separate messages for user || dev
527
+	 * @param        string $file the file that the error occurred in - just use __FILE__
528
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
529
+	 * @param        string $line the line number where the error occurred - just use __LINE__
530
+	 * @return        void
531
+	 */
532
+	public static function add_error($msg = null, $file = null, $func = null, $line = null)
533
+	{
534
+		self::_add_notice('errors', $msg, $file, $func, $line);
535
+		self::$_error_count++;
536
+	}
537
+
538
+
539
+
540
+	/**
541
+	 * If WP_DEBUG is active, throws an exception. If WP_DEBUG is off, just
542
+	 * adds an error
543
+	 *
544
+	 * @param string $msg
545
+	 * @param string $file
546
+	 * @param string $func
547
+	 * @param string $line
548
+	 * @throws EE_Error
549
+	 */
550
+	public static function throw_exception_if_debugging($msg = null, $file = null, $func = null, $line = null)
551
+	{
552
+		if (WP_DEBUG) {
553
+			throw new EE_Error($msg);
554
+		}
555
+		EE_Error::add_error($msg, $file, $func, $line);
556
+	}
557
+
558
+
559
+
560
+	/**
561
+	 *    add success message
562
+	 *
563
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
564
+	 *                            separate messages for user || dev
565
+	 * @param        string $file the file that the error occurred in - just use __FILE__
566
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
567
+	 * @param        string $line the line number where the error occurred - just use __LINE__
568
+	 * @return        void
569
+	 */
570
+	public static function add_success($msg = null, $file = null, $func = null, $line = null)
571
+	{
572
+		self::_add_notice('success', $msg, $file, $func, $line);
573
+	}
574
+
575
+
576
+
577
+	/**
578
+	 *    add attention message
579
+	 *
580
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
581
+	 *                            separate messages for user || dev
582
+	 * @param        string $file the file that the error occurred in - just use __FILE__
583
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
584
+	 * @param        string $line the line number where the error occurred - just use __LINE__
585
+	 * @return        void
586
+	 */
587
+	public static function add_attention($msg = null, $file = null, $func = null, $line = null)
588
+	{
589
+		self::_add_notice('attention', $msg, $file, $func, $line);
590
+	}
591
+
592
+
593
+
594
+	/**
595
+	 *    add success message
596
+	 *
597
+	 * @param        string $type whether the message is for a success or error notification
598
+	 * @param        string $msg  the message to display to users or developers - adding a double pipe || (OR) creates
599
+	 *                            separate messages for user || dev
600
+	 * @param        string $file the file that the error occurred in - just use __FILE__
601
+	 * @param        string $func the function/method that the error occurred in - just use __FUNCTION__
602
+	 * @param        string $line the line number where the error occurred - just use __LINE__
603
+	 * @return        void
604
+	 */
605
+	private static function _add_notice($type = 'success', $msg = null, $file = null, $func = null, $line = null)
606
+	{
607
+		if (empty($msg)) {
608
+			EE_Error::doing_it_wrong(
609
+				'EE_Error::add_' . $type . '()',
610
+				sprintf(
611
+					__('Notifications are not much use without a message! Please add a message to the EE_Error::add_%s() call made in %s on line %d',
612
+						'event_espresso'),
613
+					$type,
614
+					$file,
615
+					$line
616
+				),
617
+				EVENT_ESPRESSO_VERSION
618
+			);
619
+		}
620
+		if ($type === 'errors' && (empty($file) || empty($func) || empty($line))) {
621
+			EE_Error::doing_it_wrong(
622
+				'EE_Error::add_error()',
623
+				__('You need to provide the file name, function name, and line number that the error occurred on in order to better assist with debugging.',
624
+					'event_espresso'),
625
+				EVENT_ESPRESSO_VERSION
626
+			);
627
+		}
628
+		// get separate user and developer messages if they exist
629
+		$msg = explode('||', $msg);
630
+		$user_msg = $msg[0];
631
+		$dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
632
+		/**
633
+		 * Do an action so other code can be triggered when a notice is created
634
+		 *
635
+		 * @param string $type     can be 'errors', 'attention', or 'success'
636
+		 * @param string $user_msg message displayed to user when WP_DEBUG is off
637
+		 * @param string $user_msg message displayed to user when WP_DEBUG is on
638
+		 * @param string $file     file where error was generated
639
+		 * @param string $func     function where error was generated
640
+		 * @param string $line     line where error was generated
641
+		 */
642
+		do_action('AHEE__EE_Error___add_notice', $type, $user_msg, $dev_msg, $file, $func, $line);
643
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
644
+		// add notice if message exists
645
+		if (! empty($msg)) {
646
+			// get error code
647
+			$notice_code = EE_Error::generate_error_code($file, $func, $line);
648
+			if (WP_DEBUG && $type === 'errors') {
649
+				$msg .= '<br/><span class="tiny-text">' . $notice_code . '</span>';
650
+			}
651
+			// add notice. Index by code if it's not blank
652
+			if ($notice_code) {
653
+				self::$_espresso_notices[$type][$notice_code] = $msg;
654
+			} else {
655
+				self::$_espresso_notices[$type][] = $msg;
656
+			}
657
+			add_action('wp_footer', array('EE_Error', 'enqueue_error_scripts'), 1);
658
+		}
659
+	}
660
+
661
+
662
+
663
+	/**
664
+	 *    in some case it may be necessary to overwrite the existing success messages
665
+	 *
666
+	 * @return        void
667
+	 */
668
+	public static function overwrite_success()
669
+	{
670
+		self::$_espresso_notices['success'] = false;
671
+	}
672
+
673
+
674
+
675
+	/**
676
+	 *    in some case it may be necessary to overwrite the existing attention messages
677
+	 *
678
+	 * @return        void
679
+	 */
680
+	public static function overwrite_attention()
681
+	{
682
+		self::$_espresso_notices['attention'] = false;
683
+	}
684
+
685
+
686
+
687
+	/**
688
+	 *    in some case it may be necessary to overwrite the existing error messages
689
+	 *
690
+	 * @return        void
691
+	 */
692
+	public static function overwrite_errors()
693
+	{
694
+		self::$_espresso_notices['errors'] = false;
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 *    reset_notices
701
+	 *
702
+	 * @return void
703
+	 */
704
+	public static function reset_notices()
705
+	{
706
+		self::$_espresso_notices['success'] = false;
707
+		self::$_espresso_notices['attention'] = false;
708
+		self::$_espresso_notices['errors'] = false;
709
+	}
710
+
711
+
712
+
713
+	/**
714
+	 *    has_errors
715
+	 *
716
+	 * @return int
717
+	 */
718
+	public static function has_notices()
719
+	{
720
+		$has_notices = 0;
721
+		// check for success messages
722
+		$has_notices = self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success']) ? 3
723
+			: $has_notices;
724
+		// check for attention messages
725
+		$has_notices = self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention']) ? 2
726
+			: $has_notices;
727
+		// check for error messages
728
+		$has_notices = self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors']) ? 1
729
+			: $has_notices;
730
+		return $has_notices;
731
+	}
732
+
733
+
734
+
735
+	/**
736
+	 * This simply returns non formatted error notices as they were sent into the EE_Error object.
737
+	 *
738
+	 * @since 4.9.0
739
+	 * @return array
740
+	 */
741
+	public static function get_vanilla_notices()
742
+	{
743
+		return array(
744
+			'success'   => isset(self::$_espresso_notices['success']) ? self::$_espresso_notices['success'] : array(),
745
+			'attention' => isset(self::$_espresso_notices['attention']) ? self::$_espresso_notices['attention']
746
+				: array(),
747
+			'errors'    => isset(self::$_espresso_notices['errors']) ? self::$_espresso_notices['errors'] : array(),
748
+		);
749
+	}
750
+
751
+
752
+
753
+	/**
754
+	 *    compile all error or success messages into one string
755
+	 *
756
+	 * @see EE_Error::get_raw_notices if you want the raw notices without any preparations made to them
757
+	 * @param        boolean $format_output     whether or not to format the messages for display in the WP admin
758
+	 * @param        boolean $save_to_transient whether or not to save notices to the db for retrieval on next request
759
+	 *                                          - ONLY do this just before redirecting
760
+	 * @param        boolean $remove_empty      whether or not to unset empty messages
761
+	 * @return        array
762
+	 */
763
+	public static function get_notices($format_output = true, $save_to_transient = false, $remove_empty = true)
764
+	{
765
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
766
+		$success_messages = '';
767
+		$attention_messages = '';
768
+		$error_messages = '';
769
+		$print_scripts = false;
770
+		// either save notices to the db
771
+		if ($save_to_transient) {
772
+			update_option('ee_notices', self::$_espresso_notices);
773
+			return array();
774
+		}
775
+		// grab any notices that have been previously saved
776
+		if ($notices = get_option('ee_notices', false)) {
777
+			foreach ($notices as $type => $notice) {
778
+				if (is_array($notice) && ! empty($notice)) {
779
+					// make sure that existing notice type is an array
780
+					self::$_espresso_notices[$type] = is_array(self::$_espresso_notices[$type])
781
+													  && ! empty(self::$_espresso_notices[$type])
782
+						? self::$_espresso_notices[$type] : array();
783
+					// merge stored notices with any newly created ones
784
+					self::$_espresso_notices[$type] = array_merge(self::$_espresso_notices[$type], $notice);
785
+					$print_scripts = true;
786
+				}
787
+			}
788
+			// now clear any stored notices
789
+			update_option('ee_notices', false);
790
+		}
791
+		// check for success messages
792
+		if (self::$_espresso_notices['success'] && ! empty(self::$_espresso_notices['success'])) {
793
+			// combine messages
794
+			$success_messages .= implode(self::$_espresso_notices['success'], '<br /><br />');
795
+			$print_scripts = true;
796
+		}
797
+		// check for attention messages
798
+		if (self::$_espresso_notices['attention'] && ! empty(self::$_espresso_notices['attention'])) {
799
+			// combine messages
800
+			$attention_messages .= implode(self::$_espresso_notices['attention'], '<br /><br />');
801
+			$print_scripts = true;
802
+		}
803
+		// check for error messages
804
+		if (self::$_espresso_notices['errors'] && ! empty(self::$_espresso_notices['errors'])) {
805
+			$error_messages .= count(self::$_espresso_notices['errors']) > 1
806
+				? __('The following errors have occurred:<br />', 'event_espresso')
807
+				: __('An error has occurred:<br />', 'event_espresso');
808
+			// combine messages
809
+			$error_messages .= implode(self::$_espresso_notices['errors'], '<br /><br />');
810
+			$print_scripts = true;
811
+		}
812
+		if ($format_output) {
813
+			$notices = '<div id="espresso-notices">';
814
+			$close = is_admin() ? ''
815
+				: '<a class="close-espresso-notice hide-if-no-js"><span class="dashicons dashicons-no"></span></a>';
816
+			if ($success_messages !== '') {
817
+				$css_id = is_admin() ? 'message' : 'espresso-notices-success';
818
+				$css_class = is_admin() ? 'updated fade' : 'success fade-away';
819
+				//showMessage( $success_messages );
820
+				$notices .= '<div id="'
821
+							. $css_id
822
+							. '" class="espresso-notices '
823
+							. $css_class
824
+							. '" style="display:none;"><p>'
825
+							. $success_messages
826
+							. '</p>'
827
+							. $close
828
+							. '</div>';
829
+			}
830
+			if ($attention_messages !== '') {
831
+				$css_id = is_admin() ? 'message' : 'espresso-notices-attention';
832
+				$css_class = is_admin() ? 'updated ee-notices-attention' : 'attention fade-away';
833
+				//showMessage( $error_messages, TRUE );
834
+				$notices .= '<div id="'
835
+							. $css_id
836
+							. '" class="espresso-notices '
837
+							. $css_class
838
+							. '" style="display:none;"><p>'
839
+							. $attention_messages
840
+							. '</p>'
841
+							. $close
842
+							. '</div>';
843
+			}
844
+			if ($error_messages !== '') {
845
+				$css_id = is_admin() ? 'message' : 'espresso-notices-error';
846
+				$css_class = is_admin() ? 'error' : 'error fade-away';
847
+				//showMessage( $error_messages, TRUE );
848
+				$notices .= '<div id="'
849
+							. $css_id
850
+							. '" class="espresso-notices '
851
+							. $css_class
852
+							. '" style="display:none;"><p>'
853
+							. $error_messages
854
+							. '</p>'
855
+							. $close
856
+							. '</div>';
857
+			}
858
+			$notices .= '</div>';
859
+		} else {
860
+			$notices = array(
861
+				'success'   => $success_messages,
862
+				'attention' => $attention_messages,
863
+				'errors'    => $error_messages,
864
+			);
865
+			if ($remove_empty) {
866
+				// remove empty notices
867
+				foreach ($notices as $type => $notice) {
868
+					if (empty($notice)) {
869
+						unset($notices[$type]);
870
+					}
871
+				}
872
+			}
873
+		}
874
+		if ($print_scripts) {
875
+			self::_print_scripts();
876
+		}
877
+		return $notices;
878
+	}
879
+
880
+
881
+
882
+	/**
883
+	 *    add_persistent_admin_notice
884
+	 *
885
+	 * @param        string $pan_name     the name, or key of the Persistent Admin Notice to be stored
886
+	 * @param        string $pan_message  the message to be stored persistently until dismissed
887
+	 * @param bool          $force_update allows one to enforce the reappearance of a persistent message.
888
+	 * @return        void
889
+	 */
890
+	public static function add_persistent_admin_notice($pan_name = '', $pan_message, $force_update = false)
891
+	{
892
+		if (! empty($pan_name) && ! empty($pan_message)) {
893
+			$persistent_admin_notices = get_option('ee_pers_admin_notices', array());
894
+			//maybe initialize persistent_admin_notices
895
+			if (empty($persistent_admin_notices)) {
896
+				add_option('ee_pers_admin_notices', array(), '', 'no');
897
+			}
898
+			$pan_name = sanitize_key($pan_name);
899
+			if (! array_key_exists($pan_name, $persistent_admin_notices) || $force_update) {
900
+				$persistent_admin_notices[$pan_name] = $pan_message;
901
+				update_option('ee_pers_admin_notices', $persistent_admin_notices);
902
+			}
903
+		}
904
+	}
905
+
906
+
907
+
908
+	/**
909
+	 *    dismiss_persistent_admin_notice
910
+	 *
911
+	 * @param        string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
912
+	 * @param bool          $purge
913
+	 * @param bool          $return_immediately
914
+	 * @return        void
915
+	 */
916
+	public static function dismiss_persistent_admin_notice($pan_name = '', $purge = false, $return_immediately = false)
917
+	{
918
+		$pan_name = EE_Registry::instance()->REQ->is_set('ee_nag_notice')
919
+			? EE_Registry::instance()->REQ->get('ee_nag_notice') : $pan_name;
920
+		if (! empty($pan_name)) {
921
+			$persistent_admin_notices = get_option('ee_pers_admin_notices', array());
922
+			// check if notice we wish to dismiss is actually in the $persistent_admin_notices array
923
+			if (is_array($persistent_admin_notices) && isset($persistent_admin_notices[$pan_name])) {
924
+				// completely delete nag notice, or just NULL message so that it can NOT be added again ?
925
+				if ($purge) {
926
+					unset($persistent_admin_notices[$pan_name]);
927
+				} else {
928
+					$persistent_admin_notices[$pan_name] = null;
929
+				}
930
+				if (update_option('ee_pers_admin_notices', $persistent_admin_notices) === false) {
931
+					EE_Error::add_error(sprintf(__('The persistent admin notice for "%s" could not be deleted.',
932
+						'event_espresso'), $pan_name), __FILE__, __FUNCTION__, __LINE__);
933
+				}
934
+			}
935
+		}
936
+		if ($return_immediately) {
937
+			return;
938
+		}
939
+		if (EE_Registry::instance()->REQ->ajax) {
940
+			// grab any notices and concatenate into string
941
+			echo wp_json_encode(array('errors' => implode('<br />', EE_Error::get_notices(false))));
942
+			exit();
943
+		}
944
+		// save errors to a transient to be displayed on next request (after redirect)
945
+		EE_Error::get_notices(false, true);
946
+		$return_url = EE_Registry::instance()->REQ->is_set('return_url')
947
+			? EE_Registry::instance()->REQ->get('return_url') : '';
948
+		wp_safe_redirect(urldecode($return_url));
949
+	}
950
+
951
+
952
+
953
+	/**
954
+	 * display_persistent_admin_notices
955
+	 *
956
+	 * @param  string $pan_name    the name, or key of the Persistent Admin Notice to be stored
957
+	 * @param  string $pan_message the message to be stored persistently until dismissed
958
+	 * @param  string $return_url  URL to go back to after nag notice is dismissed
959
+	 * @return string
960
+	 */
961
+	public static function display_persistent_admin_notices($pan_name = '', $pan_message = '', $return_url = '')
962
+	{
963
+		if (! empty($pan_name) && ! empty($pan_message)) {
964
+			$args = array(
965
+				'nag_notice'    => $pan_name,
966
+				'return_url'    => urlencode($return_url),
967
+				'ajax_url'      => WP_AJAX_URL,
968
+				'unknown_error' => esc_html__(
969
+					'An unknown error has occurred on the server while attempting to dismiss this notice.',
970
+					'event_espresso'
971
+				),
972
+			);
973
+			EE_Registry::$i18n_js_strings = array_merge(
974
+				EE_Registry::$i18n_js_strings,
975
+				array('ee_dismiss' => $args)
976
+			);
977
+			return '
978 978
 			<div id="'
979
-                   . $pan_name
980
-                   . '" class="espresso-notices updated ee-nag-notice clearfix" style="border-left: 4px solid #fcb93c;">
979
+				   . $pan_name
980
+				   . '" class="espresso-notices updated ee-nag-notice clearfix" style="border-left: 4px solid #fcb93c;">
981 981
 				<p>'
982
-                   . $pan_message
983
-                   . '</p>
982
+				   . $pan_message
983
+				   . '</p>
984 984
 				<a class="dismiss-ee-nag-notice hide-if-no-js" style="float: right; cursor: pointer; text-decoration:none;" rel="'
985
-                   . $pan_name
986
-                   . '">
985
+				   . $pan_name
986
+				   . '">
987 987
 					<span class="dashicons dashicons-dismiss" style="position:relative; top:-1px; margin-right:.25em;"></span>'
988
-                   . __('Dismiss', 'event_espresso')
989
-                   . '
988
+				   . __('Dismiss', 'event_espresso')
989
+				   . '
990 990
 				</a>
991 991
 				<div style="clear:both;"></div>
992 992
 			</div>';
993
-        }
994
-        return '';
995
-    }
996
-
997
-
998
-
999
-    /**
1000
-     *    get_persistent_admin_notices
1001
-     *
1002
-     * @param string $return_url
1003
-     * @return string
1004
-     */
1005
-    public static function get_persistent_admin_notices($return_url = '')
1006
-    {
1007
-        $notices = '';
1008
-        // check for persistent admin notices
1009
-        //filter the list though so plugins can notify the admin in a different way if they want
1010
-        $persistent_admin_notices = apply_filters(
1011
-            'FHEE__EE_Error__get_persistent_admin_notices',
1012
-            get_option('ee_pers_admin_notices', false),
1013
-            'ee_pers_admin_notices',
1014
-            $return_url
1015
-        );
1016
-        if ($persistent_admin_notices) {
1017
-            // load scripts
1018
-            wp_register_script(
1019
-                'espresso_core',
1020
-                EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1021
-                array('jquery'),
1022
-                EVENT_ESPRESSO_VERSION,
1023
-                true
1024
-            );
1025
-            wp_register_script(
1026
-                'ee_error_js',
1027
-                EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1028
-                array('espresso_core'),
1029
-                EVENT_ESPRESSO_VERSION,
1030
-                true
1031
-            );
1032
-            wp_enqueue_script('ee_error_js');
1033
-            // and display notices
1034
-            foreach ($persistent_admin_notices as $pan_name => $pan_message) {
1035
-                $notices .= self::display_persistent_admin_notices($pan_name, $pan_message, $return_url);
1036
-            }
1037
-        }
1038
-        return $notices;
1039
-    }
1040
-
1041
-
1042
-
1043
-    /**
1044
-     * _print_scripts
1045
-     *
1046
-     * @param    bool $force_print
1047
-     * @return    string
1048
-     */
1049
-    private static function _print_scripts($force_print = false)
1050
-    {
1051
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
1052
-            if (wp_script_is('ee_error_js', 'enqueued')) {
1053
-                return '';
1054
-            }
1055
-            if (wp_script_is('ee_error_js', 'registered')) {
1056
-                wp_enqueue_style('espresso_default');
1057
-                wp_enqueue_style('espresso_custom_css');
1058
-                wp_enqueue_script('ee_error_js');
1059
-                wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
1060
-            }
1061
-        } else {
1062
-            return '
993
+		}
994
+		return '';
995
+	}
996
+
997
+
998
+
999
+	/**
1000
+	 *    get_persistent_admin_notices
1001
+	 *
1002
+	 * @param string $return_url
1003
+	 * @return string
1004
+	 */
1005
+	public static function get_persistent_admin_notices($return_url = '')
1006
+	{
1007
+		$notices = '';
1008
+		// check for persistent admin notices
1009
+		//filter the list though so plugins can notify the admin in a different way if they want
1010
+		$persistent_admin_notices = apply_filters(
1011
+			'FHEE__EE_Error__get_persistent_admin_notices',
1012
+			get_option('ee_pers_admin_notices', false),
1013
+			'ee_pers_admin_notices',
1014
+			$return_url
1015
+		);
1016
+		if ($persistent_admin_notices) {
1017
+			// load scripts
1018
+			wp_register_script(
1019
+				'espresso_core',
1020
+				EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1021
+				array('jquery'),
1022
+				EVENT_ESPRESSO_VERSION,
1023
+				true
1024
+			);
1025
+			wp_register_script(
1026
+				'ee_error_js',
1027
+				EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1028
+				array('espresso_core'),
1029
+				EVENT_ESPRESSO_VERSION,
1030
+				true
1031
+			);
1032
+			wp_enqueue_script('ee_error_js');
1033
+			// and display notices
1034
+			foreach ($persistent_admin_notices as $pan_name => $pan_message) {
1035
+				$notices .= self::display_persistent_admin_notices($pan_name, $pan_message, $return_url);
1036
+			}
1037
+		}
1038
+		return $notices;
1039
+	}
1040
+
1041
+
1042
+
1043
+	/**
1044
+	 * _print_scripts
1045
+	 *
1046
+	 * @param    bool $force_print
1047
+	 * @return    string
1048
+	 */
1049
+	private static function _print_scripts($force_print = false)
1050
+	{
1051
+		if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
1052
+			if (wp_script_is('ee_error_js', 'enqueued')) {
1053
+				return '';
1054
+			}
1055
+			if (wp_script_is('ee_error_js', 'registered')) {
1056
+				wp_enqueue_style('espresso_default');
1057
+				wp_enqueue_style('espresso_custom_css');
1058
+				wp_enqueue_script('ee_error_js');
1059
+				wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
1060
+			}
1061
+		} else {
1062
+			return '
1063 1063
 <script>
1064 1064
 /* <![CDATA[ */
1065 1065
 var ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
@@ -1069,143 +1069,143 @@  discard block
 block discarded – undo
1069 1069
 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
1070 1070
 <script src="' . EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js' . '?ver=' . espresso_version() . '" type="text/javascript"></script>
1071 1071
 ';
1072
-        }
1073
-        return '';
1074
-    }
1075
-
1076
-
1077
-
1078
-    /**
1079
-     *    enqueue_error_scripts
1080
-     *
1081
-     * @return        void
1082
-     */
1083
-    public static function enqueue_error_scripts()
1084
-    {
1085
-        self::_print_scripts();
1086
-    }
1087
-
1088
-
1089
-
1090
-    /**
1091
-     *    create error code from filepath, function name,
1092
-     *    and line number where exception or error was thrown
1093
-     *
1094
-     * @param string $file
1095
-     * @param string $func
1096
-     * @param string $line
1097
-     * @return string
1098
-     */
1099
-    public static function generate_error_code($file = '', $func = '', $line = '')
1100
-    {
1101
-        $file = explode('.', basename($file));
1102
-        $error_code = ! empty($file[0]) ? $file[0] : '';
1103
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
1104
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
1105
-        return $error_code;
1106
-    }
1107
-
1108
-
1109
-
1110
-    /**
1111
-     *    write exception details to log file
1112
-     *
1113
-     * @param int   $time
1114
-     * @param array $ex
1115
-     * @param bool  $clear
1116
-     * @return void
1117
-     */
1118
-    public function write_to_error_log($time = 0, $ex = array(), $clear = false)
1119
-    {
1120
-        if (empty($ex)) {
1121
-            return;
1122
-        }
1123
-        if (! $time) {
1124
-            $time = time();
1125
-        }
1126
-        $exception_log = '----------------------------------------------------------------------------------------'
1127
-                         . PHP_EOL;
1128
-        $exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
1129
-        $exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
1130
-        $exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
1131
-        $exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
1132
-        $exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
1133
-        $exception_log .= 'Stack trace: ' . PHP_EOL;
1134
-        $exception_log .= $ex['string'] . PHP_EOL;
1135
-        $exception_log .= '----------------------------------------------------------------------------------------'
1136
-                          . PHP_EOL;
1137
-        try {
1138
-            EEH_File::ensure_file_exists_and_is_writable(
1139
-                EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . self::$_exception_log_file
1140
-            );
1141
-            EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs');
1142
-            if (! $clear) {
1143
-                //get existing log file and append new log info
1144
-                $exception_log = EEH_File::get_file_contents(
1145
-                    EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . self::$_exception_log_file
1146
-                ) . $exception_log;
1147
-            }
1148
-            EEH_File::write_to_file(
1149
-                EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . self::$_exception_log_file,
1150
-                $exception_log
1151
-            );
1152
-        } catch (EE_Error $e) {
1153
-            EE_Error::add_error(sprintf(__('Event Espresso error logging could not be setup because: %s',
1154
-                'event_espresso'), $e->getMessage()));
1155
-            return;
1156
-        }
1157
-    }
1158
-
1159
-
1160
-
1161
-    /**
1162
-     * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1163
-     * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1164
-     * but the code execution is done in a manner that could lead to unexpected results
1165
-     * (i.e. running to early, or too late in WP or EE loading process).
1166
-     * A good test for knowing whether to use this method is:
1167
-     * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1168
-     * Yes -> use EE_Error::add_error() or throw new EE_Error()
1169
-     * 2. If this is loaded before something else, it won't break anything,
1170
-     * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1171
-     *
1172
-     * @uses   constant WP_DEBUG test if wp_debug is on or not
1173
-     * @param string $function      The function that was called
1174
-     * @param string $message       A message explaining what has been done incorrectly
1175
-     * @param string $version       The version of Event Espresso where the error was added
1176
-     * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1177
-     *                              for a deprecated function. This allows deprecation to occur during one version,
1178
-     *                              but not have any notices appear until a later version. This allows developers
1179
-     *                              extra time to update their code before notices appear.
1180
-     * @param int    $error_type
1181
-     */
1182
-    public static function doing_it_wrong(
1183
-        $function,
1184
-        $message,
1185
-        $version,
1186
-        $applies_when = '',
1187
-        $error_type = null
1188
-    ) {
1189
-        if (defined('WP_DEBUG') && WP_DEBUG) {
1190
-            EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1191
-        }
1192
-    }
1193
-
1194
-
1195
-
1196
-    /**
1197
-     * Like get_notices, but returns an array of all the notices of the given type.
1198
-     *
1199
-     * @return array {
1200
-     * @type array $success   all the success messages
1201
-     * @type array $errors    all the error messages
1202
-     * @type array $attention all the attention messages
1203
-     * }
1204
-     */
1205
-    public static function get_raw_notices()
1206
-    {
1207
-        return self::$_espresso_notices;
1208
-    }
1072
+		}
1073
+		return '';
1074
+	}
1075
+
1076
+
1077
+
1078
+	/**
1079
+	 *    enqueue_error_scripts
1080
+	 *
1081
+	 * @return        void
1082
+	 */
1083
+	public static function enqueue_error_scripts()
1084
+	{
1085
+		self::_print_scripts();
1086
+	}
1087
+
1088
+
1089
+
1090
+	/**
1091
+	 *    create error code from filepath, function name,
1092
+	 *    and line number where exception or error was thrown
1093
+	 *
1094
+	 * @param string $file
1095
+	 * @param string $func
1096
+	 * @param string $line
1097
+	 * @return string
1098
+	 */
1099
+	public static function generate_error_code($file = '', $func = '', $line = '')
1100
+	{
1101
+		$file = explode('.', basename($file));
1102
+		$error_code = ! empty($file[0]) ? $file[0] : '';
1103
+		$error_code .= ! empty($func) ? ' - ' . $func : '';
1104
+		$error_code .= ! empty($line) ? ' - ' . $line : '';
1105
+		return $error_code;
1106
+	}
1107
+
1108
+
1109
+
1110
+	/**
1111
+	 *    write exception details to log file
1112
+	 *
1113
+	 * @param int   $time
1114
+	 * @param array $ex
1115
+	 * @param bool  $clear
1116
+	 * @return void
1117
+	 */
1118
+	public function write_to_error_log($time = 0, $ex = array(), $clear = false)
1119
+	{
1120
+		if (empty($ex)) {
1121
+			return;
1122
+		}
1123
+		if (! $time) {
1124
+			$time = time();
1125
+		}
1126
+		$exception_log = '----------------------------------------------------------------------------------------'
1127
+						 . PHP_EOL;
1128
+		$exception_log .= '[' . date('Y-m-d H:i:s', $time) . ']  Exception Details' . PHP_EOL;
1129
+		$exception_log .= 'Message: ' . $ex['msg'] . PHP_EOL;
1130
+		$exception_log .= 'Code: ' . $ex['code'] . PHP_EOL;
1131
+		$exception_log .= 'File: ' . $ex['file'] . PHP_EOL;
1132
+		$exception_log .= 'Line No: ' . $ex['line'] . PHP_EOL;
1133
+		$exception_log .= 'Stack trace: ' . PHP_EOL;
1134
+		$exception_log .= $ex['string'] . PHP_EOL;
1135
+		$exception_log .= '----------------------------------------------------------------------------------------'
1136
+						  . PHP_EOL;
1137
+		try {
1138
+			EEH_File::ensure_file_exists_and_is_writable(
1139
+				EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . self::$_exception_log_file
1140
+			);
1141
+			EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs');
1142
+			if (! $clear) {
1143
+				//get existing log file and append new log info
1144
+				$exception_log = EEH_File::get_file_contents(
1145
+					EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . self::$_exception_log_file
1146
+				) . $exception_log;
1147
+			}
1148
+			EEH_File::write_to_file(
1149
+				EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . self::$_exception_log_file,
1150
+				$exception_log
1151
+			);
1152
+		} catch (EE_Error $e) {
1153
+			EE_Error::add_error(sprintf(__('Event Espresso error logging could not be setup because: %s',
1154
+				'event_espresso'), $e->getMessage()));
1155
+			return;
1156
+		}
1157
+	}
1158
+
1159
+
1160
+
1161
+	/**
1162
+	 * This is just a wrapper for the EEH_Debug_Tools::instance()->doing_it_wrong() method.
1163
+	 * doing_it_wrong() is used in those cases where a normal PHP error won't get thrown,
1164
+	 * but the code execution is done in a manner that could lead to unexpected results
1165
+	 * (i.e. running to early, or too late in WP or EE loading process).
1166
+	 * A good test for knowing whether to use this method is:
1167
+	 * 1. Is there going to be a PHP error if something isn't setup/used correctly?
1168
+	 * Yes -> use EE_Error::add_error() or throw new EE_Error()
1169
+	 * 2. If this is loaded before something else, it won't break anything,
1170
+	 * but just wont' do what its supposed to do? Yes -> use EE_Error::doing_it_wrong()
1171
+	 *
1172
+	 * @uses   constant WP_DEBUG test if wp_debug is on or not
1173
+	 * @param string $function      The function that was called
1174
+	 * @param string $message       A message explaining what has been done incorrectly
1175
+	 * @param string $version       The version of Event Espresso where the error was added
1176
+	 * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
1177
+	 *                              for a deprecated function. This allows deprecation to occur during one version,
1178
+	 *                              but not have any notices appear until a later version. This allows developers
1179
+	 *                              extra time to update their code before notices appear.
1180
+	 * @param int    $error_type
1181
+	 */
1182
+	public static function doing_it_wrong(
1183
+		$function,
1184
+		$message,
1185
+		$version,
1186
+		$applies_when = '',
1187
+		$error_type = null
1188
+	) {
1189
+		if (defined('WP_DEBUG') && WP_DEBUG) {
1190
+			EEH_Debug_Tools::instance()->doing_it_wrong($function, $message, $version, $applies_when, $error_type);
1191
+		}
1192
+	}
1193
+
1194
+
1195
+
1196
+	/**
1197
+	 * Like get_notices, but returns an array of all the notices of the given type.
1198
+	 *
1199
+	 * @return array {
1200
+	 * @type array $success   all the success messages
1201
+	 * @type array $errors    all the error messages
1202
+	 * @type array $attention all the attention messages
1203
+	 * }
1204
+	 */
1205
+	public static function get_raw_notices()
1206
+	{
1207
+		return self::$_espresso_notices;
1208
+	}
1209 1209
 
1210 1210
 
1211 1211
 
@@ -1221,27 +1221,27 @@  discard block
 block discarded – undo
1221 1221
  */
1222 1222
 function espresso_error_enqueue_scripts()
1223 1223
 {
1224
-    // js for error handling
1225
-    wp_register_script(
1226
-        'espresso_core',
1227
-        EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1228
-        array('jquery'),
1229
-        EVENT_ESPRESSO_VERSION,
1230
-        false
1231
-    );
1232
-    wp_register_script(
1233
-        'ee_error_js',
1234
-        EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1235
-        array('espresso_core'),
1236
-        EVENT_ESPRESSO_VERSION,
1237
-        false
1238
-    );
1224
+	// js for error handling
1225
+	wp_register_script(
1226
+		'espresso_core',
1227
+		EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
1228
+		array('jquery'),
1229
+		EVENT_ESPRESSO_VERSION,
1230
+		false
1231
+	);
1232
+	wp_register_script(
1233
+		'ee_error_js',
1234
+		EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
1235
+		array('espresso_core'),
1236
+		EVENT_ESPRESSO_VERSION,
1237
+		false
1238
+	);
1239 1239
 }
1240 1240
 
1241 1241
 if (is_admin()) {
1242
-    add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1242
+	add_action('admin_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1243 1243
 } else {
1244
-    add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1244
+	add_action('wp_enqueue_scripts', 'espresso_error_enqueue_scripts', 2);
1245 1245
 }
1246 1246
 
1247 1247
 
Please login to merge, or discard this patch.
core/admin/EE_Admin_Page_CPT.core.php 2 patches
Indentation   +1417 added lines, -1417 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -24,470 +24,470 @@  discard block
 block discarded – undo
24 24
 {
25 25
 
26 26
 
27
-    /**
28
-     * This gets set in _setup_cpt
29
-     * It will contain the object for the custom post type.
30
-     *
31
-     * @var EE_CPT_Base
32
-     */
33
-    protected $_cpt_object;
34
-
35
-
36
-
37
-    /**
38
-     * a boolean flag to set whether the current route is a cpt route or not.
39
-     *
40
-     * @var bool
41
-     */
42
-    protected $_cpt_route = false;
43
-
44
-
45
-
46
-    /**
47
-     * This property allows cpt classes to define multiple routes as cpt routes.
48
-     * //in this array we define what the custom post type for this route is.
49
-     * array(
50
-     * 'route_name' => 'custom_post_type_slug'
51
-     * )
52
-     *
53
-     * @var array
54
-     */
55
-    protected $_cpt_routes = array();
56
-
27
+	/**
28
+	 * This gets set in _setup_cpt
29
+	 * It will contain the object for the custom post type.
30
+	 *
31
+	 * @var EE_CPT_Base
32
+	 */
33
+	protected $_cpt_object;
34
+
35
+
36
+
37
+	/**
38
+	 * a boolean flag to set whether the current route is a cpt route or not.
39
+	 *
40
+	 * @var bool
41
+	 */
42
+	protected $_cpt_route = false;
43
+
44
+
45
+
46
+	/**
47
+	 * This property allows cpt classes to define multiple routes as cpt routes.
48
+	 * //in this array we define what the custom post type for this route is.
49
+	 * array(
50
+	 * 'route_name' => 'custom_post_type_slug'
51
+	 * )
52
+	 *
53
+	 * @var array
54
+	 */
55
+	protected $_cpt_routes = array();
56
+
57 57
 
58 58
 
59
-    /**
60
-     * This simply defines what the corresponding routes WP will be redirected to after completing a post save/update.
61
-     * in this format:
62
-     * array(
63
-     * 'post_type_slug' => 'edit_route'
64
-     * )
65
-     *
66
-     * @var array
67
-     */
68
-    protected $_cpt_edit_routes = array();
69
-
70
-
71
-
72
-    /**
73
-     * If child classes set the name of their main model via the $_cpt_obj_models property, EE_Admin_Page_CPT will
74
-     * attempt to retrieve the related object model for the edit pages and assign it to _cpt_page_object. the
75
-     * _cpt_model_names property should be in the following format: array(
76
-     * 'route_defined_by_action_param' => 'Model_Name')
77
-     *
78
-     * @var array $_cpt_model_names
79
-     */
80
-    protected $_cpt_model_names = array();
81
-
82
-
83
-    /**
84
-     * @var EE_CPT_Base
85
-     */
86
-    protected $_cpt_model_obj = false;
87
-
88
-
89
-
90
-    /**
91
-     * This will hold an array of autosave containers that will be used to obtain input values and hook into the WP
92
-     * autosave so we can save our inputs on the save_post hook!  Children classes should add to this array by using
93
-     * the _register_autosave_containers() method so that we don't override any other containers already registered.
94
-     * Registration of containers should be done before load_page_dependencies() is run.
95
-     *
96
-     * @var array()
97
-     */
98
-    protected $_autosave_containers = array();
99
-    protected $_autosave_fields = array();
100
-
101
-    /**
102
-     * Array mapping from admin actions to their equivalent wp core pages for custom post types. So when a user visits
103
-     * a page for an action, it will appear as if they were visiting the wp core page for that custom post type
104
-     *
105
-     * @var array
106
-     */
107
-    protected $_pagenow_map;
108
-
109
-
110
-
111
-    /**
112
-     * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
113
-     * saved.  Child classes are required to declare this method.  Typically you would use this to save any additional
114
-     * data. Keep in mind also that "save_post" runs on EVERY post update to the database. ALSO very important.  When a
115
-     * post transitions from scheduled to published, the save_post action is fired but you will NOT have any _POST data
116
-     * containing any extra info you may have from other meta saves.  So MAKE sure that you handle this accordingly.
117
-     *
118
-     * @access protected
119
-     * @abstract
120
-     * @param  string $post_id The ID of the cpt that was saved (so you can link relationally)
121
-     * @param  EE_CPT_Base $post    The post object of the cpt that was saved.
122
-     * @return void
123
-     */
124
-    abstract protected function _insert_update_cpt_item($post_id, $post);
125
-
126
-
127
-
128
-    /**
129
-     * This is hooked into the WordPress do_action('trashed_post') hook and runs after a cpt has been trashed.
130
-     *
131
-     * @abstract
132
-     * @access public
133
-     * @param  string $post_id The ID of the cpt that was trashed
134
-     * @return void
135
-     */
136
-    abstract public function trash_cpt_item($post_id);
137
-
138
-
139
-
140
-    /**
141
-     * This is hooked into the WordPress do_action('untrashed_post') hook and runs after a cpt has been untrashed
142
-     *
143
-     * @param  string $post_id theID of the cpt that was untrashed
144
-     * @return void
145
-     */
146
-    abstract public function restore_cpt_item($post_id);
147
-
148
-
149
-
150
-    /**
151
-     * This is hooked into the WordPress do_action('delete_cpt_item') hook and runs after a cpt has been fully deleted
152
-     * from the db
153
-     *
154
-     * @param  string $post_id the ID of the cpt that was deleted
155
-     * @return void
156
-     */
157
-    abstract public function delete_cpt_item($post_id);
158
-
159
-
160
-
161
-    /**
162
-     * Just utilizing the method EE_Admin exposes for doing things before page setup.
163
-     *
164
-     * @access protected
165
-     * @return void
166
-     */
167
-    protected function _before_page_setup()
168
-    {
169
-        $page = isset($this->_req_data['page']) ? $this->_req_data['page'] : $this->page_slug;
170
-        $this->_cpt_routes = array_merge(array(
171
-            'create_new' => $this->page_slug,
172
-            'edit'       => $this->page_slug,
173
-            'trash'      => $this->page_slug,
174
-        ), $this->_cpt_routes);
175
-        //let's see if the current route has a value for cpt_object_slug if it does we use that instead of the page
176
-        $this->_cpt_object = isset($this->_req_data['action']) && isset($this->_cpt_routes[$this->_req_data['action']])
177
-            ? get_post_type_object($this->_cpt_routes[$this->_req_data['action']])
178
-            : get_post_type_object($page);
179
-        //tweak pagenow for page loading.
180
-        if ( ! $this->_pagenow_map) {
181
-            $this->_pagenow_map = array(
182
-                'create_new' => 'post-new.php',
183
-                'edit'       => 'post.php',
184
-                'trash'      => 'post.php',
185
-            );
186
-        }
187
-        add_action('current_screen', array($this, 'modify_pagenow'));
188
-        //TODO the below will need to be reworked to account for the cpt routes that are NOT based off of page but action param.
189
-        //get current page from autosave
190
-        $current_page = isset($this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page'])
191
-            ? $this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page']
192
-            : null;
193
-        $this->_current_page = isset($this->_req_data['current_page'])
194
-            ? $this->_req_data['current_page']
195
-            : $current_page;
196
-        //autosave... make sure its only for the correct page
197
-        //if ( ! empty($this->_current_page) && $this->_current_page == $this->page_slug) {
198
-            //setup autosave ajax hook
199
-            //add_action('wp_ajax_ee-autosave', array( $this, 'do_extra_autosave_stuff' ), 10 ); //TODO reactivate when 4.2 autosave is implemented
200
-        //}
201
-    }
202
-
203
-
204
-
205
-    /**
206
-     * Simply ensure that we simulate the correct post route for cpt screens
207
-     *
208
-     * @param WP_Screen $current_screen
209
-     * @return void
210
-     */
211
-    public function modify_pagenow($current_screen)
212
-    {
213
-        global $pagenow, $hook_suffix;
214
-        //possibly reset pagenow.
215
-        if ( ! empty($this->_req_data['page'])
216
-             && $this->_req_data['page'] == $this->page_slug
217
-             && ! empty($this->_req_data['action'])
218
-             && isset($this->_pagenow_map[$this->_req_data['action']])
219
-        ) {
220
-            $pagenow = $this->_pagenow_map[$this->_req_data['action']];
221
-            $hook_suffix = $pagenow;
222
-        }
223
-    }
224
-
225
-
226
-
227
-    /**
228
-     * This method is used to register additional autosave containers to the _autosave_containers property.
229
-     *
230
-     * @todo We should automate this at some point by creating a wrapper for add_post_metabox and in our wrapper we
231
-     *       automatically register the id for the post metabox as a container.
232
-     * @param  array $ids an array of ids for containers that hold form inputs we want autosave to pickup.  Typically
233
-     *                    you would send along the id of a metabox container.
234
-     * @return void
235
-     */
236
-    protected function _register_autosave_containers($ids)
237
-    {
238
-        $this->_autosave_containers = array_merge($this->_autosave_fields, (array)$ids);
239
-    }
240
-
241
-
242
-
243
-    /**
244
-     * Something nifty.  We're going to loop through all the registered metaboxes and if the CALLBACK is an instance of
245
-     * EE_Admin_Page OR EE_Admin_Hooks, then we'll add the id to our _autosave_containers array.
246
-     */
247
-    protected function _set_autosave_containers()
248
-    {
249
-        global $wp_meta_boxes;
250
-        $containers = array();
251
-        if (empty($wp_meta_boxes)) {
252
-            return;
253
-        }
254
-        $current_metaboxes = isset($wp_meta_boxes[$this->page_slug]) ? $wp_meta_boxes[$this->page_slug] : array();
255
-        foreach ($current_metaboxes as $box_context) {
256
-            foreach ($box_context as $box_details) {
257
-                foreach ($box_details as $box) {
258
-                    if (
259
-                        is_array($box['callback'])
260
-                        && (
261
-                            $box['callback'][0] instanceof EE_Admin_Page
262
-                            || $box['callback'][0] instanceof EE_Admin_Hooks
263
-                        )
264
-                    ) {
265
-                        $containers[] = $box['id'];
266
-                    }
267
-                }
268
-            }
269
-        }
270
-        $this->_autosave_containers = array_merge($this->_autosave_containers, $containers);
271
-        //add hidden inputs container
272
-        $this->_autosave_containers[] = 'ee-cpt-hidden-inputs';
273
-    }
274
-
275
-
276
-
277
-    protected function _load_autosave_scripts_styles()
278
-    {
279
-        /*wp_register_script('cpt-autosave', EE_ADMIN_URL . 'assets/ee-cpt-autosave.js', array('ee-serialize-full-array', 'event_editor_js'), EVENT_ESPRESSO_VERSION, TRUE );
59
+	/**
60
+	 * This simply defines what the corresponding routes WP will be redirected to after completing a post save/update.
61
+	 * in this format:
62
+	 * array(
63
+	 * 'post_type_slug' => 'edit_route'
64
+	 * )
65
+	 *
66
+	 * @var array
67
+	 */
68
+	protected $_cpt_edit_routes = array();
69
+
70
+
71
+
72
+	/**
73
+	 * If child classes set the name of their main model via the $_cpt_obj_models property, EE_Admin_Page_CPT will
74
+	 * attempt to retrieve the related object model for the edit pages and assign it to _cpt_page_object. the
75
+	 * _cpt_model_names property should be in the following format: array(
76
+	 * 'route_defined_by_action_param' => 'Model_Name')
77
+	 *
78
+	 * @var array $_cpt_model_names
79
+	 */
80
+	protected $_cpt_model_names = array();
81
+
82
+
83
+	/**
84
+	 * @var EE_CPT_Base
85
+	 */
86
+	protected $_cpt_model_obj = false;
87
+
88
+
89
+
90
+	/**
91
+	 * This will hold an array of autosave containers that will be used to obtain input values and hook into the WP
92
+	 * autosave so we can save our inputs on the save_post hook!  Children classes should add to this array by using
93
+	 * the _register_autosave_containers() method so that we don't override any other containers already registered.
94
+	 * Registration of containers should be done before load_page_dependencies() is run.
95
+	 *
96
+	 * @var array()
97
+	 */
98
+	protected $_autosave_containers = array();
99
+	protected $_autosave_fields = array();
100
+
101
+	/**
102
+	 * Array mapping from admin actions to their equivalent wp core pages for custom post types. So when a user visits
103
+	 * a page for an action, it will appear as if they were visiting the wp core page for that custom post type
104
+	 *
105
+	 * @var array
106
+	 */
107
+	protected $_pagenow_map;
108
+
109
+
110
+
111
+	/**
112
+	 * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
113
+	 * saved.  Child classes are required to declare this method.  Typically you would use this to save any additional
114
+	 * data. Keep in mind also that "save_post" runs on EVERY post update to the database. ALSO very important.  When a
115
+	 * post transitions from scheduled to published, the save_post action is fired but you will NOT have any _POST data
116
+	 * containing any extra info you may have from other meta saves.  So MAKE sure that you handle this accordingly.
117
+	 *
118
+	 * @access protected
119
+	 * @abstract
120
+	 * @param  string $post_id The ID of the cpt that was saved (so you can link relationally)
121
+	 * @param  EE_CPT_Base $post    The post object of the cpt that was saved.
122
+	 * @return void
123
+	 */
124
+	abstract protected function _insert_update_cpt_item($post_id, $post);
125
+
126
+
127
+
128
+	/**
129
+	 * This is hooked into the WordPress do_action('trashed_post') hook and runs after a cpt has been trashed.
130
+	 *
131
+	 * @abstract
132
+	 * @access public
133
+	 * @param  string $post_id The ID of the cpt that was trashed
134
+	 * @return void
135
+	 */
136
+	abstract public function trash_cpt_item($post_id);
137
+
138
+
139
+
140
+	/**
141
+	 * This is hooked into the WordPress do_action('untrashed_post') hook and runs after a cpt has been untrashed
142
+	 *
143
+	 * @param  string $post_id theID of the cpt that was untrashed
144
+	 * @return void
145
+	 */
146
+	abstract public function restore_cpt_item($post_id);
147
+
148
+
149
+
150
+	/**
151
+	 * This is hooked into the WordPress do_action('delete_cpt_item') hook and runs after a cpt has been fully deleted
152
+	 * from the db
153
+	 *
154
+	 * @param  string $post_id the ID of the cpt that was deleted
155
+	 * @return void
156
+	 */
157
+	abstract public function delete_cpt_item($post_id);
158
+
159
+
160
+
161
+	/**
162
+	 * Just utilizing the method EE_Admin exposes for doing things before page setup.
163
+	 *
164
+	 * @access protected
165
+	 * @return void
166
+	 */
167
+	protected function _before_page_setup()
168
+	{
169
+		$page = isset($this->_req_data['page']) ? $this->_req_data['page'] : $this->page_slug;
170
+		$this->_cpt_routes = array_merge(array(
171
+			'create_new' => $this->page_slug,
172
+			'edit'       => $this->page_slug,
173
+			'trash'      => $this->page_slug,
174
+		), $this->_cpt_routes);
175
+		//let's see if the current route has a value for cpt_object_slug if it does we use that instead of the page
176
+		$this->_cpt_object = isset($this->_req_data['action']) && isset($this->_cpt_routes[$this->_req_data['action']])
177
+			? get_post_type_object($this->_cpt_routes[$this->_req_data['action']])
178
+			: get_post_type_object($page);
179
+		//tweak pagenow for page loading.
180
+		if ( ! $this->_pagenow_map) {
181
+			$this->_pagenow_map = array(
182
+				'create_new' => 'post-new.php',
183
+				'edit'       => 'post.php',
184
+				'trash'      => 'post.php',
185
+			);
186
+		}
187
+		add_action('current_screen', array($this, 'modify_pagenow'));
188
+		//TODO the below will need to be reworked to account for the cpt routes that are NOT based off of page but action param.
189
+		//get current page from autosave
190
+		$current_page = isset($this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page'])
191
+			? $this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page']
192
+			: null;
193
+		$this->_current_page = isset($this->_req_data['current_page'])
194
+			? $this->_req_data['current_page']
195
+			: $current_page;
196
+		//autosave... make sure its only for the correct page
197
+		//if ( ! empty($this->_current_page) && $this->_current_page == $this->page_slug) {
198
+			//setup autosave ajax hook
199
+			//add_action('wp_ajax_ee-autosave', array( $this, 'do_extra_autosave_stuff' ), 10 ); //TODO reactivate when 4.2 autosave is implemented
200
+		//}
201
+	}
202
+
203
+
204
+
205
+	/**
206
+	 * Simply ensure that we simulate the correct post route for cpt screens
207
+	 *
208
+	 * @param WP_Screen $current_screen
209
+	 * @return void
210
+	 */
211
+	public function modify_pagenow($current_screen)
212
+	{
213
+		global $pagenow, $hook_suffix;
214
+		//possibly reset pagenow.
215
+		if ( ! empty($this->_req_data['page'])
216
+			 && $this->_req_data['page'] == $this->page_slug
217
+			 && ! empty($this->_req_data['action'])
218
+			 && isset($this->_pagenow_map[$this->_req_data['action']])
219
+		) {
220
+			$pagenow = $this->_pagenow_map[$this->_req_data['action']];
221
+			$hook_suffix = $pagenow;
222
+		}
223
+	}
224
+
225
+
226
+
227
+	/**
228
+	 * This method is used to register additional autosave containers to the _autosave_containers property.
229
+	 *
230
+	 * @todo We should automate this at some point by creating a wrapper for add_post_metabox and in our wrapper we
231
+	 *       automatically register the id for the post metabox as a container.
232
+	 * @param  array $ids an array of ids for containers that hold form inputs we want autosave to pickup.  Typically
233
+	 *                    you would send along the id of a metabox container.
234
+	 * @return void
235
+	 */
236
+	protected function _register_autosave_containers($ids)
237
+	{
238
+		$this->_autosave_containers = array_merge($this->_autosave_fields, (array)$ids);
239
+	}
240
+
241
+
242
+
243
+	/**
244
+	 * Something nifty.  We're going to loop through all the registered metaboxes and if the CALLBACK is an instance of
245
+	 * EE_Admin_Page OR EE_Admin_Hooks, then we'll add the id to our _autosave_containers array.
246
+	 */
247
+	protected function _set_autosave_containers()
248
+	{
249
+		global $wp_meta_boxes;
250
+		$containers = array();
251
+		if (empty($wp_meta_boxes)) {
252
+			return;
253
+		}
254
+		$current_metaboxes = isset($wp_meta_boxes[$this->page_slug]) ? $wp_meta_boxes[$this->page_slug] : array();
255
+		foreach ($current_metaboxes as $box_context) {
256
+			foreach ($box_context as $box_details) {
257
+				foreach ($box_details as $box) {
258
+					if (
259
+						is_array($box['callback'])
260
+						&& (
261
+							$box['callback'][0] instanceof EE_Admin_Page
262
+							|| $box['callback'][0] instanceof EE_Admin_Hooks
263
+						)
264
+					) {
265
+						$containers[] = $box['id'];
266
+					}
267
+				}
268
+			}
269
+		}
270
+		$this->_autosave_containers = array_merge($this->_autosave_containers, $containers);
271
+		//add hidden inputs container
272
+		$this->_autosave_containers[] = 'ee-cpt-hidden-inputs';
273
+	}
274
+
275
+
276
+
277
+	protected function _load_autosave_scripts_styles()
278
+	{
279
+		/*wp_register_script('cpt-autosave', EE_ADMIN_URL . 'assets/ee-cpt-autosave.js', array('ee-serialize-full-array', 'event_editor_js'), EVENT_ESPRESSO_VERSION, TRUE );
280 280
         wp_enqueue_script('cpt-autosave');/**/ //todo re-enable when we start doing autosave again in 4.2
281 281
 
282
-        //filter _autosave_containers
283
-        $containers = apply_filters('FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
284
-            $this->_autosave_containers, $this);
285
-        $containers = apply_filters('FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
286
-            $containers, $this);
287
-
288
-        wp_localize_script('event_editor_js', 'EE_AUTOSAVE_IDS',
289
-            $containers); //todo once we enable autosaves, this needs to be switched to localize with "cpt-autosave"
290
-
291
-        $unsaved_data_msg = array(
292
-            'eventmsg'     => sprintf(__("The changes you made to this %s will be lost if you navigate away from this page.",
293
-                'event_espresso'), $this->_cpt_object->labels->singular_name),
294
-            'inputChanged' => 0,
295
-        );
296
-        wp_localize_script('event_editor_js', 'UNSAVED_DATA_MSG', $unsaved_data_msg);
297
-    }
298
-
299
-
300
-
301
-    public function load_page_dependencies()
302
-    {
303
-        try {
304
-            $this->_load_page_dependencies();
305
-        } catch (EE_Error $e) {
306
-            $e->get_error();
307
-        }
308
-    }
309
-
310
-
311
-
312
-    /**
313
-     * overloading the EE_Admin_Page parent load_page_dependencies so we can get the cpt stuff added in appropriately
314
-     *
315
-     * @access protected
316
-     * @return void
317
-     */
318
-    protected function _load_page_dependencies()
319
-    {
320
-        //we only add stuff if this is a cpt_route!
321
-        if ( ! $this->_cpt_route) {
322
-            parent::_load_page_dependencies();
323
-            return;
324
-        }
325
-        // now let's do some automatic filters into the wp_system
326
-        // and we'll check to make sure the CHILD class
327
-        // automatically has the required methods in place.
328
-        // the following filters are for setting all the redirects
329
-        // on DEFAULT WP custom post type actions
330
-        // let's add a hidden input to the post-edit form
331
-        // so we know when we have to trigger our custom redirects!
332
-        // Otherwise the redirects will happen on ALL post saves which wouldn't be good of course!
333
-        add_action('edit_form_after_title', array($this, 'cpt_post_form_hidden_input'));
334
-        // inject our Admin page nav tabs...
335
-        // let's make sure the nav tabs are set if they aren't already
336
-        // if ( empty( $this->_nav_tabs ) ) $this->_set_nav_tabs();
337
-        add_action('post_edit_form_tag', array($this, 'inject_nav_tabs'));
338
-        // modify the post_updated messages array
339
-        add_action('post_updated_messages', array($this, 'post_update_messages'), 10);
340
-        // add shortlink button to cpt edit screens.  We can do this as a universal thing BECAUSE,
341
-        // cpts use the same format for shortlinks as posts!
342
-        add_filter('pre_get_shortlink', array($this, 'add_shortlink_button_to_editor'), 10, 4);
343
-        // This basically allows us to change the title of the "publish" metabox area
344
-        // on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
345
-        if ( ! empty($this->_labels['publishbox'])) {
346
-            $box_label = is_array($this->_labels['publishbox'])
347
-                         && isset($this->_labels['publishbox'][$this->_req_action])
348
-                    ? $this->_labels['publishbox'][$this->_req_action]
349
-                    : $this->_labels['publishbox'];
350
-            add_meta_box(
351
-                'submitdiv',
352
-                $box_label,
353
-                'post_submit_meta_box',
354
-                $this->_cpt_routes[$this->_req_action],
355
-                'side',
356
-                'core'
357
-            );
358
-        }
359
-        //let's add page_templates metabox if this cpt added support for it.
360
-        if ($this->_supports_page_templates($this->_cpt_object->name)) {
361
-            add_meta_box(
362
-                'page_templates',
363
-                __('Page Template', 'event_espresso'),
364
-                array($this, 'page_template_meta_box'),
365
-                $this->_cpt_routes[$this->_req_action],
366
-                'side',
367
-                'default'
368
-            );
369
-        }
370
-        //this is a filter that allows the addition of extra html after the permalink field on the wp post edit-form
371
-        if (method_exists($this, 'extra_permalink_field_buttons')) {
372
-            add_filter('get_sample_permalink_html', array($this, 'extra_permalink_field_buttons'), 10, 4);
373
-        }
374
-        //add preview button
375
-        add_filter('get_sample_permalink_html', array($this, 'preview_button_html'), 5, 4);
376
-        //insert our own post_stati dropdown
377
-        add_action('post_submitbox_misc_actions', array($this, 'custom_post_stati_dropdown'), 10);
378
-        //This allows adding additional information to the publish post submitbox on the wp post edit form
379
-        if (method_exists($this, 'extra_misc_actions_publish_box')) {
380
-            add_action('post_submitbox_misc_actions', array($this, 'extra_misc_actions_publish_box'), 10);
381
-        }
382
-        // This allows for adding additional stuff after the title field on the wp post edit form.
383
-        // This is also before the wp_editor for post description field.
384
-        if (method_exists($this, 'edit_form_after_title')) {
385
-            add_action('edit_form_after_title', array($this, 'edit_form_after_title'), 10);
386
-        }
387
-        /**
388
-         * Filtering WP's esc_url to capture urls pointing to core wp routes so they point to our route.
389
-         */
390
-        add_filter('clean_url', array($this, 'switch_core_wp_urls_with_ours'), 10, 3);
391
-        parent::_load_page_dependencies();
392
-        // notice we are ALSO going to load the pagenow hook set for this route
393
-        // (see _before_page_setup for the reset of the pagenow global ).
394
-        // This is for any plugins that are doing things properly
395
-        // and hooking into the load page hook for core wp cpt routes.
396
-        global $pagenow;
397
-        do_action('load-' . $pagenow);
398
-        $this->modify_current_screen();
399
-        add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
400
-        //we route REALLY early.
401
-        try {
402
-            $this->_route_admin_request();
403
-        } catch (EE_Error $e) {
404
-            $e->get_error();
405
-        }
406
-    }
407
-
408
-
409
-
410
-    /**
411
-     * Since we don't want users going to default core wp routes, this will check any wp urls run through the
412
-     * esc_url() method and if we see a url matching a pattern for our routes, we'll modify it to point to OUR
413
-     * route instead.
414
-     *
415
-     * @param string $good_protocol_url The escaped url.
416
-     * @param string $original_url      The original url.
417
-     * @param string $_context          The context sent to the esc_url method.
418
-     * @return string possibly a new url for our route.
419
-     */
420
-    public function switch_core_wp_urls_with_ours($good_protocol_url, $original_url, $_context)
421
-    {
422
-        $routes_to_match = array(
423
-            0 => array(
424
-                'edit.php?post_type=espresso_attendees',
425
-                'admin.php?page=espresso_registrations&action=contact_list',
426
-            ),
427
-            1 => array(
428
-                'edit.php?post_type=' . $this->_cpt_object->name,
429
-                'admin.php?page=' . $this->_cpt_object->name,
430
-            ),
431
-        );
432
-        foreach ($routes_to_match as $route_matches) {
433
-            if (strpos($good_protocol_url, $route_matches[0]) !== false) {
434
-                return str_replace($route_matches[0], $route_matches[1], $good_protocol_url);
435
-            }
436
-        }
437
-        return $good_protocol_url;
438
-    }
439
-
440
-
441
-
442
-    /**
443
-     * Determine whether the current cpt supports page templates or not.
444
-     *
445
-     * @since %VER%
446
-     * @param string $cpt_name The cpt slug we're checking on.
447
-     * @return bool True supported, false not.
448
-     */
449
-    private function _supports_page_templates($cpt_name)
450
-    {
451
-
452
-        $cpt_args = EE_Register_CPTs::get_CPTs();
453
-        $cpt_args = isset($cpt_args[$cpt_name]) ? $cpt_args[$cpt_name]['args'] : array();
454
-        $cpt_has_support = ! empty($cpt_args['page_templates']);
455
-
456
-        //if the installed version of WP is > 4.7 we do some additional checks.
457
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
458
-            $post_templates = wp_get_theme()->get_post_templates();
459
-            //if there are $post_templates for this cpt, then we return false for this method because
460
-            //that means we aren't going to load our page template manager and leave that up to the native
461
-            //cpt template manager.
462
-            $cpt_has_support = ! isset($post_templates[$cpt_name]) ? $cpt_has_support : false;
463
-        }
464
-
465
-        return $cpt_has_support;
466
-    }
467
-
468
-
469
-    /**
470
-     * Callback for the page_templates metabox selector.
471
-     *
472
-     * @since %VER%
473
-     * @return void
474
-     */
475
-    public function page_template_meta_box()
476
-    {
477
-        global $post;
478
-        $template = '';
479
-
480
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
481
-            $page_template_count = count(get_page_templates());
482
-        } else {
483
-            $page_template_count = count(get_page_templates($post));
484
-        };
485
-
486
-        if ($page_template_count) {
487
-            $page_template = get_post_meta($post->ID, '_wp_page_template', true);
488
-            $template      = ! empty($page_template) ? $page_template : '';
489
-        }
490
-        ?>
282
+		//filter _autosave_containers
283
+		$containers = apply_filters('FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
284
+			$this->_autosave_containers, $this);
285
+		$containers = apply_filters('FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
286
+			$containers, $this);
287
+
288
+		wp_localize_script('event_editor_js', 'EE_AUTOSAVE_IDS',
289
+			$containers); //todo once we enable autosaves, this needs to be switched to localize with "cpt-autosave"
290
+
291
+		$unsaved_data_msg = array(
292
+			'eventmsg'     => sprintf(__("The changes you made to this %s will be lost if you navigate away from this page.",
293
+				'event_espresso'), $this->_cpt_object->labels->singular_name),
294
+			'inputChanged' => 0,
295
+		);
296
+		wp_localize_script('event_editor_js', 'UNSAVED_DATA_MSG', $unsaved_data_msg);
297
+	}
298
+
299
+
300
+
301
+	public function load_page_dependencies()
302
+	{
303
+		try {
304
+			$this->_load_page_dependencies();
305
+		} catch (EE_Error $e) {
306
+			$e->get_error();
307
+		}
308
+	}
309
+
310
+
311
+
312
+	/**
313
+	 * overloading the EE_Admin_Page parent load_page_dependencies so we can get the cpt stuff added in appropriately
314
+	 *
315
+	 * @access protected
316
+	 * @return void
317
+	 */
318
+	protected function _load_page_dependencies()
319
+	{
320
+		//we only add stuff if this is a cpt_route!
321
+		if ( ! $this->_cpt_route) {
322
+			parent::_load_page_dependencies();
323
+			return;
324
+		}
325
+		// now let's do some automatic filters into the wp_system
326
+		// and we'll check to make sure the CHILD class
327
+		// automatically has the required methods in place.
328
+		// the following filters are for setting all the redirects
329
+		// on DEFAULT WP custom post type actions
330
+		// let's add a hidden input to the post-edit form
331
+		// so we know when we have to trigger our custom redirects!
332
+		// Otherwise the redirects will happen on ALL post saves which wouldn't be good of course!
333
+		add_action('edit_form_after_title', array($this, 'cpt_post_form_hidden_input'));
334
+		// inject our Admin page nav tabs...
335
+		// let's make sure the nav tabs are set if they aren't already
336
+		// if ( empty( $this->_nav_tabs ) ) $this->_set_nav_tabs();
337
+		add_action('post_edit_form_tag', array($this, 'inject_nav_tabs'));
338
+		// modify the post_updated messages array
339
+		add_action('post_updated_messages', array($this, 'post_update_messages'), 10);
340
+		// add shortlink button to cpt edit screens.  We can do this as a universal thing BECAUSE,
341
+		// cpts use the same format for shortlinks as posts!
342
+		add_filter('pre_get_shortlink', array($this, 'add_shortlink_button_to_editor'), 10, 4);
343
+		// This basically allows us to change the title of the "publish" metabox area
344
+		// on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
345
+		if ( ! empty($this->_labels['publishbox'])) {
346
+			$box_label = is_array($this->_labels['publishbox'])
347
+						 && isset($this->_labels['publishbox'][$this->_req_action])
348
+					? $this->_labels['publishbox'][$this->_req_action]
349
+					: $this->_labels['publishbox'];
350
+			add_meta_box(
351
+				'submitdiv',
352
+				$box_label,
353
+				'post_submit_meta_box',
354
+				$this->_cpt_routes[$this->_req_action],
355
+				'side',
356
+				'core'
357
+			);
358
+		}
359
+		//let's add page_templates metabox if this cpt added support for it.
360
+		if ($this->_supports_page_templates($this->_cpt_object->name)) {
361
+			add_meta_box(
362
+				'page_templates',
363
+				__('Page Template', 'event_espresso'),
364
+				array($this, 'page_template_meta_box'),
365
+				$this->_cpt_routes[$this->_req_action],
366
+				'side',
367
+				'default'
368
+			);
369
+		}
370
+		//this is a filter that allows the addition of extra html after the permalink field on the wp post edit-form
371
+		if (method_exists($this, 'extra_permalink_field_buttons')) {
372
+			add_filter('get_sample_permalink_html', array($this, 'extra_permalink_field_buttons'), 10, 4);
373
+		}
374
+		//add preview button
375
+		add_filter('get_sample_permalink_html', array($this, 'preview_button_html'), 5, 4);
376
+		//insert our own post_stati dropdown
377
+		add_action('post_submitbox_misc_actions', array($this, 'custom_post_stati_dropdown'), 10);
378
+		//This allows adding additional information to the publish post submitbox on the wp post edit form
379
+		if (method_exists($this, 'extra_misc_actions_publish_box')) {
380
+			add_action('post_submitbox_misc_actions', array($this, 'extra_misc_actions_publish_box'), 10);
381
+		}
382
+		// This allows for adding additional stuff after the title field on the wp post edit form.
383
+		// This is also before the wp_editor for post description field.
384
+		if (method_exists($this, 'edit_form_after_title')) {
385
+			add_action('edit_form_after_title', array($this, 'edit_form_after_title'), 10);
386
+		}
387
+		/**
388
+		 * Filtering WP's esc_url to capture urls pointing to core wp routes so they point to our route.
389
+		 */
390
+		add_filter('clean_url', array($this, 'switch_core_wp_urls_with_ours'), 10, 3);
391
+		parent::_load_page_dependencies();
392
+		// notice we are ALSO going to load the pagenow hook set for this route
393
+		// (see _before_page_setup for the reset of the pagenow global ).
394
+		// This is for any plugins that are doing things properly
395
+		// and hooking into the load page hook for core wp cpt routes.
396
+		global $pagenow;
397
+		do_action('load-' . $pagenow);
398
+		$this->modify_current_screen();
399
+		add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
400
+		//we route REALLY early.
401
+		try {
402
+			$this->_route_admin_request();
403
+		} catch (EE_Error $e) {
404
+			$e->get_error();
405
+		}
406
+	}
407
+
408
+
409
+
410
+	/**
411
+	 * Since we don't want users going to default core wp routes, this will check any wp urls run through the
412
+	 * esc_url() method and if we see a url matching a pattern for our routes, we'll modify it to point to OUR
413
+	 * route instead.
414
+	 *
415
+	 * @param string $good_protocol_url The escaped url.
416
+	 * @param string $original_url      The original url.
417
+	 * @param string $_context          The context sent to the esc_url method.
418
+	 * @return string possibly a new url for our route.
419
+	 */
420
+	public function switch_core_wp_urls_with_ours($good_protocol_url, $original_url, $_context)
421
+	{
422
+		$routes_to_match = array(
423
+			0 => array(
424
+				'edit.php?post_type=espresso_attendees',
425
+				'admin.php?page=espresso_registrations&action=contact_list',
426
+			),
427
+			1 => array(
428
+				'edit.php?post_type=' . $this->_cpt_object->name,
429
+				'admin.php?page=' . $this->_cpt_object->name,
430
+			),
431
+		);
432
+		foreach ($routes_to_match as $route_matches) {
433
+			if (strpos($good_protocol_url, $route_matches[0]) !== false) {
434
+				return str_replace($route_matches[0], $route_matches[1], $good_protocol_url);
435
+			}
436
+		}
437
+		return $good_protocol_url;
438
+	}
439
+
440
+
441
+
442
+	/**
443
+	 * Determine whether the current cpt supports page templates or not.
444
+	 *
445
+	 * @since %VER%
446
+	 * @param string $cpt_name The cpt slug we're checking on.
447
+	 * @return bool True supported, false not.
448
+	 */
449
+	private function _supports_page_templates($cpt_name)
450
+	{
451
+
452
+		$cpt_args = EE_Register_CPTs::get_CPTs();
453
+		$cpt_args = isset($cpt_args[$cpt_name]) ? $cpt_args[$cpt_name]['args'] : array();
454
+		$cpt_has_support = ! empty($cpt_args['page_templates']);
455
+
456
+		//if the installed version of WP is > 4.7 we do some additional checks.
457
+		if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
458
+			$post_templates = wp_get_theme()->get_post_templates();
459
+			//if there are $post_templates for this cpt, then we return false for this method because
460
+			//that means we aren't going to load our page template manager and leave that up to the native
461
+			//cpt template manager.
462
+			$cpt_has_support = ! isset($post_templates[$cpt_name]) ? $cpt_has_support : false;
463
+		}
464
+
465
+		return $cpt_has_support;
466
+	}
467
+
468
+
469
+	/**
470
+	 * Callback for the page_templates metabox selector.
471
+	 *
472
+	 * @since %VER%
473
+	 * @return void
474
+	 */
475
+	public function page_template_meta_box()
476
+	{
477
+		global $post;
478
+		$template = '';
479
+
480
+		if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
481
+			$page_template_count = count(get_page_templates());
482
+		} else {
483
+			$page_template_count = count(get_page_templates($post));
484
+		};
485
+
486
+		if ($page_template_count) {
487
+			$page_template = get_post_meta($post->ID, '_wp_page_template', true);
488
+			$template      = ! empty($page_template) ? $page_template : '';
489
+		}
490
+		?>
491 491
         <p><strong><?php _e('Template') ?></strong></p>
492 492
         <label class="screen-reader-text" for="page_template"><?php _e('Page Template') ?></label><select
493 493
             name="page_template" id="page_template">
@@ -495,450 +495,450 @@  discard block
 block discarded – undo
495 495
         <?php page_template_dropdown($template); ?>
496 496
     </select>
497 497
         <?php
498
-    }
499
-
500
-
501
-
502
-    /**
503
-     * if this post is a draft or scheduled post then we provide a preview button for user to click
504
-     * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
505
-     *
506
-     * @param  string $return    the current html
507
-     * @param  int    $id        the post id for the page
508
-     * @param  string $new_title What the title is
509
-     * @param  string $new_slug  what the slug is
510
-     * @return string            The new html string for the permalink area
511
-     */
512
-    public function preview_button_html($return, $id, $new_title, $new_slug)
513
-    {
514
-        $post = get_post($id);
515
-        if ('publish' !== get_post_status($post)) {
516
-            //include shims for the `get_preview_post_link` function
517
-            require_once( EE_CORE . 'wordpress-shims.php' );
518
-            $return .= '<span_id="view-post-btn"><a target="_blank" href="'
519
-                       . get_preview_post_link($id)
520
-                       . '" class="button button-small">'
521
-                       . __('Preview', 'event_espresso')
522
-                       . '</a></span>'
523
-                       . "\n";
524
-        }
525
-        return $return;
526
-    }
527
-
528
-
529
-
530
-    /**
531
-     * add our custom post stati dropdown on the wp post page for this cpt
532
-     *
533
-     * @return void
534
-     */
535
-    public function custom_post_stati_dropdown()
536
-    {
537
-
538
-        $statuses         = $this->_cpt_model_obj->get_custom_post_statuses();
539
-        $cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
540
-            ? $statuses[$this->_cpt_model_obj->status()]
541
-            : '';
542
-        $template_args    = array(
543
-            'cur_status'            => $this->_cpt_model_obj->status(),
544
-            'statuses'              => $statuses,
545
-            'cur_status_label'      => $cur_status_label,
546
-            'localized_status_save' => sprintf(__('Save %s', 'event_espresso'), $cur_status_label),
547
-        );
548
-        //we'll add a trash post status (WP doesn't add one for some reason)
549
-        if ($this->_cpt_model_obj->status() === 'trash') {
550
-            $template_args['cur_status_label'] = __('Trashed', 'event_espresso');
551
-            $statuses['trash']                 = __('Trashed', 'event_espresso');
552
-            $template_args['statuses']         = $statuses;
553
-        }
554
-
555
-        $template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
556
-        EEH_Template::display_template($template, $template_args);
557
-    }
558
-
559
-
560
-
561
-    public function setup_autosave_hooks()
562
-    {
563
-        $this->_set_autosave_containers();
564
-        $this->_load_autosave_scripts_styles();
565
-    }
566
-
567
-
568
-
569
-    /**
570
-     * This is run on all WordPress autosaves AFTER the autosave is complete and sends along a $_POST object (available
571
-     * in $this->_req_data) containing: post_ID of the saved post autosavenonce for the saved post We'll do the check
572
-     * for the nonce in here, but then this method looks for two things:
573
-     * 1. Execute a method (if exists) matching 'ee_autosave_' and appended with the given route. OR
574
-     * 2. do_actions() for global or class specific actions that have been registered (for plugins/addons not in an
575
-     * EE_Admin_Page class. PLEASE NOTE: Data will be returned using the _return_json() object and so the
576
-     * $_template_args property should be used to hold the $data array.  We're expecting the following things set in
577
-     * template args.
578
-     *    1. $template_args['error'] = IF there is an error you can add the message in here.
579
-     *    2. $template_args['data']['items'] = an array of items that are setup in key index pairs of 'where_values_go'
580
-     *    => 'values_to_add'.  In other words, for the datetime metabox we'll have something like
581
-     *    $this->_template_args['data']['items'] = array(
582
-     *        'event-datetime-ids' => '1,2,3';
583
-     *    );
584
-     *    Keep in mind the following things:
585
-     *    - "where" index is for the input with the id as that string.
586
-     *    - "what" index is what will be used for the value of that input.
587
-     *
588
-     * @return void
589
-     */
590
-    public function do_extra_autosave_stuff()
591
-    {
592
-        //next let's check for the autosave nonce (we'll use _verify_nonce )
593
-        $nonce = isset($this->_req_data['autosavenonce'])
594
-                ? $this->_req_data['autosavenonce']
595
-                : null;
596
-        $this->_verify_nonce($nonce, 'autosave');
597
-        //make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
598
-        if ( ! defined('DOING_AUTOSAVE')) {
599
-            define('DOING_AUTOSAVE', true);
600
-        }
601
-        //if we made it here then the nonce checked out.  Let's run our methods and actions
602
-        $autosave = "_ee_autosave_{$this->_current_view}";
603
-        if (method_exists($this, $autosave)) {
604
-            $this->$autosave();
605
-        } else {
606
-            $this->_template_args['success'] = true;
607
-        }
608
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
609
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
610
-        //now let's return json
611
-        $this->_return_json();
612
-    }
613
-
614
-
615
-
616
-    /**
617
-     * This takes care of setting up default routes and pages that utilize the core WP admin pages.
618
-     * Child classes can override the defaults (in cases for adding metaboxes etc.)
619
-     * but take care that you include the defaults here otherwise your core WP admin pages for the cpt won't work!
620
-     *
621
-     * @access protected
622
-     * @throws EE_Error
623
-     * @return void
624
-     */
625
-    protected function _extend_page_config_for_cpt()
626
-    {
627
-        //before doing anything we need to make sure this runs ONLY when the loaded page matches the set page_slug
628
-        if (isset($this->_req_data['page']) && $this->_req_data['page'] !== $this->page_slug) {
629
-            return;
630
-        }
631
-        //set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
632
-        if ( ! empty($this->_cpt_object)) {
633
-            $this->_page_routes = array_merge(array(
634
-                'create_new' => '_create_new_cpt_item',
635
-                'edit'       => '_edit_cpt_item',
636
-            ), $this->_page_routes);
637
-            $this->_page_config = array_merge(array(
638
-                'create_new' => array(
639
-                    'nav'           => array(
640
-                        'label' => $this->_cpt_object->labels->add_new_item,
641
-                        'order' => 5,
642
-                    ),
643
-                    'require_nonce' => false,
644
-                ),
645
-                'edit'       => array(
646
-                    'nav'           => array(
647
-                        'label'      => $this->_cpt_object->labels->edit_item,
648
-                        'order'      => 5,
649
-                        'persistent' => false,
650
-                        'url'        => '',
651
-                    ),
652
-                    'require_nonce' => false,
653
-                ),
654
-            ),
655
-                $this->_page_config
656
-            );
657
-        }
658
-        //load the next section only if this is a matching cpt route as set in the cpt routes array.
659
-        if ( ! isset($this->_cpt_routes[$this->_req_action])) {
660
-            return;
661
-        }
662
-        $this->_cpt_route = isset($this->_cpt_routes[$this->_req_action]) ? true : false;
663
-        //add_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', array( $this, 'modify_current_screen') );
664
-        if (empty($this->_cpt_object)) {
665
-            $msg = sprintf(__('This page has been set as being related to a registered custom post type, however, the custom post type object could not be retrieved. There are two possible reasons for this:  1. The "%s" does not match a registered post type. or 2. The custom post type is not registered for the "%s" action as indexed in the "$_cpt_routes" property on this class (%s).'),
666
-                $this->page_slug, $this->_req_action, get_class($this));
667
-            throw new EE_Error($msg);
668
-        }
669
-        if ($this->_cpt_route) {
670
-            $id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
671
-            $this->_set_model_object($id);
672
-        }
673
-    }
674
-
675
-
676
-
677
-    /**
678
-     * Sets the _cpt_model_object property using what has been set for the _cpt_model_name and a given id.
679
-     *
680
-     * @access protected
681
-     * @param int  $id The id to retrieve the model object for. If empty we set a default object.
682
-     * @param bool $ignore_route_check
683
-     * @param string $req_type whether the current route is for inserting, updating, or deleting the CPT
684
-     * @throws EE_Error
685
-     */
686
-    protected function _set_model_object($id = null, $ignore_route_check = false, $req_type = '')
687
-    {
688
-        $model = null;
689
-        if (
690
-            empty($this->_cpt_model_names)
691
-            || (
692
-                ! $ignore_route_check
693
-                && ! isset($this->_cpt_routes[$this->_req_action])
694
-            ) || (
695
-                $this->_cpt_model_obj instanceof EE_CPT_Base
696
-                && $this->_cpt_model_obj->ID() === $id
697
-            )
698
-        ) {
699
-            //get out cuz we either don't have a model name OR the object has already been set and it has the same id as what has been sent.
700
-            return;
701
-        }
702
-        //if ignore_route_check is true, then get the model name via EE_Register_CPTs
703
-        if ($ignore_route_check) {
704
-            $model_names = EE_Register_CPTs::get_cpt_model_names();
705
-            $post_type   = get_post_type($id);
706
-            if (isset($model_names[$post_type])) {
707
-                $model = EE_Registry::instance()->load_model($model_names[$post_type]);
708
-            }
709
-        } else {
710
-            $model = EE_Registry::instance()->load_model($this->_cpt_model_names[$this->_req_action]);
711
-        }
712
-        if ($model instanceof EEM_Base) {
713
-            $this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
714
-        }
715
-        do_action(
716
-            'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
717
-            $this->_cpt_model_obj,
718
-            $req_type
719
-        );
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * admin_init_global
726
-     * This runs all the code that we want executed within the WP admin_init hook.
727
-     * This method executes for ALL EE Admin pages.
728
-     *
729
-     * @access public
730
-     * @return void
731
-     */
732
-    public function admin_init_global()
733
-    {
734
-        $post = isset($this->_req_data['post']) ? get_post($this->_req_data['post']) : null;
735
-        //its possible this is a new save so let's catch that instead
736
-        $post = isset($this->_req_data['post_ID']) ? get_post($this->_req_data['post_ID']) : $post;
737
-        $post_type = $post ? $post->post_type : false;
738
-        $current_route = isset($this->_req_data['current_route'])
739
-            ? $this->_req_data['current_route']
740
-            : 'shouldneverwork';
741
-        $route_to_check = $post_type && isset($this->_cpt_routes[$current_route])
742
-            ? $this->_cpt_routes[$current_route]
743
-            : '';
744
-        add_filter('get_delete_post_link', array($this, 'modify_delete_post_link'), 10, 3);
745
-        add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 3);
746
-        if ($post_type === $route_to_check) {
747
-            add_filter('redirect_post_location', array($this, 'cpt_post_location_redirect'), 10, 2);
748
-        }
749
-        //now let's filter redirect if we're on a revision page and the revision is for an event CPT.
750
-        $revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
751
-        if ( ! empty($revision)) {
752
-            $action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
753
-            //doing a restore?
754
-            if ( ! empty($action) && $action === 'restore') {
755
-                //get post for revision
756
-                $rev_post = get_post($revision);
757
-                $rev_parent = get_post($rev_post->post_parent);
758
-                //only do our redirect filter AND our restore revision action if the post_type for the parent is one of our cpts.
759
-                if ($rev_parent && $rev_parent->post_type === $this->page_slug) {
760
-                    add_filter('wp_redirect', array($this, 'revision_redirect'), 10, 2);
761
-                    //restores of revisions
762
-                    add_action('wp_restore_post_revision', array($this, 'restore_revision'), 10, 2);
763
-                }
764
-            }
765
-        }
766
-        //NOTE we ONLY want to run these hooks if we're on the right class for the given post type.  Otherwise we could see some really freaky things happen!
767
-        if ($post_type && $post_type === $route_to_check) {
768
-            //$post_id, $post
769
-            add_action('save_post', array($this, 'insert_update'), 10, 3);
770
-            //$post_id
771
-            add_action('trashed_post', array($this, 'before_trash_cpt_item'), 10);
772
-            add_action('trashed_post', array($this, 'dont_permanently_delete_ee_cpts'), 10);
773
-            add_action('untrashed_post', array($this, 'before_restore_cpt_item'), 10);
774
-            add_action('after_delete_post', array($this, 'before_delete_cpt_item'), 10);
775
-        }
776
-    }
777
-
778
-
779
-
780
-    /**
781
-     * Callback for the WordPress trashed_post hook.
782
-     * Execute some basic checks before calling the trash_cpt_item declared in the child class.
783
-     *
784
-     * @param int $post_id
785
-     * @throws \EE_Error
786
-     */
787
-    public function before_trash_cpt_item($post_id)
788
-    {
789
-        $this->_set_model_object($post_id, true, 'trash');
790
-        //if our cpt object isn't existent then get out immediately.
791
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
792
-            return;
793
-        }
794
-        $this->trash_cpt_item($post_id);
795
-    }
796
-
797
-
798
-
799
-    /**
800
-     * Callback for the WordPress untrashed_post hook.
801
-     * Execute some basic checks before calling the restore_cpt_method in the child class.
802
-     *
803
-     * @param $post_id
804
-     * @throws \EE_Error
805
-     */
806
-    public function before_restore_cpt_item($post_id)
807
-    {
808
-        $this->_set_model_object($post_id, true, 'restore');
809
-        //if our cpt object isn't existent then get out immediately.
810
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
811
-            return;
812
-        }
813
-        $this->restore_cpt_item($post_id);
814
-    }
815
-
816
-
817
-
818
-    /**
819
-     * Callback for the WordPress after_delete_post hook.
820
-     * Execute some basic checks before calling the delete_cpt_item method in the child class.
821
-     *
822
-     * @param $post_id
823
-     * @throws \EE_Error
824
-     */
825
-    public function before_delete_cpt_item($post_id)
826
-    {
827
-        $this->_set_model_object($post_id, true, 'delete');
828
-        //if our cpt object isn't existent then get out immediately.
829
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
830
-            return;
831
-        }
832
-        $this->delete_cpt_item($post_id);
833
-    }
834
-
835
-
836
-
837
-    /**
838
-     * This simply verifies if the cpt_model_object is instantiated for the given page and throws an error message
839
-     * accordingly.
840
-     *
841
-     * @access public
842
-     * @throws EE_Error
843
-     * @return void
844
-     */
845
-    public function verify_cpt_object()
846
-    {
847
-        $label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
848
-        // verify event object
849
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
850
-            throw new EE_Error(sprintf(__('Something has gone wrong with the page load because we are unable to set up the object for the %1$s.  This usually happens when the given id for the page route is NOT for the correct custom post type for this page',
851
-                    'event_espresso'), $label));
852
-        }
853
-        //if auto-draft then throw an error
854
-        if ($this->_cpt_model_obj->get('status') === 'auto-draft') {
855
-            EE_Error::overwrite_errors();
856
-            EE_Error::add_error(sprintf(__('This %1$s was saved without a title, description, or excerpt which means that none of the extra details you added were saved properly.  All autodrafts will show up in the "draft" view of your event list table.  You can delete them from there. Please click the "Add %1$s" button to refresh and restart.'),
857
-                    $label), __FILE__, __FUNCTION__, __LINE__);
858
-        }
859
-    }
860
-
861
-
862
-
863
-    /**
864
-     * admin_footer_scripts_global
865
-     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
866
-     * will apply on ALL EE_Admin pages.
867
-     *
868
-     * @access public
869
-     * @return void
870
-     */
871
-    public function admin_footer_scripts_global()
872
-    {
873
-        $this->_add_admin_page_ajax_loading_img();
874
-        $this->_add_admin_page_overlay();
875
-    }
876
-
877
-
878
-
879
-    /**
880
-     * add in any global scripts for cpt routes
881
-     *
882
-     * @return void
883
-     */
884
-    public function load_global_scripts_styles()
885
-    {
886
-        parent::load_global_scripts_styles();
887
-        if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
888
-            //setup custom post status object for localize script but only if we've got a cpt object
889
-            $statuses = $this->_cpt_model_obj->get_custom_post_statuses();
890
-            if ( ! empty($statuses)) {
891
-                //get ALL statuses!
892
-                $statuses = $this->_cpt_model_obj->get_all_post_statuses();
893
-                //setup object
894
-                $ee_cpt_statuses = array();
895
-                foreach ($statuses as $status => $label) {
896
-                    $ee_cpt_statuses[$status] = array(
897
-                        'label'      => $label,
898
-                        'save_label' => sprintf(__('Save as %s', 'event_espresso'), $label),
899
-                    );
900
-                }
901
-                wp_localize_script('ee_admin_js', 'eeCPTstatuses', $ee_cpt_statuses);
902
-            }
903
-        }
904
-    }
905
-
906
-
907
-
908
-    /**
909
-     * This is a wrapper for the insert/update routes for cpt items so we can add things that are common to ALL
910
-     * insert/updates
911
-     *
912
-     * @param  int     $post_id ID of post being updated
913
-     * @param  WP_Post $post    Post object from WP
914
-     * @param  bool    $update  Whether this is an update or a new save.
915
-     * @return void
916
-     * @throws \EE_Error
917
-     */
918
-    public function insert_update($post_id, $post, $update)
919
-    {
920
-        //make sure that if this is a revision OR trash action that we don't do any updates!
921
-        if (
922
-            isset($this->_req_data['action'])
923
-            && (
924
-                $this->_req_data['action'] === 'restore'
925
-                || $this->_req_data['action'] === 'trash'
926
-            )
927
-        ) {
928
-            return;
929
-        }
930
-        $this->_set_model_object($post_id, true, 'insert_update');
931
-        //if our cpt object is not instantiated and its NOT the same post_id as what is triggering this callback, then exit.
932
-        if ($update
933
-            && (
934
-                ! $this->_cpt_model_obj instanceof EE_CPT_Base
935
-                || $this->_cpt_model_obj->ID() !== $post_id
936
-            )
937
-        ) {
938
-            return;
939
-        }
940
-        //check for autosave and update our req_data property accordingly.
941
-        /*if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE && isset( $this->_req_data['ee_autosave_data'] ) ) {
498
+	}
499
+
500
+
501
+
502
+	/**
503
+	 * if this post is a draft or scheduled post then we provide a preview button for user to click
504
+	 * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
505
+	 *
506
+	 * @param  string $return    the current html
507
+	 * @param  int    $id        the post id for the page
508
+	 * @param  string $new_title What the title is
509
+	 * @param  string $new_slug  what the slug is
510
+	 * @return string            The new html string for the permalink area
511
+	 */
512
+	public function preview_button_html($return, $id, $new_title, $new_slug)
513
+	{
514
+		$post = get_post($id);
515
+		if ('publish' !== get_post_status($post)) {
516
+			//include shims for the `get_preview_post_link` function
517
+			require_once( EE_CORE . 'wordpress-shims.php' );
518
+			$return .= '<span_id="view-post-btn"><a target="_blank" href="'
519
+					   . get_preview_post_link($id)
520
+					   . '" class="button button-small">'
521
+					   . __('Preview', 'event_espresso')
522
+					   . '</a></span>'
523
+					   . "\n";
524
+		}
525
+		return $return;
526
+	}
527
+
528
+
529
+
530
+	/**
531
+	 * add our custom post stati dropdown on the wp post page for this cpt
532
+	 *
533
+	 * @return void
534
+	 */
535
+	public function custom_post_stati_dropdown()
536
+	{
537
+
538
+		$statuses         = $this->_cpt_model_obj->get_custom_post_statuses();
539
+		$cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
540
+			? $statuses[$this->_cpt_model_obj->status()]
541
+			: '';
542
+		$template_args    = array(
543
+			'cur_status'            => $this->_cpt_model_obj->status(),
544
+			'statuses'              => $statuses,
545
+			'cur_status_label'      => $cur_status_label,
546
+			'localized_status_save' => sprintf(__('Save %s', 'event_espresso'), $cur_status_label),
547
+		);
548
+		//we'll add a trash post status (WP doesn't add one for some reason)
549
+		if ($this->_cpt_model_obj->status() === 'trash') {
550
+			$template_args['cur_status_label'] = __('Trashed', 'event_espresso');
551
+			$statuses['trash']                 = __('Trashed', 'event_espresso');
552
+			$template_args['statuses']         = $statuses;
553
+		}
554
+
555
+		$template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
556
+		EEH_Template::display_template($template, $template_args);
557
+	}
558
+
559
+
560
+
561
+	public function setup_autosave_hooks()
562
+	{
563
+		$this->_set_autosave_containers();
564
+		$this->_load_autosave_scripts_styles();
565
+	}
566
+
567
+
568
+
569
+	/**
570
+	 * This is run on all WordPress autosaves AFTER the autosave is complete and sends along a $_POST object (available
571
+	 * in $this->_req_data) containing: post_ID of the saved post autosavenonce for the saved post We'll do the check
572
+	 * for the nonce in here, but then this method looks for two things:
573
+	 * 1. Execute a method (if exists) matching 'ee_autosave_' and appended with the given route. OR
574
+	 * 2. do_actions() for global or class specific actions that have been registered (for plugins/addons not in an
575
+	 * EE_Admin_Page class. PLEASE NOTE: Data will be returned using the _return_json() object and so the
576
+	 * $_template_args property should be used to hold the $data array.  We're expecting the following things set in
577
+	 * template args.
578
+	 *    1. $template_args['error'] = IF there is an error you can add the message in here.
579
+	 *    2. $template_args['data']['items'] = an array of items that are setup in key index pairs of 'where_values_go'
580
+	 *    => 'values_to_add'.  In other words, for the datetime metabox we'll have something like
581
+	 *    $this->_template_args['data']['items'] = array(
582
+	 *        'event-datetime-ids' => '1,2,3';
583
+	 *    );
584
+	 *    Keep in mind the following things:
585
+	 *    - "where" index is for the input with the id as that string.
586
+	 *    - "what" index is what will be used for the value of that input.
587
+	 *
588
+	 * @return void
589
+	 */
590
+	public function do_extra_autosave_stuff()
591
+	{
592
+		//next let's check for the autosave nonce (we'll use _verify_nonce )
593
+		$nonce = isset($this->_req_data['autosavenonce'])
594
+				? $this->_req_data['autosavenonce']
595
+				: null;
596
+		$this->_verify_nonce($nonce, 'autosave');
597
+		//make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
598
+		if ( ! defined('DOING_AUTOSAVE')) {
599
+			define('DOING_AUTOSAVE', true);
600
+		}
601
+		//if we made it here then the nonce checked out.  Let's run our methods and actions
602
+		$autosave = "_ee_autosave_{$this->_current_view}";
603
+		if (method_exists($this, $autosave)) {
604
+			$this->$autosave();
605
+		} else {
606
+			$this->_template_args['success'] = true;
607
+		}
608
+		do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
609
+		do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
610
+		//now let's return json
611
+		$this->_return_json();
612
+	}
613
+
614
+
615
+
616
+	/**
617
+	 * This takes care of setting up default routes and pages that utilize the core WP admin pages.
618
+	 * Child classes can override the defaults (in cases for adding metaboxes etc.)
619
+	 * but take care that you include the defaults here otherwise your core WP admin pages for the cpt won't work!
620
+	 *
621
+	 * @access protected
622
+	 * @throws EE_Error
623
+	 * @return void
624
+	 */
625
+	protected function _extend_page_config_for_cpt()
626
+	{
627
+		//before doing anything we need to make sure this runs ONLY when the loaded page matches the set page_slug
628
+		if (isset($this->_req_data['page']) && $this->_req_data['page'] !== $this->page_slug) {
629
+			return;
630
+		}
631
+		//set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
632
+		if ( ! empty($this->_cpt_object)) {
633
+			$this->_page_routes = array_merge(array(
634
+				'create_new' => '_create_new_cpt_item',
635
+				'edit'       => '_edit_cpt_item',
636
+			), $this->_page_routes);
637
+			$this->_page_config = array_merge(array(
638
+				'create_new' => array(
639
+					'nav'           => array(
640
+						'label' => $this->_cpt_object->labels->add_new_item,
641
+						'order' => 5,
642
+					),
643
+					'require_nonce' => false,
644
+				),
645
+				'edit'       => array(
646
+					'nav'           => array(
647
+						'label'      => $this->_cpt_object->labels->edit_item,
648
+						'order'      => 5,
649
+						'persistent' => false,
650
+						'url'        => '',
651
+					),
652
+					'require_nonce' => false,
653
+				),
654
+			),
655
+				$this->_page_config
656
+			);
657
+		}
658
+		//load the next section only if this is a matching cpt route as set in the cpt routes array.
659
+		if ( ! isset($this->_cpt_routes[$this->_req_action])) {
660
+			return;
661
+		}
662
+		$this->_cpt_route = isset($this->_cpt_routes[$this->_req_action]) ? true : false;
663
+		//add_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', array( $this, 'modify_current_screen') );
664
+		if (empty($this->_cpt_object)) {
665
+			$msg = sprintf(__('This page has been set as being related to a registered custom post type, however, the custom post type object could not be retrieved. There are two possible reasons for this:  1. The "%s" does not match a registered post type. or 2. The custom post type is not registered for the "%s" action as indexed in the "$_cpt_routes" property on this class (%s).'),
666
+				$this->page_slug, $this->_req_action, get_class($this));
667
+			throw new EE_Error($msg);
668
+		}
669
+		if ($this->_cpt_route) {
670
+			$id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
671
+			$this->_set_model_object($id);
672
+		}
673
+	}
674
+
675
+
676
+
677
+	/**
678
+	 * Sets the _cpt_model_object property using what has been set for the _cpt_model_name and a given id.
679
+	 *
680
+	 * @access protected
681
+	 * @param int  $id The id to retrieve the model object for. If empty we set a default object.
682
+	 * @param bool $ignore_route_check
683
+	 * @param string $req_type whether the current route is for inserting, updating, or deleting the CPT
684
+	 * @throws EE_Error
685
+	 */
686
+	protected function _set_model_object($id = null, $ignore_route_check = false, $req_type = '')
687
+	{
688
+		$model = null;
689
+		if (
690
+			empty($this->_cpt_model_names)
691
+			|| (
692
+				! $ignore_route_check
693
+				&& ! isset($this->_cpt_routes[$this->_req_action])
694
+			) || (
695
+				$this->_cpt_model_obj instanceof EE_CPT_Base
696
+				&& $this->_cpt_model_obj->ID() === $id
697
+			)
698
+		) {
699
+			//get out cuz we either don't have a model name OR the object has already been set and it has the same id as what has been sent.
700
+			return;
701
+		}
702
+		//if ignore_route_check is true, then get the model name via EE_Register_CPTs
703
+		if ($ignore_route_check) {
704
+			$model_names = EE_Register_CPTs::get_cpt_model_names();
705
+			$post_type   = get_post_type($id);
706
+			if (isset($model_names[$post_type])) {
707
+				$model = EE_Registry::instance()->load_model($model_names[$post_type]);
708
+			}
709
+		} else {
710
+			$model = EE_Registry::instance()->load_model($this->_cpt_model_names[$this->_req_action]);
711
+		}
712
+		if ($model instanceof EEM_Base) {
713
+			$this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
714
+		}
715
+		do_action(
716
+			'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
717
+			$this->_cpt_model_obj,
718
+			$req_type
719
+		);
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * admin_init_global
726
+	 * This runs all the code that we want executed within the WP admin_init hook.
727
+	 * This method executes for ALL EE Admin pages.
728
+	 *
729
+	 * @access public
730
+	 * @return void
731
+	 */
732
+	public function admin_init_global()
733
+	{
734
+		$post = isset($this->_req_data['post']) ? get_post($this->_req_data['post']) : null;
735
+		//its possible this is a new save so let's catch that instead
736
+		$post = isset($this->_req_data['post_ID']) ? get_post($this->_req_data['post_ID']) : $post;
737
+		$post_type = $post ? $post->post_type : false;
738
+		$current_route = isset($this->_req_data['current_route'])
739
+			? $this->_req_data['current_route']
740
+			: 'shouldneverwork';
741
+		$route_to_check = $post_type && isset($this->_cpt_routes[$current_route])
742
+			? $this->_cpt_routes[$current_route]
743
+			: '';
744
+		add_filter('get_delete_post_link', array($this, 'modify_delete_post_link'), 10, 3);
745
+		add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 3);
746
+		if ($post_type === $route_to_check) {
747
+			add_filter('redirect_post_location', array($this, 'cpt_post_location_redirect'), 10, 2);
748
+		}
749
+		//now let's filter redirect if we're on a revision page and the revision is for an event CPT.
750
+		$revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
751
+		if ( ! empty($revision)) {
752
+			$action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
753
+			//doing a restore?
754
+			if ( ! empty($action) && $action === 'restore') {
755
+				//get post for revision
756
+				$rev_post = get_post($revision);
757
+				$rev_parent = get_post($rev_post->post_parent);
758
+				//only do our redirect filter AND our restore revision action if the post_type for the parent is one of our cpts.
759
+				if ($rev_parent && $rev_parent->post_type === $this->page_slug) {
760
+					add_filter('wp_redirect', array($this, 'revision_redirect'), 10, 2);
761
+					//restores of revisions
762
+					add_action('wp_restore_post_revision', array($this, 'restore_revision'), 10, 2);
763
+				}
764
+			}
765
+		}
766
+		//NOTE we ONLY want to run these hooks if we're on the right class for the given post type.  Otherwise we could see some really freaky things happen!
767
+		if ($post_type && $post_type === $route_to_check) {
768
+			//$post_id, $post
769
+			add_action('save_post', array($this, 'insert_update'), 10, 3);
770
+			//$post_id
771
+			add_action('trashed_post', array($this, 'before_trash_cpt_item'), 10);
772
+			add_action('trashed_post', array($this, 'dont_permanently_delete_ee_cpts'), 10);
773
+			add_action('untrashed_post', array($this, 'before_restore_cpt_item'), 10);
774
+			add_action('after_delete_post', array($this, 'before_delete_cpt_item'), 10);
775
+		}
776
+	}
777
+
778
+
779
+
780
+	/**
781
+	 * Callback for the WordPress trashed_post hook.
782
+	 * Execute some basic checks before calling the trash_cpt_item declared in the child class.
783
+	 *
784
+	 * @param int $post_id
785
+	 * @throws \EE_Error
786
+	 */
787
+	public function before_trash_cpt_item($post_id)
788
+	{
789
+		$this->_set_model_object($post_id, true, 'trash');
790
+		//if our cpt object isn't existent then get out immediately.
791
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
792
+			return;
793
+		}
794
+		$this->trash_cpt_item($post_id);
795
+	}
796
+
797
+
798
+
799
+	/**
800
+	 * Callback for the WordPress untrashed_post hook.
801
+	 * Execute some basic checks before calling the restore_cpt_method in the child class.
802
+	 *
803
+	 * @param $post_id
804
+	 * @throws \EE_Error
805
+	 */
806
+	public function before_restore_cpt_item($post_id)
807
+	{
808
+		$this->_set_model_object($post_id, true, 'restore');
809
+		//if our cpt object isn't existent then get out immediately.
810
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
811
+			return;
812
+		}
813
+		$this->restore_cpt_item($post_id);
814
+	}
815
+
816
+
817
+
818
+	/**
819
+	 * Callback for the WordPress after_delete_post hook.
820
+	 * Execute some basic checks before calling the delete_cpt_item method in the child class.
821
+	 *
822
+	 * @param $post_id
823
+	 * @throws \EE_Error
824
+	 */
825
+	public function before_delete_cpt_item($post_id)
826
+	{
827
+		$this->_set_model_object($post_id, true, 'delete');
828
+		//if our cpt object isn't existent then get out immediately.
829
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
830
+			return;
831
+		}
832
+		$this->delete_cpt_item($post_id);
833
+	}
834
+
835
+
836
+
837
+	/**
838
+	 * This simply verifies if the cpt_model_object is instantiated for the given page and throws an error message
839
+	 * accordingly.
840
+	 *
841
+	 * @access public
842
+	 * @throws EE_Error
843
+	 * @return void
844
+	 */
845
+	public function verify_cpt_object()
846
+	{
847
+		$label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
848
+		// verify event object
849
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
850
+			throw new EE_Error(sprintf(__('Something has gone wrong with the page load because we are unable to set up the object for the %1$s.  This usually happens when the given id for the page route is NOT for the correct custom post type for this page',
851
+					'event_espresso'), $label));
852
+		}
853
+		//if auto-draft then throw an error
854
+		if ($this->_cpt_model_obj->get('status') === 'auto-draft') {
855
+			EE_Error::overwrite_errors();
856
+			EE_Error::add_error(sprintf(__('This %1$s was saved without a title, description, or excerpt which means that none of the extra details you added were saved properly.  All autodrafts will show up in the "draft" view of your event list table.  You can delete them from there. Please click the "Add %1$s" button to refresh and restart.'),
857
+					$label), __FILE__, __FUNCTION__, __LINE__);
858
+		}
859
+	}
860
+
861
+
862
+
863
+	/**
864
+	 * admin_footer_scripts_global
865
+	 * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
866
+	 * will apply on ALL EE_Admin pages.
867
+	 *
868
+	 * @access public
869
+	 * @return void
870
+	 */
871
+	public function admin_footer_scripts_global()
872
+	{
873
+		$this->_add_admin_page_ajax_loading_img();
874
+		$this->_add_admin_page_overlay();
875
+	}
876
+
877
+
878
+
879
+	/**
880
+	 * add in any global scripts for cpt routes
881
+	 *
882
+	 * @return void
883
+	 */
884
+	public function load_global_scripts_styles()
885
+	{
886
+		parent::load_global_scripts_styles();
887
+		if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
888
+			//setup custom post status object for localize script but only if we've got a cpt object
889
+			$statuses = $this->_cpt_model_obj->get_custom_post_statuses();
890
+			if ( ! empty($statuses)) {
891
+				//get ALL statuses!
892
+				$statuses = $this->_cpt_model_obj->get_all_post_statuses();
893
+				//setup object
894
+				$ee_cpt_statuses = array();
895
+				foreach ($statuses as $status => $label) {
896
+					$ee_cpt_statuses[$status] = array(
897
+						'label'      => $label,
898
+						'save_label' => sprintf(__('Save as %s', 'event_espresso'), $label),
899
+					);
900
+				}
901
+				wp_localize_script('ee_admin_js', 'eeCPTstatuses', $ee_cpt_statuses);
902
+			}
903
+		}
904
+	}
905
+
906
+
907
+
908
+	/**
909
+	 * This is a wrapper for the insert/update routes for cpt items so we can add things that are common to ALL
910
+	 * insert/updates
911
+	 *
912
+	 * @param  int     $post_id ID of post being updated
913
+	 * @param  WP_Post $post    Post object from WP
914
+	 * @param  bool    $update  Whether this is an update or a new save.
915
+	 * @return void
916
+	 * @throws \EE_Error
917
+	 */
918
+	public function insert_update($post_id, $post, $update)
919
+	{
920
+		//make sure that if this is a revision OR trash action that we don't do any updates!
921
+		if (
922
+			isset($this->_req_data['action'])
923
+			&& (
924
+				$this->_req_data['action'] === 'restore'
925
+				|| $this->_req_data['action'] === 'trash'
926
+			)
927
+		) {
928
+			return;
929
+		}
930
+		$this->_set_model_object($post_id, true, 'insert_update');
931
+		//if our cpt object is not instantiated and its NOT the same post_id as what is triggering this callback, then exit.
932
+		if ($update
933
+			&& (
934
+				! $this->_cpt_model_obj instanceof EE_CPT_Base
935
+				|| $this->_cpt_model_obj->ID() !== $post_id
936
+			)
937
+		) {
938
+			return;
939
+		}
940
+		//check for autosave and update our req_data property accordingly.
941
+		/*if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE && isset( $this->_req_data['ee_autosave_data'] ) ) {
942 942
             foreach( (array) $this->_req_data['ee_autosave_data'] as $id => $values ) {
943 943
 
944 944
                 foreach ( (array) $values as $key => $value ) {
@@ -948,527 +948,527 @@  discard block
 block discarded – undo
948 948
 
949 949
         }/**/ //TODO reactivate after autosave is implemented in 4.2
950 950
 
951
-        //take care of updating any selected page_template IF this cpt supports it.
952
-        if ($this->_supports_page_templates($post->post_type) && ! empty($this->_req_data['page_template'])) {
953
-            //wp version aware.
954
-            if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
955
-                $page_templates = wp_get_theme()->get_page_templates();
956
-            } else {
957
-                $post->page_template = $this->_req_data['page_template'];
958
-                $page_templates      = wp_get_theme()->get_page_templates($post);
959
-            }
960
-            if ('default' != $this->_req_data['page_template'] && ! isset($page_templates[$this->_req_data['page_template']])) {
961
-                EE_Error::add_error(__('Invalid Page Template.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
962
-            } else {
963
-                update_post_meta($post_id, '_wp_page_template', $this->_req_data['page_template']);
964
-            }
965
-        }
966
-        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
967
-            return;
968
-        } //TODO we'll remove this after reimplementing autosave in 4.2
969
-        $this->_insert_update_cpt_item($post_id, $post);
970
-    }
971
-
972
-
973
-
974
-    /**
975
-     * This hooks into the wp_trash_post() function and removes the `_wp_trash_meta_status` and `_wp_trash_meta_time`
976
-     * post meta IF the trashed post is one of our CPT's - note this method should only be called with our cpt routes
977
-     * so we don't have to check for our CPT.
978
-     *
979
-     * @param  int $post_id ID of the post
980
-     * @return void
981
-     */
982
-    public function dont_permanently_delete_ee_cpts($post_id)
983
-    {
984
-        //only do this if we're actually processing one of our CPTs
985
-        //if our cpt object isn't existent then get out immediately.
986
-        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
987
-            return;
988
-        }
989
-        delete_post_meta($post_id, '_wp_trash_meta_status');
990
-        delete_post_meta($post_id, '_wp_trash_meta_time');
991
-        //our cpts may have comments so let's take care of that too
992
-        delete_post_meta($post_id, '_wp_trash_meta_comments_status');
993
-    }
994
-
995
-
996
-
997
-    /**
998
-     * This is a wrapper for the restore_cpt_revision route for cpt items so we can make sure that when a revision is
999
-     * triggered that we restore related items.  In order to work cpt classes MUST have a restore_cpt_revision method
1000
-     * in them. We also have our OWN action in here so addons can hook into the restore process easily.
1001
-     *
1002
-     * @param  int $post_id     ID of cpt item
1003
-     * @param  int $revision_id ID of revision being restored
1004
-     * @return void
1005
-     */
1006
-    public function restore_revision($post_id, $revision_id)
1007
-    {
1008
-        $this->_restore_cpt_item($post_id, $revision_id);
1009
-        //global action
1010
-        do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
1011
-        //class specific action so you can limit hooking into a specific page.
1012
-        do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
1013
-    }
1014
-
1015
-
1016
-
1017
-    /**
1018
-     * @see restore_revision() for details
1019
-     * @param  int $post_id     ID of cpt item
1020
-     * @param  int $revision_id ID of revision for item
1021
-     * @return void
1022
-     */
1023
-    abstract protected function _restore_cpt_item($post_id, $revision_id);
1024
-
1025
-
1026
-
1027
-    /**
1028
-     * Execution of this method is added to the end of the load_page_dependencies method in the parent
1029
-     * so that we can fix a bug where default core metaboxes were not being called in the sidebar.
1030
-     * To fix we have to reset the current_screen using the page_slug
1031
-     * (which is identical - or should be - to our registered_post_type id.)
1032
-     * Also, since the core WP file loads the admin_header.php for WP
1033
-     * (and there are a bunch of other things edit-form-advanced.php loads that need to happen really early)
1034
-     * we need to load it NOW, hence our _route_admin_request in here. (Otherwise screen options won't be set).
1035
-     *
1036
-     * @return void
1037
-     */
1038
-    public function modify_current_screen()
1039
-    {
1040
-        //ONLY do this if the current page_route IS a cpt route
1041
-        if ( ! $this->_cpt_route) {
1042
-            return;
1043
-        }
1044
-        //routing things REALLY early b/c this is a cpt admin page
1045
-        set_current_screen($this->_cpt_routes[$this->_req_action]);
1046
-        $this->_current_screen       = get_current_screen();
1047
-        $this->_current_screen->base = 'event-espresso';
1048
-        $this->_add_help_tabs(); //we make sure we add any help tabs back in!
1049
-        /*try {
951
+		//take care of updating any selected page_template IF this cpt supports it.
952
+		if ($this->_supports_page_templates($post->post_type) && ! empty($this->_req_data['page_template'])) {
953
+			//wp version aware.
954
+			if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
955
+				$page_templates = wp_get_theme()->get_page_templates();
956
+			} else {
957
+				$post->page_template = $this->_req_data['page_template'];
958
+				$page_templates      = wp_get_theme()->get_page_templates($post);
959
+			}
960
+			if ('default' != $this->_req_data['page_template'] && ! isset($page_templates[$this->_req_data['page_template']])) {
961
+				EE_Error::add_error(__('Invalid Page Template.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
962
+			} else {
963
+				update_post_meta($post_id, '_wp_page_template', $this->_req_data['page_template']);
964
+			}
965
+		}
966
+		if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
967
+			return;
968
+		} //TODO we'll remove this after reimplementing autosave in 4.2
969
+		$this->_insert_update_cpt_item($post_id, $post);
970
+	}
971
+
972
+
973
+
974
+	/**
975
+	 * This hooks into the wp_trash_post() function and removes the `_wp_trash_meta_status` and `_wp_trash_meta_time`
976
+	 * post meta IF the trashed post is one of our CPT's - note this method should only be called with our cpt routes
977
+	 * so we don't have to check for our CPT.
978
+	 *
979
+	 * @param  int $post_id ID of the post
980
+	 * @return void
981
+	 */
982
+	public function dont_permanently_delete_ee_cpts($post_id)
983
+	{
984
+		//only do this if we're actually processing one of our CPTs
985
+		//if our cpt object isn't existent then get out immediately.
986
+		if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
987
+			return;
988
+		}
989
+		delete_post_meta($post_id, '_wp_trash_meta_status');
990
+		delete_post_meta($post_id, '_wp_trash_meta_time');
991
+		//our cpts may have comments so let's take care of that too
992
+		delete_post_meta($post_id, '_wp_trash_meta_comments_status');
993
+	}
994
+
995
+
996
+
997
+	/**
998
+	 * This is a wrapper for the restore_cpt_revision route for cpt items so we can make sure that when a revision is
999
+	 * triggered that we restore related items.  In order to work cpt classes MUST have a restore_cpt_revision method
1000
+	 * in them. We also have our OWN action in here so addons can hook into the restore process easily.
1001
+	 *
1002
+	 * @param  int $post_id     ID of cpt item
1003
+	 * @param  int $revision_id ID of revision being restored
1004
+	 * @return void
1005
+	 */
1006
+	public function restore_revision($post_id, $revision_id)
1007
+	{
1008
+		$this->_restore_cpt_item($post_id, $revision_id);
1009
+		//global action
1010
+		do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
1011
+		//class specific action so you can limit hooking into a specific page.
1012
+		do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
1013
+	}
1014
+
1015
+
1016
+
1017
+	/**
1018
+	 * @see restore_revision() for details
1019
+	 * @param  int $post_id     ID of cpt item
1020
+	 * @param  int $revision_id ID of revision for item
1021
+	 * @return void
1022
+	 */
1023
+	abstract protected function _restore_cpt_item($post_id, $revision_id);
1024
+
1025
+
1026
+
1027
+	/**
1028
+	 * Execution of this method is added to the end of the load_page_dependencies method in the parent
1029
+	 * so that we can fix a bug where default core metaboxes were not being called in the sidebar.
1030
+	 * To fix we have to reset the current_screen using the page_slug
1031
+	 * (which is identical - or should be - to our registered_post_type id.)
1032
+	 * Also, since the core WP file loads the admin_header.php for WP
1033
+	 * (and there are a bunch of other things edit-form-advanced.php loads that need to happen really early)
1034
+	 * we need to load it NOW, hence our _route_admin_request in here. (Otherwise screen options won't be set).
1035
+	 *
1036
+	 * @return void
1037
+	 */
1038
+	public function modify_current_screen()
1039
+	{
1040
+		//ONLY do this if the current page_route IS a cpt route
1041
+		if ( ! $this->_cpt_route) {
1042
+			return;
1043
+		}
1044
+		//routing things REALLY early b/c this is a cpt admin page
1045
+		set_current_screen($this->_cpt_routes[$this->_req_action]);
1046
+		$this->_current_screen       = get_current_screen();
1047
+		$this->_current_screen->base = 'event-espresso';
1048
+		$this->_add_help_tabs(); //we make sure we add any help tabs back in!
1049
+		/*try {
1050 1050
             $this->_route_admin_request();
1051 1051
         } catch ( EE_Error $e ) {
1052 1052
             $e->get_error();
1053 1053
         }/**/
1054
-    }
1055
-
1056
-
1057
-
1058
-    /**
1059
-     * This allows child classes to modify the default editor title that appears when people add a new or edit an
1060
-     * existing CPT item.     * This uses the _labels property set by the child class via _define_page_props. Just make
1061
-     * sure you have a key in _labels property that equals 'editor_title' and the value can be whatever you want the
1062
-     * default to be.
1063
-     *
1064
-     * @param string $title The new title (or existing if there is no editor_title defined)
1065
-     * @return string
1066
-     */
1067
-    public function add_custom_editor_default_title($title)
1068
-    {
1069
-        return isset($this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]])
1070
-            ? $this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]]
1071
-            : $title;
1072
-    }
1073
-
1074
-
1075
-
1076
-    /**
1077
-     * hooks into the wp_get_shortlink button and makes sure that the shortlink gets generated
1078
-     *
1079
-     * @param string $shortlink   The already generated shortlink
1080
-     * @param int    $id          Post ID for this item
1081
-     * @param string $context     The context for the link
1082
-     * @param bool   $allow_slugs Whether to allow post slugs in the shortlink.
1083
-     * @return string
1084
-     */
1085
-    public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1086
-    {
1087
-        if ( ! empty($id) && get_option('permalink_structure') !== '') {
1088
-            $post = get_post($id);
1089
-            if (isset($post->post_type) && $this->page_slug === $post->post_type) {
1090
-                $shortlink = home_url('?p=' . $post->ID);
1091
-            }
1092
-        }
1093
-        return $shortlink;
1094
-    }
1095
-
1096
-
1097
-
1098
-    /**
1099
-     * overriding the parent route_admin_request method so we DON'T run the route twice on cpt core page loads (it's
1100
-     * already run in modify_current_screen())
1101
-     *
1102
-     * @return void
1103
-     */
1104
-    public function route_admin_request()
1105
-    {
1106
-        if ($this->_cpt_route) {
1107
-            return;
1108
-        }
1109
-        try {
1110
-            $this->_route_admin_request();
1111
-        } catch (EE_Error $e) {
1112
-            $e->get_error();
1113
-        }
1114
-    }
1115
-
1116
-
1117
-
1118
-    /**
1119
-     * Add a hidden form input to cpt core pages so that we know to do redirects to our routes on saves
1120
-     *
1121
-     * @return void
1122
-     */
1123
-    public function cpt_post_form_hidden_input()
1124
-    {
1125
-        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1126
-        //we're also going to add the route value and the current page so we can direct autosave parsing correctly
1127
-        echo '<div id="ee-cpt-hidden-inputs">';
1128
-        echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1129
-        echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1130
-        echo '</div>';
1131
-    }
1132
-
1133
-
1134
-
1135
-    /**
1136
-     * This allows us to redirect the location of revision restores when they happen so it goes to our CPT routes.
1137
-     *
1138
-     * @param  string $location Original location url
1139
-     * @param  int    $status   Status for http header
1140
-     * @return string           new (or original) url to redirect to.
1141
-     */
1142
-    public function revision_redirect($location, $status)
1143
-    {
1144
-        //get revision
1145
-        $rev_id = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
1146
-        //can't do anything without revision so let's get out if not present
1147
-        if (empty($rev_id)) {
1148
-            return $location;
1149
-        }
1150
-        //get rev_post_data
1151
-        $rev = get_post($rev_id);
1152
-        $admin_url = $this->_admin_base_url;
1153
-        $query_args = array(
1154
-            'action'   => 'edit',
1155
-            'post'     => $rev->post_parent,
1156
-            'revision' => $rev_id,
1157
-            'message'  => 5,
1158
-        );
1159
-        $this->_process_notices($query_args, true);
1160
-        return self::add_query_args_and_nonce($query_args, $admin_url);
1161
-    }
1162
-
1163
-
1164
-
1165
-    /**
1166
-     * Modify the edit post link generated by wp core function so that EE CPTs get setup differently.
1167
-     *
1168
-     * @param  string $link    the original generated link
1169
-     * @param  int    $id      post id
1170
-     * @param  string $context optional, defaults to display.  How to write the '&'
1171
-     * @return string          the link
1172
-     */
1173
-    public function modify_edit_post_link($link, $id, $context)
1174
-    {
1175
-        $post = get_post($id);
1176
-        if ( ! isset($this->_req_data['action'])
1177
-             || ! isset($this->_cpt_routes[$this->_req_data['action']])
1178
-             || $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1179
-        ) {
1180
-            return $link;
1181
-        }
1182
-        $query_args = array(
1183
-            'action' => isset($this->_cpt_edit_routes[$post->post_type])
1184
-                ? $this->_cpt_edit_routes[$post->post_type]
1185
-                : 'edit',
1186
-            'post'   => $id,
1187
-        );
1188
-        return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1189
-    }
1190
-
1191
-
1192
-    /**
1193
-     * Modify the trash link on our cpt edit pages so it has the required query var for triggering redirect properly on
1194
-     * our routes.
1195
-     *
1196
-     * @param  string $delete_link  original delete link
1197
-     * @param  int    $post_id      id of cpt object
1198
-     * @param  bool   $force_delete whether this is forcing a hard delete instead of trash
1199
-     * @return string new delete link
1200
-     * @throws EE_Error
1201
-     */
1202
-    public function modify_delete_post_link($delete_link, $post_id, $force_delete)
1203
-    {
1204
-        $post = get_post($post_id);
1205
-
1206
-        if (empty($this->_req_data['action'])
1207
-            || ! isset($this->_cpt_routes[$this->_req_data['action']])
1208
-            || ! $post instanceof WP_Post
1209
-            || $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1210
-        ) {
1211
-            return $delete_link;
1212
-        }
1213
-        $this->_set_model_object($post->ID, true);
1214
-
1215
-        //returns something like `trash_event` or `trash_attendee` or `trash_venue`
1216
-        $action = 'trash_' . str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1217
-
1218
-        return EE_Admin_Page::add_query_args_and_nonce(
1219
-            array(
1220
-                'page' => $this->_req_data['page'],
1221
-                'action' => $action,
1222
-                $this->_cpt_model_obj->get_model()->get_primary_key_field()->get_name()
1223
-                    => $post->ID
1224
-            ),
1225
-            admin_url()
1226
-        );
1227
-    }
1228
-
1229
-
1230
-
1231
-    /**
1232
-     * This is the callback for the 'redirect_post_location' filter in wp-admin/post.php
1233
-     * so that we can hijack the default redirect locations for wp custom post types
1234
-     * that WE'RE using and send back to OUR routes.  This should only be hooked in on the right route.
1235
-     *
1236
-     * @param  string $location This is the incoming currently set redirect location
1237
-     * @param  string $post_id  This is the 'ID' value of the wp_posts table
1238
-     * @return string           the new location to redirect to
1239
-     */
1240
-    public function cpt_post_location_redirect($location, $post_id)
1241
-    {
1242
-        //we DO have a match so let's setup the url
1243
-        //we have to get the post to determine our route
1244
-        $post       = get_post($post_id);
1245
-        $edit_route = $this->_cpt_edit_routes[$post->post_type];
1246
-        //shared query_args
1247
-        $query_args = array('action' => $edit_route, 'post' => $post_id);
1248
-        $admin_url  = $this->_admin_base_url;
1249
-        if (isset($this->_req_data['save']) || isset($this->_req_data['publish'])) {
1250
-            $status = get_post_status($post_id);
1251
-            if (isset($this->_req_data['publish'])) {
1252
-                switch ($status) {
1253
-                    case 'pending':
1254
-                        $message = 8;
1255
-                        break;
1256
-                    case 'future':
1257
-                        $message = 9;
1258
-                        break;
1259
-                    default:
1260
-                        $message = 6;
1261
-                }
1262
-            } else {
1263
-                $message = 'draft' === $status ? 10 : 1;
1264
-            }
1265
-        } else if (isset($this->_req_data['addmeta']) && $this->_req_data['addmeta']) {
1266
-            $message = 2;
1267
-            //			$append = '#postcustom';
1268
-        } else if (isset($this->_req_data['deletemeta']) && $this->_req_data['deletemeta']) {
1269
-            $message = 3;
1270
-            //			$append = '#postcustom';
1271
-        } elseif ($this->_req_data['action'] === 'post-quickpress-save-cont') {
1272
-            $message = 7;
1273
-        } else {
1274
-            $message = 4;
1275
-        }
1276
-        //change the message if the post type is not viewable on the frontend
1277
-        $this->_cpt_object = get_post_type_object($post->post_type);
1278
-        $message           = $message === 1 && ! $this->_cpt_object->publicly_queryable ? 4 : $message;
1279
-        $query_args = array_merge(array('message' => $message), $query_args);
1280
-        $this->_process_notices($query_args, true);
1281
-        return self::add_query_args_and_nonce($query_args, $admin_url);
1282
-    }
1283
-
1284
-
1285
-
1286
-    /**
1287
-     * This method is called to inject nav tabs on core WP cpt pages
1288
-     *
1289
-     * @access public
1290
-     * @return void
1291
-     */
1292
-    public function inject_nav_tabs()
1293
-    {
1294
-        //can we hijack and insert the nav_tabs?
1295
-        $nav_tabs = $this->_get_main_nav_tabs();
1296
-        //first close off existing form tag
1297
-        $html = '>';
1298
-        $html .= $nav_tabs;
1299
-        //now let's handle the remaining tag ( missing ">" is CORRECT )
1300
-        $html .= '<span></span';
1301
-        echo $html;
1302
-    }
1303
-
1304
-
1305
-
1306
-    /**
1307
-     * This just sets up the post update messages when an update form is loaded
1308
-     *
1309
-     * @access public
1310
-     * @param  array $messages the original messages array
1311
-     * @return array           the new messages array
1312
-     */
1313
-    public function post_update_messages($messages)
1314
-    {
1315
-        global $post;
1316
-        $id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1317
-        $id = empty($id) && is_object($post) ? $post->ID : null;
1318
-        //		$post_type = $post ? $post->post_type : false;
1319
-        /*$current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route'] : 'shouldneverwork';
1054
+	}
1055
+
1056
+
1057
+
1058
+	/**
1059
+	 * This allows child classes to modify the default editor title that appears when people add a new or edit an
1060
+	 * existing CPT item.     * This uses the _labels property set by the child class via _define_page_props. Just make
1061
+	 * sure you have a key in _labels property that equals 'editor_title' and the value can be whatever you want the
1062
+	 * default to be.
1063
+	 *
1064
+	 * @param string $title The new title (or existing if there is no editor_title defined)
1065
+	 * @return string
1066
+	 */
1067
+	public function add_custom_editor_default_title($title)
1068
+	{
1069
+		return isset($this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]])
1070
+			? $this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]]
1071
+			: $title;
1072
+	}
1073
+
1074
+
1075
+
1076
+	/**
1077
+	 * hooks into the wp_get_shortlink button and makes sure that the shortlink gets generated
1078
+	 *
1079
+	 * @param string $shortlink   The already generated shortlink
1080
+	 * @param int    $id          Post ID for this item
1081
+	 * @param string $context     The context for the link
1082
+	 * @param bool   $allow_slugs Whether to allow post slugs in the shortlink.
1083
+	 * @return string
1084
+	 */
1085
+	public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1086
+	{
1087
+		if ( ! empty($id) && get_option('permalink_structure') !== '') {
1088
+			$post = get_post($id);
1089
+			if (isset($post->post_type) && $this->page_slug === $post->post_type) {
1090
+				$shortlink = home_url('?p=' . $post->ID);
1091
+			}
1092
+		}
1093
+		return $shortlink;
1094
+	}
1095
+
1096
+
1097
+
1098
+	/**
1099
+	 * overriding the parent route_admin_request method so we DON'T run the route twice on cpt core page loads (it's
1100
+	 * already run in modify_current_screen())
1101
+	 *
1102
+	 * @return void
1103
+	 */
1104
+	public function route_admin_request()
1105
+	{
1106
+		if ($this->_cpt_route) {
1107
+			return;
1108
+		}
1109
+		try {
1110
+			$this->_route_admin_request();
1111
+		} catch (EE_Error $e) {
1112
+			$e->get_error();
1113
+		}
1114
+	}
1115
+
1116
+
1117
+
1118
+	/**
1119
+	 * Add a hidden form input to cpt core pages so that we know to do redirects to our routes on saves
1120
+	 *
1121
+	 * @return void
1122
+	 */
1123
+	public function cpt_post_form_hidden_input()
1124
+	{
1125
+		echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1126
+		//we're also going to add the route value and the current page so we can direct autosave parsing correctly
1127
+		echo '<div id="ee-cpt-hidden-inputs">';
1128
+		echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1129
+		echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1130
+		echo '</div>';
1131
+	}
1132
+
1133
+
1134
+
1135
+	/**
1136
+	 * This allows us to redirect the location of revision restores when they happen so it goes to our CPT routes.
1137
+	 *
1138
+	 * @param  string $location Original location url
1139
+	 * @param  int    $status   Status for http header
1140
+	 * @return string           new (or original) url to redirect to.
1141
+	 */
1142
+	public function revision_redirect($location, $status)
1143
+	{
1144
+		//get revision
1145
+		$rev_id = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
1146
+		//can't do anything without revision so let's get out if not present
1147
+		if (empty($rev_id)) {
1148
+			return $location;
1149
+		}
1150
+		//get rev_post_data
1151
+		$rev = get_post($rev_id);
1152
+		$admin_url = $this->_admin_base_url;
1153
+		$query_args = array(
1154
+			'action'   => 'edit',
1155
+			'post'     => $rev->post_parent,
1156
+			'revision' => $rev_id,
1157
+			'message'  => 5,
1158
+		);
1159
+		$this->_process_notices($query_args, true);
1160
+		return self::add_query_args_and_nonce($query_args, $admin_url);
1161
+	}
1162
+
1163
+
1164
+
1165
+	/**
1166
+	 * Modify the edit post link generated by wp core function so that EE CPTs get setup differently.
1167
+	 *
1168
+	 * @param  string $link    the original generated link
1169
+	 * @param  int    $id      post id
1170
+	 * @param  string $context optional, defaults to display.  How to write the '&'
1171
+	 * @return string          the link
1172
+	 */
1173
+	public function modify_edit_post_link($link, $id, $context)
1174
+	{
1175
+		$post = get_post($id);
1176
+		if ( ! isset($this->_req_data['action'])
1177
+			 || ! isset($this->_cpt_routes[$this->_req_data['action']])
1178
+			 || $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1179
+		) {
1180
+			return $link;
1181
+		}
1182
+		$query_args = array(
1183
+			'action' => isset($this->_cpt_edit_routes[$post->post_type])
1184
+				? $this->_cpt_edit_routes[$post->post_type]
1185
+				: 'edit',
1186
+			'post'   => $id,
1187
+		);
1188
+		return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1189
+	}
1190
+
1191
+
1192
+	/**
1193
+	 * Modify the trash link on our cpt edit pages so it has the required query var for triggering redirect properly on
1194
+	 * our routes.
1195
+	 *
1196
+	 * @param  string $delete_link  original delete link
1197
+	 * @param  int    $post_id      id of cpt object
1198
+	 * @param  bool   $force_delete whether this is forcing a hard delete instead of trash
1199
+	 * @return string new delete link
1200
+	 * @throws EE_Error
1201
+	 */
1202
+	public function modify_delete_post_link($delete_link, $post_id, $force_delete)
1203
+	{
1204
+		$post = get_post($post_id);
1205
+
1206
+		if (empty($this->_req_data['action'])
1207
+			|| ! isset($this->_cpt_routes[$this->_req_data['action']])
1208
+			|| ! $post instanceof WP_Post
1209
+			|| $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1210
+		) {
1211
+			return $delete_link;
1212
+		}
1213
+		$this->_set_model_object($post->ID, true);
1214
+
1215
+		//returns something like `trash_event` or `trash_attendee` or `trash_venue`
1216
+		$action = 'trash_' . str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1217
+
1218
+		return EE_Admin_Page::add_query_args_and_nonce(
1219
+			array(
1220
+				'page' => $this->_req_data['page'],
1221
+				'action' => $action,
1222
+				$this->_cpt_model_obj->get_model()->get_primary_key_field()->get_name()
1223
+					=> $post->ID
1224
+			),
1225
+			admin_url()
1226
+		);
1227
+	}
1228
+
1229
+
1230
+
1231
+	/**
1232
+	 * This is the callback for the 'redirect_post_location' filter in wp-admin/post.php
1233
+	 * so that we can hijack the default redirect locations for wp custom post types
1234
+	 * that WE'RE using and send back to OUR routes.  This should only be hooked in on the right route.
1235
+	 *
1236
+	 * @param  string $location This is the incoming currently set redirect location
1237
+	 * @param  string $post_id  This is the 'ID' value of the wp_posts table
1238
+	 * @return string           the new location to redirect to
1239
+	 */
1240
+	public function cpt_post_location_redirect($location, $post_id)
1241
+	{
1242
+		//we DO have a match so let's setup the url
1243
+		//we have to get the post to determine our route
1244
+		$post       = get_post($post_id);
1245
+		$edit_route = $this->_cpt_edit_routes[$post->post_type];
1246
+		//shared query_args
1247
+		$query_args = array('action' => $edit_route, 'post' => $post_id);
1248
+		$admin_url  = $this->_admin_base_url;
1249
+		if (isset($this->_req_data['save']) || isset($this->_req_data['publish'])) {
1250
+			$status = get_post_status($post_id);
1251
+			if (isset($this->_req_data['publish'])) {
1252
+				switch ($status) {
1253
+					case 'pending':
1254
+						$message = 8;
1255
+						break;
1256
+					case 'future':
1257
+						$message = 9;
1258
+						break;
1259
+					default:
1260
+						$message = 6;
1261
+				}
1262
+			} else {
1263
+				$message = 'draft' === $status ? 10 : 1;
1264
+			}
1265
+		} else if (isset($this->_req_data['addmeta']) && $this->_req_data['addmeta']) {
1266
+			$message = 2;
1267
+			//			$append = '#postcustom';
1268
+		} else if (isset($this->_req_data['deletemeta']) && $this->_req_data['deletemeta']) {
1269
+			$message = 3;
1270
+			//			$append = '#postcustom';
1271
+		} elseif ($this->_req_data['action'] === 'post-quickpress-save-cont') {
1272
+			$message = 7;
1273
+		} else {
1274
+			$message = 4;
1275
+		}
1276
+		//change the message if the post type is not viewable on the frontend
1277
+		$this->_cpt_object = get_post_type_object($post->post_type);
1278
+		$message           = $message === 1 && ! $this->_cpt_object->publicly_queryable ? 4 : $message;
1279
+		$query_args = array_merge(array('message' => $message), $query_args);
1280
+		$this->_process_notices($query_args, true);
1281
+		return self::add_query_args_and_nonce($query_args, $admin_url);
1282
+	}
1283
+
1284
+
1285
+
1286
+	/**
1287
+	 * This method is called to inject nav tabs on core WP cpt pages
1288
+	 *
1289
+	 * @access public
1290
+	 * @return void
1291
+	 */
1292
+	public function inject_nav_tabs()
1293
+	{
1294
+		//can we hijack and insert the nav_tabs?
1295
+		$nav_tabs = $this->_get_main_nav_tabs();
1296
+		//first close off existing form tag
1297
+		$html = '>';
1298
+		$html .= $nav_tabs;
1299
+		//now let's handle the remaining tag ( missing ">" is CORRECT )
1300
+		$html .= '<span></span';
1301
+		echo $html;
1302
+	}
1303
+
1304
+
1305
+
1306
+	/**
1307
+	 * This just sets up the post update messages when an update form is loaded
1308
+	 *
1309
+	 * @access public
1310
+	 * @param  array $messages the original messages array
1311
+	 * @return array           the new messages array
1312
+	 */
1313
+	public function post_update_messages($messages)
1314
+	{
1315
+		global $post;
1316
+		$id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1317
+		$id = empty($id) && is_object($post) ? $post->ID : null;
1318
+		//		$post_type = $post ? $post->post_type : false;
1319
+		/*$current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route'] : 'shouldneverwork';
1320 1320
 
1321 1321
         $route_to_check = $post_type && isset( $this->_cpt_routes[$current_route]) ? $this->_cpt_routes[$current_route] : '';/**/
1322
-        $messages[$post->post_type] = array(
1323
-            0 => '', //Unused. Messages start at index 1.
1324
-            1 => sprintf(
1325
-                __('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1326
-                $this->_cpt_object->labels->singular_name,
1327
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1328
-                '</a>'
1329
-            ),
1330
-            2 => __('Custom field updated'),
1331
-            3 => __('Custom field deleted.'),
1332
-            4 => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1333
-            5 => isset($_GET['revision']) ? sprintf(__('%s restored to revision from %s', 'event_espresso'),
1334
-                $this->_cpt_object->labels->singular_name, wp_post_revision_title((int)$_GET['revision'], false))
1335
-                : false,
1336
-            6 => sprintf(
1337
-                __('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1338
-                $this->_cpt_object->labels->singular_name,
1339
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1340
-                '</a>'
1341
-            ),
1342
-            7 => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1343
-            8 => sprintf(
1344
-                __('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1345
-                $this->_cpt_object->labels->singular_name,
1346
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1347
-                '</a>'
1348
-            ),
1349
-            9 => sprintf(
1350
-                __('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1351
-                $this->_cpt_object->labels->singular_name,
1352
-                '<strong>' . date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)) . '</strong>',
1353
-                '<a target="_blank" href="' . esc_url(get_permalink($id)),
1354
-                '</a>'
1355
-            ),
1356
-            10 => sprintf(
1357
-                __('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1358
-                $this->_cpt_object->labels->singular_name,
1359
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1360
-                '</a>'
1361
-            ),
1362
-        );
1363
-        return $messages;
1364
-    }
1365
-
1366
-
1367
-
1368
-    /**
1369
-     * default method for the 'create_new' route for cpt admin pages.
1370
-     * For reference what to include in here, see wp-admin/post-new.php
1371
-     *
1372
-     * @access  protected
1373
-     * @return void
1374
-     */
1375
-    protected function _create_new_cpt_item()
1376
-    {
1377
-        // gather template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1378
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1379
-        $post_type        = $this->_cpt_routes[$this->_req_action];
1380
-        $post_type_object = $this->_cpt_object;
1381
-        $title            = $post_type_object->labels->add_new_item;
1382
-        $editing          = true;
1383
-        wp_enqueue_script('autosave');
1384
-        $post    = $post = get_default_post_to_edit($this->_cpt_routes[$this->_req_action], true);
1385
-        $post_ID = $post->ID;
1386
-        add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1387
-        //modify the default editor title field with default title.
1388
-        add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1389
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1390
-    }
1391
-
1392
-
1393
-
1394
-    public function add_new_admin_page_global()
1395
-    {
1396
-        $admin_page = ! empty($this->_req_data['post']) ? 'post-php' : 'post-new-php';
1397
-        ?>
1322
+		$messages[$post->post_type] = array(
1323
+			0 => '', //Unused. Messages start at index 1.
1324
+			1 => sprintf(
1325
+				__('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1326
+				$this->_cpt_object->labels->singular_name,
1327
+				'<a href="' . esc_url(get_permalink($id)) . '">',
1328
+				'</a>'
1329
+			),
1330
+			2 => __('Custom field updated'),
1331
+			3 => __('Custom field deleted.'),
1332
+			4 => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1333
+			5 => isset($_GET['revision']) ? sprintf(__('%s restored to revision from %s', 'event_espresso'),
1334
+				$this->_cpt_object->labels->singular_name, wp_post_revision_title((int)$_GET['revision'], false))
1335
+				: false,
1336
+			6 => sprintf(
1337
+				__('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1338
+				$this->_cpt_object->labels->singular_name,
1339
+				'<a href="' . esc_url(get_permalink($id)) . '">',
1340
+				'</a>'
1341
+			),
1342
+			7 => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1343
+			8 => sprintf(
1344
+				__('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1345
+				$this->_cpt_object->labels->singular_name,
1346
+				'<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1347
+				'</a>'
1348
+			),
1349
+			9 => sprintf(
1350
+				__('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1351
+				$this->_cpt_object->labels->singular_name,
1352
+				'<strong>' . date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)) . '</strong>',
1353
+				'<a target="_blank" href="' . esc_url(get_permalink($id)),
1354
+				'</a>'
1355
+			),
1356
+			10 => sprintf(
1357
+				__('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1358
+				$this->_cpt_object->labels->singular_name,
1359
+				'<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1360
+				'</a>'
1361
+			),
1362
+		);
1363
+		return $messages;
1364
+	}
1365
+
1366
+
1367
+
1368
+	/**
1369
+	 * default method for the 'create_new' route for cpt admin pages.
1370
+	 * For reference what to include in here, see wp-admin/post-new.php
1371
+	 *
1372
+	 * @access  protected
1373
+	 * @return void
1374
+	 */
1375
+	protected function _create_new_cpt_item()
1376
+	{
1377
+		// gather template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1378
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1379
+		$post_type        = $this->_cpt_routes[$this->_req_action];
1380
+		$post_type_object = $this->_cpt_object;
1381
+		$title            = $post_type_object->labels->add_new_item;
1382
+		$editing          = true;
1383
+		wp_enqueue_script('autosave');
1384
+		$post    = $post = get_default_post_to_edit($this->_cpt_routes[$this->_req_action], true);
1385
+		$post_ID = $post->ID;
1386
+		add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1387
+		//modify the default editor title field with default title.
1388
+		add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1389
+		include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1390
+	}
1391
+
1392
+
1393
+
1394
+	public function add_new_admin_page_global()
1395
+	{
1396
+		$admin_page = ! empty($this->_req_data['post']) ? 'post-php' : 'post-new-php';
1397
+		?>
1398 1398
         <script type="text/javascript">
1399 1399
             adminpage = '<?php echo $admin_page; ?>';
1400 1400
         </script>
1401 1401
         <?php
1402
-    }
1403
-
1404
-
1405
-
1406
-    /**
1407
-     * default method for the 'edit' route for cpt admin pages
1408
-     * For reference on what to put in here, refer to wp-admin/post.php
1409
-     *
1410
-     * @access protected
1411
-     * @return string   template for edit cpt form
1412
-     */
1413
-    protected function _edit_cpt_item()
1414
-    {
1415
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1416
-        $post_id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1417
-        $post = ! empty($post_id) ? get_post($post_id, OBJECT, 'edit') : null;
1418
-        if (empty ($post)) {
1419
-            wp_die(__('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?'));
1420
-        }
1421
-        if ( ! empty($_GET['get-post-lock'])) {
1422
-            wp_set_post_lock($post_id);
1423
-            wp_redirect(get_edit_post_link($post_id, 'url'));
1424
-            exit();
1425
-        }
1426
-
1427
-        // template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1428
-        $editing          = true;
1429
-        $post_ID          = $post_id;
1430
-        $post_type        = $this->_cpt_routes[$this->_req_action];
1431
-        $post_type_object = $this->_cpt_object;
1432
-
1433
-        if ( ! wp_check_post_lock($post->ID)) {
1434
-            $active_post_lock = wp_set_post_lock($post->ID);
1435
-            //wp_enqueue_script('autosave');
1436
-        }
1437
-        $title = $this->_cpt_object->labels->edit_item;
1438
-        add_action('admin_footer', '_admin_notice_post_locked');
1439
-        if (isset($this->_cpt_routes[$this->_req_data['action']])
1440
-            && ! isset($this->_labels['hide_add_button_on_cpt_route'][$this->_req_data['action']])
1441
-        ) {
1442
-            $create_new_action = apply_filters('FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
1443
-                'create_new', $this);
1444
-            $post_new_file = EE_Admin_Page::add_query_args_and_nonce(array(
1445
-                'action' => $create_new_action,
1446
-                'page'   => $this->page_slug,
1447
-            ), 'admin.php');
1448
-        }
1449
-        if (post_type_supports($this->_cpt_routes[$this->_req_action], 'comments')) {
1450
-            wp_enqueue_script('admin-comments');
1451
-            enqueue_comment_hotkeys_js();
1452
-        }
1453
-        add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1454
-        //modify the default editor title field with default title.
1455
-        add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1456
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1457
-    }
1458
-
1459
-
1460
-
1461
-    /**
1462
-     * some getters
1463
-     */
1464
-    /**
1465
-     * This returns the protected _cpt_model_obj property
1466
-     *
1467
-     * @return EE_CPT_Base
1468
-     */
1469
-    public function get_cpt_model_obj()
1470
-    {
1471
-        return $this->_cpt_model_obj;
1472
-    }
1402
+	}
1403
+
1404
+
1405
+
1406
+	/**
1407
+	 * default method for the 'edit' route for cpt admin pages
1408
+	 * For reference on what to put in here, refer to wp-admin/post.php
1409
+	 *
1410
+	 * @access protected
1411
+	 * @return string   template for edit cpt form
1412
+	 */
1413
+	protected function _edit_cpt_item()
1414
+	{
1415
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1416
+		$post_id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1417
+		$post = ! empty($post_id) ? get_post($post_id, OBJECT, 'edit') : null;
1418
+		if (empty ($post)) {
1419
+			wp_die(__('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?'));
1420
+		}
1421
+		if ( ! empty($_GET['get-post-lock'])) {
1422
+			wp_set_post_lock($post_id);
1423
+			wp_redirect(get_edit_post_link($post_id, 'url'));
1424
+			exit();
1425
+		}
1426
+
1427
+		// template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1428
+		$editing          = true;
1429
+		$post_ID          = $post_id;
1430
+		$post_type        = $this->_cpt_routes[$this->_req_action];
1431
+		$post_type_object = $this->_cpt_object;
1432
+
1433
+		if ( ! wp_check_post_lock($post->ID)) {
1434
+			$active_post_lock = wp_set_post_lock($post->ID);
1435
+			//wp_enqueue_script('autosave');
1436
+		}
1437
+		$title = $this->_cpt_object->labels->edit_item;
1438
+		add_action('admin_footer', '_admin_notice_post_locked');
1439
+		if (isset($this->_cpt_routes[$this->_req_data['action']])
1440
+			&& ! isset($this->_labels['hide_add_button_on_cpt_route'][$this->_req_data['action']])
1441
+		) {
1442
+			$create_new_action = apply_filters('FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
1443
+				'create_new', $this);
1444
+			$post_new_file = EE_Admin_Page::add_query_args_and_nonce(array(
1445
+				'action' => $create_new_action,
1446
+				'page'   => $this->page_slug,
1447
+			), 'admin.php');
1448
+		}
1449
+		if (post_type_supports($this->_cpt_routes[$this->_req_action], 'comments')) {
1450
+			wp_enqueue_script('admin-comments');
1451
+			enqueue_comment_hotkeys_js();
1452
+		}
1453
+		add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1454
+		//modify the default editor title field with default title.
1455
+		add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1456
+		include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1457
+	}
1458
+
1459
+
1460
+
1461
+	/**
1462
+	 * some getters
1463
+	 */
1464
+	/**
1465
+	 * This returns the protected _cpt_model_obj property
1466
+	 *
1467
+	 * @return EE_CPT_Base
1468
+	 */
1469
+	public function get_cpt_model_obj()
1470
+	{
1471
+		return $this->_cpt_model_obj;
1472
+	}
1473 1473
 
1474 1474
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
      */
236 236
     protected function _register_autosave_containers($ids)
237 237
     {
238
-        $this->_autosave_containers = array_merge($this->_autosave_fields, (array)$ids);
238
+        $this->_autosave_containers = array_merge($this->_autosave_fields, (array) $ids);
239 239
     }
240 240
 
241 241
 
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
         //filter _autosave_containers
283 283
         $containers = apply_filters('FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
284 284
             $this->_autosave_containers, $this);
285
-        $containers = apply_filters('FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
285
+        $containers = apply_filters('FHEE__EE_Admin_Page_CPT__'.get_class($this).'___load_autosave_scripts_styles__containers',
286 286
             $containers, $this);
287 287
 
288 288
         wp_localize_script('event_editor_js', 'EE_AUTOSAVE_IDS',
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
         // This is for any plugins that are doing things properly
395 395
         // and hooking into the load page hook for core wp cpt routes.
396 396
         global $pagenow;
397
-        do_action('load-' . $pagenow);
397
+        do_action('load-'.$pagenow);
398 398
         $this->modify_current_screen();
399 399
         add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
400 400
         //we route REALLY early.
@@ -425,8 +425,8 @@  discard block
 block discarded – undo
425 425
                 'admin.php?page=espresso_registrations&action=contact_list',
426 426
             ),
427 427
             1 => array(
428
-                'edit.php?post_type=' . $this->_cpt_object->name,
429
-                'admin.php?page=' . $this->_cpt_object->name,
428
+                'edit.php?post_type='.$this->_cpt_object->name,
429
+                'admin.php?page='.$this->_cpt_object->name,
430 430
             ),
431 431
         );
432 432
         foreach ($routes_to_match as $route_matches) {
@@ -454,7 +454,7 @@  discard block
 block discarded – undo
454 454
         $cpt_has_support = ! empty($cpt_args['page_templates']);
455 455
 
456 456
         //if the installed version of WP is > 4.7 we do some additional checks.
457
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
457
+        if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
458 458
             $post_templates = wp_get_theme()->get_post_templates();
459 459
             //if there are $post_templates for this cpt, then we return false for this method because
460 460
             //that means we aren't going to load our page template manager and leave that up to the native
@@ -477,7 +477,7 @@  discard block
 block discarded – undo
477 477
         global $post;
478 478
         $template = '';
479 479
 
480
-        if (EE_Recommended_Versions::check_wp_version('4.7','>=')) {
480
+        if (EE_Recommended_Versions::check_wp_version('4.7', '>=')) {
481 481
             $page_template_count = count(get_page_templates());
482 482
         } else {
483 483
             $page_template_count = count(get_page_templates($post));
@@ -514,7 +514,7 @@  discard block
 block discarded – undo
514 514
         $post = get_post($id);
515 515
         if ('publish' !== get_post_status($post)) {
516 516
             //include shims for the `get_preview_post_link` function
517
-            require_once( EE_CORE . 'wordpress-shims.php' );
517
+            require_once(EE_CORE.'wordpress-shims.php');
518 518
             $return .= '<span_id="view-post-btn"><a target="_blank" href="'
519 519
                        . get_preview_post_link($id)
520 520
                        . '" class="button button-small">'
@@ -552,7 +552,7 @@  discard block
 block discarded – undo
552 552
             $template_args['statuses']         = $statuses;
553 553
         }
554 554
 
555
-        $template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
555
+        $template = EE_ADMIN_TEMPLATE.'status_dropdown.template.php';
556 556
         EEH_Template::display_template($template, $template_args);
557 557
     }
558 558
 
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
             $this->_template_args['success'] = true;
607 607
         }
608 608
         do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
609
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
609
+        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_'.get_class($this), $this);
610 610
         //now let's return json
611 611
         $this->_return_json();
612 612
     }
@@ -1009,7 +1009,7 @@  discard block
 block discarded – undo
1009 1009
         //global action
1010 1010
         do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
1011 1011
         //class specific action so you can limit hooking into a specific page.
1012
-        do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
1012
+        do_action('AHEE_EE_Admin_Page_CPT_'.get_class($this).'__restore_revision', $post_id, $revision_id);
1013 1013
     }
1014 1014
 
1015 1015
 
@@ -1087,7 +1087,7 @@  discard block
 block discarded – undo
1087 1087
         if ( ! empty($id) && get_option('permalink_structure') !== '') {
1088 1088
             $post = get_post($id);
1089 1089
             if (isset($post->post_type) && $this->page_slug === $post->post_type) {
1090
-                $shortlink = home_url('?p=' . $post->ID);
1090
+                $shortlink = home_url('?p='.$post->ID);
1091 1091
             }
1092 1092
         }
1093 1093
         return $shortlink;
@@ -1122,11 +1122,11 @@  discard block
 block discarded – undo
1122 1122
      */
1123 1123
     public function cpt_post_form_hidden_input()
1124 1124
     {
1125
-        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1125
+        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="'.$this->_admin_base_url.'" />';
1126 1126
         //we're also going to add the route value and the current page so we can direct autosave parsing correctly
1127 1127
         echo '<div id="ee-cpt-hidden-inputs">';
1128
-        echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1129
-        echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1128
+        echo '<input type="hidden" id="current_route" name="current_route" value="'.$this->_current_view.'" />';
1129
+        echo '<input type="hidden" id="current_page" name="current_page" value="'.$this->page_slug.'" />';
1130 1130
         echo '</div>';
1131 1131
     }
1132 1132
 
@@ -1213,7 +1213,7 @@  discard block
 block discarded – undo
1213 1213
         $this->_set_model_object($post->ID, true);
1214 1214
 
1215 1215
         //returns something like `trash_event` or `trash_attendee` or `trash_venue`
1216
-        $action = 'trash_' . str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1216
+        $action = 'trash_'.str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1217 1217
 
1218 1218
         return EE_Admin_Page::add_query_args_and_nonce(
1219 1219
             array(
@@ -1324,39 +1324,39 @@  discard block
 block discarded – undo
1324 1324
             1 => sprintf(
1325 1325
                 __('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1326 1326
                 $this->_cpt_object->labels->singular_name,
1327
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1327
+                '<a href="'.esc_url(get_permalink($id)).'">',
1328 1328
                 '</a>'
1329 1329
             ),
1330 1330
             2 => __('Custom field updated'),
1331 1331
             3 => __('Custom field deleted.'),
1332 1332
             4 => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1333 1333
             5 => isset($_GET['revision']) ? sprintf(__('%s restored to revision from %s', 'event_espresso'),
1334
-                $this->_cpt_object->labels->singular_name, wp_post_revision_title((int)$_GET['revision'], false))
1334
+                $this->_cpt_object->labels->singular_name, wp_post_revision_title((int) $_GET['revision'], false))
1335 1335
                 : false,
1336 1336
             6 => sprintf(
1337 1337
                 __('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1338 1338
                 $this->_cpt_object->labels->singular_name,
1339
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1339
+                '<a href="'.esc_url(get_permalink($id)).'">',
1340 1340
                 '</a>'
1341 1341
             ),
1342 1342
             7 => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1343 1343
             8 => sprintf(
1344 1344
                 __('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1345 1345
                 $this->_cpt_object->labels->singular_name,
1346
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1346
+                '<a target="_blank" href="'.esc_url(add_query_arg('preview', 'true', get_permalink($id))).'">',
1347 1347
                 '</a>'
1348 1348
             ),
1349 1349
             9 => sprintf(
1350 1350
                 __('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1351 1351
                 $this->_cpt_object->labels->singular_name,
1352
-                '<strong>' . date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)) . '</strong>',
1353
-                '<a target="_blank" href="' . esc_url(get_permalink($id)),
1352
+                '<strong>'.date_i18n(__('M j, Y @ G:i'), strtotime($post->post_date)).'</strong>',
1353
+                '<a target="_blank" href="'.esc_url(get_permalink($id)),
1354 1354
                 '</a>'
1355 1355
             ),
1356 1356
             10 => sprintf(
1357 1357
                 __('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1358 1358
                 $this->_cpt_object->labels->singular_name,
1359
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1359
+                '<a target="_blank" href="'.esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1360 1360
                 '</a>'
1361 1361
             ),
1362 1362
         );
@@ -1386,7 +1386,7 @@  discard block
 block discarded – undo
1386 1386
         add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1387 1387
         //modify the default editor title field with default title.
1388 1388
         add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1389
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1389
+        include_once WP_ADMIN_PATH.'edit-form-advanced.php';
1390 1390
     }
1391 1391
 
1392 1392
 
@@ -1453,7 +1453,7 @@  discard block
 block discarded – undo
1453 1453
         add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1454 1454
         //modify the default editor title field with default title.
1455 1455
         add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1456
-        include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1456
+        include_once WP_ADMIN_PATH.'edit-form-advanced.php';
1457 1457
     }
1458 1458
 
1459 1459
 
Please login to merge, or discard this patch.
admin/extend/registration_form/Extend_Registration_Form_Admin_Page.core.php 1 patch
Indentation   +1088 added lines, -1088 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if (! defined('EVENT_ESPRESSO_VERSION')) {
3
-    exit('NO direct script access allowed');
3
+	exit('NO direct script access allowed');
4 4
 }
5 5
 
6 6
 /**
@@ -25,1093 +25,1093 @@  discard block
 block discarded – undo
25 25
 {
26 26
 
27 27
 
28
-    /**
29
-     * @Constructor
30
-     * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
31
-     * @access public
32
-     */
33
-    public function __construct($routing = true)
34
-    {
35
-        define('REGISTRATION_FORM_CAF_ADMIN', EE_CORE_CAF_ADMIN_EXTEND . 'registration_form' . DS);
36
-        define('REGISTRATION_FORM_CAF_ASSETS_PATH', REGISTRATION_FORM_CAF_ADMIN . 'assets' . DS);
37
-        define('REGISTRATION_FORM_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/assets/');
38
-        define('REGISTRATION_FORM_CAF_TEMPLATE_PATH', REGISTRATION_FORM_CAF_ADMIN . 'templates' . DS);
39
-        define('REGISTRATION_FORM_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/templates/');
40
-        parent::__construct($routing);
41
-    }
42
-
43
-
44
-    protected function _extend_page_config()
45
-    {
46
-        $this->_admin_base_path = REGISTRATION_FORM_CAF_ADMIN;
47
-        $qst_id = ! empty($this->_req_data['QST_ID']) && ! is_array($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0;
48
-        $qsg_id = ! empty($this->_req_data['QSG_ID']) && ! is_array($this->_req_data['QSG_ID']) ? $this->_req_data['QSG_ID'] : 0;
49
-
50
-        $new_page_routes    = array(
51
-            'question_groups'    => array(
52
-                'func'       => '_question_groups_overview_list_table',
53
-                'capability' => 'ee_read_question_groups',
54
-            ),
55
-            'add_question'       => array(
56
-                'func'       => '_edit_question',
57
-                'capability' => 'ee_edit_questions',
58
-            ),
59
-            'insert_question'    => array(
60
-                'func'       => '_insert_or_update_question',
61
-                'args'       => array('new_question' => true),
62
-                'capability' => 'ee_edit_questions',
63
-                'noheader'   => true,
64
-            ),
65
-            'duplicate_question' => array(
66
-                'func'       => '_duplicate_question',
67
-                'capability' => 'ee_edit_questions',
68
-                'noheader'   => true,
69
-            ),
70
-            'trash_question'     => array(
71
-                'func'       => '_trash_question',
72
-                'capability' => 'ee_delete_question',
73
-                'obj_id'     => $qst_id,
74
-                'noheader'   => true,
75
-            ),
76
-
77
-            'restore_question' => array(
78
-                'func'       => '_trash_or_restore_questions',
79
-                'capability' => 'ee_delete_question',
80
-                'obj_id'     => $qst_id,
81
-                'args'       => array('trash' => false),
82
-                'noheader'   => true,
83
-            ),
84
-
85
-            'delete_question' => array(
86
-                'func'       => '_delete_question',
87
-                'capability' => 'ee_delete_question',
88
-                'obj_id'     => $qst_id,
89
-                'noheader'   => true,
90
-            ),
91
-
92
-            'trash_questions' => array(
93
-                'func'       => '_trash_or_restore_questions',
94
-                'capability' => 'ee_delete_questions',
95
-                'args'       => array('trash' => true),
96
-                'noheader'   => true,
97
-            ),
98
-
99
-            'restore_questions' => array(
100
-                'func'       => '_trash_or_restore_questions',
101
-                'capability' => 'ee_delete_questions',
102
-                'args'       => array('trash' => false),
103
-                'noheader'   => true,
104
-            ),
105
-
106
-            'delete_questions' => array(
107
-                'func'       => '_delete_questions',
108
-                'args'       => array(),
109
-                'capability' => 'ee_delete_questions',
110
-                'noheader'   => true,
111
-            ),
112
-
113
-            'add_question_group' => array(
114
-                'func'       => '_edit_question_group',
115
-                'capability' => 'ee_edit_question_groups',
116
-            ),
117
-
118
-            'edit_question_group' => array(
119
-                'func'       => '_edit_question_group',
120
-                'capability' => 'ee_edit_question_group',
121
-                'obj_id'     => $qsg_id,
122
-                'args'       => array('edit'),
123
-            ),
124
-
125
-            'delete_question_groups' => array(
126
-                'func'       => '_delete_question_groups',
127
-                'capability' => 'ee_delete_question_groups',
128
-                'noheader'   => true,
129
-            ),
130
-
131
-            'delete_question_group' => array(
132
-                'func'       => '_delete_question_groups',
133
-                'capability' => 'ee_delete_question_group',
134
-                'obj_id'     => $qsg_id,
135
-                'noheader'   => true,
136
-            ),
137
-
138
-            'trash_question_group' => array(
139
-                'func'       => '_trash_or_restore_question_groups',
140
-                'args'       => array('trash' => true),
141
-                'capability' => 'ee_delete_question_group',
142
-                'obj_id'     => $qsg_id,
143
-                'noheader'   => true,
144
-            ),
145
-
146
-            'restore_question_group' => array(
147
-                'func'       => '_trash_or_restore_question_groups',
148
-                'args'       => array('trash' => false),
149
-                'capability' => 'ee_delete_question_group',
150
-                'obj_id'     => $qsg_id,
151
-                'noheader'   => true,
152
-            ),
153
-
154
-            'insert_question_group' => array(
155
-                'func'       => '_insert_or_update_question_group',
156
-                'args'       => array('new_question_group' => true),
157
-                'capability' => 'ee_edit_question_groups',
158
-                'noheader'   => true,
159
-            ),
160
-
161
-            'update_question_group' => array(
162
-                'func'       => '_insert_or_update_question_group',
163
-                'args'       => array('new_question_group' => false),
164
-                'capability' => 'ee_edit_question_group',
165
-                'obj_id'     => $qsg_id,
166
-                'noheader'   => true,
167
-            ),
168
-
169
-            'trash_question_groups' => array(
170
-                'func'       => '_trash_or_restore_question_groups',
171
-                'args'       => array('trash' => true),
172
-                'capability' => 'ee_delete_question_groups',
173
-                'noheader'   => array('trash' => false),
174
-            ),
175
-
176
-            'restore_question_groups' => array(
177
-                'func'       => '_trash_or_restore_question_groups',
178
-                'args'       => array('trash' => false),
179
-                'capability' => 'ee_delete_question_groups',
180
-                'noheader'   => true,
181
-            ),
182
-
183
-
184
-            'espresso_update_question_group_order' => array(
185
-                'func'       => 'update_question_group_order',
186
-                'capability' => 'ee_edit_question_groups',
187
-                'noheader'   => true,
188
-            ),
189
-
190
-            'view_reg_form_settings' => array(
191
-                'func'       => '_reg_form_settings',
192
-                'capability' => 'manage_options',
193
-            ),
194
-
195
-            'update_reg_form_settings' => array(
196
-                'func'       => '_update_reg_form_settings',
197
-                'capability' => 'manage_options',
198
-                'noheader'   => true,
199
-            ),
200
-        );
201
-        $this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
202
-
203
-        $new_page_config    = array(
204
-
205
-            'question_groups' => array(
206
-                'nav'           => array(
207
-                    'label' => esc_html__('Question Groups', 'event_espresso'),
208
-                    'order' => 20,
209
-                ),
210
-                'list_table'    => 'Registration_Form_Question_Groups_Admin_List_Table',
211
-                'help_tabs'     => array(
212
-                    'registration_form_question_groups_help_tab'                           => array(
213
-                        'title'    => esc_html__('Question Groups', 'event_espresso'),
214
-                        'filename' => 'registration_form_question_groups',
215
-                    ),
216
-                    'registration_form_question_groups_table_column_headings_help_tab'     => array(
217
-                        'title'    => esc_html__('Question Groups Table Column Headings', 'event_espresso'),
218
-                        'filename' => 'registration_form_question_groups_table_column_headings',
219
-                    ),
220
-                    'registration_form_question_groups_views_bulk_actions_search_help_tab' => array(
221
-                        'title'    => esc_html__('Question Groups Views & Bulk Actions & Search', 'event_espresso'),
222
-                        'filename' => 'registration_form_question_groups_views_bulk_actions_search',
223
-                    ),
224
-                ),
225
-                'help_tour'     => array('Registration_Form_Question_Groups_Help_Tour'),
226
-                'metaboxes'     => $this->_default_espresso_metaboxes,
227
-                'require_nonce' => false,
228
-                'qtips'         => array(
229
-                    'EE_Registration_Form_Tips',
230
-                ),
231
-            ),
232
-
233
-            'add_question' => array(
234
-                'nav'           => array(
235
-                    'label'      => esc_html__('Add Question', 'event_espresso'),
236
-                    'order'      => 5,
237
-                    'persistent' => false,
238
-                ),
239
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
240
-                'help_tabs'     => array(
241
-                    'registration_form_add_question_help_tab' => array(
242
-                        'title'    => esc_html__('Add Question', 'event_espresso'),
243
-                        'filename' => 'registration_form_add_question',
244
-                    ),
245
-                ),
246
-                'help_tour'     => array('Registration_Form_Add_Question_Help_Tour'),
247
-                'require_nonce' => false,
248
-            ),
249
-
250
-            'add_question_group' => array(
251
-                'nav'           => array(
252
-                    'label'      => esc_html__('Add Question Group', 'event_espresso'),
253
-                    'order'      => 5,
254
-                    'persistent' => false,
255
-                ),
256
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
257
-                'help_tabs'     => array(
258
-                    'registration_form_add_question_group_help_tab' => array(
259
-                        'title'    => esc_html__('Add Question Group', 'event_espresso'),
260
-                        'filename' => 'registration_form_add_question_group',
261
-                    ),
262
-                ),
263
-                'help_tour'     => array('Registration_Form_Add_Question_Group_Help_Tour'),
264
-                'require_nonce' => false,
265
-            ),
266
-
267
-            'edit_question_group' => array(
268
-                'nav'           => array(
269
-                    'label'      => esc_html__('Edit Question Group', 'event_espresso'),
270
-                    'order'      => 5,
271
-                    'persistent' => false,
272
-                    'url'        => isset($this->_req_data['question_group_id']) ? add_query_arg(array('question_group_id' => $this->_req_data['question_group_id']),
273
-                        $this->_current_page_view_url) : $this->_admin_base_url,
274
-                ),
275
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
276
-                'help_tabs'     => array(
277
-                    'registration_form_edit_question_group_help_tab' => array(
278
-                        'title'    => esc_html__('Edit Question Group', 'event_espresso'),
279
-                        'filename' => 'registration_form_edit_question_group',
280
-                    ),
281
-                ),
282
-                'help_tour'     => array('Registration_Form_Edit_Question_Group_Help_Tour'),
283
-                'require_nonce' => false,
284
-            ),
285
-
286
-            'view_reg_form_settings' => array(
287
-                'nav'           => array(
288
-                    'label' => esc_html__('Reg Form Settings', 'event_espresso'),
289
-                    'order' => 40,
290
-                ),
291
-                'labels'        => array(
292
-                    'publishbox' => esc_html__('Update Settings', 'event_espresso'),
293
-                ),
294
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
295
-                'help_tabs'     => array(
296
-                    'registration_form_reg_form_settings_help_tab' => array(
297
-                        'title'    => esc_html__('Registration Form Settings', 'event_espresso'),
298
-                        'filename' => 'registration_form_reg_form_settings',
299
-                    ),
300
-                ),
301
-                'help_tour'     => array('Registration_Form_Settings_Help_Tour'),
302
-                'require_nonce' => false,
303
-            ),
304
-
305
-        );
306
-        $this->_page_config = array_merge($this->_page_config, $new_page_config);
307
-
308
-        //change the list table we're going to use so it's the NEW list table!
309
-        $this->_page_config['default']['list_table'] = 'Extend_Registration_Form_Questions_Admin_List_Table';
310
-
311
-
312
-        //additional labels
313
-        $new_labels               = array(
314
-            'add_question'          => esc_html__('Add New Question', 'event_espresso'),
315
-            'delete_question'       => esc_html__('Delete Question', 'event_espresso'),
316
-            'add_question_group'    => esc_html__('Add New Question Group', 'event_espresso'),
317
-            'edit_question_group'   => esc_html__('Edit Question Group', 'event_espresso'),
318
-            'delete_question_group' => esc_html__('Delete Question Group', 'event_espresso'),
319
-        );
320
-        $this->_labels['buttons'] = array_merge($this->_labels['buttons'], $new_labels);
321
-
322
-    }
323
-
324
-
325
-    protected function _ajax_hooks()
326
-    {
327
-        add_action('wp_ajax_espresso_update_question_group_order', array($this, 'update_question_group_order'));
328
-    }
329
-
330
-
331
-    public function load_scripts_styles_question_groups()
332
-    {
333
-        wp_enqueue_script('espresso_ajax_table_sorting');
334
-    }
335
-
336
-
337
-    public function load_scripts_styles_add_question_group()
338
-    {
339
-        $this->load_scripts_styles_forms();
340
-        $this->load_sortable_question_script();
341
-    }
342
-
343
-    public function load_scripts_styles_edit_question_group()
344
-    {
345
-        $this->load_scripts_styles_forms();
346
-        $this->load_sortable_question_script();
347
-    }
348
-
349
-
350
-    /**
351
-     * registers and enqueues script for questions
352
-     *
353
-     * @return void
354
-     */
355
-    public function load_sortable_question_script()
356
-    {
357
-        wp_register_script('ee-question-sortable', REGISTRATION_FORM_CAF_ASSETS_URL . 'ee_question_order.js',
358
-            array('jquery-ui-sortable'), EVENT_ESPRESSO_VERSION, true);
359
-        wp_enqueue_script('ee-question-sortable');
360
-    }
361
-
362
-
363
-    protected function _set_list_table_views_default()
364
-    {
365
-        $this->_views = array(
366
-            'all' => array(
367
-                'slug'        => 'all',
368
-                'label'       => esc_html__('View All Questions', 'event_espresso'),
369
-                'count'       => 0,
370
-                'bulk_action' => array(
371
-                    'trash_questions' => esc_html__('Trash', 'event_espresso'),
372
-                ),
373
-            ),
374
-        );
375
-
376
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_questions',
377
-            'espresso_registration_form_trash_questions')
378
-        ) {
379
-            $this->_views['trash'] = array(
380
-                'slug'        => 'trash',
381
-                'label'       => esc_html__('Trash', 'event_espresso'),
382
-                'count'       => 0,
383
-                'bulk_action' => array(
384
-                    'delete_questions'  => esc_html__('Delete Permanently', 'event_espresso'),
385
-                    'restore_questions' => esc_html__('Restore', 'event_espresso'),
386
-                ),
387
-            );
388
-        }
389
-    }
390
-
391
-
392
-    protected function _set_list_table_views_question_groups()
393
-    {
394
-        $this->_views = array(
395
-            'all' => array(
396
-                'slug'        => 'all',
397
-                'label'       => esc_html__('All', 'event_espresso'),
398
-                'count'       => 0,
399
-                'bulk_action' => array(
400
-                    'trash_question_groups' => esc_html__('Trash', 'event_espresso'),
401
-                ),
402
-            ),
403
-        );
404
-
405
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_question_groups',
406
-            'espresso_registration_form_trash_question_groups')
407
-        ) {
408
-            $this->_views['trash'] = array(
409
-                'slug'        => 'trash',
410
-                'label'       => esc_html__('Trash', 'event_espresso'),
411
-                'count'       => 0,
412
-                'bulk_action' => array(
413
-                    'delete_question_groups'  => esc_html__('Delete Permanently', 'event_espresso'),
414
-                    'restore_question_groups' => esc_html__('Restore', 'event_espresso'),
415
-                ),
416
-            );
417
-        }
418
-    }
419
-
420
-
421
-    protected function _questions_overview_list_table()
422
-    {
423
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
424
-                'add_question',
425
-                'add_question',
426
-                array(),
427
-                'add-new-h2'
428
-            );
429
-        parent::_questions_overview_list_table();
430
-    }
431
-
432
-
433
-    protected function _question_groups_overview_list_table()
434
-    {
435
-        $this->_search_btn_label = esc_html__('Question Groups', 'event_espresso');
436
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
437
-                'add_question_group',
438
-                'add_question_group',
439
-                array(),
440
-                'add-new-h2'
441
-            );
442
-        $this->display_admin_list_table_page_with_sidebar();
443
-    }
444
-
445
-
446
-    protected function _delete_question()
447
-    {
448
-        $success = $this->_delete_items($this->_question_model);
449
-        $this->_redirect_after_action(
450
-            $success,
451
-            $this->_question_model->item_name($success),
452
-            'deleted',
453
-            array('action' => 'default', 'status' => 'all')
454
-        );
455
-    }
456
-
457
-
458
-    protected function _delete_questions()
459
-    {
460
-        $success = $this->_delete_items($this->_question_model);
461
-        $this->_redirect_after_action(
462
-            $success,
463
-            $this->_question_model->item_name($success),
464
-            'deleted permanently',
465
-            array('action' => 'default', 'status' => 'trash')
466
-        );
467
-    }
468
-
469
-
470
-    /**
471
-     * Performs the deletion of a single or multiple questions or question groups.
472
-     *
473
-     * @param EEM_Soft_Delete_Base $model
474
-     * @return int number of items deleted permanently
475
-     */
476
-    private function _delete_items(EEM_Soft_Delete_Base $model)
477
-    {
478
-        $success = 0;
479
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
480
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
481
-            // if array has more than one element than success message should be plural
482
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
483
-            // cycle thru bulk action checkboxes
484
-            while (list($ID, $value) = each($this->_req_data['checkbox'])) {
485
-                if (! $this->_delete_item($ID, $model)) {
486
-                    $success = 0;
487
-                }
488
-            }
489
-
490
-        } elseif (! empty($this->_req_data['QSG_ID'])) {
491
-            $success = $this->_delete_item($this->_req_data['QSG_ID'], $model);
492
-
493
-        } elseif (! empty($this->_req_data['QST_ID'])) {
494
-            $success = $this->_delete_item($this->_req_data['QST_ID'], $model);
495
-        } else {
496
-            EE_Error::add_error(sprintf(esc_html__("No Questions or Question Groups were selected for deleting. This error usually shows when you've attempted to delete via bulk action but there were no selections.",
497
-                "event_espresso")), __FILE__, __FUNCTION__, __LINE__);
498
-        }
499
-        return $success;
500
-    }
501
-
502
-    /**
503
-     * Deletes the specified question (and its associated question options) or question group
504
-     *
505
-     * @param int                  $id
506
-     * @param EEM_Soft_Delete_Base $model
507
-     * @return boolean
508
-     */
509
-    protected function _delete_item($id, $model)
510
-    {
511
-        if ($model instanceof EEM_Question) {
512
-            EEM_Question_Option::instance()->delete_permanently(array(array('QST_ID' => absint($id))));
513
-        }
514
-        return $model->delete_permanently_by_ID(absint($id));
515
-    }
516
-
517
-
518
-    /******************************    QUESTION GROUPS    ******************************/
519
-
520
-
521
-    protected function _edit_question_group($type = 'add')
522
-    {
523
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
524
-        $ID = isset($this->_req_data['QSG_ID']) && ! empty($this->_req_data['QSG_ID']) ? absint($this->_req_data['QSG_ID']) : false;
525
-
526
-        switch ($this->_req_action) {
527
-            case 'add_question_group' :
528
-                $this->_admin_page_title = esc_html__('Add Question Group', 'event_espresso');
529
-                break;
530
-            case 'edit_question_group' :
531
-                $this->_admin_page_title = esc_html__('Edit Question Group', 'event_espresso');
532
-                break;
533
-            default :
534
-                $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
535
-        }
536
-        // add ID to title if editing
537
-        $this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
538
-        if ($ID) {
539
-            /** @var EE_Question_Group $questionGroup */
540
-            $questionGroup            = $this->_question_group_model->get_one_by_ID($ID);
541
-            $additional_hidden_fields = array('QSG_ID' => array('type' => 'hidden', 'value' => $ID));
542
-            $this->_set_add_edit_form_tags('update_question_group', $additional_hidden_fields);
543
-        } else {
544
-            /** @var EE_Question_Group $questionGroup */
545
-            $questionGroup = EEM_Question_Group::instance()->create_default_object();
546
-            $questionGroup->set_order_to_latest();
547
-            $this->_set_add_edit_form_tags('insert_question_group');
548
-        }
549
-        $this->_template_args['values']         = $this->_yes_no_values;
550
-        $this->_template_args['all_questions']  = $questionGroup->questions_in_and_not_in_group();
551
-        $this->_template_args['QSG_ID']         = $ID ? $ID : true;
552
-        $this->_template_args['question_group'] = $questionGroup;
553
-
554
-        $redirect_URL = add_query_arg(array('action' => 'question_groups'), $this->_admin_base_url);
555
-        $this->_set_publish_post_box_vars('id', $ID, false, $redirect_URL);
556
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'question_groups_main_meta_box.template.php',
557
-            $this->_template_args, true);
558
-
559
-        // the details template wrapper
560
-        $this->display_admin_page_with_sidebar();
561
-    }
562
-
563
-
564
-    protected function _delete_question_groups()
565
-    {
566
-        $success = $this->_delete_items($this->_question_group_model);
567
-        $this->_redirect_after_action($success, $this->_question_group_model->item_name($success),
568
-            'deleted permanently', array('action' => 'question_groups', 'status' => 'trash'));
569
-    }
570
-
571
-
572
-    /**
573
-     * @param bool $new_question_group
574
-     */
575
-    protected function _insert_or_update_question_group($new_question_group = true)
576
-    {
577
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
578
-        $set_column_values = $this->_set_column_values_for($this->_question_group_model);
579
-        if ($new_question_group) {
580
-            $QSG_ID  = $this->_question_group_model->insert($set_column_values);
581
-            $success = $QSG_ID ? 1 : 0;
582
-        } else {
583
-            $QSG_ID = absint($this->_req_data['QSG_ID']);
584
-            unset($set_column_values['QSG_ID']);
585
-            $success = $this->_question_group_model->update($set_column_values, array(array('QSG_ID' => $QSG_ID)));
586
-        }
587
-        $phone_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(EEM_Attendee::system_question_phone);
588
-        // update the existing related questions
589
-        // BUT FIRST...  delete the phone question from the Question_Group_Question if it is being added to this question group (therefore removed from the existing group)
590
-        if (isset($this->_req_data['questions'], $this->_req_data['questions'][$phone_question_id])) {
591
-            // delete where QST ID = system phone question ID and Question Group ID is NOT this group
592
-            EEM_Question_Group_Question::instance()->delete(array(
593
-                array(
594
-                    'QST_ID' => $phone_question_id,
595
-                    'QSG_ID' => array('!=', $QSG_ID),
596
-                ),
597
-            ));
598
-        }
599
-        /** @type EE_Question_Group $question_group */
600
-        $question_group = $this->_question_group_model->get_one_by_ID($QSG_ID);
601
-        $questions      = $question_group->questions();
602
-        // make sure system phone question is added to list of questions for this group
603
-        if (! isset($questions[$phone_question_id])) {
604
-            $questions[$phone_question_id] = EEM_Question::instance()->get_one_by_ID($phone_question_id);
605
-        }
606
-
607
-        foreach ($questions as $question_ID => $question) {
608
-            // first we always check for order.
609
-            if (! empty($this->_req_data['question_orders'][$question_ID])) {
610
-                //update question order
611
-                $question_group->update_question_order($question_ID, $this->_req_data['question_orders'][$question_ID]);
612
-            }
613
-
614
-            // then we always check if adding or removing.
615
-            if (isset($this->_req_data['questions'], $this->_req_data['questions'][$question_ID])) {
616
-                $question_group->add_question($question_ID);
617
-            } else {
618
-                // not found, remove it (but only if not a system question for the personal group with the exception of lname system question - we allow removal of it)
619
-                if (
620
-                in_array(
621
-                    $question->system_ID(),
622
-                    EEM_Question::instance()->required_system_questions_in_system_question_group($question_group->system_group())
623
-                )
624
-                ) {
625
-                    continue;
626
-                } else {
627
-                    $question_group->remove_question($question_ID);
628
-                }
629
-            }
630
-        }
631
-        // save new related questions
632
-        if (isset($this->_req_data['questions'])) {
633
-            foreach ($this->_req_data['questions'] as $QST_ID) {
634
-                $question_group->add_question($QST_ID);
635
-                if (isset($this->_req_data['question_orders'][$QST_ID])) {
636
-                    $question_group->update_question_order($QST_ID, $this->_req_data['question_orders'][$QST_ID]);
637
-                }
638
-            }
639
-        }
640
-
641
-        if ($success !== false) {
642
-            $msg = $new_question_group ? sprintf(esc_html__('The %s has been created', 'event_espresso'),
643
-                $this->_question_group_model->item_name()) : sprintf(esc_html__('The %s has been updated',
644
-                'event_espresso'), $this->_question_group_model->item_name());
645
-            EE_Error::add_success($msg);
646
-        }
647
-        $this->_redirect_after_action(false, '', '', array('action' => 'edit_question_group', 'QSG_ID' => $QSG_ID),
648
-            true);
649
-
650
-    }
651
-
652
-    /**
653
-     * duplicates a question and all its question options and redirects to the new question.
654
-     */
655
-    public function _duplicate_question()
656
-    {
657
-        $question_ID = (int)$this->_req_data['QST_ID'];
658
-        $question    = EEM_Question::instance()->get_one_by_ID($question_ID);
659
-        if ($question instanceof EE_Question) {
660
-            $new_question = $question->duplicate();
661
-            if ($new_question instanceof EE_Question) {
662
-                $this->_redirect_after_action(true, esc_html__('Question', 'event_espresso'),
663
-                    esc_html__('Duplicated', 'event_espresso'),
664
-                    array('action' => 'edit_question', 'QST_ID' => $new_question->ID()), true);
665
-            } else {
666
-                global $wpdb;
667
-                EE_Error::add_error(sprintf(esc_html__('Could not duplicate question with ID %1$d because: %2$s',
668
-                    'event_espresso'), $question_ID, $wpdb->last_error), __FILE__, __FUNCTION__, __LINE__);
669
-                $this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
670
-            }
671
-        } else {
672
-            EE_Error::add_error(sprintf(esc_html__('Could not duplicate question with ID %d because it didn\'t exist!',
673
-                'event_espresso'), $question_ID), __FILE__, __FUNCTION__, __LINE__);
674
-            $this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
675
-        }
676
-    }
677
-
678
-
679
-    /**
680
-     * @param bool $trash
681
-     */
682
-    protected function _trash_or_restore_question_groups($trash = true)
683
-    {
684
-        $this->_trash_or_restore_items($this->_question_group_model, $trash);
685
-    }
686
-
687
-
688
-    /**
689
-     *_trash_question
690
-     */
691
-    protected function _trash_question()
692
-    {
693
-        $success    = $this->_question_model->delete_by_ID((int)$this->_req_data['QST_ID']);
694
-        $query_args = array('action' => 'default', 'status' => 'all');
695
-        $this->_redirect_after_action($success, $this->_question_model->item_name($success), 'trashed', $query_args);
696
-    }
697
-
698
-
699
-    /**
700
-     * @param bool $trash
701
-     */
702
-    protected function _trash_or_restore_questions($trash = true)
703
-    {
704
-        $this->_trash_or_restore_items($this->_question_model, $trash);
705
-    }
706
-
707
-
708
-    /**
709
-     * Internally used to delete or restore items, using the request data. Meant to be
710
-     * flexible between question or question groups
711
-     *
712
-     * @param EEM_Soft_Delete_Base $model
713
-     * @param boolean              $trash whether to trash or restore
714
-     */
715
-    private function _trash_or_restore_items(EEM_Soft_Delete_Base $model, $trash = true)
716
-    {
717
-
718
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
719
-
720
-        $success = 1;
721
-        //Checkboxes
722
-        //echo "trash $trash";
723
-        //var_dump($this->_req_data['checkbox']);die;
724
-        if (isset($this->_req_data['checkbox'])) {
725
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
726
-                // if array has more than one element than success message should be plural
727
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
728
-                // cycle thru bulk action checkboxes
729
-                while (list($ID, $value) = each($this->_req_data['checkbox'])) {
730
-                    if (! $model->delete_or_restore_by_ID($trash, absint($ID))) {
731
-                        $success = 0;
732
-                    }
733
-                }
734
-
735
-            } else {
736
-                // grab single id and delete
737
-                $ID = absint($this->_req_data['checkbox']);
738
-                if (! $model->delete_or_restore_by_ID($trash, $ID)) {
739
-                    $success = 0;
740
-                }
741
-            }
742
-
743
-        } else {
744
-            // delete via trash link
745
-            // grab single id and delete
746
-            $ID = absint($this->_req_data[$model->primary_key_name()]);
747
-            if (! $model->delete_or_restore_by_ID($trash, $ID)) {
748
-                $success = 0;
749
-            }
750
-
751
-        }
752
-
753
-
754
-        $action = $model instanceof EEM_Question ? 'default' : 'question_groups';//strtolower( $model->item_name(2) );
755
-        //echo "action :$action";
756
-        //$action = 'questions' ? 'default' : $action;
757
-        if ($trash) {
758
-            $action_desc = 'trashed';
759
-            $status      = 'trash';
760
-        } else {
761
-            $action_desc = 'restored';
762
-            $status      = 'all';
763
-        }
764
-        $this->_redirect_after_action($success, $model->item_name($success), $action_desc,
765
-            array('action' => $action, 'status' => $status));
766
-    }
767
-
768
-
769
-    /**
770
-     * @param            $per_page
771
-     * @param int        $current_page
772
-     * @param bool|false $count
773
-     * @return \EE_Soft_Delete_Base_Class[]|int
774
-     */
775
-    public function get_trashed_questions($per_page, $current_page = 1, $count = false)
776
-    {
777
-        $query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
778
-
779
-        if ($count) {
780
-            //note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
781
-            $where   = isset($query_params[0]) ? array($query_params[0]) : array();
782
-            $results = $this->_question_model->count_deleted($where);
783
-        } else {
784
-            //note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
785
-            $results = $this->_question_model->get_all_deleted($query_params);
786
-        }
787
-        return $results;
788
-    }
789
-
790
-
791
-    /**
792
-     * @param            $per_page
793
-     * @param int        $current_page
794
-     * @param bool|false $count
795
-     * @return \EE_Soft_Delete_Base_Class[]
796
-     */
797
-    public function get_question_groups($per_page, $current_page = 1, $count = false)
798
-    {
799
-        $questionGroupModel = EEM_Question_Group::instance();
800
-        $query_params       = $this->get_query_params($questionGroupModel, $per_page, $current_page);
801
-        if ($count) {
802
-            $where   = isset($query_params[0]) ? array($query_params[0]) : array();
803
-            $results = $questionGroupModel->count($where);
804
-        } else {
805
-            $results = $questionGroupModel->get_all($query_params);
806
-        }
807
-        return $results;
808
-    }
809
-
810
-
811
-    /**
812
-     * @param      $per_page
813
-     * @param int  $current_page
814
-     * @param bool $count
815
-     * @return \EE_Soft_Delete_Base_Class[]|int
816
-     */
817
-    public function get_trashed_question_groups($per_page, $current_page = 1, $count = false)
818
-    {
819
-        $questionGroupModel = EEM_Question_Group::instance();
820
-        $query_params       = $this->get_query_params($questionGroupModel, $per_page, $current_page);
821
-        if ($count) {
822
-            $where                 = isset($query_params[0]) ? array($query_params[0]) : array();
823
-            $query_params['limit'] = null;
824
-            $results               = $questionGroupModel->count_deleted($where);
825
-        } else {
826
-            $results = $questionGroupModel->get_all_deleted($query_params);
827
-        }
828
-        return $results;
829
-    }
830
-
831
-
832
-    /**
833
-     * method for performing updates to question order
834
-     *
835
-     * @return array results array
836
-     */
837
-    public function update_question_group_order()
838
-    {
839
-
840
-        $success = esc_html__('Question group order was updated successfully.', 'event_espresso');
841
-
842
-        // grab our row IDs
843
-        $row_ids = isset($this->_req_data['row_ids']) && ! empty($this->_req_data['row_ids'])
844
-            ? explode(',', rtrim($this->_req_data['row_ids'], ','))
845
-            : array();
846
-
847
-        $perpage = ! empty($this->_req_data['perpage'])
848
-            ? (int)$this->_req_data['perpage']
849
-            : null;
850
-        $curpage = ! empty($this->_req_data['curpage'])
851
-            ? (int)$this->_req_data['curpage']
852
-            : null;
853
-
854
-        if (! empty($row_ids)) {
855
-            //figure out where we start the row_id count at for the current page.
856
-            $qsgcount = empty($curpage) ? 0 : ($curpage - 1) * $perpage;
857
-
858
-            $row_count = count($row_ids);
859
-            for ($i = 0; $i < $row_count; $i++) {
860
-                //Update the questions when re-ordering
861
-                $updated = EEM_Question_Group::instance()->update(
862
-                    array('QSG_order' => $qsgcount),
863
-                    array(array('QSG_ID' => $row_ids[$i]))
864
-                );
865
-                if ($updated === false) {
866
-                    $success = false;
867
-                }
868
-                $qsgcount++;
869
-            }
870
-        } else {
871
-            $success = false;
872
-        }
873
-
874
-        $errors = ! $success
875
-            ? esc_html__('An error occurred. The question group order was not updated.', 'event_espresso')
876
-            : false;
877
-
878
-        echo wp_json_encode(array('return_data' => false, 'success' => $success, 'errors' => $errors));
879
-        die();
880
-
881
-    }
882
-
883
-
884
-
885
-    /***************************************        REGISTRATION SETTINGS        ***************************************/
886
-
887
-
888
-    /**
889
-     * _reg_form_settings
890
-     *
891
-     * @throws \EE_Error
892
-     */
893
-    protected function _reg_form_settings()
894
-    {
895
-        $this->_template_args['values'] = $this->_yes_no_values;
896
-        add_action(
897
-            'AHEE__Extend_Registration_Form_Admin_Page___reg_form_settings_template',
898
-            array($this, 'email_validation_settings_form'),
899
-            2
900
-        );
901
-        $this->_template_args = (array)apply_filters(
902
-            'FHEE__Extend_Registration_Form_Admin_Page___reg_form_settings___template_args',
903
-            $this->_template_args
904
-        );
905
-        $this->_set_add_edit_form_tags('update_reg_form_settings');
906
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
907
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
908
-            REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'reg_form_settings.template.php',
909
-            $this->_template_args,
910
-            true
911
-        );
912
-        $this->display_admin_page_with_sidebar();
913
-    }
914
-
915
-
916
-    /**
917
-     * _update_reg_form_settings
918
-     */
919
-    protected function _update_reg_form_settings()
920
-    {
921
-        EE_Registry::instance()->CFG->registration = $this->update_email_validation_settings_form(
922
-            EE_Registry::instance()->CFG->registration
923
-        );
924
-        EE_Registry::instance()->CFG->registration = apply_filters(
925
-            'FHEE__Extend_Registration_Form_Admin_Page___update_reg_form_settings__CFG_registration',
926
-            EE_Registry::instance()->CFG->registration
927
-        );
928
-        $success                                   = $this->_update_espresso_configuration(
929
-            esc_html__('Registration Form Options', 'event_espresso'),
930
-            EE_Registry::instance()->CFG,
931
-            __FILE__, __FUNCTION__, __LINE__
932
-        );
933
-        $this->_redirect_after_action($success, esc_html__('Registration Form Options', 'event_espresso'), 'updated',
934
-            array('action' => 'view_reg_form_settings'));
935
-    }
936
-
937
-
938
-    /**
939
-     * email_validation_settings_form
940
-     *
941
-     * @access    public
942
-     * @return    void
943
-     * @throws \EE_Error
944
-     */
945
-    public function email_validation_settings_form()
946
-    {
947
-        echo $this->_email_validation_settings_form()->get_html();
948
-    }
949
-
950
-
951
-    /**
952
-     * _email_validation_settings_form
953
-     *
954
-     * @access protected
955
-     * @return EE_Form_Section_Proper
956
-     * @throws \EE_Error
957
-     */
958
-    protected function _email_validation_settings_form()
959
-    {
960
-        return new EE_Form_Section_Proper(
961
-            array(
962
-                'name'            => 'email_validation_settings',
963
-                'html_id'         => 'email_validation_settings',
964
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
965
-                'subsections'     => apply_filters(
966
-                    'FHEE__Extend_Registration_Form_Admin_Page___email_validation_settings_form__form_subsections',
967
-                    array(
968
-                        'email_validation_hdr'   => new EE_Form_Section_HTML(
969
-                            EEH_HTML::h2(esc_html__('Email Validation Settings', 'event_espresso'))
970
-                        ),
971
-                        'email_validation_level' => new EE_Select_Input(
972
-                            array(
973
-                                'basic'      => esc_html__('Basic', 'event_espresso'),
974
-                                'wp_default' => esc_html__('WordPress Default', 'event_espresso'),
975
-                                'i18n'       => esc_html__('International', 'event_espresso'),
976
-                                'i18n_dns'   => esc_html__('International + DNS Check', 'event_espresso'),
977
-                            ),
978
-                            array(
979
-                                'html_label_text' => esc_html__('Email Validation Level', 'event_espresso')
980
-                                                     . EEH_Template::get_help_tab_link('email_validation_info'),
981
-                                'html_help_text'  => esc_html__('These levels range from basic validation ( ie: [email protected] ) to more advanced checks against international email addresses (ie: üñîçøðé@example.com ) with additional MX and A record checks to confirm the domain actually exists. More information on on each level can be found within the help section.',
982
-                                    'event_espresso'),
983
-                                'default'         => isset(EE_Registry::instance()->CFG->registration->email_validation_level)
984
-                                    ? EE_Registry::instance()->CFG->registration->email_validation_level
985
-                                    : 'wp_default',
986
-                                'required'        => false,
987
-                            )
988
-                        ),
989
-                    )
990
-                ),
991
-            )
992
-        );
993
-    }
994
-
995
-
996
-    /**
997
-     * update_email_validation_settings_form
998
-     *
999
-     * @access    public
1000
-     * @param \EE_Registration_Config $EE_Registration_Config
1001
-     * @return \EE_Registration_Config
1002
-     */
1003
-    public function update_email_validation_settings_form(EE_Registration_Config $EE_Registration_Config)
1004
-    {
1005
-        $prev_email_validation_level = $EE_Registration_Config->email_validation_level;
1006
-        try {
1007
-            $email_validation_settings_form = $this->_email_validation_settings_form();
1008
-            // if not displaying a form, then check for form submission
1009
-            if ($email_validation_settings_form->was_submitted()) {
1010
-                // capture form data
1011
-                $email_validation_settings_form->receive_form_submission();
1012
-                // validate form data
1013
-                if ($email_validation_settings_form->is_valid()) {
1014
-                    // grab validated data from form
1015
-                    $valid_data = $email_validation_settings_form->valid_data();
1016
-                    if (isset($valid_data['email_validation_level'])) {
1017
-                        $email_validation_level = $valid_data['email_validation_level'];
1018
-                        // now if they want to use international email addresses
1019
-                        if ($email_validation_level === 'i18n' || $email_validation_level === 'i18n_dns') {
1020
-                            // in case we need to reset their email validation level,
1021
-                            // make sure that the previous value wasn't already set to one of the i18n options.
1022
-                            if ($prev_email_validation_level === 'i18n' || $prev_email_validation_level === 'i18n_dns') {
1023
-                                // if so, then reset it back to "basic" since that is the only other option that,
1024
-                                // despite offering poor validation, supports i18n email addresses
1025
-                                $prev_email_validation_level = 'basic';
1026
-                            }
1027
-                            // confirm our i18n email validation will work on the server
1028
-                            if (! $this->_verify_pcre_support($EE_Registration_Config, $email_validation_level)) {
1029
-                                // or reset email validation level to previous value
1030
-                                $email_validation_level = $prev_email_validation_level;
1031
-                            }
1032
-                        }
1033
-                        $EE_Registration_Config->email_validation_level = $email_validation_level;
1034
-                    } else {
1035
-                        EE_Error::add_error(
1036
-                            esc_html__(
1037
-                                'Invalid or missing Email Validation settings. Please refresh the form and try again.',
1038
-                                'event_espresso'
1039
-                            ),
1040
-                            __FILE__, __FUNCTION__, __LINE__
1041
-                        );
1042
-                    }
1043
-                } else {
1044
-                    if ($email_validation_settings_form->submission_error_message() !== '') {
1045
-                        EE_Error::add_error(
1046
-                            $email_validation_settings_form->submission_error_message(),
1047
-                            __FILE__, __FUNCTION__, __LINE__
1048
-                        );
1049
-                    }
1050
-                }
1051
-            }
1052
-        } catch (EE_Error $e) {
1053
-            $e->get_error();
1054
-        }
1055
-        return $EE_Registration_Config;
1056
-    }
1057
-
1058
-
1059
-    /**
1060
-     * confirms that the server's PHP version has the PCRE module enabled,
1061
-     * and that the PCRE version works with our i18n email validation
1062
-     *
1063
-     * @param \EE_Registration_Config $EE_Registration_Config
1064
-     * @param string                  $email_validation_level
1065
-     * @return bool
1066
-     */
1067
-    private function _verify_pcre_support(EE_Registration_Config $EE_Registration_Config, $email_validation_level)
1068
-    {
1069
-        // first check that PCRE is enabled
1070
-        if (! defined('PREG_BAD_UTF8_ERROR')) {
1071
-            EE_Error::add_error(
1072
-                sprintf(
1073
-                    esc_html__(
1074
-                        'We\'re sorry, but it appears that your server\'s version of PHP was not compiled with PCRE unicode support.%1$sPlease contact your hosting company and ask them whether the PCRE compiled with your version of PHP on your server can be been built with the "--enable-unicode-properties" and "--enable-utf8" configuration switches to enable more complex regex expressions.%1$sIf they are unable, or unwilling to do so, then your server will not support international email addresses using UTF-8 unicode characters. This means you will either have to lower your email validation level to "Basic" or "WordPress Default", or switch to a hosting company that has/can enable PCRE unicode support on the server.',
1075
-                        'event_espresso'
1076
-                    ),
1077
-                    '<br />'
1078
-                ),
1079
-                __FILE__,
1080
-                __FUNCTION__,
1081
-                __LINE__
1082
-            );
1083
-            return false;
1084
-        } else {
1085
-            // PCRE support is enabled, but let's still
1086
-            // perform a test to see if the server will support it.
1087
-            // but first, save the updated validation level to the config,
1088
-            // so that the validation strategy picks it up.
1089
-            // this will get bumped back down if it doesn't work
1090
-            $EE_Registration_Config->email_validation_level = $email_validation_level;
1091
-            try {
1092
-                $email_validator    = new EE_Email_Validation_Strategy();
1093
-                $i18n_email_address = apply_filters(
1094
-                    'FHEE__Extend_Registration_Form_Admin_Page__update_email_validation_settings_form__i18n_email_address',
1095
-                    'jägerjü[email protected]'
1096
-                );
1097
-                $email_validator->validate($i18n_email_address);
1098
-            } catch (Exception $e) {
1099
-                EE_Error::add_error(
1100
-                    sprintf(
1101
-                        esc_html__(
1102
-                            'We\'re sorry, but it appears that your server\'s configuration will not support the "International" or "International + DNS Check" email validation levels.%1$sTo correct this issue, please consult with your hosting company regarding your server\'s PCRE settings.%1$sIt is recommended that your PHP version be configured to use PCRE 8.10 or newer.%1$sMore information regarding PCRE versions and installation can be found here: %2$s',
1103
-                            'event_espresso'
1104
-                        ),
1105
-                        '<br />',
1106
-                        '<a href="http://php.net/manual/en/pcre.installation.php" target="_blank">http://php.net/manual/en/pcre.installation.php</a>'
1107
-                    ),
1108
-                    __FILE__, __FUNCTION__, __LINE__
1109
-                );
1110
-                return false;
1111
-            }
1112
-        }
1113
-        return true;
1114
-    }
28
+	/**
29
+	 * @Constructor
30
+	 * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
31
+	 * @access public
32
+	 */
33
+	public function __construct($routing = true)
34
+	{
35
+		define('REGISTRATION_FORM_CAF_ADMIN', EE_CORE_CAF_ADMIN_EXTEND . 'registration_form' . DS);
36
+		define('REGISTRATION_FORM_CAF_ASSETS_PATH', REGISTRATION_FORM_CAF_ADMIN . 'assets' . DS);
37
+		define('REGISTRATION_FORM_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/assets/');
38
+		define('REGISTRATION_FORM_CAF_TEMPLATE_PATH', REGISTRATION_FORM_CAF_ADMIN . 'templates' . DS);
39
+		define('REGISTRATION_FORM_CAF_TEMPLATE_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registration_form/templates/');
40
+		parent::__construct($routing);
41
+	}
42
+
43
+
44
+	protected function _extend_page_config()
45
+	{
46
+		$this->_admin_base_path = REGISTRATION_FORM_CAF_ADMIN;
47
+		$qst_id = ! empty($this->_req_data['QST_ID']) && ! is_array($this->_req_data['QST_ID']) ? $this->_req_data['QST_ID'] : 0;
48
+		$qsg_id = ! empty($this->_req_data['QSG_ID']) && ! is_array($this->_req_data['QSG_ID']) ? $this->_req_data['QSG_ID'] : 0;
49
+
50
+		$new_page_routes    = array(
51
+			'question_groups'    => array(
52
+				'func'       => '_question_groups_overview_list_table',
53
+				'capability' => 'ee_read_question_groups',
54
+			),
55
+			'add_question'       => array(
56
+				'func'       => '_edit_question',
57
+				'capability' => 'ee_edit_questions',
58
+			),
59
+			'insert_question'    => array(
60
+				'func'       => '_insert_or_update_question',
61
+				'args'       => array('new_question' => true),
62
+				'capability' => 'ee_edit_questions',
63
+				'noheader'   => true,
64
+			),
65
+			'duplicate_question' => array(
66
+				'func'       => '_duplicate_question',
67
+				'capability' => 'ee_edit_questions',
68
+				'noheader'   => true,
69
+			),
70
+			'trash_question'     => array(
71
+				'func'       => '_trash_question',
72
+				'capability' => 'ee_delete_question',
73
+				'obj_id'     => $qst_id,
74
+				'noheader'   => true,
75
+			),
76
+
77
+			'restore_question' => array(
78
+				'func'       => '_trash_or_restore_questions',
79
+				'capability' => 'ee_delete_question',
80
+				'obj_id'     => $qst_id,
81
+				'args'       => array('trash' => false),
82
+				'noheader'   => true,
83
+			),
84
+
85
+			'delete_question' => array(
86
+				'func'       => '_delete_question',
87
+				'capability' => 'ee_delete_question',
88
+				'obj_id'     => $qst_id,
89
+				'noheader'   => true,
90
+			),
91
+
92
+			'trash_questions' => array(
93
+				'func'       => '_trash_or_restore_questions',
94
+				'capability' => 'ee_delete_questions',
95
+				'args'       => array('trash' => true),
96
+				'noheader'   => true,
97
+			),
98
+
99
+			'restore_questions' => array(
100
+				'func'       => '_trash_or_restore_questions',
101
+				'capability' => 'ee_delete_questions',
102
+				'args'       => array('trash' => false),
103
+				'noheader'   => true,
104
+			),
105
+
106
+			'delete_questions' => array(
107
+				'func'       => '_delete_questions',
108
+				'args'       => array(),
109
+				'capability' => 'ee_delete_questions',
110
+				'noheader'   => true,
111
+			),
112
+
113
+			'add_question_group' => array(
114
+				'func'       => '_edit_question_group',
115
+				'capability' => 'ee_edit_question_groups',
116
+			),
117
+
118
+			'edit_question_group' => array(
119
+				'func'       => '_edit_question_group',
120
+				'capability' => 'ee_edit_question_group',
121
+				'obj_id'     => $qsg_id,
122
+				'args'       => array('edit'),
123
+			),
124
+
125
+			'delete_question_groups' => array(
126
+				'func'       => '_delete_question_groups',
127
+				'capability' => 'ee_delete_question_groups',
128
+				'noheader'   => true,
129
+			),
130
+
131
+			'delete_question_group' => array(
132
+				'func'       => '_delete_question_groups',
133
+				'capability' => 'ee_delete_question_group',
134
+				'obj_id'     => $qsg_id,
135
+				'noheader'   => true,
136
+			),
137
+
138
+			'trash_question_group' => array(
139
+				'func'       => '_trash_or_restore_question_groups',
140
+				'args'       => array('trash' => true),
141
+				'capability' => 'ee_delete_question_group',
142
+				'obj_id'     => $qsg_id,
143
+				'noheader'   => true,
144
+			),
145
+
146
+			'restore_question_group' => array(
147
+				'func'       => '_trash_or_restore_question_groups',
148
+				'args'       => array('trash' => false),
149
+				'capability' => 'ee_delete_question_group',
150
+				'obj_id'     => $qsg_id,
151
+				'noheader'   => true,
152
+			),
153
+
154
+			'insert_question_group' => array(
155
+				'func'       => '_insert_or_update_question_group',
156
+				'args'       => array('new_question_group' => true),
157
+				'capability' => 'ee_edit_question_groups',
158
+				'noheader'   => true,
159
+			),
160
+
161
+			'update_question_group' => array(
162
+				'func'       => '_insert_or_update_question_group',
163
+				'args'       => array('new_question_group' => false),
164
+				'capability' => 'ee_edit_question_group',
165
+				'obj_id'     => $qsg_id,
166
+				'noheader'   => true,
167
+			),
168
+
169
+			'trash_question_groups' => array(
170
+				'func'       => '_trash_or_restore_question_groups',
171
+				'args'       => array('trash' => true),
172
+				'capability' => 'ee_delete_question_groups',
173
+				'noheader'   => array('trash' => false),
174
+			),
175
+
176
+			'restore_question_groups' => array(
177
+				'func'       => '_trash_or_restore_question_groups',
178
+				'args'       => array('trash' => false),
179
+				'capability' => 'ee_delete_question_groups',
180
+				'noheader'   => true,
181
+			),
182
+
183
+
184
+			'espresso_update_question_group_order' => array(
185
+				'func'       => 'update_question_group_order',
186
+				'capability' => 'ee_edit_question_groups',
187
+				'noheader'   => true,
188
+			),
189
+
190
+			'view_reg_form_settings' => array(
191
+				'func'       => '_reg_form_settings',
192
+				'capability' => 'manage_options',
193
+			),
194
+
195
+			'update_reg_form_settings' => array(
196
+				'func'       => '_update_reg_form_settings',
197
+				'capability' => 'manage_options',
198
+				'noheader'   => true,
199
+			),
200
+		);
201
+		$this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
202
+
203
+		$new_page_config    = array(
204
+
205
+			'question_groups' => array(
206
+				'nav'           => array(
207
+					'label' => esc_html__('Question Groups', 'event_espresso'),
208
+					'order' => 20,
209
+				),
210
+				'list_table'    => 'Registration_Form_Question_Groups_Admin_List_Table',
211
+				'help_tabs'     => array(
212
+					'registration_form_question_groups_help_tab'                           => array(
213
+						'title'    => esc_html__('Question Groups', 'event_espresso'),
214
+						'filename' => 'registration_form_question_groups',
215
+					),
216
+					'registration_form_question_groups_table_column_headings_help_tab'     => array(
217
+						'title'    => esc_html__('Question Groups Table Column Headings', 'event_espresso'),
218
+						'filename' => 'registration_form_question_groups_table_column_headings',
219
+					),
220
+					'registration_form_question_groups_views_bulk_actions_search_help_tab' => array(
221
+						'title'    => esc_html__('Question Groups Views & Bulk Actions & Search', 'event_espresso'),
222
+						'filename' => 'registration_form_question_groups_views_bulk_actions_search',
223
+					),
224
+				),
225
+				'help_tour'     => array('Registration_Form_Question_Groups_Help_Tour'),
226
+				'metaboxes'     => $this->_default_espresso_metaboxes,
227
+				'require_nonce' => false,
228
+				'qtips'         => array(
229
+					'EE_Registration_Form_Tips',
230
+				),
231
+			),
232
+
233
+			'add_question' => array(
234
+				'nav'           => array(
235
+					'label'      => esc_html__('Add Question', 'event_espresso'),
236
+					'order'      => 5,
237
+					'persistent' => false,
238
+				),
239
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
240
+				'help_tabs'     => array(
241
+					'registration_form_add_question_help_tab' => array(
242
+						'title'    => esc_html__('Add Question', 'event_espresso'),
243
+						'filename' => 'registration_form_add_question',
244
+					),
245
+				),
246
+				'help_tour'     => array('Registration_Form_Add_Question_Help_Tour'),
247
+				'require_nonce' => false,
248
+			),
249
+
250
+			'add_question_group' => array(
251
+				'nav'           => array(
252
+					'label'      => esc_html__('Add Question Group', 'event_espresso'),
253
+					'order'      => 5,
254
+					'persistent' => false,
255
+				),
256
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
257
+				'help_tabs'     => array(
258
+					'registration_form_add_question_group_help_tab' => array(
259
+						'title'    => esc_html__('Add Question Group', 'event_espresso'),
260
+						'filename' => 'registration_form_add_question_group',
261
+					),
262
+				),
263
+				'help_tour'     => array('Registration_Form_Add_Question_Group_Help_Tour'),
264
+				'require_nonce' => false,
265
+			),
266
+
267
+			'edit_question_group' => array(
268
+				'nav'           => array(
269
+					'label'      => esc_html__('Edit Question Group', 'event_espresso'),
270
+					'order'      => 5,
271
+					'persistent' => false,
272
+					'url'        => isset($this->_req_data['question_group_id']) ? add_query_arg(array('question_group_id' => $this->_req_data['question_group_id']),
273
+						$this->_current_page_view_url) : $this->_admin_base_url,
274
+				),
275
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
276
+				'help_tabs'     => array(
277
+					'registration_form_edit_question_group_help_tab' => array(
278
+						'title'    => esc_html__('Edit Question Group', 'event_espresso'),
279
+						'filename' => 'registration_form_edit_question_group',
280
+					),
281
+				),
282
+				'help_tour'     => array('Registration_Form_Edit_Question_Group_Help_Tour'),
283
+				'require_nonce' => false,
284
+			),
285
+
286
+			'view_reg_form_settings' => array(
287
+				'nav'           => array(
288
+					'label' => esc_html__('Reg Form Settings', 'event_espresso'),
289
+					'order' => 40,
290
+				),
291
+				'labels'        => array(
292
+					'publishbox' => esc_html__('Update Settings', 'event_espresso'),
293
+				),
294
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
295
+				'help_tabs'     => array(
296
+					'registration_form_reg_form_settings_help_tab' => array(
297
+						'title'    => esc_html__('Registration Form Settings', 'event_espresso'),
298
+						'filename' => 'registration_form_reg_form_settings',
299
+					),
300
+				),
301
+				'help_tour'     => array('Registration_Form_Settings_Help_Tour'),
302
+				'require_nonce' => false,
303
+			),
304
+
305
+		);
306
+		$this->_page_config = array_merge($this->_page_config, $new_page_config);
307
+
308
+		//change the list table we're going to use so it's the NEW list table!
309
+		$this->_page_config['default']['list_table'] = 'Extend_Registration_Form_Questions_Admin_List_Table';
310
+
311
+
312
+		//additional labels
313
+		$new_labels               = array(
314
+			'add_question'          => esc_html__('Add New Question', 'event_espresso'),
315
+			'delete_question'       => esc_html__('Delete Question', 'event_espresso'),
316
+			'add_question_group'    => esc_html__('Add New Question Group', 'event_espresso'),
317
+			'edit_question_group'   => esc_html__('Edit Question Group', 'event_espresso'),
318
+			'delete_question_group' => esc_html__('Delete Question Group', 'event_espresso'),
319
+		);
320
+		$this->_labels['buttons'] = array_merge($this->_labels['buttons'], $new_labels);
321
+
322
+	}
323
+
324
+
325
+	protected function _ajax_hooks()
326
+	{
327
+		add_action('wp_ajax_espresso_update_question_group_order', array($this, 'update_question_group_order'));
328
+	}
329
+
330
+
331
+	public function load_scripts_styles_question_groups()
332
+	{
333
+		wp_enqueue_script('espresso_ajax_table_sorting');
334
+	}
335
+
336
+
337
+	public function load_scripts_styles_add_question_group()
338
+	{
339
+		$this->load_scripts_styles_forms();
340
+		$this->load_sortable_question_script();
341
+	}
342
+
343
+	public function load_scripts_styles_edit_question_group()
344
+	{
345
+		$this->load_scripts_styles_forms();
346
+		$this->load_sortable_question_script();
347
+	}
348
+
349
+
350
+	/**
351
+	 * registers and enqueues script for questions
352
+	 *
353
+	 * @return void
354
+	 */
355
+	public function load_sortable_question_script()
356
+	{
357
+		wp_register_script('ee-question-sortable', REGISTRATION_FORM_CAF_ASSETS_URL . 'ee_question_order.js',
358
+			array('jquery-ui-sortable'), EVENT_ESPRESSO_VERSION, true);
359
+		wp_enqueue_script('ee-question-sortable');
360
+	}
361
+
362
+
363
+	protected function _set_list_table_views_default()
364
+	{
365
+		$this->_views = array(
366
+			'all' => array(
367
+				'slug'        => 'all',
368
+				'label'       => esc_html__('View All Questions', 'event_espresso'),
369
+				'count'       => 0,
370
+				'bulk_action' => array(
371
+					'trash_questions' => esc_html__('Trash', 'event_espresso'),
372
+				),
373
+			),
374
+		);
375
+
376
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_questions',
377
+			'espresso_registration_form_trash_questions')
378
+		) {
379
+			$this->_views['trash'] = array(
380
+				'slug'        => 'trash',
381
+				'label'       => esc_html__('Trash', 'event_espresso'),
382
+				'count'       => 0,
383
+				'bulk_action' => array(
384
+					'delete_questions'  => esc_html__('Delete Permanently', 'event_espresso'),
385
+					'restore_questions' => esc_html__('Restore', 'event_espresso'),
386
+				),
387
+			);
388
+		}
389
+	}
390
+
391
+
392
+	protected function _set_list_table_views_question_groups()
393
+	{
394
+		$this->_views = array(
395
+			'all' => array(
396
+				'slug'        => 'all',
397
+				'label'       => esc_html__('All', 'event_espresso'),
398
+				'count'       => 0,
399
+				'bulk_action' => array(
400
+					'trash_question_groups' => esc_html__('Trash', 'event_espresso'),
401
+				),
402
+			),
403
+		);
404
+
405
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_question_groups',
406
+			'espresso_registration_form_trash_question_groups')
407
+		) {
408
+			$this->_views['trash'] = array(
409
+				'slug'        => 'trash',
410
+				'label'       => esc_html__('Trash', 'event_espresso'),
411
+				'count'       => 0,
412
+				'bulk_action' => array(
413
+					'delete_question_groups'  => esc_html__('Delete Permanently', 'event_espresso'),
414
+					'restore_question_groups' => esc_html__('Restore', 'event_espresso'),
415
+				),
416
+			);
417
+		}
418
+	}
419
+
420
+
421
+	protected function _questions_overview_list_table()
422
+	{
423
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
424
+				'add_question',
425
+				'add_question',
426
+				array(),
427
+				'add-new-h2'
428
+			);
429
+		parent::_questions_overview_list_table();
430
+	}
431
+
432
+
433
+	protected function _question_groups_overview_list_table()
434
+	{
435
+		$this->_search_btn_label = esc_html__('Question Groups', 'event_espresso');
436
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
437
+				'add_question_group',
438
+				'add_question_group',
439
+				array(),
440
+				'add-new-h2'
441
+			);
442
+		$this->display_admin_list_table_page_with_sidebar();
443
+	}
444
+
445
+
446
+	protected function _delete_question()
447
+	{
448
+		$success = $this->_delete_items($this->_question_model);
449
+		$this->_redirect_after_action(
450
+			$success,
451
+			$this->_question_model->item_name($success),
452
+			'deleted',
453
+			array('action' => 'default', 'status' => 'all')
454
+		);
455
+	}
456
+
457
+
458
+	protected function _delete_questions()
459
+	{
460
+		$success = $this->_delete_items($this->_question_model);
461
+		$this->_redirect_after_action(
462
+			$success,
463
+			$this->_question_model->item_name($success),
464
+			'deleted permanently',
465
+			array('action' => 'default', 'status' => 'trash')
466
+		);
467
+	}
468
+
469
+
470
+	/**
471
+	 * Performs the deletion of a single or multiple questions or question groups.
472
+	 *
473
+	 * @param EEM_Soft_Delete_Base $model
474
+	 * @return int number of items deleted permanently
475
+	 */
476
+	private function _delete_items(EEM_Soft_Delete_Base $model)
477
+	{
478
+		$success = 0;
479
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
480
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
481
+			// if array has more than one element than success message should be plural
482
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
483
+			// cycle thru bulk action checkboxes
484
+			while (list($ID, $value) = each($this->_req_data['checkbox'])) {
485
+				if (! $this->_delete_item($ID, $model)) {
486
+					$success = 0;
487
+				}
488
+			}
489
+
490
+		} elseif (! empty($this->_req_data['QSG_ID'])) {
491
+			$success = $this->_delete_item($this->_req_data['QSG_ID'], $model);
492
+
493
+		} elseif (! empty($this->_req_data['QST_ID'])) {
494
+			$success = $this->_delete_item($this->_req_data['QST_ID'], $model);
495
+		} else {
496
+			EE_Error::add_error(sprintf(esc_html__("No Questions or Question Groups were selected for deleting. This error usually shows when you've attempted to delete via bulk action but there were no selections.",
497
+				"event_espresso")), __FILE__, __FUNCTION__, __LINE__);
498
+		}
499
+		return $success;
500
+	}
501
+
502
+	/**
503
+	 * Deletes the specified question (and its associated question options) or question group
504
+	 *
505
+	 * @param int                  $id
506
+	 * @param EEM_Soft_Delete_Base $model
507
+	 * @return boolean
508
+	 */
509
+	protected function _delete_item($id, $model)
510
+	{
511
+		if ($model instanceof EEM_Question) {
512
+			EEM_Question_Option::instance()->delete_permanently(array(array('QST_ID' => absint($id))));
513
+		}
514
+		return $model->delete_permanently_by_ID(absint($id));
515
+	}
516
+
517
+
518
+	/******************************    QUESTION GROUPS    ******************************/
519
+
520
+
521
+	protected function _edit_question_group($type = 'add')
522
+	{
523
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
524
+		$ID = isset($this->_req_data['QSG_ID']) && ! empty($this->_req_data['QSG_ID']) ? absint($this->_req_data['QSG_ID']) : false;
525
+
526
+		switch ($this->_req_action) {
527
+			case 'add_question_group' :
528
+				$this->_admin_page_title = esc_html__('Add Question Group', 'event_espresso');
529
+				break;
530
+			case 'edit_question_group' :
531
+				$this->_admin_page_title = esc_html__('Edit Question Group', 'event_espresso');
532
+				break;
533
+			default :
534
+				$this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
535
+		}
536
+		// add ID to title if editing
537
+		$this->_admin_page_title = $ID ? $this->_admin_page_title . ' # ' . $ID : $this->_admin_page_title;
538
+		if ($ID) {
539
+			/** @var EE_Question_Group $questionGroup */
540
+			$questionGroup            = $this->_question_group_model->get_one_by_ID($ID);
541
+			$additional_hidden_fields = array('QSG_ID' => array('type' => 'hidden', 'value' => $ID));
542
+			$this->_set_add_edit_form_tags('update_question_group', $additional_hidden_fields);
543
+		} else {
544
+			/** @var EE_Question_Group $questionGroup */
545
+			$questionGroup = EEM_Question_Group::instance()->create_default_object();
546
+			$questionGroup->set_order_to_latest();
547
+			$this->_set_add_edit_form_tags('insert_question_group');
548
+		}
549
+		$this->_template_args['values']         = $this->_yes_no_values;
550
+		$this->_template_args['all_questions']  = $questionGroup->questions_in_and_not_in_group();
551
+		$this->_template_args['QSG_ID']         = $ID ? $ID : true;
552
+		$this->_template_args['question_group'] = $questionGroup;
553
+
554
+		$redirect_URL = add_query_arg(array('action' => 'question_groups'), $this->_admin_base_url);
555
+		$this->_set_publish_post_box_vars('id', $ID, false, $redirect_URL);
556
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'question_groups_main_meta_box.template.php',
557
+			$this->_template_args, true);
558
+
559
+		// the details template wrapper
560
+		$this->display_admin_page_with_sidebar();
561
+	}
562
+
563
+
564
+	protected function _delete_question_groups()
565
+	{
566
+		$success = $this->_delete_items($this->_question_group_model);
567
+		$this->_redirect_after_action($success, $this->_question_group_model->item_name($success),
568
+			'deleted permanently', array('action' => 'question_groups', 'status' => 'trash'));
569
+	}
570
+
571
+
572
+	/**
573
+	 * @param bool $new_question_group
574
+	 */
575
+	protected function _insert_or_update_question_group($new_question_group = true)
576
+	{
577
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
578
+		$set_column_values = $this->_set_column_values_for($this->_question_group_model);
579
+		if ($new_question_group) {
580
+			$QSG_ID  = $this->_question_group_model->insert($set_column_values);
581
+			$success = $QSG_ID ? 1 : 0;
582
+		} else {
583
+			$QSG_ID = absint($this->_req_data['QSG_ID']);
584
+			unset($set_column_values['QSG_ID']);
585
+			$success = $this->_question_group_model->update($set_column_values, array(array('QSG_ID' => $QSG_ID)));
586
+		}
587
+		$phone_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(EEM_Attendee::system_question_phone);
588
+		// update the existing related questions
589
+		// BUT FIRST...  delete the phone question from the Question_Group_Question if it is being added to this question group (therefore removed from the existing group)
590
+		if (isset($this->_req_data['questions'], $this->_req_data['questions'][$phone_question_id])) {
591
+			// delete where QST ID = system phone question ID and Question Group ID is NOT this group
592
+			EEM_Question_Group_Question::instance()->delete(array(
593
+				array(
594
+					'QST_ID' => $phone_question_id,
595
+					'QSG_ID' => array('!=', $QSG_ID),
596
+				),
597
+			));
598
+		}
599
+		/** @type EE_Question_Group $question_group */
600
+		$question_group = $this->_question_group_model->get_one_by_ID($QSG_ID);
601
+		$questions      = $question_group->questions();
602
+		// make sure system phone question is added to list of questions for this group
603
+		if (! isset($questions[$phone_question_id])) {
604
+			$questions[$phone_question_id] = EEM_Question::instance()->get_one_by_ID($phone_question_id);
605
+		}
606
+
607
+		foreach ($questions as $question_ID => $question) {
608
+			// first we always check for order.
609
+			if (! empty($this->_req_data['question_orders'][$question_ID])) {
610
+				//update question order
611
+				$question_group->update_question_order($question_ID, $this->_req_data['question_orders'][$question_ID]);
612
+			}
613
+
614
+			// then we always check if adding or removing.
615
+			if (isset($this->_req_data['questions'], $this->_req_data['questions'][$question_ID])) {
616
+				$question_group->add_question($question_ID);
617
+			} else {
618
+				// not found, remove it (but only if not a system question for the personal group with the exception of lname system question - we allow removal of it)
619
+				if (
620
+				in_array(
621
+					$question->system_ID(),
622
+					EEM_Question::instance()->required_system_questions_in_system_question_group($question_group->system_group())
623
+				)
624
+				) {
625
+					continue;
626
+				} else {
627
+					$question_group->remove_question($question_ID);
628
+				}
629
+			}
630
+		}
631
+		// save new related questions
632
+		if (isset($this->_req_data['questions'])) {
633
+			foreach ($this->_req_data['questions'] as $QST_ID) {
634
+				$question_group->add_question($QST_ID);
635
+				if (isset($this->_req_data['question_orders'][$QST_ID])) {
636
+					$question_group->update_question_order($QST_ID, $this->_req_data['question_orders'][$QST_ID]);
637
+				}
638
+			}
639
+		}
640
+
641
+		if ($success !== false) {
642
+			$msg = $new_question_group ? sprintf(esc_html__('The %s has been created', 'event_espresso'),
643
+				$this->_question_group_model->item_name()) : sprintf(esc_html__('The %s has been updated',
644
+				'event_espresso'), $this->_question_group_model->item_name());
645
+			EE_Error::add_success($msg);
646
+		}
647
+		$this->_redirect_after_action(false, '', '', array('action' => 'edit_question_group', 'QSG_ID' => $QSG_ID),
648
+			true);
649
+
650
+	}
651
+
652
+	/**
653
+	 * duplicates a question and all its question options and redirects to the new question.
654
+	 */
655
+	public function _duplicate_question()
656
+	{
657
+		$question_ID = (int)$this->_req_data['QST_ID'];
658
+		$question    = EEM_Question::instance()->get_one_by_ID($question_ID);
659
+		if ($question instanceof EE_Question) {
660
+			$new_question = $question->duplicate();
661
+			if ($new_question instanceof EE_Question) {
662
+				$this->_redirect_after_action(true, esc_html__('Question', 'event_espresso'),
663
+					esc_html__('Duplicated', 'event_espresso'),
664
+					array('action' => 'edit_question', 'QST_ID' => $new_question->ID()), true);
665
+			} else {
666
+				global $wpdb;
667
+				EE_Error::add_error(sprintf(esc_html__('Could not duplicate question with ID %1$d because: %2$s',
668
+					'event_espresso'), $question_ID, $wpdb->last_error), __FILE__, __FUNCTION__, __LINE__);
669
+				$this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
670
+			}
671
+		} else {
672
+			EE_Error::add_error(sprintf(esc_html__('Could not duplicate question with ID %d because it didn\'t exist!',
673
+				'event_espresso'), $question_ID), __FILE__, __FUNCTION__, __LINE__);
674
+			$this->_redirect_after_action(false, '', '', array('action' => 'default'), false);
675
+		}
676
+	}
677
+
678
+
679
+	/**
680
+	 * @param bool $trash
681
+	 */
682
+	protected function _trash_or_restore_question_groups($trash = true)
683
+	{
684
+		$this->_trash_or_restore_items($this->_question_group_model, $trash);
685
+	}
686
+
687
+
688
+	/**
689
+	 *_trash_question
690
+	 */
691
+	protected function _trash_question()
692
+	{
693
+		$success    = $this->_question_model->delete_by_ID((int)$this->_req_data['QST_ID']);
694
+		$query_args = array('action' => 'default', 'status' => 'all');
695
+		$this->_redirect_after_action($success, $this->_question_model->item_name($success), 'trashed', $query_args);
696
+	}
697
+
698
+
699
+	/**
700
+	 * @param bool $trash
701
+	 */
702
+	protected function _trash_or_restore_questions($trash = true)
703
+	{
704
+		$this->_trash_or_restore_items($this->_question_model, $trash);
705
+	}
706
+
707
+
708
+	/**
709
+	 * Internally used to delete or restore items, using the request data. Meant to be
710
+	 * flexible between question or question groups
711
+	 *
712
+	 * @param EEM_Soft_Delete_Base $model
713
+	 * @param boolean              $trash whether to trash or restore
714
+	 */
715
+	private function _trash_or_restore_items(EEM_Soft_Delete_Base $model, $trash = true)
716
+	{
717
+
718
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
719
+
720
+		$success = 1;
721
+		//Checkboxes
722
+		//echo "trash $trash";
723
+		//var_dump($this->_req_data['checkbox']);die;
724
+		if (isset($this->_req_data['checkbox'])) {
725
+			if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
726
+				// if array has more than one element than success message should be plural
727
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
728
+				// cycle thru bulk action checkboxes
729
+				while (list($ID, $value) = each($this->_req_data['checkbox'])) {
730
+					if (! $model->delete_or_restore_by_ID($trash, absint($ID))) {
731
+						$success = 0;
732
+					}
733
+				}
734
+
735
+			} else {
736
+				// grab single id and delete
737
+				$ID = absint($this->_req_data['checkbox']);
738
+				if (! $model->delete_or_restore_by_ID($trash, $ID)) {
739
+					$success = 0;
740
+				}
741
+			}
742
+
743
+		} else {
744
+			// delete via trash link
745
+			// grab single id and delete
746
+			$ID = absint($this->_req_data[$model->primary_key_name()]);
747
+			if (! $model->delete_or_restore_by_ID($trash, $ID)) {
748
+				$success = 0;
749
+			}
750
+
751
+		}
752
+
753
+
754
+		$action = $model instanceof EEM_Question ? 'default' : 'question_groups';//strtolower( $model->item_name(2) );
755
+		//echo "action :$action";
756
+		//$action = 'questions' ? 'default' : $action;
757
+		if ($trash) {
758
+			$action_desc = 'trashed';
759
+			$status      = 'trash';
760
+		} else {
761
+			$action_desc = 'restored';
762
+			$status      = 'all';
763
+		}
764
+		$this->_redirect_after_action($success, $model->item_name($success), $action_desc,
765
+			array('action' => $action, 'status' => $status));
766
+	}
767
+
768
+
769
+	/**
770
+	 * @param            $per_page
771
+	 * @param int        $current_page
772
+	 * @param bool|false $count
773
+	 * @return \EE_Soft_Delete_Base_Class[]|int
774
+	 */
775
+	public function get_trashed_questions($per_page, $current_page = 1, $count = false)
776
+	{
777
+		$query_params = $this->get_query_params(EEM_Question::instance(), $per_page, $current_page);
778
+
779
+		if ($count) {
780
+			//note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
781
+			$where   = isset($query_params[0]) ? array($query_params[0]) : array();
782
+			$results = $this->_question_model->count_deleted($where);
783
+		} else {
784
+			//note: this a subclass of EEM_Soft_Delete_Base, so this is actually only getting non-trashed items
785
+			$results = $this->_question_model->get_all_deleted($query_params);
786
+		}
787
+		return $results;
788
+	}
789
+
790
+
791
+	/**
792
+	 * @param            $per_page
793
+	 * @param int        $current_page
794
+	 * @param bool|false $count
795
+	 * @return \EE_Soft_Delete_Base_Class[]
796
+	 */
797
+	public function get_question_groups($per_page, $current_page = 1, $count = false)
798
+	{
799
+		$questionGroupModel = EEM_Question_Group::instance();
800
+		$query_params       = $this->get_query_params($questionGroupModel, $per_page, $current_page);
801
+		if ($count) {
802
+			$where   = isset($query_params[0]) ? array($query_params[0]) : array();
803
+			$results = $questionGroupModel->count($where);
804
+		} else {
805
+			$results = $questionGroupModel->get_all($query_params);
806
+		}
807
+		return $results;
808
+	}
809
+
810
+
811
+	/**
812
+	 * @param      $per_page
813
+	 * @param int  $current_page
814
+	 * @param bool $count
815
+	 * @return \EE_Soft_Delete_Base_Class[]|int
816
+	 */
817
+	public function get_trashed_question_groups($per_page, $current_page = 1, $count = false)
818
+	{
819
+		$questionGroupModel = EEM_Question_Group::instance();
820
+		$query_params       = $this->get_query_params($questionGroupModel, $per_page, $current_page);
821
+		if ($count) {
822
+			$where                 = isset($query_params[0]) ? array($query_params[0]) : array();
823
+			$query_params['limit'] = null;
824
+			$results               = $questionGroupModel->count_deleted($where);
825
+		} else {
826
+			$results = $questionGroupModel->get_all_deleted($query_params);
827
+		}
828
+		return $results;
829
+	}
830
+
831
+
832
+	/**
833
+	 * method for performing updates to question order
834
+	 *
835
+	 * @return array results array
836
+	 */
837
+	public function update_question_group_order()
838
+	{
839
+
840
+		$success = esc_html__('Question group order was updated successfully.', 'event_espresso');
841
+
842
+		// grab our row IDs
843
+		$row_ids = isset($this->_req_data['row_ids']) && ! empty($this->_req_data['row_ids'])
844
+			? explode(',', rtrim($this->_req_data['row_ids'], ','))
845
+			: array();
846
+
847
+		$perpage = ! empty($this->_req_data['perpage'])
848
+			? (int)$this->_req_data['perpage']
849
+			: null;
850
+		$curpage = ! empty($this->_req_data['curpage'])
851
+			? (int)$this->_req_data['curpage']
852
+			: null;
853
+
854
+		if (! empty($row_ids)) {
855
+			//figure out where we start the row_id count at for the current page.
856
+			$qsgcount = empty($curpage) ? 0 : ($curpage - 1) * $perpage;
857
+
858
+			$row_count = count($row_ids);
859
+			for ($i = 0; $i < $row_count; $i++) {
860
+				//Update the questions when re-ordering
861
+				$updated = EEM_Question_Group::instance()->update(
862
+					array('QSG_order' => $qsgcount),
863
+					array(array('QSG_ID' => $row_ids[$i]))
864
+				);
865
+				if ($updated === false) {
866
+					$success = false;
867
+				}
868
+				$qsgcount++;
869
+			}
870
+		} else {
871
+			$success = false;
872
+		}
873
+
874
+		$errors = ! $success
875
+			? esc_html__('An error occurred. The question group order was not updated.', 'event_espresso')
876
+			: false;
877
+
878
+		echo wp_json_encode(array('return_data' => false, 'success' => $success, 'errors' => $errors));
879
+		die();
880
+
881
+	}
882
+
883
+
884
+
885
+	/***************************************        REGISTRATION SETTINGS        ***************************************/
886
+
887
+
888
+	/**
889
+	 * _reg_form_settings
890
+	 *
891
+	 * @throws \EE_Error
892
+	 */
893
+	protected function _reg_form_settings()
894
+	{
895
+		$this->_template_args['values'] = $this->_yes_no_values;
896
+		add_action(
897
+			'AHEE__Extend_Registration_Form_Admin_Page___reg_form_settings_template',
898
+			array($this, 'email_validation_settings_form'),
899
+			2
900
+		);
901
+		$this->_template_args = (array)apply_filters(
902
+			'FHEE__Extend_Registration_Form_Admin_Page___reg_form_settings___template_args',
903
+			$this->_template_args
904
+		);
905
+		$this->_set_add_edit_form_tags('update_reg_form_settings');
906
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
907
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
908
+			REGISTRATION_FORM_CAF_TEMPLATE_PATH . 'reg_form_settings.template.php',
909
+			$this->_template_args,
910
+			true
911
+		);
912
+		$this->display_admin_page_with_sidebar();
913
+	}
914
+
915
+
916
+	/**
917
+	 * _update_reg_form_settings
918
+	 */
919
+	protected function _update_reg_form_settings()
920
+	{
921
+		EE_Registry::instance()->CFG->registration = $this->update_email_validation_settings_form(
922
+			EE_Registry::instance()->CFG->registration
923
+		);
924
+		EE_Registry::instance()->CFG->registration = apply_filters(
925
+			'FHEE__Extend_Registration_Form_Admin_Page___update_reg_form_settings__CFG_registration',
926
+			EE_Registry::instance()->CFG->registration
927
+		);
928
+		$success                                   = $this->_update_espresso_configuration(
929
+			esc_html__('Registration Form Options', 'event_espresso'),
930
+			EE_Registry::instance()->CFG,
931
+			__FILE__, __FUNCTION__, __LINE__
932
+		);
933
+		$this->_redirect_after_action($success, esc_html__('Registration Form Options', 'event_espresso'), 'updated',
934
+			array('action' => 'view_reg_form_settings'));
935
+	}
936
+
937
+
938
+	/**
939
+	 * email_validation_settings_form
940
+	 *
941
+	 * @access    public
942
+	 * @return    void
943
+	 * @throws \EE_Error
944
+	 */
945
+	public function email_validation_settings_form()
946
+	{
947
+		echo $this->_email_validation_settings_form()->get_html();
948
+	}
949
+
950
+
951
+	/**
952
+	 * _email_validation_settings_form
953
+	 *
954
+	 * @access protected
955
+	 * @return EE_Form_Section_Proper
956
+	 * @throws \EE_Error
957
+	 */
958
+	protected function _email_validation_settings_form()
959
+	{
960
+		return new EE_Form_Section_Proper(
961
+			array(
962
+				'name'            => 'email_validation_settings',
963
+				'html_id'         => 'email_validation_settings',
964
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
965
+				'subsections'     => apply_filters(
966
+					'FHEE__Extend_Registration_Form_Admin_Page___email_validation_settings_form__form_subsections',
967
+					array(
968
+						'email_validation_hdr'   => new EE_Form_Section_HTML(
969
+							EEH_HTML::h2(esc_html__('Email Validation Settings', 'event_espresso'))
970
+						),
971
+						'email_validation_level' => new EE_Select_Input(
972
+							array(
973
+								'basic'      => esc_html__('Basic', 'event_espresso'),
974
+								'wp_default' => esc_html__('WordPress Default', 'event_espresso'),
975
+								'i18n'       => esc_html__('International', 'event_espresso'),
976
+								'i18n_dns'   => esc_html__('International + DNS Check', 'event_espresso'),
977
+							),
978
+							array(
979
+								'html_label_text' => esc_html__('Email Validation Level', 'event_espresso')
980
+													 . EEH_Template::get_help_tab_link('email_validation_info'),
981
+								'html_help_text'  => esc_html__('These levels range from basic validation ( ie: [email protected] ) to more advanced checks against international email addresses (ie: üñîçøðé@example.com ) with additional MX and A record checks to confirm the domain actually exists. More information on on each level can be found within the help section.',
982
+									'event_espresso'),
983
+								'default'         => isset(EE_Registry::instance()->CFG->registration->email_validation_level)
984
+									? EE_Registry::instance()->CFG->registration->email_validation_level
985
+									: 'wp_default',
986
+								'required'        => false,
987
+							)
988
+						),
989
+					)
990
+				),
991
+			)
992
+		);
993
+	}
994
+
995
+
996
+	/**
997
+	 * update_email_validation_settings_form
998
+	 *
999
+	 * @access    public
1000
+	 * @param \EE_Registration_Config $EE_Registration_Config
1001
+	 * @return \EE_Registration_Config
1002
+	 */
1003
+	public function update_email_validation_settings_form(EE_Registration_Config $EE_Registration_Config)
1004
+	{
1005
+		$prev_email_validation_level = $EE_Registration_Config->email_validation_level;
1006
+		try {
1007
+			$email_validation_settings_form = $this->_email_validation_settings_form();
1008
+			// if not displaying a form, then check for form submission
1009
+			if ($email_validation_settings_form->was_submitted()) {
1010
+				// capture form data
1011
+				$email_validation_settings_form->receive_form_submission();
1012
+				// validate form data
1013
+				if ($email_validation_settings_form->is_valid()) {
1014
+					// grab validated data from form
1015
+					$valid_data = $email_validation_settings_form->valid_data();
1016
+					if (isset($valid_data['email_validation_level'])) {
1017
+						$email_validation_level = $valid_data['email_validation_level'];
1018
+						// now if they want to use international email addresses
1019
+						if ($email_validation_level === 'i18n' || $email_validation_level === 'i18n_dns') {
1020
+							// in case we need to reset their email validation level,
1021
+							// make sure that the previous value wasn't already set to one of the i18n options.
1022
+							if ($prev_email_validation_level === 'i18n' || $prev_email_validation_level === 'i18n_dns') {
1023
+								// if so, then reset it back to "basic" since that is the only other option that,
1024
+								// despite offering poor validation, supports i18n email addresses
1025
+								$prev_email_validation_level = 'basic';
1026
+							}
1027
+							// confirm our i18n email validation will work on the server
1028
+							if (! $this->_verify_pcre_support($EE_Registration_Config, $email_validation_level)) {
1029
+								// or reset email validation level to previous value
1030
+								$email_validation_level = $prev_email_validation_level;
1031
+							}
1032
+						}
1033
+						$EE_Registration_Config->email_validation_level = $email_validation_level;
1034
+					} else {
1035
+						EE_Error::add_error(
1036
+							esc_html__(
1037
+								'Invalid or missing Email Validation settings. Please refresh the form and try again.',
1038
+								'event_espresso'
1039
+							),
1040
+							__FILE__, __FUNCTION__, __LINE__
1041
+						);
1042
+					}
1043
+				} else {
1044
+					if ($email_validation_settings_form->submission_error_message() !== '') {
1045
+						EE_Error::add_error(
1046
+							$email_validation_settings_form->submission_error_message(),
1047
+							__FILE__, __FUNCTION__, __LINE__
1048
+						);
1049
+					}
1050
+				}
1051
+			}
1052
+		} catch (EE_Error $e) {
1053
+			$e->get_error();
1054
+		}
1055
+		return $EE_Registration_Config;
1056
+	}
1057
+
1058
+
1059
+	/**
1060
+	 * confirms that the server's PHP version has the PCRE module enabled,
1061
+	 * and that the PCRE version works with our i18n email validation
1062
+	 *
1063
+	 * @param \EE_Registration_Config $EE_Registration_Config
1064
+	 * @param string                  $email_validation_level
1065
+	 * @return bool
1066
+	 */
1067
+	private function _verify_pcre_support(EE_Registration_Config $EE_Registration_Config, $email_validation_level)
1068
+	{
1069
+		// first check that PCRE is enabled
1070
+		if (! defined('PREG_BAD_UTF8_ERROR')) {
1071
+			EE_Error::add_error(
1072
+				sprintf(
1073
+					esc_html__(
1074
+						'We\'re sorry, but it appears that your server\'s version of PHP was not compiled with PCRE unicode support.%1$sPlease contact your hosting company and ask them whether the PCRE compiled with your version of PHP on your server can be been built with the "--enable-unicode-properties" and "--enable-utf8" configuration switches to enable more complex regex expressions.%1$sIf they are unable, or unwilling to do so, then your server will not support international email addresses using UTF-8 unicode characters. This means you will either have to lower your email validation level to "Basic" or "WordPress Default", or switch to a hosting company that has/can enable PCRE unicode support on the server.',
1075
+						'event_espresso'
1076
+					),
1077
+					'<br />'
1078
+				),
1079
+				__FILE__,
1080
+				__FUNCTION__,
1081
+				__LINE__
1082
+			);
1083
+			return false;
1084
+		} else {
1085
+			// PCRE support is enabled, but let's still
1086
+			// perform a test to see if the server will support it.
1087
+			// but first, save the updated validation level to the config,
1088
+			// so that the validation strategy picks it up.
1089
+			// this will get bumped back down if it doesn't work
1090
+			$EE_Registration_Config->email_validation_level = $email_validation_level;
1091
+			try {
1092
+				$email_validator    = new EE_Email_Validation_Strategy();
1093
+				$i18n_email_address = apply_filters(
1094
+					'FHEE__Extend_Registration_Form_Admin_Page__update_email_validation_settings_form__i18n_email_address',
1095
+					'jägerjü[email protected]'
1096
+				);
1097
+				$email_validator->validate($i18n_email_address);
1098
+			} catch (Exception $e) {
1099
+				EE_Error::add_error(
1100
+					sprintf(
1101
+						esc_html__(
1102
+							'We\'re sorry, but it appears that your server\'s configuration will not support the "International" or "International + DNS Check" email validation levels.%1$sTo correct this issue, please consult with your hosting company regarding your server\'s PCRE settings.%1$sIt is recommended that your PHP version be configured to use PCRE 8.10 or newer.%1$sMore information regarding PCRE versions and installation can be found here: %2$s',
1103
+							'event_espresso'
1104
+						),
1105
+						'<br />',
1106
+						'<a href="http://php.net/manual/en/pcre.installation.php" target="_blank">http://php.net/manual/en/pcre.installation.php</a>'
1107
+					),
1108
+					__FILE__, __FUNCTION__, __LINE__
1109
+				);
1110
+				return false;
1111
+			}
1112
+		}
1113
+		return true;
1114
+	}
1115 1115
 
1116 1116
 
1117 1117
 }
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.
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_models/EEM_Base.model.php 2 patches
Indentation   +5910 added lines, -5910 removed lines patch added patch discarded remove patch
@@ -32,5918 +32,5918 @@
 block discarded – undo
32 32
 abstract class EEM_Base extends EE_Base implements ResettableInterface
33 33
 {
34 34
 
35
-    //admin posty
36
-    //basic -> grants access to mine -> if they don't have it, select none
37
-    //*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
38
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
39
-    //*_published -> grants access to published -> if they dont have it, select non-published
40
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
41
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
42
-    //frontend posty
43
-    //by default has access to published
44
-    //basic -> grants access to mine that aren't published, and all published
45
-    //*_others ->grants access to others that aren't private, all mine
46
-    //*_private -> grants full access
47
-    //frontend non-posty
48
-    //like admin posty
49
-    //category-y
50
-    //assign -> grants access to join-table
51
-    //(delete, edit)
52
-    //payment-method-y
53
-    //for each registered payment method,
54
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
55
-    /**
56
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
57
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
58
-     * They almost always WILL NOT, but it's not necessarily a requirement.
59
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
60
-     *
61
-     * @var boolean
62
-     */
63
-    private $_values_already_prepared_by_model_object = 0;
64
-
65
-    /**
66
-     * when $_values_already_prepared_by_model_object equals this, we assume
67
-     * the data is just like form input that needs to have the model fields'
68
-     * prepare_for_set and prepare_for_use_in_db called on it
69
-     */
70
-    const not_prepared_by_model_object = 0;
71
-
72
-    /**
73
-     * when $_values_already_prepared_by_model_object equals this, we
74
-     * assume this value is coming from a model object and doesn't need to have
75
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
76
-     */
77
-    const prepared_by_model_object = 1;
78
-
79
-    /**
80
-     * when $_values_already_prepared_by_model_object equals this, we assume
81
-     * the values are already to be used in the database (ie no processing is done
82
-     * on them by the model's fields)
83
-     */
84
-    const prepared_for_use_in_db = 2;
85
-
86
-
87
-    protected $singular_item = 'Item';
88
-
89
-    protected $plural_item   = 'Items';
90
-
91
-    /**
92
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
93
-     */
94
-    protected $_tables;
95
-
96
-    /**
97
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
98
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
99
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
100
-     *
101
-     * @var \EE_Model_Field_Base[] $_fields
102
-     */
103
-    protected $_fields;
104
-
105
-    /**
106
-     * array of different kinds of relations
107
-     *
108
-     * @var \EE_Model_Relation_Base[] $_model_relations
109
-     */
110
-    protected $_model_relations;
111
-
112
-    /**
113
-     * @var \EE_Index[] $_indexes
114
-     */
115
-    protected $_indexes = array();
116
-
117
-    /**
118
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
119
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
120
-     * by setting the same columns as used in these queries in the query yourself.
121
-     *
122
-     * @var EE_Default_Where_Conditions
123
-     */
124
-    protected $_default_where_conditions_strategy;
125
-
126
-    /**
127
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
128
-     * This is particularly useful when you want something between 'none' and 'default'
129
-     *
130
-     * @var EE_Default_Where_Conditions
131
-     */
132
-    protected $_minimum_where_conditions_strategy;
133
-
134
-    /**
135
-     * String describing how to find the "owner" of this model's objects.
136
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
137
-     * But when there isn't, this indicates which related model, or transiently-related model,
138
-     * has the foreign key to the wp_users table.
139
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
140
-     * related to events, and events have a foreign key to wp_users.
141
-     * On EEM_Transaction, this would be 'Transaction.Event'
142
-     *
143
-     * @var string
144
-     */
145
-    protected $_model_chain_to_wp_user = '';
146
-
147
-    /**
148
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
149
-     * don't need it (particularly CPT models)
150
-     *
151
-     * @var bool
152
-     */
153
-    protected $_ignore_where_strategy = false;
154
-
155
-    /**
156
-     * String used in caps relating to this model. Eg, if the caps relating to this
157
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
158
-     *
159
-     * @var string. If null it hasn't been initialized yet. If false then we
160
-     * have indicated capabilities don't apply to this
161
-     */
162
-    protected $_caps_slug = null;
163
-
164
-    /**
165
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
166
-     * and next-level keys are capability names, and each's value is a
167
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
168
-     * they specify which context to use (ie, frontend, backend, edit or delete)
169
-     * and then each capability in the corresponding sub-array that they're missing
170
-     * adds the where conditions onto the query.
171
-     *
172
-     * @var array
173
-     */
174
-    protected $_cap_restrictions = array(
175
-        self::caps_read       => array(),
176
-        self::caps_read_admin => array(),
177
-        self::caps_edit       => array(),
178
-        self::caps_delete     => array(),
179
-    );
180
-
181
-    /**
182
-     * Array defining which cap restriction generators to use to create default
183
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
184
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
185
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
186
-     * automatically set this to false (not just null).
187
-     *
188
-     * @var EE_Restriction_Generator_Base[]
189
-     */
190
-    protected $_cap_restriction_generators = array();
191
-
192
-    /**
193
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
194
-     */
195
-    const caps_read       = 'read';
196
-
197
-    const caps_read_admin = 'read_admin';
198
-
199
-    const caps_edit       = 'edit';
200
-
201
-    const caps_delete     = 'delete';
202
-
203
-    /**
204
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
205
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
206
-     * maps to 'read' because when looking for relevant permissions we're going to use
207
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
208
-     *
209
-     * @var array
210
-     */
211
-    protected $_cap_contexts_to_cap_action_map = array(
212
-        self::caps_read       => 'read',
213
-        self::caps_read_admin => 'read',
214
-        self::caps_edit       => 'edit',
215
-        self::caps_delete     => 'delete',
216
-    );
217
-
218
-    /**
219
-     * Timezone
220
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
221
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
222
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
223
-     * EE_Datetime_Field data type will have access to it.
224
-     *
225
-     * @var string
226
-     */
227
-    protected $_timezone;
228
-
229
-
230
-    /**
231
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
232
-     * multisite.
233
-     *
234
-     * @var int
235
-     */
236
-    protected static $_model_query_blog_id;
237
-
238
-    /**
239
-     * A copy of _fields, except the array keys are the model names pointed to by
240
-     * the field
241
-     *
242
-     * @var EE_Model_Field_Base[]
243
-     */
244
-    private $_cache_foreign_key_to_fields = array();
245
-
246
-    /**
247
-     * Cached list of all the fields on the model, indexed by their name
248
-     *
249
-     * @var EE_Model_Field_Base[]
250
-     */
251
-    private $_cached_fields = null;
252
-
253
-    /**
254
-     * Cached list of all the fields on the model, except those that are
255
-     * marked as only pertinent to the database
256
-     *
257
-     * @var EE_Model_Field_Base[]
258
-     */
259
-    private $_cached_fields_non_db_only = null;
260
-
261
-    /**
262
-     * A cached reference to the primary key for quick lookup
263
-     *
264
-     * @var EE_Model_Field_Base
265
-     */
266
-    private $_primary_key_field = null;
267
-
268
-    /**
269
-     * Flag indicating whether this model has a primary key or not
270
-     *
271
-     * @var boolean
272
-     */
273
-    protected $_has_primary_key_field = null;
274
-
275
-    /**
276
-     * Whether or not this model is based off a table in WP core only (CPTs should set
277
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
278
-     *
279
-     * @var boolean
280
-     */
281
-    protected $_wp_core_model = false;
282
-
283
-    /**
284
-     *    List of valid operators that can be used for querying.
285
-     * The keys are all operators we'll accept, the values are the real SQL
286
-     * operators used
287
-     *
288
-     * @var array
289
-     */
290
-    protected $_valid_operators = array(
291
-        '='           => '=',
292
-        '<='          => '<=',
293
-        '<'           => '<',
294
-        '>='          => '>=',
295
-        '>'           => '>',
296
-        '!='          => '!=',
297
-        'LIKE'        => 'LIKE',
298
-        'like'        => 'LIKE',
299
-        'NOT_LIKE'    => 'NOT LIKE',
300
-        'not_like'    => 'NOT LIKE',
301
-        'NOT LIKE'    => 'NOT LIKE',
302
-        'not like'    => 'NOT LIKE',
303
-        'IN'          => 'IN',
304
-        'in'          => 'IN',
305
-        'NOT_IN'      => 'NOT IN',
306
-        'not_in'      => 'NOT IN',
307
-        'NOT IN'      => 'NOT IN',
308
-        'not in'      => 'NOT IN',
309
-        'between'     => 'BETWEEN',
310
-        'BETWEEN'     => 'BETWEEN',
311
-        'IS_NOT_NULL' => 'IS NOT NULL',
312
-        'is_not_null' => 'IS NOT NULL',
313
-        'IS NOT NULL' => 'IS NOT NULL',
314
-        'is not null' => 'IS NOT NULL',
315
-        'IS_NULL'     => 'IS NULL',
316
-        'is_null'     => 'IS NULL',
317
-        'IS NULL'     => 'IS NULL',
318
-        'is null'     => 'IS NULL',
319
-        'REGEXP'      => 'REGEXP',
320
-        'regexp'      => 'REGEXP',
321
-        'NOT_REGEXP'  => 'NOT REGEXP',
322
-        'not_regexp'  => 'NOT REGEXP',
323
-        'NOT REGEXP'  => 'NOT REGEXP',
324
-        'not regexp'  => 'NOT REGEXP',
325
-    );
326
-
327
-    /**
328
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
329
-     *
330
-     * @var array
331
-     */
332
-    protected $_in_style_operators = array('IN', 'NOT IN');
333
-
334
-    /**
335
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
336
-     * '12-31-2012'"
337
-     *
338
-     * @var array
339
-     */
340
-    protected $_between_style_operators = array('BETWEEN');
341
-
342
-    /**
343
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
344
-     * on a join table.
345
-     *
346
-     * @var array
347
-     */
348
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
349
-
350
-    /**
351
-     * Allowed values for $query_params['order'] for ordering in queries
352
-     *
353
-     * @var array
354
-     */
355
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
356
-
357
-    /**
358
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
359
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
360
-     *
361
-     * @var array
362
-     */
363
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
364
-
365
-    /**
366
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
367
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
368
-     *
369
-     * @var array
370
-     */
371
-    private $_allowed_query_params = array(
372
-        0,
373
-        'limit',
374
-        'order_by',
375
-        'group_by',
376
-        'having',
377
-        'force_join',
378
-        'order',
379
-        'on_join_limit',
380
-        'default_where_conditions',
381
-        'caps',
382
-    );
383
-
384
-    /**
385
-     * All the data types that can be used in $wpdb->prepare statements.
386
-     *
387
-     * @var array
388
-     */
389
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
390
-
391
-    /**
392
-     *    EE_Registry Object
393
-     *
394
-     * @var    object
395
-     * @access    protected
396
-     */
397
-    protected $EE = null;
398
-
399
-
400
-    /**
401
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
402
-     *
403
-     * @var int
404
-     */
405
-    protected $_show_next_x_db_queries = 0;
406
-
407
-    /**
408
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
409
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
410
-     *
411
-     * @var array
412
-     */
413
-    protected $_custom_selections = array();
414
-
415
-    /**
416
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
417
-     * caches every model object we've fetched from the DB on this request
418
-     *
419
-     * @var array
420
-     */
421
-    protected $_entity_map;
422
-
423
-    /**
424
-     * constant used to show EEM_Base has not yet verified the db on this http request
425
-     */
426
-    const db_verified_none = 0;
427
-
428
-    /**
429
-     * constant used to show EEM_Base has verified the EE core db on this http request,
430
-     * but not the addons' dbs
431
-     */
432
-    const db_verified_core = 1;
433
-
434
-    /**
435
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
436
-     * the EE core db too)
437
-     */
438
-    const db_verified_addons = 2;
439
-
440
-    /**
441
-     * indicates whether an EEM_Base child has already re-verified the DB
442
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
443
-     * looking like EEM_Base::db_verified_*
444
-     *
445
-     * @var int - 0 = none, 1 = core, 2 = addons
446
-     */
447
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
448
-
449
-    /**
450
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
451
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
452
-     *        registrations for non-trashed tickets for non-trashed datetimes)
453
-     */
454
-    const default_where_conditions_all = 'all';
455
-
456
-    /**
457
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
458
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
459
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
460
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
461
-     *        models which share tables with other models, this can return data for the wrong model.
462
-     */
463
-    const default_where_conditions_this_only = 'this_model_only';
464
-
465
-    /**
466
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
467
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
468
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
469
-     */
470
-    const default_where_conditions_others_only = 'other_models_only';
471
-
472
-    /**
473
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
474
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
475
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
476
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
477
-     *        (regardless of whether those events and venues are trashed)
478
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
479
-     *        events.
480
-     */
481
-    const default_where_conditions_minimum_all = 'minimum';
482
-
483
-    /**
484
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
485
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
486
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
487
-     *        not)
488
-     */
489
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
490
-
491
-    /**
492
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
493
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
494
-     *        it's possible it will return table entries for other models. You should use
495
-     *        EEM_Base::default_where_conditions_minimum_all instead.
496
-     */
497
-    const default_where_conditions_none = 'none';
498
-
499
-
500
-
501
-    /**
502
-     * About all child constructors:
503
-     * they should define the _tables, _fields and _model_relations arrays.
504
-     * Should ALWAYS be called after child constructor.
505
-     * In order to make the child constructors to be as simple as possible, this parent constructor
506
-     * finalizes constructing all the object's attributes.
507
-     * Generally, rather than requiring a child to code
508
-     * $this->_tables = array(
509
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
510
-     *        ...);
511
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
512
-     * each EE_Table has a function to set the table's alias after the constructor, using
513
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
514
-     * do something similar.
515
-     *
516
-     * @param null $timezone
517
-     * @throws EE_Error
518
-     */
519
-    protected function __construct($timezone = null)
520
-    {
521
-        // check that the model has not been loaded too soon
522
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
523
-            throw new EE_Error (
524
-                sprintf(
525
-                    __('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.',
526
-                        'event_espresso'),
527
-                    get_class($this)
528
-                )
529
-            );
530
-        }
531
-        /**
532
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
533
-         */
534
-        if (empty(EEM_Base::$_model_query_blog_id)) {
535
-            EEM_Base::set_model_query_blog_id();
536
-        }
537
-        /**
538
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
539
-         * just use EE_Register_Model_Extension
540
-         *
541
-         * @var EE_Table_Base[] $_tables
542
-         */
543
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
544
-        foreach ($this->_tables as $table_alias => $table_obj) {
545
-            /** @var $table_obj EE_Table_Base */
546
-            $table_obj->_construct_finalize_with_alias($table_alias);
547
-            if ($table_obj instanceof EE_Secondary_Table) {
548
-                /** @var $table_obj EE_Secondary_Table */
549
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
550
-            }
551
-        }
552
-        /**
553
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
554
-         * EE_Register_Model_Extension
555
-         *
556
-         * @param EE_Model_Field_Base[] $_fields
557
-         */
558
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
559
-        $this->_invalidate_field_caches();
560
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
561
-            if (! array_key_exists($table_alias, $this->_tables)) {
562
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
563
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
564
-            }
565
-            foreach ($fields_for_table as $field_name => $field_obj) {
566
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
-                //primary key field base has a slightly different _construct_finalize
568
-                /** @var $field_obj EE_Model_Field_Base */
569
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
-            }
571
-        }
572
-        // everything is related to Extra_Meta
573
-        if (get_class($this) !== 'EEM_Extra_Meta') {
574
-            //make extra meta related to everything, but don't block deleting things just
575
-            //because they have related extra meta info. For now just orphan those extra meta
576
-            //in the future we should automatically delete them
577
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        //and change logs
580
-        if (get_class($this) !== 'EEM_Change_Log') {
581
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
-        }
583
-        /**
584
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
-         * EE_Register_Model_Extension
586
-         *
587
-         * @param EE_Model_Relation_Base[] $_model_relations
588
-         */
589
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
590
-            $this->_model_relations);
591
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
592
-            /** @var $relation_obj EE_Model_Relation_Base */
593
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
594
-        }
595
-        foreach ($this->_indexes as $index_name => $index_obj) {
596
-            /** @var $index_obj EE_Index */
597
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
598
-        }
599
-        $this->set_timezone($timezone);
600
-        //finalize default where condition strategy, or set default
601
-        if (! $this->_default_where_conditions_strategy) {
602
-            //nothing was set during child constructor, so set default
603
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
604
-        }
605
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
606
-        if (! $this->_minimum_where_conditions_strategy) {
607
-            //nothing was set during child constructor, so set default
608
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
609
-        }
610
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
611
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
612
-        //to indicate to NOT set it, set it to the logical default
613
-        if ($this->_caps_slug === null) {
614
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
615
-        }
616
-        //initialize the standard cap restriction generators if none were specified by the child constructor
617
-        if ($this->_cap_restriction_generators !== false) {
618
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
619
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
620
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
621
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
622
-                        new EE_Restriction_Generator_Protected(),
623
-                        $cap_context,
624
-                        $this
625
-                    );
626
-                }
627
-            }
628
-        }
629
-        //if there are cap restriction generators, use them to make the default cap restrictions
630
-        if ($this->_cap_restriction_generators !== false) {
631
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
632
-                if (! $generator_object) {
633
-                    continue;
634
-                }
635
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
636
-                    throw new EE_Error(
637
-                        sprintf(
638
-                            __('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.',
639
-                                'event_espresso'),
640
-                            $context,
641
-                            $this->get_this_model_name()
642
-                        )
643
-                    );
644
-                }
645
-                $action = $this->cap_action_for_context($context);
646
-                if (! $generator_object->construction_finalized()) {
647
-                    $generator_object->_construct_finalize($this, $action);
648
-                }
649
-            }
650
-        }
651
-        do_action('AHEE__' . get_class($this) . '__construct__end');
652
-    }
653
-
654
-
655
-
656
-    /**
657
-     * Generates the cap restrictions for the given context, or if they were
658
-     * already generated just gets what's cached
659
-     *
660
-     * @param string $context one of EEM_Base::valid_cap_contexts()
661
-     * @return EE_Default_Where_Conditions[]
662
-     */
663
-    protected function _generate_cap_restrictions($context)
664
-    {
665
-        if (isset($this->_cap_restriction_generators[$context])
666
-            && $this->_cap_restriction_generators[$context]
667
-               instanceof
668
-               EE_Restriction_Generator_Base
669
-        ) {
670
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
671
-        } else {
672
-            return array();
673
-        }
674
-    }
675
-
676
-
677
-
678
-    /**
679
-     * Used to set the $_model_query_blog_id static property.
680
-     *
681
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
682
-     *                      value for get_current_blog_id() will be used.
683
-     */
684
-    public static function set_model_query_blog_id($blog_id = 0)
685
-    {
686
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
687
-    }
688
-
689
-
690
-
691
-    /**
692
-     * Returns whatever is set as the internal $model_query_blog_id.
693
-     *
694
-     * @return int
695
-     */
696
-    public static function get_model_query_blog_id()
697
-    {
698
-        return EEM_Base::$_model_query_blog_id;
699
-    }
700
-
701
-
702
-
703
-    /**
704
-     * This function is a singleton method used to instantiate the Espresso_model object
705
-     *
706
-     * @param string            $timezone string representing the timezone we want to set for returned Date Time Strings
707
-     *                                    (and any incoming timezone data that gets saved).
708
-     *                                    Note this just sends the timezone info to the date time model field objects.
709
-     *                                    Default is NULL
710
-     *                                    (and will be assumed using the set timezone in the 'timezone_string' wp option)
711
-     * @param ModelFieldFactory $model_field_factory
712
-     * @return static (as in the concrete child class)
713
-     * @throws InvalidArgumentException
714
-     * @throws InvalidInterfaceException
715
-     * @throws InvalidDataTypeException
716
-     * @throws EE_Error
717
-     */
718
-    public static function instance($timezone = null, ModelFieldFactory $model_field_factory = null)
719
-    {
720
-        // check if instance of Espresso_model already exists
721
-        if (! static::$_instance instanceof static) {
722
-            $model_field_factory = self::getModelFieldFactory($model_field_factory);
723
-            // instantiate Espresso_model
724
-            static::$_instance = new static($timezone, $model_field_factory);
725
-        }
726
-        //we might have a timezone set, let set_timezone decide what to do with it
727
-        static::$_instance->set_timezone($timezone);
728
-        // Espresso_model object
729
-        return static::$_instance;
730
-    }
731
-
732
-
733
-
734
-    /**
735
-     * @param $model_field_factory
736
-     * @return ModelFieldFactory
737
-     * @throws InvalidArgumentException
738
-     * @throws InvalidDataTypeException
739
-     * @throws InvalidInterfaceException
740
-     */
741
-    private static function getModelFieldFactory($model_field_factory)
742
-    {
743
-        return $model_field_factory instanceof ModelFieldFactory
744
-            ? $model_field_factory
745
-            : LoaderFactory::getLoader()->load('EventEspresso\core\services\database\ModelFieldFactory');
746
-    }
747
-
748
-
749
-
750
-    /**
751
-     * resets the model and returns it
752
-     *
753
-     * @param null | string          $timezone
754
-     * @param ModelFieldFactory|null $model_field_factory
755
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
756
-     * @throws ReflectionException
757
-     * all its properties reset; if it wasn't instantiated, returns null)
758
-     * @throws EE_Error
759
-     * @throws InvalidArgumentException
760
-     * @throws InvalidDataTypeException
761
-     * @throws InvalidInterfaceException
762
-     */
763
-    public static function reset($timezone = null, ModelFieldFactory $model_field_factory = null)
764
-    {
765
-        if (static::$_instance instanceof EEM_Base) {
766
-            //let's try to NOT swap out the current instance for a new one
767
-            //because if someone has a reference to it, we can't remove their reference
768
-            //so it's best to keep using the same reference, but change the original object
769
-            //reset all its properties to their original values as defined in the class
770
-            $r = new ReflectionClass(get_class(static::$_instance));
771
-            $static_properties = $r->getStaticProperties();
772
-            foreach ($r->getDefaultProperties() as $property => $value) {
773
-                //don't set instance to null like it was originally,
774
-                //but it's static anyways, and we're ignoring static properties (for now at least)
775
-                if (! isset($static_properties[$property])) {
776
-                    static::$_instance->{$property} = $value;
777
-                }
778
-            }
779
-            //and then directly call its constructor again, like we would if we were creating a new one
780
-            $model_field_factory = self::getModelFieldFactory($model_field_factory);
781
-            static::$_instance->__construct($timezone, $model_field_factory);
782
-            return self::instance();
783
-        }
784
-        return null;
785
-    }
786
-
787
-
788
-
789
-    /**
790
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
791
-     *
792
-     * @param  boolean $translated return localized strings or JUST the array.
793
-     * @return array
794
-     * @throws EE_Error
795
-     */
796
-    public function status_array($translated = false)
797
-    {
798
-        if (! array_key_exists('Status', $this->_model_relations)) {
799
-            return array();
800
-        }
801
-        $model_name = $this->get_this_model_name();
802
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
803
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
804
-        $status_array = array();
805
-        foreach ($stati as $status) {
806
-            $status_array[$status->ID()] = $status->get('STS_code');
807
-        }
808
-        return $translated
809
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
810
-            : $status_array;
811
-    }
812
-
813
-
814
-
815
-    /**
816
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
817
-     *
818
-     * @param array $query_params             {
819
-     * @var array $0 (where) array {
820
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
821
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
822
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
823
-     *                                        conditions based on related models (and even
824
-     *                                        models-related-to-related-models) prepend the model's name onto the field
825
-     *                                        name. Eg,
826
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
827
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
828
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
829
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
830
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
831
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
832
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
833
-     *                                        to Venues (even when each of those models actually consisted of two
834
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
835
-     *                                        just having
836
-     *                                        "Venue.VNU_ID", you could have
837
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
838
-     *                                        events are related to Registrations, which are related to Attendees). You
839
-     *                                        can take it even further with
840
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
841
-     *                                        (from the default of '='), change the value to an numerically-indexed
842
-     *                                        array, where the first item in the list is the operator. eg: array(
843
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
844
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
845
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
846
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
847
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
848
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
849
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
850
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
851
-     *                                        the value is a field, simply provide a third array item (true) to the
852
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
853
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
854
-     *                                        Note: you can also use related model field names like you would any other
855
-     *                                        field name. eg:
856
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
857
-     *                                        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__>' =>
858
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
859
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
860
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
861
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
862
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
863
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
864
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
865
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
866
-     *                                        "stick" until you specify an AND. eg
867
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
868
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
869
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
870
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
871
-     *                                        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 >>
872
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
873
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
874
-     *                                        too, eg:
875
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
876
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
877
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
878
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
879
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
880
-     *                                        the OFFSET, the 2nd is the LIMIT
881
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
882
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
883
-     *                                        following format array('on_join_limit'
884
-     *                                        => array( 'table_alias', array(1,2) ) ).
885
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
886
-     *                                        values are either 'ASC' or 'DESC'.
887
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
888
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
889
-     *                                        DESC..." respectively. Like the
890
-     *                                        'where' conditions, these fields can be on related models. Eg
891
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
892
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
893
-     *                                        Attendee, Price, Datetime, etc.)
894
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
895
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
896
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
897
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
898
-     *                                        order by the primary key. Eg,
899
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
900
-     *                                        //(will join with the Datetime model's table(s) and order by its field
901
-     *                                        DTT_EVT_start) or
902
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
903
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
904
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
905
-     *                                        'group_by'=>'VNU_ID', or
906
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
907
-     *                                        if no
908
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
909
-     *                                        model's primary key (or combined primary keys). This avoids some
910
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
911
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
912
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
913
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
914
-     *                                        results)
915
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
916
-     *                                        array where values are models to be joined in the query.Eg
917
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
918
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
919
-     *                                        probably only want to do this in hopes of increasing efficiency, as
920
-     *                                        related models which belongs to the current model
921
-     *                                        (ie, the current model has a foreign key to them, like how Registration
922
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
923
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
924
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
925
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
926
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
927
-     *                                        default where conditions set it to 'other_models_only'. If you only want
928
-     *                                        this model's default where conditions added to the query, use
929
-     *                                        'this_model_only'. If you want to use all default where conditions
930
-     *                                        (default), set to 'all'.
931
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
932
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
933
-     *                                        everything? Or should we only show the current user items they should be
934
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
935
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
936
-     *                                        }
937
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
938
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
939
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
940
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
941
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
942
-     *                                        array( array(
943
-     *                                        'OR'=>array(
944
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
945
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
946
-     *                                        )
947
-     *                                        ),
948
-     *                                        'limit'=>10,
949
-     *                                        'group_by'=>'TXN_ID'
950
-     *                                        ));
951
-     *                                        get all the answers to the question titled "shirt size" for event with id
952
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
953
-     *                                        'Question.QST_display_text'=>'shirt size',
954
-     *                                        'Registration.Event.EVT_ID'=>12
955
-     *                                        ),
956
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
957
-     *                                        ));
958
-     * @throws EE_Error
959
-     */
960
-    public function get_all($query_params = array())
961
-    {
962
-        if (isset($query_params['limit'])
963
-            && ! isset($query_params['group_by'])
964
-        ) {
965
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
966
-        }
967
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
968
-    }
969
-
970
-
971
-
972
-    /**
973
-     * Modifies the query parameters so we only get back model objects
974
-     * that "belong" to the current user
975
-     *
976
-     * @param array $query_params @see EEM_Base::get_all()
977
-     * @return array like EEM_Base::get_all
978
-     */
979
-    public function alter_query_params_to_only_include_mine($query_params = array())
980
-    {
981
-        $wp_user_field_name = $this->wp_user_field_name();
982
-        if ($wp_user_field_name) {
983
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
984
-        }
985
-        return $query_params;
986
-    }
987
-
988
-
989
-
990
-    /**
991
-     * Returns the name of the field's name that points to the WP_User table
992
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
993
-     * foreign key to the WP_User table)
994
-     *
995
-     * @return string|boolean string on success, boolean false when there is no
996
-     * foreign key to the WP_User table
997
-     */
998
-    public function wp_user_field_name()
999
-    {
1000
-        try {
1001
-            if (! empty($this->_model_chain_to_wp_user)) {
1002
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
1003
-                $last_model_name = end($models_to_follow_to_wp_users);
1004
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
1005
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
1006
-            } else {
1007
-                $model_with_fk_to_wp_users = $this;
1008
-                $model_chain_to_wp_user = '';
1009
-            }
1010
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
1011
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
1012
-        } catch (EE_Error $e) {
1013
-            return false;
1014
-        }
1015
-    }
1016
-
1017
-
1018
-
1019
-    /**
1020
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
1021
-     * (or transiently-related model) has a foreign key to the wp_users table;
1022
-     * useful for finding if model objects of this type are 'owned' by the current user.
1023
-     * This is an empty string when the foreign key is on this model and when it isn't,
1024
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
1025
-     * (or transiently-related model)
1026
-     *
1027
-     * @return string
1028
-     */
1029
-    public function model_chain_to_wp_user()
1030
-    {
1031
-        return $this->_model_chain_to_wp_user;
1032
-    }
1033
-
1034
-
1035
-
1036
-    /**
1037
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1038
-     * like how registrations don't have a foreign key to wp_users, but the
1039
-     * events they are for are), or is unrelated to wp users.
1040
-     * generally available
1041
-     *
1042
-     * @return boolean
1043
-     */
1044
-    public function is_owned()
1045
-    {
1046
-        if ($this->model_chain_to_wp_user()) {
1047
-            return true;
1048
-        }
1049
-        try {
1050
-            $this->get_foreign_key_to('WP_User');
1051
-            return true;
1052
-        } catch (EE_Error $e) {
1053
-            return false;
1054
-        }
1055
-    }
1056
-
1057
-
1058
-
1059
-    /**
1060
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1061
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1062
-     * the model)
1063
-     *
1064
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1065
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1066
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1067
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1068
-     *                                  override this and set the select to "*", or a specific column name, like
1069
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1070
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1071
-     *                                  the aliases used to refer to this selection, and values are to be
1072
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1073
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1074
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1075
-     * @throws EE_Error
1076
-     */
1077
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1078
-    {
1079
-        // remember the custom selections, if any, and type cast as array
1080
-        // (unless $columns_to_select is an object, then just set as an empty array)
1081
-        // Note: (array) 'some string' === array( 'some string' )
1082
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1083
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1084
-        $select_expressions = $columns_to_select !== null
1085
-            ? $this->_construct_select_from_input($columns_to_select)
1086
-            : $this->_construct_default_select_sql($model_query_info);
1087
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1088
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1089
-    }
1090
-
1091
-
1092
-
1093
-    /**
1094
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1095
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1096
-     * take care of joins, field preparation etc.
1097
-     *
1098
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1099
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1100
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1101
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1102
-     *                                  override this and set the select to "*", or a specific column name, like
1103
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1104
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1105
-     *                                  the aliases used to refer to this selection, and values are to be
1106
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1107
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1108
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1109
-     * @throws EE_Error
1110
-     */
1111
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1112
-    {
1113
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1114
-    }
1115
-
1116
-
1117
-
1118
-    /**
1119
-     * For creating a custom select statement
1120
-     *
1121
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1122
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1123
-     *                                 SQL, and 1=>is the datatype
1124
-     * @throws EE_Error
1125
-     * @return string
1126
-     */
1127
-    private function _construct_select_from_input($columns_to_select)
1128
-    {
1129
-        if (is_array($columns_to_select)) {
1130
-            $select_sql_array = array();
1131
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1132
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1133
-                    throw new EE_Error(
1134
-                        sprintf(
1135
-                            __(
1136
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1137
-                                "event_espresso"
1138
-                            ),
1139
-                            $selection_and_datatype,
1140
-                            $alias
1141
-                        )
1142
-                    );
1143
-                }
1144
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1145
-                    throw new EE_Error(
1146
-                        sprintf(
1147
-                            __(
1148
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1149
-                                "event_espresso"
1150
-                            ),
1151
-                            $selection_and_datatype[1],
1152
-                            $selection_and_datatype[0],
1153
-                            $alias,
1154
-                            implode(",", $this->_valid_wpdb_data_types)
1155
-                        )
1156
-                    );
1157
-                }
1158
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1159
-            }
1160
-            $columns_to_select_string = implode(", ", $select_sql_array);
1161
-        } else {
1162
-            $columns_to_select_string = $columns_to_select;
1163
-        }
1164
-        return $columns_to_select_string;
1165
-    }
1166
-
1167
-
1168
-
1169
-    /**
1170
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1171
-     *
1172
-     * @return string
1173
-     * @throws EE_Error
1174
-     */
1175
-    public function primary_key_name()
1176
-    {
1177
-        return $this->get_primary_key_field()->get_name();
1178
-    }
1179
-
1180
-
1181
-
1182
-    /**
1183
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1184
-     * If there is no primary key on this model, $id is treated as primary key string
1185
-     *
1186
-     * @param mixed $id int or string, depending on the type of the model's primary key
1187
-     * @return EE_Base_Class
1188
-     */
1189
-    public function get_one_by_ID($id)
1190
-    {
1191
-        if ($this->get_from_entity_map($id)) {
1192
-            return $this->get_from_entity_map($id);
1193
-        }
1194
-        return $this->get_one(
1195
-            $this->alter_query_params_to_restrict_by_ID(
1196
-                $id,
1197
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1198
-            )
1199
-        );
1200
-    }
1201
-
1202
-
1203
-
1204
-    /**
1205
-     * Alters query parameters to only get items with this ID are returned.
1206
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1207
-     * or could just be a simple primary key ID
1208
-     *
1209
-     * @param int   $id
1210
-     * @param array $query_params
1211
-     * @return array of normal query params, @see EEM_Base::get_all
1212
-     * @throws EE_Error
1213
-     */
1214
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1215
-    {
1216
-        if (! isset($query_params[0])) {
1217
-            $query_params[0] = array();
1218
-        }
1219
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1220
-        if ($conditions_from_id === null) {
1221
-            $query_params[0][$this->primary_key_name()] = $id;
1222
-        } else {
1223
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1224
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1225
-        }
1226
-        return $query_params;
1227
-    }
1228
-
1229
-
1230
-
1231
-    /**
1232
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1233
-     * array. If no item is found, null is returned.
1234
-     *
1235
-     * @param array $query_params like EEM_Base's $query_params variable.
1236
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1237
-     * @throws EE_Error
1238
-     */
1239
-    public function get_one($query_params = array())
1240
-    {
1241
-        if (! is_array($query_params)) {
1242
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1243
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1244
-                    gettype($query_params)), '4.6.0');
1245
-            $query_params = array();
1246
-        }
1247
-        $query_params['limit'] = 1;
1248
-        $items = $this->get_all($query_params);
1249
-        if (empty($items)) {
1250
-            return null;
1251
-        }
1252
-        return array_shift($items);
1253
-    }
1254
-
1255
-
1256
-
1257
-    /**
1258
-     * Returns the next x number of items in sequence from the given value as
1259
-     * found in the database matching the given query conditions.
1260
-     *
1261
-     * @param mixed $current_field_value    Value used for the reference point.
1262
-     * @param null  $field_to_order_by      What field is used for the
1263
-     *                                      reference point.
1264
-     * @param int   $limit                  How many to return.
1265
-     * @param array $query_params           Extra conditions on the query.
1266
-     * @param null  $columns_to_select      If left null, then an array of
1267
-     *                                      EE_Base_Class objects is returned,
1268
-     *                                      otherwise you can indicate just the
1269
-     *                                      columns you want returned.
1270
-     * @return EE_Base_Class[]|array
1271
-     * @throws EE_Error
1272
-     */
1273
-    public function next_x(
1274
-        $current_field_value,
1275
-        $field_to_order_by = null,
1276
-        $limit = 1,
1277
-        $query_params = array(),
1278
-        $columns_to_select = null
1279
-    ) {
1280
-        return $this->_get_consecutive(
1281
-            $current_field_value,
1282
-            '>',
1283
-            $field_to_order_by,
1284
-            $limit,
1285
-            $query_params,
1286
-            $columns_to_select
1287
-        );
1288
-    }
1289
-
1290
-
1291
-
1292
-    /**
1293
-     * Returns the previous x number of items in sequence from the given value
1294
-     * as found in the database matching the given query conditions.
1295
-     *
1296
-     * @param mixed $current_field_value    Value used for the reference point.
1297
-     * @param null  $field_to_order_by      What field is used for the
1298
-     *                                      reference point.
1299
-     * @param int   $limit                  How many to return.
1300
-     * @param array $query_params           Extra conditions on the query.
1301
-     * @param null  $columns_to_select      If left null, then an array of
1302
-     *                                      EE_Base_Class objects is returned,
1303
-     *                                      otherwise you can indicate just the
1304
-     *                                      columns you want returned.
1305
-     * @return EE_Base_Class[]|array
1306
-     * @throws EE_Error
1307
-     */
1308
-    public function previous_x(
1309
-        $current_field_value,
1310
-        $field_to_order_by = null,
1311
-        $limit = 1,
1312
-        $query_params = array(),
1313
-        $columns_to_select = null
1314
-    ) {
1315
-        return $this->_get_consecutive(
1316
-            $current_field_value,
1317
-            '<',
1318
-            $field_to_order_by,
1319
-            $limit,
1320
-            $query_params,
1321
-            $columns_to_select
1322
-        );
1323
-    }
1324
-
1325
-
1326
-
1327
-    /**
1328
-     * Returns the next item in sequence from the given value as found in the
1329
-     * database matching the given query conditions.
1330
-     *
1331
-     * @param mixed $current_field_value    Value used for the reference point.
1332
-     * @param null  $field_to_order_by      What field is used for the
1333
-     *                                      reference point.
1334
-     * @param array $query_params           Extra conditions on the query.
1335
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1336
-     *                                      object is returned, otherwise you
1337
-     *                                      can indicate just the columns you
1338
-     *                                      want and a single array indexed by
1339
-     *                                      the columns will be returned.
1340
-     * @return EE_Base_Class|null|array()
1341
-     * @throws EE_Error
1342
-     */
1343
-    public function next(
1344
-        $current_field_value,
1345
-        $field_to_order_by = null,
1346
-        $query_params = array(),
1347
-        $columns_to_select = null
1348
-    ) {
1349
-        $results = $this->_get_consecutive(
1350
-            $current_field_value,
1351
-            '>',
1352
-            $field_to_order_by,
1353
-            1,
1354
-            $query_params,
1355
-            $columns_to_select
1356
-        );
1357
-        return empty($results) ? null : reset($results);
1358
-    }
1359
-
1360
-
1361
-
1362
-    /**
1363
-     * Returns the previous item in sequence from the given value as found in
1364
-     * the database matching the given query conditions.
1365
-     *
1366
-     * @param mixed $current_field_value    Value used for the reference point.
1367
-     * @param null  $field_to_order_by      What field is used for the
1368
-     *                                      reference point.
1369
-     * @param array $query_params           Extra conditions on the query.
1370
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1371
-     *                                      object is returned, otherwise you
1372
-     *                                      can indicate just the columns you
1373
-     *                                      want and a single array indexed by
1374
-     *                                      the columns will be returned.
1375
-     * @return EE_Base_Class|null|array()
1376
-     * @throws EE_Error
1377
-     */
1378
-    public function previous(
1379
-        $current_field_value,
1380
-        $field_to_order_by = null,
1381
-        $query_params = array(),
1382
-        $columns_to_select = null
1383
-    ) {
1384
-        $results = $this->_get_consecutive(
1385
-            $current_field_value,
1386
-            '<',
1387
-            $field_to_order_by,
1388
-            1,
1389
-            $query_params,
1390
-            $columns_to_select
1391
-        );
1392
-        return empty($results) ? null : reset($results);
1393
-    }
1394
-
1395
-
1396
-
1397
-    /**
1398
-     * Returns the a consecutive number of items in sequence from the given
1399
-     * value as found in the database matching the given query conditions.
1400
-     *
1401
-     * @param mixed  $current_field_value   Value used for the reference point.
1402
-     * @param string $operand               What operand is used for the sequence.
1403
-     * @param string $field_to_order_by     What field is used for the reference point.
1404
-     * @param int    $limit                 How many to return.
1405
-     * @param array  $query_params          Extra conditions on the query.
1406
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1407
-     *                                      otherwise you can indicate just the columns you want returned.
1408
-     * @return EE_Base_Class[]|array
1409
-     * @throws EE_Error
1410
-     */
1411
-    protected function _get_consecutive(
1412
-        $current_field_value,
1413
-        $operand = '>',
1414
-        $field_to_order_by = null,
1415
-        $limit = 1,
1416
-        $query_params = array(),
1417
-        $columns_to_select = null
1418
-    ) {
1419
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1420
-        if (empty($field_to_order_by)) {
1421
-            if ($this->has_primary_key_field()) {
1422
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1423
-            } else {
1424
-                if (WP_DEBUG) {
1425
-                    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).',
1426
-                        'event_espresso'));
1427
-                }
1428
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1429
-                return array();
1430
-            }
1431
-        }
1432
-        if (! is_array($query_params)) {
1433
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1434
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1435
-                    gettype($query_params)), '4.6.0');
1436
-            $query_params = array();
1437
-        }
1438
-        //let's add the where query param for consecutive look up.
1439
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1440
-        $query_params['limit'] = $limit;
1441
-        //set direction
1442
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1443
-        $query_params['order_by'] = $operand === '>'
1444
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1445
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1446
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1447
-        if (empty($columns_to_select)) {
1448
-            return $this->get_all($query_params);
1449
-        }
1450
-        //getting just the fields
1451
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1452
-    }
1453
-
1454
-
1455
-
1456
-    /**
1457
-     * This sets the _timezone property after model object has been instantiated.
1458
-     *
1459
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1460
-     */
1461
-    public function set_timezone($timezone)
1462
-    {
1463
-        if ($timezone !== null) {
1464
-            $this->_timezone = $timezone;
1465
-        }
1466
-        //note we need to loop through relations and set the timezone on those objects as well.
1467
-        foreach ($this->_model_relations as $relation) {
1468
-            $relation->set_timezone($timezone);
1469
-        }
1470
-        //and finally we do the same for any datetime fields
1471
-        foreach ($this->_fields as $field) {
1472
-            if ($field instanceof EE_Datetime_Field) {
1473
-                $field->set_timezone($timezone);
1474
-            }
1475
-        }
1476
-    }
1477
-
1478
-
1479
-
1480
-    /**
1481
-     * This just returns whatever is set for the current timezone.
1482
-     *
1483
-     * @access public
1484
-     * @return string
1485
-     */
1486
-    public function get_timezone()
1487
-    {
1488
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1489
-        if (empty($this->_timezone)) {
1490
-            foreach ($this->_fields as $field) {
1491
-                if ($field instanceof EE_Datetime_Field) {
1492
-                    $this->set_timezone($field->get_timezone());
1493
-                    break;
1494
-                }
1495
-            }
1496
-        }
1497
-        //if timezone STILL empty then return the default timezone for the site.
1498
-        if (empty($this->_timezone)) {
1499
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1500
-        }
1501
-        return $this->_timezone;
1502
-    }
1503
-
1504
-
1505
-
1506
-    /**
1507
-     * This returns the date formats set for the given field name and also ensures that
1508
-     * $this->_timezone property is set correctly.
1509
-     *
1510
-     * @since 4.6.x
1511
-     * @param string $field_name The name of the field the formats are being retrieved for.
1512
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1513
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1514
-     * @return array formats in an array with the date format first, and the time format last.
1515
-     */
1516
-    public function get_formats_for($field_name, $pretty = false)
1517
-    {
1518
-        $field_settings = $this->field_settings_for($field_name);
1519
-        //if not a valid EE_Datetime_Field then throw error
1520
-        if (! $field_settings instanceof EE_Datetime_Field) {
1521
-            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.',
1522
-                'event_espresso'), $field_name));
1523
-        }
1524
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1525
-        //the field.
1526
-        $this->_timezone = $field_settings->get_timezone();
1527
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1528
-    }
1529
-
1530
-
1531
-
1532
-    /**
1533
-     * This returns the current time in a format setup for a query on this model.
1534
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1535
-     * it will return:
1536
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1537
-     *  NOW
1538
-     *  - or a unix timestamp (equivalent to time())
1539
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1540
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1541
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1542
-     * @since 4.6.x
1543
-     * @param string $field_name       The field the current time is needed for.
1544
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1545
-     *                                 formatted string matching the set format for the field in the set timezone will
1546
-     *                                 be returned.
1547
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1548
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1549
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1550
-     *                                 exception is triggered.
1551
-     */
1552
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1553
-    {
1554
-        $formats = $this->get_formats_for($field_name);
1555
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1556
-        if ($timestamp) {
1557
-            return $DateTime->format('U');
1558
-        }
1559
-        //not returning timestamp, so return formatted string in timezone.
1560
-        switch ($what) {
1561
-            case 'time' :
1562
-                return $DateTime->format($formats[1]);
1563
-                break;
1564
-            case 'date' :
1565
-                return $DateTime->format($formats[0]);
1566
-                break;
1567
-            default :
1568
-                return $DateTime->format(implode(' ', $formats));
1569
-                break;
1570
-        }
1571
-    }
1572
-
1573
-
1574
-
1575
-    /**
1576
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1577
-     * for the model are.  Returns a DateTime object.
1578
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1579
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1580
-     * ignored.
1581
-     *
1582
-     * @param string $field_name      The field being setup.
1583
-     * @param string $timestring      The date time string being used.
1584
-     * @param string $incoming_format The format for the time string.
1585
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1586
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1587
-     *                                format is
1588
-     *                                'U', this is ignored.
1589
-     * @return DateTime
1590
-     * @throws EE_Error
1591
-     */
1592
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1593
-    {
1594
-        //just using this to ensure the timezone is set correctly internally
1595
-        $this->get_formats_for($field_name);
1596
-        //load EEH_DTT_Helper
1597
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1598
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1599
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1600
-    }
1601
-
1602
-
1603
-
1604
-    /**
1605
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1606
-     *
1607
-     * @return EE_Table_Base[]
1608
-     */
1609
-    public function get_tables()
1610
-    {
1611
-        return $this->_tables;
1612
-    }
1613
-
1614
-
1615
-
1616
-    /**
1617
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1618
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1619
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1620
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1621
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1622
-     * model object with EVT_ID = 1
1623
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1624
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1625
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1626
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1627
-     * are not specified)
1628
-     *
1629
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1630
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1631
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1632
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1633
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1634
-     *                                         ID=34, we'd use this method as follows:
1635
-     *                                         EEM_Transaction::instance()->update(
1636
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1637
-     *                                         array(array('TXN_ID'=>34)));
1638
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1639
-     *                                         in client code into what's expected to be stored on each field. Eg,
1640
-     *                                         consider updating Question's QST_admin_label field is of type
1641
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1642
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1643
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1644
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1645
-     *                                         TRUE, it is assumed that you've already called
1646
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1647
-     *                                         malicious javascript. However, if
1648
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1649
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1650
-     *                                         and every other field, before insertion. We provide this parameter
1651
-     *                                         because model objects perform their prepare_for_set function on all
1652
-     *                                         their values, and so don't need to be called again (and in many cases,
1653
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1654
-     *                                         prepare_for_set method...)
1655
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1656
-     *                                         in this model's entity map according to $fields_n_values that match
1657
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1658
-     *                                         by setting this to FALSE, but be aware that model objects being used
1659
-     *                                         could get out-of-sync with the database
1660
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1661
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1662
-     *                                         bad)
1663
-     * @throws EE_Error
1664
-     */
1665
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1666
-    {
1667
-        if (! is_array($query_params)) {
1668
-            EE_Error::doing_it_wrong('EEM_Base::update',
1669
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1670
-                    gettype($query_params)), '4.6.0');
1671
-            $query_params = array();
1672
-        }
1673
-        /**
1674
-         * Action called before a model update call has been made.
1675
-         *
1676
-         * @param EEM_Base $model
1677
-         * @param array    $fields_n_values the updated fields and their new values
1678
-         * @param array    $query_params    @see EEM_Base::get_all()
1679
-         */
1680
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1681
-        /**
1682
-         * Filters the fields about to be updated given the query parameters. You can provide the
1683
-         * $query_params to $this->get_all() to find exactly which records will be updated
1684
-         *
1685
-         * @param array    $fields_n_values fields and their new values
1686
-         * @param EEM_Base $model           the model being queried
1687
-         * @param array    $query_params    see EEM_Base::get_all()
1688
-         */
1689
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1690
-            $query_params);
1691
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1692
-        //to do that, for each table, verify that it's PK isn't null.
1693
-        $tables = $this->get_tables();
1694
-        //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
1695
-        //NOTE: we should make this code more efficient by NOT querying twice
1696
-        //before the real update, but that needs to first go through ALPHA testing
1697
-        //as it's dangerous. says Mike August 8 2014
1698
-        //we want to make sure the default_where strategy is ignored
1699
-        $this->_ignore_where_strategy = true;
1700
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1701
-        foreach ($wpdb_select_results as $wpdb_result) {
1702
-            // type cast stdClass as array
1703
-            $wpdb_result = (array)$wpdb_result;
1704
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1705
-            if ($this->has_primary_key_field()) {
1706
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1707
-            } else {
1708
-                //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)
1709
-                $main_table_pk_value = null;
1710
-            }
1711
-            //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
1712
-            //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
1713
-            if (count($tables) > 1) {
1714
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1715
-                //in that table, and so we'll want to insert one
1716
-                foreach ($tables as $table_obj) {
1717
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1718
-                    //if there is no private key for this table on the results, it means there's no entry
1719
-                    //in this table, right? so insert a row in the current table, using any fields available
1720
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1721
-                           && $wpdb_result[$this_table_pk_column])
1722
-                    ) {
1723
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1724
-                            $main_table_pk_value);
1725
-                        //if we died here, report the error
1726
-                        if (! $success) {
1727
-                            return false;
1728
-                        }
1729
-                    }
1730
-                }
1731
-            }
1732
-            //				//and now check that if we have cached any models by that ID on the model, that
1733
-            //				//they also get updated properly
1734
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1735
-            //				if( $model_object ){
1736
-            //					foreach( $fields_n_values as $field => $value ){
1737
-            //						$model_object->set($field, $value);
1738
-            //let's make sure default_where strategy is followed now
1739
-            $this->_ignore_where_strategy = false;
1740
-        }
1741
-        //if we want to keep model objects in sync, AND
1742
-        //if this wasn't called from a model object (to update itself)
1743
-        //then we want to make sure we keep all the existing
1744
-        //model objects in sync with the db
1745
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1746
-            if ($this->has_primary_key_field()) {
1747
-                $model_objs_affected_ids = $this->get_col($query_params);
1748
-            } else {
1749
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1750
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1751
-                $model_objs_affected_ids = array();
1752
-                foreach ($models_affected_key_columns as $row) {
1753
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1754
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1755
-                }
1756
-            }
1757
-            if (! $model_objs_affected_ids) {
1758
-                //wait wait wait- if nothing was affected let's stop here
1759
-                return 0;
1760
-            }
1761
-            foreach ($model_objs_affected_ids as $id) {
1762
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1763
-                if ($model_obj_in_entity_map) {
1764
-                    foreach ($fields_n_values as $field => $new_value) {
1765
-                        $model_obj_in_entity_map->set($field, $new_value);
1766
-                    }
1767
-                }
1768
-            }
1769
-            //if there is a primary key on this model, we can now do a slight optimization
1770
-            if ($this->has_primary_key_field()) {
1771
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1772
-                $query_params = array(
1773
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1774
-                    'limit'                    => count($model_objs_affected_ids),
1775
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1776
-                );
1777
-            }
1778
-        }
1779
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1780
-        $SQL = "UPDATE "
1781
-               . $model_query_info->get_full_join_sql()
1782
-               . " SET "
1783
-               . $this->_construct_update_sql($fields_n_values)
1784
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1785
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1786
-        /**
1787
-         * Action called after a model update call has been made.
1788
-         *
1789
-         * @param EEM_Base $model
1790
-         * @param array    $fields_n_values the updated fields and their new values
1791
-         * @param array    $query_params    @see EEM_Base::get_all()
1792
-         * @param int      $rows_affected
1793
-         */
1794
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1795
-        return $rows_affected;//how many supposedly got updated
1796
-    }
1797
-
1798
-
1799
-
1800
-    /**
1801
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1802
-     * are teh values of the field specified (or by default the primary key field)
1803
-     * that matched the query params. Note that you should pass the name of the
1804
-     * model FIELD, not the database table's column name.
1805
-     *
1806
-     * @param array  $query_params @see EEM_Base::get_all()
1807
-     * @param string $field_to_select
1808
-     * @return array just like $wpdb->get_col()
1809
-     * @throws EE_Error
1810
-     */
1811
-    public function get_col($query_params = array(), $field_to_select = null)
1812
-    {
1813
-        if ($field_to_select) {
1814
-            $field = $this->field_settings_for($field_to_select);
1815
-        } elseif ($this->has_primary_key_field()) {
1816
-            $field = $this->get_primary_key_field();
1817
-        } else {
1818
-            //no primary key, just grab the first column
1819
-            $field = reset($this->field_settings());
1820
-        }
1821
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1822
-        $select_expressions = $field->get_qualified_column();
1823
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1824
-        return $this->_do_wpdb_query('get_col', array($SQL));
1825
-    }
1826
-
1827
-
1828
-
1829
-    /**
1830
-     * Returns a single column value for a single row from the database
1831
-     *
1832
-     * @param array  $query_params    @see EEM_Base::get_all()
1833
-     * @param string $field_to_select @see EEM_Base::get_col()
1834
-     * @return string
1835
-     * @throws EE_Error
1836
-     */
1837
-    public function get_var($query_params = array(), $field_to_select = null)
1838
-    {
1839
-        $query_params['limit'] = 1;
1840
-        $col = $this->get_col($query_params, $field_to_select);
1841
-        if (! empty($col)) {
1842
-            return reset($col);
1843
-        }
1844
-        return null;
1845
-    }
1846
-
1847
-
1848
-
1849
-    /**
1850
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1851
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1852
-     * injection, but currently no further filtering is done
1853
-     *
1854
-     * @global      $wpdb
1855
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1856
-     *                               be updated to in the DB
1857
-     * @return string of SQL
1858
-     * @throws EE_Error
1859
-     */
1860
-    public function _construct_update_sql($fields_n_values)
1861
-    {
1862
-        /** @type WPDB $wpdb */
1863
-        global $wpdb;
1864
-        $cols_n_values = array();
1865
-        foreach ($fields_n_values as $field_name => $value) {
1866
-            $field_obj = $this->field_settings_for($field_name);
1867
-            //if the value is NULL, we want to assign the value to that.
1868
-            //wpdb->prepare doesn't really handle that properly
1869
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1870
-            $value_sql = $prepared_value === null ? 'NULL'
1871
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1872
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1873
-        }
1874
-        return implode(",", $cols_n_values);
1875
-    }
1876
-
1877
-
1878
-
1879
-    /**
1880
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1881
-     * Performs a HARD delete, meaning the database row should always be removed,
1882
-     * not just have a flag field on it switched
1883
-     * Wrapper for EEM_Base::delete_permanently()
1884
-     *
1885
-     * @param mixed $id
1886
-     * @return boolean whether the row got deleted or not
1887
-     * @throws EE_Error
1888
-     */
1889
-    public function delete_permanently_by_ID($id)
1890
-    {
1891
-        return $this->delete_permanently(
1892
-            array(
1893
-                array($this->get_primary_key_field()->get_name() => $id),
1894
-                'limit' => 1,
1895
-            )
1896
-        );
1897
-    }
1898
-
1899
-
1900
-
1901
-    /**
1902
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1903
-     * Wrapper for EEM_Base::delete()
1904
-     *
1905
-     * @param mixed $id
1906
-     * @return boolean whether the row got deleted or not
1907
-     * @throws EE_Error
1908
-     */
1909
-    public function delete_by_ID($id)
1910
-    {
1911
-        return $this->delete(
1912
-            array(
1913
-                array($this->get_primary_key_field()->get_name() => $id),
1914
-                'limit' => 1,
1915
-            )
1916
-        );
1917
-    }
1918
-
1919
-
1920
-
1921
-    /**
1922
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1923
-     * meaning if the model has a field that indicates its been "trashed" or
1924
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1925
-     *
1926
-     * @see EEM_Base::delete_permanently
1927
-     * @param array   $query_params
1928
-     * @param boolean $allow_blocking
1929
-     * @return int how many rows got deleted
1930
-     * @throws EE_Error
1931
-     */
1932
-    public function delete($query_params, $allow_blocking = true)
1933
-    {
1934
-        return $this->delete_permanently($query_params, $allow_blocking);
1935
-    }
1936
-
1937
-
1938
-
1939
-    /**
1940
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1941
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1942
-     * as archived, not actually deleted
1943
-     *
1944
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1945
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1946
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1947
-     *                                deletes regardless of other objects which may depend on it. Its generally
1948
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1949
-     *                                DB
1950
-     * @return int how many rows got deleted
1951
-     * @throws EE_Error
1952
-     */
1953
-    public function delete_permanently($query_params, $allow_blocking = true)
1954
-    {
1955
-        /**
1956
-         * Action called just before performing a real deletion query. You can use the
1957
-         * model and its $query_params to find exactly which items will be deleted
1958
-         *
1959
-         * @param EEM_Base $model
1960
-         * @param array    $query_params   @see EEM_Base::get_all()
1961
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1962
-         *                                 to block (prevent) this deletion
1963
-         */
1964
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1965
-        //some MySQL databases may be running safe mode, which may restrict
1966
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1967
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1968
-        //to delete them
1969
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1970
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1971
-        if ($deletion_where) {
1972
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1973
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1974
-            $table_aliases = array_keys($this->_tables);
1975
-            $SQL = "DELETE "
1976
-                   . implode(", ", $table_aliases)
1977
-                   . " FROM "
1978
-                   . $model_query_info->get_full_join_sql()
1979
-                   . " WHERE "
1980
-                   . $deletion_where;
1981
-            //		/echo "delete sql:$SQL";
1982
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1983
-        } else {
1984
-            $rows_deleted = 0;
1985
-        }
1986
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1987
-        if ($this->has_primary_key_field()) {
1988
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1989
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1990
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1991
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1992
-                }
1993
-            }
1994
-        }
1995
-        /**
1996
-         * Action called just after performing a real deletion query. Although at this point the
1997
-         * items should have been deleted
1998
-         *
1999
-         * @param EEM_Base $model
2000
-         * @param array    $query_params @see EEM_Base::get_all()
2001
-         * @param int      $rows_deleted
2002
-         */
2003
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
2004
-        return $rows_deleted;//how many supposedly got deleted
2005
-    }
2006
-
2007
-
2008
-
2009
-    /**
2010
-     * Checks all the relations that throw error messages when there are blocking related objects
2011
-     * for related model objects. If there are any related model objects on those relations,
2012
-     * adds an EE_Error, and return true
2013
-     *
2014
-     * @param EE_Base_Class|int $this_model_obj_or_id
2015
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2016
-     *                                                 should be ignored when determining whether there are related
2017
-     *                                                 model objects which block this model object's deletion. Useful
2018
-     *                                                 if you know A is related to B and are considering deleting A,
2019
-     *                                                 but want to see if A has any other objects blocking its deletion
2020
-     *                                                 before removing the relation between A and B
2021
-     * @return boolean
2022
-     * @throws EE_Error
2023
-     */
2024
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2025
-    {
2026
-        //first, if $ignore_this_model_obj was supplied, get its model
2027
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2028
-            $ignored_model = $ignore_this_model_obj->get_model();
2029
-        } else {
2030
-            $ignored_model = null;
2031
-        }
2032
-        //now check all the relations of $this_model_obj_or_id and see if there
2033
-        //are any related model objects blocking it?
2034
-        $is_blocked = false;
2035
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2036
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2037
-                //if $ignore_this_model_obj was supplied, then for the query
2038
-                //on that model needs to be told to ignore $ignore_this_model_obj
2039
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2040
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2041
-                        array(
2042
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2043
-                                '!=',
2044
-                                $ignore_this_model_obj->ID(),
2045
-                            ),
2046
-                        ),
2047
-                    ));
2048
-                } else {
2049
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2050
-                }
2051
-                if ($related_model_objects) {
2052
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2053
-                    $is_blocked = true;
2054
-                }
2055
-            }
2056
-        }
2057
-        return $is_blocked;
2058
-    }
2059
-
2060
-
2061
-
2062
-    /**
2063
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2064
-     * well.
2065
-     *
2066
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2067
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2068
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
2069
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
2070
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
2071
-     *                                      easily corrupt your DB
2072
-     * @throws EE_Error
2073
-     * @return string    everything that comes after the WHERE statement.
2074
-     */
2075
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2076
-    {
2077
-        if ($this->has_primary_key_field()) {
2078
-            $primary_table = $this->_get_main_table();
2079
-            $other_tables = $this->_get_other_tables();
2080
-            $deletes = $query = array();
2081
-            foreach ($objects_for_deletion as $delete_object) {
2082
-                //before we mark this object for deletion,
2083
-                //make sure there's no related objects blocking its deletion (if we're checking)
2084
-                if (
2085
-                    $allow_blocking
2086
-                    && $this->delete_is_blocked_by_related_models(
2087
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
2088
-                    )
2089
-                ) {
2090
-                    continue;
2091
-                }
2092
-                //primary table deletes
2093
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2094
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2095
-                }
2096
-                //other tables
2097
-                if (! empty($other_tables)) {
2098
-                    foreach ($other_tables as $ot) {
2099
-                        //first check if we've got the foreign key column here.
2100
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2101
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2102
-                        }
2103
-                        // wait! it's entirely possible that we'll have a the primary key
2104
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
2105
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2106
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2107
-                        }
2108
-                        // finally, it is possible that the fk for this table is found
2109
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
2110
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2111
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2112
-                        }
2113
-                    }
2114
-                }
2115
-            }
2116
-            //we should have deletes now, so let's just go through and setup the where statement
2117
-            foreach ($deletes as $column => $values) {
2118
-                //make sure we have unique $values;
2119
-                $values = array_unique($values);
2120
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2121
-            }
2122
-            return ! empty($query) ? implode(' AND ', $query) : '';
2123
-        }
2124
-        if (count($this->get_combined_primary_key_fields()) > 1) {
2125
-            $ways_to_identify_a_row = array();
2126
-            $fields = $this->get_combined_primary_key_fields();
2127
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2128
-            foreach ($objects_for_deletion as $delete_object) {
2129
-                $values_for_each_cpk_for_a_row = array();
2130
-                foreach ($fields as $cpk_field) {
2131
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2132
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2133
-                                                           . "="
2134
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
2135
-                    }
2136
-                }
2137
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2138
-            }
2139
-            return implode(" OR ", $ways_to_identify_a_row);
2140
-        }
2141
-        //so there's no primary key and no combined key...
2142
-        //sorry, can't help you
2143
-        throw new EE_Error(
2144
-            sprintf(
2145
-                __(
2146
-                    "Cannot delete objects of type %s because there is no primary key NOR combined key",
2147
-                    "event_espresso"
2148
-                ), get_class($this)
2149
-            )
2150
-        );
2151
-    }
2152
-
2153
-
2154
-
2155
-    /**
2156
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2157
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2158
-     * column
2159
-     *
2160
-     * @param array  $query_params   like EEM_Base::get_all's
2161
-     * @param string $field_to_count field on model to count by (not column name)
2162
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2163
-     *                               that by the setting $distinct to TRUE;
2164
-     * @return int
2165
-     * @throws EE_Error
2166
-     */
2167
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2168
-    {
2169
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2170
-        if ($field_to_count) {
2171
-            $field_obj = $this->field_settings_for($field_to_count);
2172
-            $column_to_count = $field_obj->get_qualified_column();
2173
-        } elseif ($this->has_primary_key_field()) {
2174
-            $pk_field_obj = $this->get_primary_key_field();
2175
-            $column_to_count = $pk_field_obj->get_qualified_column();
2176
-        } else {
2177
-            //there's no primary key
2178
-            //if we're counting distinct items, and there's no primary key,
2179
-            //we need to list out the columns for distinction;
2180
-            //otherwise we can just use star
2181
-            if ($distinct) {
2182
-                $columns_to_use = array();
2183
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2184
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2185
-                }
2186
-                $column_to_count = implode(',', $columns_to_use);
2187
-            } else {
2188
-                $column_to_count = '*';
2189
-            }
2190
-        }
2191
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2192
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2193
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2194
-    }
2195
-
2196
-
2197
-
2198
-    /**
2199
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2200
-     *
2201
-     * @param array  $query_params like EEM_Base::get_all
2202
-     * @param string $field_to_sum name of field (array key in $_fields array)
2203
-     * @return float
2204
-     * @throws EE_Error
2205
-     */
2206
-    public function sum($query_params, $field_to_sum = null)
2207
-    {
2208
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2209
-        if ($field_to_sum) {
2210
-            $field_obj = $this->field_settings_for($field_to_sum);
2211
-        } else {
2212
-            $field_obj = $this->get_primary_key_field();
2213
-        }
2214
-        $column_to_count = $field_obj->get_qualified_column();
2215
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2216
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2217
-        $data_type = $field_obj->get_wpdb_data_type();
2218
-        if ($data_type === '%d' || $data_type === '%s') {
2219
-            return (float)$return_value;
2220
-        }
2221
-        //must be %f
2222
-        return (float)$return_value;
2223
-    }
2224
-
2225
-
2226
-
2227
-    /**
2228
-     * Just calls the specified method on $wpdb with the given arguments
2229
-     * Consolidates a little extra error handling code
2230
-     *
2231
-     * @param string $wpdb_method
2232
-     * @param array  $arguments_to_provide
2233
-     * @throws EE_Error
2234
-     * @global wpdb  $wpdb
2235
-     * @return mixed
2236
-     */
2237
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2238
-    {
2239
-        //if we're in maintenance mode level 2, DON'T run any queries
2240
-        //because level 2 indicates the database needs updating and
2241
-        //is probably out of sync with the code
2242
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2243
-            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.",
2244
-                "event_espresso")));
2245
-        }
2246
-        /** @type WPDB $wpdb */
2247
-        global $wpdb;
2248
-        if (! method_exists($wpdb, $wpdb_method)) {
2249
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2250
-                'event_espresso'), $wpdb_method));
2251
-        }
2252
-        if (WP_DEBUG) {
2253
-            $old_show_errors_value = $wpdb->show_errors;
2254
-            $wpdb->show_errors(false);
2255
-        }
2256
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2257
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2258
-        if (WP_DEBUG) {
2259
-            $wpdb->show_errors($old_show_errors_value);
2260
-            if (! empty($wpdb->last_error)) {
2261
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2262
-            }
2263
-            if ($result === false) {
2264
-                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"',
2265
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2266
-            }
2267
-        } elseif ($result === false) {
2268
-            EE_Error::add_error(
2269
-                sprintf(
2270
-                    __('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"',
2271
-                        'event_espresso'),
2272
-                    $wpdb_method,
2273
-                    var_export($arguments_to_provide, true),
2274
-                    $wpdb->last_error
2275
-                ),
2276
-                __FILE__,
2277
-                __FUNCTION__,
2278
-                __LINE__
2279
-            );
2280
-        }
2281
-        return $result;
2282
-    }
2283
-
2284
-
2285
-
2286
-    /**
2287
-     * Attempts to run the indicated WPDB method with the provided arguments,
2288
-     * and if there's an error tries to verify the DB is correct. Uses
2289
-     * the static property EEM_Base::$_db_verification_level to determine whether
2290
-     * we should try to fix the EE core db, the addons, or just give up
2291
-     *
2292
-     * @param string $wpdb_method
2293
-     * @param array  $arguments_to_provide
2294
-     * @return mixed
2295
-     */
2296
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2297
-    {
2298
-        /** @type WPDB $wpdb */
2299
-        global $wpdb;
2300
-        $wpdb->last_error = null;
2301
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2302
-        // was there an error running the query? but we don't care on new activations
2303
-        // (we're going to setup the DB anyway on new activations)
2304
-        if (($result === false || ! empty($wpdb->last_error))
2305
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2306
-        ) {
2307
-            switch (EEM_Base::$_db_verification_level) {
2308
-                case EEM_Base::db_verified_none :
2309
-                    // let's double-check core's DB
2310
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2311
-                    break;
2312
-                case EEM_Base::db_verified_core :
2313
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2314
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2315
-                    break;
2316
-                case EEM_Base::db_verified_addons :
2317
-                    // ummmm... you in trouble
2318
-                    return $result;
2319
-                    break;
2320
-            }
2321
-            if (! empty($error_message)) {
2322
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2323
-                trigger_error($error_message);
2324
-            }
2325
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2326
-        }
2327
-        return $result;
2328
-    }
2329
-
2330
-
2331
-
2332
-    /**
2333
-     * Verifies the EE core database is up-to-date and records that we've done it on
2334
-     * EEM_Base::$_db_verification_level
2335
-     *
2336
-     * @param string $wpdb_method
2337
-     * @param array  $arguments_to_provide
2338
-     * @return string
2339
-     */
2340
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2341
-    {
2342
-        /** @type WPDB $wpdb */
2343
-        global $wpdb;
2344
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2345
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2346
-        $error_message = sprintf(
2347
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2348
-                'event_espresso'),
2349
-            $wpdb->last_error,
2350
-            $wpdb_method,
2351
-            wp_json_encode($arguments_to_provide)
2352
-        );
2353
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2354
-        return $error_message;
2355
-    }
2356
-
2357
-
2358
-
2359
-    /**
2360
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2361
-     * EEM_Base::$_db_verification_level
2362
-     *
2363
-     * @param $wpdb_method
2364
-     * @param $arguments_to_provide
2365
-     * @return string
2366
-     */
2367
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2368
-    {
2369
-        /** @type WPDB $wpdb */
2370
-        global $wpdb;
2371
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2372
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2373
-        $error_message = sprintf(
2374
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2375
-                'event_espresso'),
2376
-            $wpdb->last_error,
2377
-            $wpdb_method,
2378
-            wp_json_encode($arguments_to_provide)
2379
-        );
2380
-        EE_System::instance()->initialize_addons();
2381
-        return $error_message;
2382
-    }
2383
-
2384
-
2385
-
2386
-    /**
2387
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2388
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2389
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2390
-     * ..."
2391
-     *
2392
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2393
-     * @return string
2394
-     */
2395
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2396
-    {
2397
-        return " FROM " . $model_query_info->get_full_join_sql() .
2398
-               $model_query_info->get_where_sql() .
2399
-               $model_query_info->get_group_by_sql() .
2400
-               $model_query_info->get_having_sql() .
2401
-               $model_query_info->get_order_by_sql() .
2402
-               $model_query_info->get_limit_sql();
2403
-    }
2404
-
2405
-
2406
-
2407
-    /**
2408
-     * Set to easily debug the next X queries ran from this model.
2409
-     *
2410
-     * @param int $count
2411
-     */
2412
-    public function show_next_x_db_queries($count = 1)
2413
-    {
2414
-        $this->_show_next_x_db_queries = $count;
2415
-    }
2416
-
2417
-
2418
-
2419
-    /**
2420
-     * @param $sql_query
2421
-     */
2422
-    public function show_db_query_if_previously_requested($sql_query)
2423
-    {
2424
-        if ($this->_show_next_x_db_queries > 0) {
2425
-            echo $sql_query;
2426
-            $this->_show_next_x_db_queries--;
2427
-        }
2428
-    }
2429
-
2430
-
2431
-
2432
-    /**
2433
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2434
-     * There are the 3 cases:
2435
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2436
-     * $otherModelObject has no ID, it is first saved.
2437
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2438
-     * has no ID, it is first saved.
2439
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2440
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2441
-     * join table
2442
-     *
2443
-     * @param        EE_Base_Class                     /int $thisModelObject
2444
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2445
-     * @param string $relationName                     , key in EEM_Base::_relations
2446
-     *                                                 an attendee to a group, you also want to specify which role they
2447
-     *                                                 will have in that group. So you would use this parameter to
2448
-     *                                                 specify array('role-column-name'=>'role-id')
2449
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2450
-     *                                                 to for relation to methods that allow you to further specify
2451
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2452
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2453
-     *                                                 because these will be inserted in any new rows created as well.
2454
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2455
-     * @throws EE_Error
2456
-     */
2457
-    public function add_relationship_to(
2458
-        $id_or_obj,
2459
-        $other_model_id_or_obj,
2460
-        $relationName,
2461
-        $extra_join_model_fields_n_values = array()
2462
-    ) {
2463
-        $relation_obj = $this->related_settings_for($relationName);
2464
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2465
-    }
2466
-
2467
-
2468
-
2469
-    /**
2470
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2471
-     * There are the 3 cases:
2472
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2473
-     * error
2474
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2475
-     * an error
2476
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2477
-     *
2478
-     * @param        EE_Base_Class /int $id_or_obj
2479
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2480
-     * @param string $relationName key in EEM_Base::_relations
2481
-     * @return boolean of success
2482
-     * @throws EE_Error
2483
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2484
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2485
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2486
-     *                             because these will be inserted in any new rows created as well.
2487
-     */
2488
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2489
-    {
2490
-        $relation_obj = $this->related_settings_for($relationName);
2491
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2492
-    }
2493
-
2494
-
2495
-
2496
-    /**
2497
-     * @param mixed           $id_or_obj
2498
-     * @param string          $relationName
2499
-     * @param array           $where_query_params
2500
-     * @param EE_Base_Class[] objects to which relations were removed
2501
-     * @return \EE_Base_Class[]
2502
-     * @throws EE_Error
2503
-     */
2504
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2505
-    {
2506
-        $relation_obj = $this->related_settings_for($relationName);
2507
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2508
-    }
2509
-
2510
-
2511
-
2512
-    /**
2513
-     * Gets all the related items of the specified $model_name, using $query_params.
2514
-     * Note: by default, we remove the "default query params"
2515
-     * because we want to get even deleted items etc.
2516
-     *
2517
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2518
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2519
-     * @param array  $query_params like EEM_Base::get_all
2520
-     * @return EE_Base_Class[]
2521
-     * @throws EE_Error
2522
-     */
2523
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2524
-    {
2525
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2526
-        $relation_settings = $this->related_settings_for($model_name);
2527
-        return $relation_settings->get_all_related($model_obj, $query_params);
2528
-    }
2529
-
2530
-
2531
-
2532
-    /**
2533
-     * Deletes all the model objects across the relation indicated by $model_name
2534
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2535
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2536
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2537
-     *
2538
-     * @param EE_Base_Class|int|string $id_or_obj
2539
-     * @param string                   $model_name
2540
-     * @param array                    $query_params
2541
-     * @return int how many deleted
2542
-     * @throws EE_Error
2543
-     */
2544
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2545
-    {
2546
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2547
-        $relation_settings = $this->related_settings_for($model_name);
2548
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2549
-    }
2550
-
2551
-
2552
-
2553
-    /**
2554
-     * Hard deletes all the model objects across the relation indicated by $model_name
2555
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2556
-     * the model objects can't be hard deleted because of blocking related model objects,
2557
-     * just does a soft-delete on them instead.
2558
-     *
2559
-     * @param EE_Base_Class|int|string $id_or_obj
2560
-     * @param string                   $model_name
2561
-     * @param array                    $query_params
2562
-     * @return int how many deleted
2563
-     * @throws EE_Error
2564
-     */
2565
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2566
-    {
2567
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2568
-        $relation_settings = $this->related_settings_for($model_name);
2569
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2570
-    }
2571
-
2572
-
2573
-
2574
-    /**
2575
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2576
-     * unless otherwise specified in the $query_params
2577
-     *
2578
-     * @param        int             /EE_Base_Class $id_or_obj
2579
-     * @param string $model_name     like 'Event', or 'Registration'
2580
-     * @param array  $query_params   like EEM_Base::get_all's
2581
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2582
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2583
-     *                               that by the setting $distinct to TRUE;
2584
-     * @return int
2585
-     * @throws EE_Error
2586
-     */
2587
-    public function count_related(
2588
-        $id_or_obj,
2589
-        $model_name,
2590
-        $query_params = array(),
2591
-        $field_to_count = null,
2592
-        $distinct = false
2593
-    ) {
2594
-        $related_model = $this->get_related_model_obj($model_name);
2595
-        //we're just going to use the query params on the related model's normal get_all query,
2596
-        //except add a condition to say to match the current mod
2597
-        if (! isset($query_params['default_where_conditions'])) {
2598
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2599
-        }
2600
-        $this_model_name = $this->get_this_model_name();
2601
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2602
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2603
-        return $related_model->count($query_params, $field_to_count, $distinct);
2604
-    }
2605
-
2606
-
2607
-
2608
-    /**
2609
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2610
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2611
-     *
2612
-     * @param        int           /EE_Base_Class $id_or_obj
2613
-     * @param string $model_name   like 'Event', or 'Registration'
2614
-     * @param array  $query_params like EEM_Base::get_all's
2615
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2616
-     * @return float
2617
-     * @throws EE_Error
2618
-     */
2619
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2620
-    {
2621
-        $related_model = $this->get_related_model_obj($model_name);
2622
-        if (! is_array($query_params)) {
2623
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2624
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2625
-                    gettype($query_params)), '4.6.0');
2626
-            $query_params = array();
2627
-        }
2628
-        //we're just going to use the query params on the related model's normal get_all query,
2629
-        //except add a condition to say to match the current mod
2630
-        if (! isset($query_params['default_where_conditions'])) {
2631
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2632
-        }
2633
-        $this_model_name = $this->get_this_model_name();
2634
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2635
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2636
-        return $related_model->sum($query_params, $field_to_sum);
2637
-    }
2638
-
2639
-
2640
-
2641
-    /**
2642
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2643
-     * $modelObject
2644
-     *
2645
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2646
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2647
-     * @param array               $query_params     like EEM_Base::get_all's
2648
-     * @return EE_Base_Class
2649
-     * @throws EE_Error
2650
-     */
2651
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2652
-    {
2653
-        $query_params['limit'] = 1;
2654
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2655
-        if ($results) {
2656
-            return array_shift($results);
2657
-        }
2658
-        return null;
2659
-    }
2660
-
2661
-
2662
-
2663
-    /**
2664
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2665
-     *
2666
-     * @return string
2667
-     */
2668
-    public function get_this_model_name()
2669
-    {
2670
-        return str_replace("EEM_", "", get_class($this));
2671
-    }
2672
-
2673
-
2674
-
2675
-    /**
2676
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2677
-     *
2678
-     * @return EE_Any_Foreign_Model_Name_Field
2679
-     * @throws EE_Error
2680
-     */
2681
-    public function get_field_containing_related_model_name()
2682
-    {
2683
-        foreach ($this->field_settings(true) as $field) {
2684
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2685
-                $field_with_model_name = $field;
2686
-            }
2687
-        }
2688
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2689
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2690
-                $this->get_this_model_name()));
2691
-        }
2692
-        return $field_with_model_name;
2693
-    }
2694
-
2695
-
2696
-
2697
-    /**
2698
-     * Inserts a new entry into the database, for each table.
2699
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2700
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2701
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2702
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2703
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2704
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2705
-     *
2706
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2707
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2708
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2709
-     *                              of EEM_Base)
2710
-     * @return int new primary key on main table that got inserted
2711
-     * @throws EE_Error
2712
-     */
2713
-    public function insert($field_n_values)
2714
-    {
2715
-        /**
2716
-         * Filters the fields and their values before inserting an item using the models
2717
-         *
2718
-         * @param array    $fields_n_values keys are the fields and values are their new values
2719
-         * @param EEM_Base $model           the model used
2720
-         */
2721
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2722
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2723
-            $main_table = $this->_get_main_table();
2724
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2725
-            if ($new_id !== false) {
2726
-                foreach ($this->_get_other_tables() as $other_table) {
2727
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2728
-                }
2729
-            }
2730
-            /**
2731
-             * Done just after attempting to insert a new model object
2732
-             *
2733
-             * @param EEM_Base   $model           used
2734
-             * @param array      $fields_n_values fields and their values
2735
-             * @param int|string the              ID of the newly-inserted model object
2736
-             */
2737
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2738
-            return $new_id;
2739
-        }
2740
-        return false;
2741
-    }
2742
-
2743
-
2744
-
2745
-    /**
2746
-     * Checks that the result would satisfy the unique indexes on this model
2747
-     *
2748
-     * @param array  $field_n_values
2749
-     * @param string $action
2750
-     * @return boolean
2751
-     * @throws EE_Error
2752
-     */
2753
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2754
-    {
2755
-        foreach ($this->unique_indexes() as $index_name => $index) {
2756
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2757
-            if ($this->exists(array($uniqueness_where_params))) {
2758
-                EE_Error::add_error(
2759
-                    sprintf(
2760
-                        __(
2761
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2762
-                            "event_espresso"
2763
-                        ),
2764
-                        $action,
2765
-                        $this->_get_class_name(),
2766
-                        $index_name,
2767
-                        implode(",", $index->field_names()),
2768
-                        http_build_query($uniqueness_where_params)
2769
-                    ),
2770
-                    __FILE__,
2771
-                    __FUNCTION__,
2772
-                    __LINE__
2773
-                );
2774
-                return false;
2775
-            }
2776
-        }
2777
-        return true;
2778
-    }
2779
-
2780
-
2781
-
2782
-    /**
2783
-     * Checks the database for an item that conflicts (ie, if this item were
2784
-     * saved to the DB would break some uniqueness requirement, like a primary key
2785
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2786
-     * can be either an EE_Base_Class or an array of fields n values
2787
-     *
2788
-     * @param EE_Base_Class|array $obj_or_fields_array
2789
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2790
-     *                                                 when looking for conflicts
2791
-     *                                                 (ie, if false, we ignore the model object's primary key
2792
-     *                                                 when finding "conflicts". If true, it's also considered).
2793
-     *                                                 Only works for INT primary key,
2794
-     *                                                 STRING primary keys cannot be ignored
2795
-     * @throws EE_Error
2796
-     * @return EE_Base_Class|array
2797
-     */
2798
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2799
-    {
2800
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2801
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2802
-        } elseif (is_array($obj_or_fields_array)) {
2803
-            $fields_n_values = $obj_or_fields_array;
2804
-        } else {
2805
-            throw new EE_Error(
2806
-                sprintf(
2807
-                    __(
2808
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2809
-                        "event_espresso"
2810
-                    ),
2811
-                    get_class($this),
2812
-                    $obj_or_fields_array
2813
-                )
2814
-            );
2815
-        }
2816
-        $query_params = array();
2817
-        if ($this->has_primary_key_field()
2818
-            && ($include_primary_key
2819
-                || $this->get_primary_key_field()
2820
-                   instanceof
2821
-                   EE_Primary_Key_String_Field)
2822
-            && isset($fields_n_values[$this->primary_key_name()])
2823
-        ) {
2824
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2825
-        }
2826
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2827
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2828
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2829
-        }
2830
-        //if there is nothing to base this search on, then we shouldn't find anything
2831
-        if (empty($query_params)) {
2832
-            return array();
2833
-        }
2834
-        return $this->get_one($query_params);
2835
-    }
2836
-
2837
-
2838
-
2839
-    /**
2840
-     * Like count, but is optimized and returns a boolean instead of an int
2841
-     *
2842
-     * @param array $query_params
2843
-     * @return boolean
2844
-     * @throws EE_Error
2845
-     */
2846
-    public function exists($query_params)
2847
-    {
2848
-        $query_params['limit'] = 1;
2849
-        return $this->count($query_params) > 0;
2850
-    }
2851
-
2852
-
2853
-
2854
-    /**
2855
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2856
-     *
2857
-     * @param int|string $id
2858
-     * @return boolean
2859
-     * @throws EE_Error
2860
-     */
2861
-    public function exists_by_ID($id)
2862
-    {
2863
-        return $this->exists(
2864
-            array(
2865
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2866
-                array(
2867
-                    $this->primary_key_name() => $id,
2868
-                ),
2869
-            )
2870
-        );
2871
-    }
2872
-
2873
-
2874
-
2875
-    /**
2876
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2877
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2878
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2879
-     * on the main table)
2880
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2881
-     * cases where we want to call it directly rather than via insert().
2882
-     *
2883
-     * @access   protected
2884
-     * @param EE_Table_Base $table
2885
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2886
-     *                                       float
2887
-     * @param int           $new_id          for now we assume only int keys
2888
-     * @throws EE_Error
2889
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2890
-     * @return int ID of new row inserted, or FALSE on failure
2891
-     */
2892
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2893
-    {
2894
-        global $wpdb;
2895
-        $insertion_col_n_values = array();
2896
-        $format_for_insertion = array();
2897
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2898
-        foreach ($fields_on_table as $field_name => $field_obj) {
2899
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2900
-            if ($field_obj->is_auto_increment()) {
2901
-                continue;
2902
-            }
2903
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2904
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2905
-            if ($prepared_value !== null) {
2906
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2907
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2908
-            }
2909
-        }
2910
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2911
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2912
-            //so add the fk to the main table as a column
2913
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2914
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2915
-        }
2916
-        //insert the new entry
2917
-        $result = $this->_do_wpdb_query('insert',
2918
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2919
-        if ($result === false) {
2920
-            return false;
2921
-        }
2922
-        //ok, now what do we return for the ID of the newly-inserted thing?
2923
-        if ($this->has_primary_key_field()) {
2924
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2925
-                return $wpdb->insert_id;
2926
-            }
2927
-            //it's not an auto-increment primary key, so
2928
-            //it must have been supplied
2929
-            return $fields_n_values[$this->get_primary_key_field()->get_name()];
2930
-        }
2931
-        //we can't return a  primary key because there is none. instead return
2932
-        //a unique string indicating this model
2933
-        return $this->get_index_primary_key_string($fields_n_values);
2934
-    }
2935
-
2936
-
2937
-
2938
-    /**
2939
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2940
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2941
-     * and there is no default, we pass it along. WPDB will take care of it)
2942
-     *
2943
-     * @param EE_Model_Field_Base $field_obj
2944
-     * @param array               $fields_n_values
2945
-     * @return mixed string|int|float depending on what the table column will be expecting
2946
-     * @throws EE_Error
2947
-     */
2948
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2949
-    {
2950
-        //if this field doesn't allow nullable, don't allow it
2951
-        if (
2952
-            ! $field_obj->is_nullable()
2953
-            && (
2954
-                ! isset($fields_n_values[$field_obj->get_name()])
2955
-                || $fields_n_values[$field_obj->get_name()] === null
2956
-            )
2957
-        ) {
2958
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2959
-        }
2960
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2961
-            ? $fields_n_values[$field_obj->get_name()]
2962
-            : null;
2963
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2964
-    }
2965
-
2966
-
2967
-
2968
-    /**
2969
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2970
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2971
-     * the field's prepare_for_set() method.
2972
-     *
2973
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2974
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2975
-     *                                   top of file)
2976
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2977
-     *                                   $value is a custom selection
2978
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2979
-     */
2980
-    private function _prepare_value_for_use_in_db($value, $field)
2981
-    {
2982
-        if ($field && $field instanceof EE_Model_Field_Base) {
2983
-            switch ($this->_values_already_prepared_by_model_object) {
2984
-                /** @noinspection PhpMissingBreakStatementInspection */
2985
-                case self::not_prepared_by_model_object:
2986
-                    $value = $field->prepare_for_set($value);
2987
-                //purposefully left out "return"
2988
-                case self::prepared_by_model_object:
2989
-                    /** @noinspection SuspiciousAssignmentsInspection */
2990
-                    $value = $field->prepare_for_use_in_db($value);
2991
-                case self::prepared_for_use_in_db:
2992
-                    //leave the value alone
2993
-            }
2994
-            return $value;
2995
-        }
2996
-        return $value;
2997
-    }
2998
-
2999
-
3000
-
3001
-    /**
3002
-     * Returns the main table on this model
3003
-     *
3004
-     * @return EE_Primary_Table
3005
-     * @throws EE_Error
3006
-     */
3007
-    protected function _get_main_table()
3008
-    {
3009
-        foreach ($this->_tables as $table) {
3010
-            if ($table instanceof EE_Primary_Table) {
3011
-                return $table;
3012
-            }
3013
-        }
3014
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3015
-            'event_espresso'), get_class($this)));
3016
-    }
3017
-
3018
-
3019
-
3020
-    /**
3021
-     * table
3022
-     * returns EE_Primary_Table table name
3023
-     *
3024
-     * @return string
3025
-     * @throws EE_Error
3026
-     */
3027
-    public function table()
3028
-    {
3029
-        return $this->_get_main_table()->get_table_name();
3030
-    }
3031
-
3032
-
3033
-
3034
-    /**
3035
-     * table
3036
-     * returns first EE_Secondary_Table table name
3037
-     *
3038
-     * @return string
3039
-     */
3040
-    public function second_table()
3041
-    {
3042
-        // grab second table from tables array
3043
-        $second_table = end($this->_tables);
3044
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3045
-    }
3046
-
3047
-
3048
-
3049
-    /**
3050
-     * get_table_obj_by_alias
3051
-     * returns table name given it's alias
3052
-     *
3053
-     * @param string $table_alias
3054
-     * @return EE_Primary_Table | EE_Secondary_Table
3055
-     */
3056
-    public function get_table_obj_by_alias($table_alias = '')
3057
-    {
3058
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3059
-    }
3060
-
3061
-
3062
-
3063
-    /**
3064
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3065
-     *
3066
-     * @return EE_Secondary_Table[]
3067
-     */
3068
-    protected function _get_other_tables()
3069
-    {
3070
-        $other_tables = array();
3071
-        foreach ($this->_tables as $table_alias => $table) {
3072
-            if ($table instanceof EE_Secondary_Table) {
3073
-                $other_tables[$table_alias] = $table;
3074
-            }
3075
-        }
3076
-        return $other_tables;
3077
-    }
3078
-
3079
-
3080
-
3081
-    /**
3082
-     * Finds all the fields that correspond to the given table
3083
-     *
3084
-     * @param string $table_alias , array key in EEM_Base::_tables
3085
-     * @return EE_Model_Field_Base[]
3086
-     */
3087
-    public function _get_fields_for_table($table_alias)
3088
-    {
3089
-        return $this->_fields[$table_alias];
3090
-    }
3091
-
3092
-
3093
-
3094
-    /**
3095
-     * Recurses through all the where parameters, and finds all the related models we'll need
3096
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3097
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3098
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3099
-     * related Registration, Transaction, and Payment models.
3100
-     *
3101
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3102
-     * @return EE_Model_Query_Info_Carrier
3103
-     * @throws EE_Error
3104
-     */
3105
-    public function _extract_related_models_from_query($query_params)
3106
-    {
3107
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3108
-        if (array_key_exists(0, $query_params)) {
3109
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3110
-        }
3111
-        if (array_key_exists('group_by', $query_params)) {
3112
-            if (is_array($query_params['group_by'])) {
3113
-                $this->_extract_related_models_from_sub_params_array_values(
3114
-                    $query_params['group_by'],
3115
-                    $query_info_carrier,
3116
-                    'group_by'
3117
-                );
3118
-            } elseif (! empty ($query_params['group_by'])) {
3119
-                $this->_extract_related_model_info_from_query_param(
3120
-                    $query_params['group_by'],
3121
-                    $query_info_carrier,
3122
-                    'group_by'
3123
-                );
3124
-            }
3125
-        }
3126
-        if (array_key_exists('having', $query_params)) {
3127
-            $this->_extract_related_models_from_sub_params_array_keys(
3128
-                $query_params[0],
3129
-                $query_info_carrier,
3130
-                'having'
3131
-            );
3132
-        }
3133
-        if (array_key_exists('order_by', $query_params)) {
3134
-            if (is_array($query_params['order_by'])) {
3135
-                $this->_extract_related_models_from_sub_params_array_keys(
3136
-                    $query_params['order_by'],
3137
-                    $query_info_carrier,
3138
-                    'order_by'
3139
-                );
3140
-            } elseif (! empty($query_params['order_by'])) {
3141
-                $this->_extract_related_model_info_from_query_param(
3142
-                    $query_params['order_by'],
3143
-                    $query_info_carrier,
3144
-                    'order_by'
3145
-                );
3146
-            }
3147
-        }
3148
-        if (array_key_exists('force_join', $query_params)) {
3149
-            $this->_extract_related_models_from_sub_params_array_values(
3150
-                $query_params['force_join'],
3151
-                $query_info_carrier,
3152
-                'force_join'
3153
-            );
3154
-        }
3155
-        return $query_info_carrier;
3156
-    }
3157
-
3158
-
3159
-
3160
-    /**
3161
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3162
-     *
3163
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3164
-     *                                                      $query_params['having']
3165
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3166
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3167
-     * @throws EE_Error
3168
-     * @return \EE_Model_Query_Info_Carrier
3169
-     */
3170
-    private function _extract_related_models_from_sub_params_array_keys(
3171
-        $sub_query_params,
3172
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3173
-        $query_param_type
3174
-    ) {
3175
-        if (! empty($sub_query_params)) {
3176
-            $sub_query_params = (array)$sub_query_params;
3177
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3178
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3179
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3180
-                    $query_param_type);
3181
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3182
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3183
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3184
-                //of array('Registration.TXN_ID'=>23)
3185
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3186
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3187
-                    if (! is_array($possibly_array_of_params)) {
3188
-                        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'))",
3189
-                            "event_espresso"),
3190
-                            $param, $possibly_array_of_params));
3191
-                    }
3192
-                    $this->_extract_related_models_from_sub_params_array_keys(
3193
-                        $possibly_array_of_params,
3194
-                        $model_query_info_carrier, $query_param_type
3195
-                    );
3196
-                } elseif ($query_param_type === 0 //ie WHERE
3197
-                          && is_array($possibly_array_of_params)
3198
-                          && isset($possibly_array_of_params[2])
3199
-                          && $possibly_array_of_params[2] == true
3200
-                ) {
3201
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3202
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3203
-                    //from which we should extract query parameters!
3204
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3205
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3206
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3207
-                    }
3208
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3209
-                        $model_query_info_carrier, $query_param_type);
3210
-                }
3211
-            }
3212
-        }
3213
-        return $model_query_info_carrier;
3214
-    }
3215
-
3216
-
3217
-
3218
-    /**
3219
-     * For extracting related models from forced_joins, where the array values contain the info about what
3220
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3221
-     *
3222
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3223
-     *                                                      $query_params['having']
3224
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3225
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3226
-     * @throws EE_Error
3227
-     * @return \EE_Model_Query_Info_Carrier
3228
-     */
3229
-    private function _extract_related_models_from_sub_params_array_values(
3230
-        $sub_query_params,
3231
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3232
-        $query_param_type
3233
-    ) {
3234
-        if (! empty($sub_query_params)) {
3235
-            if (! is_array($sub_query_params)) {
3236
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3237
-                    $sub_query_params));
3238
-            }
3239
-            foreach ($sub_query_params as $param) {
3240
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3241
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3242
-                    $query_param_type);
3243
-            }
3244
-        }
3245
-        return $model_query_info_carrier;
3246
-    }
3247
-
3248
-
3249
-
3250
-    /**
3251
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3252
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3253
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3254
-     * but use them in a different order. Eg, we need to know what models we are querying
3255
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3256
-     * other models before we can finalize the where clause SQL.
3257
-     *
3258
-     * @param array $query_params
3259
-     * @throws EE_Error
3260
-     * @return EE_Model_Query_Info_Carrier
3261
-     */
3262
-    public function _create_model_query_info_carrier($query_params)
3263
-    {
3264
-        if (! is_array($query_params)) {
3265
-            EE_Error::doing_it_wrong(
3266
-                'EEM_Base::_create_model_query_info_carrier',
3267
-                sprintf(
3268
-                    __(
3269
-                        '$query_params should be an array, you passed a variable of type %s',
3270
-                        'event_espresso'
3271
-                    ),
3272
-                    gettype($query_params)
3273
-                ),
3274
-                '4.6.0'
3275
-            );
3276
-            $query_params = array();
3277
-        }
3278
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3279
-        //first check if we should alter the query to account for caps or not
3280
-        //because the caps might require us to do extra joins
3281
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3282
-            $query_params[0] = $where_query_params = array_replace_recursive(
3283
-                $where_query_params,
3284
-                $this->caps_where_conditions(
3285
-                    $query_params['caps']
3286
-                )
3287
-            );
3288
-        }
3289
-        $query_object = $this->_extract_related_models_from_query($query_params);
3290
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3291
-        foreach ($where_query_params as $key => $value) {
3292
-            if (is_int($key)) {
3293
-                throw new EE_Error(
3294
-                    sprintf(
3295
-                        __(
3296
-                            "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.",
3297
-                            "event_espresso"
3298
-                        ),
3299
-                        $key,
3300
-                        var_export($value, true),
3301
-                        var_export($query_params, true),
3302
-                        get_class($this)
3303
-                    )
3304
-                );
3305
-            }
3306
-        }
3307
-        if (
3308
-            array_key_exists('default_where_conditions', $query_params)
3309
-            && ! empty($query_params['default_where_conditions'])
3310
-        ) {
3311
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3312
-        } else {
3313
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3314
-        }
3315
-        $where_query_params = array_merge(
3316
-            $this->_get_default_where_conditions_for_models_in_query(
3317
-                $query_object,
3318
-                $use_default_where_conditions,
3319
-                $where_query_params
3320
-            ),
3321
-            $where_query_params
3322
-        );
3323
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3324
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3325
-        // So we need to setup a subquery and use that for the main join.
3326
-        // Note for now this only works on the primary table for the model.
3327
-        // So for instance, you could set the limit array like this:
3328
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3329
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3330
-            $query_object->set_main_model_join_sql(
3331
-                $this->_construct_limit_join_select(
3332
-                    $query_params['on_join_limit'][0],
3333
-                    $query_params['on_join_limit'][1]
3334
-                )
3335
-            );
3336
-        }
3337
-        //set limit
3338
-        if (array_key_exists('limit', $query_params)) {
3339
-            if (is_array($query_params['limit'])) {
3340
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3341
-                    $e = sprintf(
3342
-                        __(
3343
-                            "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)",
3344
-                            "event_espresso"
3345
-                        ),
3346
-                        http_build_query($query_params['limit'])
3347
-                    );
3348
-                    throw new EE_Error($e . "|" . $e);
3349
-                }
3350
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3351
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3352
-            } elseif (! empty ($query_params['limit'])) {
3353
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3354
-            }
3355
-        }
3356
-        //set order by
3357
-        if (array_key_exists('order_by', $query_params)) {
3358
-            if (is_array($query_params['order_by'])) {
3359
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3360
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3361
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3362
-                if (array_key_exists('order', $query_params)) {
3363
-                    throw new EE_Error(
3364
-                        sprintf(
3365
-                            __(
3366
-                                "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 ",
3367
-                                "event_espresso"
3368
-                            ),
3369
-                            get_class($this),
3370
-                            implode(", ", array_keys($query_params['order_by'])),
3371
-                            implode(", ", $query_params['order_by']),
3372
-                            $query_params['order']
3373
-                        )
3374
-                    );
3375
-                }
3376
-                $this->_extract_related_models_from_sub_params_array_keys(
3377
-                    $query_params['order_by'],
3378
-                    $query_object,
3379
-                    'order_by'
3380
-                );
3381
-                //assume it's an array of fields to order by
3382
-                $order_array = array();
3383
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3384
-                    $order = $this->_extract_order($order);
3385
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3386
-                }
3387
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3388
-            } elseif (! empty ($query_params['order_by'])) {
3389
-                $this->_extract_related_model_info_from_query_param(
3390
-                    $query_params['order_by'],
3391
-                    $query_object,
3392
-                    'order',
3393
-                    $query_params['order_by']
3394
-                );
3395
-                $order = isset($query_params['order'])
3396
-                    ? $this->_extract_order($query_params['order'])
3397
-                    : 'DESC';
3398
-                $query_object->set_order_by_sql(
3399
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3400
-                );
3401
-            }
3402
-        }
3403
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3404
-        if (! array_key_exists('order_by', $query_params)
3405
-            && array_key_exists('order', $query_params)
3406
-            && ! empty($query_params['order'])
3407
-        ) {
3408
-            $pk_field = $this->get_primary_key_field();
3409
-            $order = $this->_extract_order($query_params['order']);
3410
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3411
-        }
3412
-        //set group by
3413
-        if (array_key_exists('group_by', $query_params)) {
3414
-            if (is_array($query_params['group_by'])) {
3415
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3416
-                $group_by_array = array();
3417
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3418
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3419
-                }
3420
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3421
-            } elseif (! empty ($query_params['group_by'])) {
3422
-                $query_object->set_group_by_sql(
3423
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3424
-                );
3425
-            }
3426
-        }
3427
-        //set having
3428
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3429
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3430
-        }
3431
-        //now, just verify they didn't pass anything wack
3432
-        foreach ($query_params as $query_key => $query_value) {
3433
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3434
-                throw new EE_Error(
3435
-                    sprintf(
3436
-                        __(
3437
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3438
-                            'event_espresso'
3439
-                        ),
3440
-                        $query_key,
3441
-                        get_class($this),
3442
-                        //						print_r( $this->_allowed_query_params, TRUE )
3443
-                        implode(',', $this->_allowed_query_params)
3444
-                    )
3445
-                );
3446
-            }
3447
-        }
3448
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3449
-        if (empty($main_model_join_sql)) {
3450
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3451
-        }
3452
-        return $query_object;
3453
-    }
3454
-
3455
-
3456
-
3457
-    /**
3458
-     * Gets the where conditions that should be imposed on the query based on the
3459
-     * context (eg reading frontend, backend, edit or delete).
3460
-     *
3461
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3462
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3463
-     * @throws EE_Error
3464
-     */
3465
-    public function caps_where_conditions($context = self::caps_read)
3466
-    {
3467
-        EEM_Base::verify_is_valid_cap_context($context);
3468
-        $cap_where_conditions = array();
3469
-        $cap_restrictions = $this->caps_missing($context);
3470
-        /**
3471
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3472
-         */
3473
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3474
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3475
-                $restriction_if_no_cap->get_default_where_conditions());
3476
-        }
3477
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3478
-            $cap_restrictions);
3479
-    }
3480
-
3481
-
3482
-
3483
-    /**
3484
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3485
-     * otherwise throws an exception
3486
-     *
3487
-     * @param string $should_be_order_string
3488
-     * @return string either ASC, asc, DESC or desc
3489
-     * @throws EE_Error
3490
-     */
3491
-    private function _extract_order($should_be_order_string)
3492
-    {
3493
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3494
-            return $should_be_order_string;
3495
-        }
3496
-        throw new EE_Error(
3497
-            sprintf(
3498
-                __(
3499
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3500
-                    "event_espresso"
3501
-                ), get_class($this), $should_be_order_string
3502
-            )
3503
-        );
3504
-    }
3505
-
3506
-
3507
-
3508
-    /**
3509
-     * Looks at all the models which are included in this query, and asks each
3510
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3511
-     * so they can be merged
3512
-     *
3513
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3514
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3515
-     *                                                                  'none' means NO default where conditions will
3516
-     *                                                                  be used AT ALL during this query.
3517
-     *                                                                  'other_models_only' means default where
3518
-     *                                                                  conditions from other models will be used, but
3519
-     *                                                                  not for this primary model. 'all', the default,
3520
-     *                                                                  means default where conditions will apply as
3521
-     *                                                                  normal
3522
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3523
-     * @throws EE_Error
3524
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3525
-     */
3526
-    private function _get_default_where_conditions_for_models_in_query(
3527
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3528
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3529
-        $where_query_params = array()
3530
-    ) {
3531
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3532
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3533
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3534
-                "event_espresso"), $use_default_where_conditions,
3535
-                implode(", ", $allowed_used_default_where_conditions_values)));
3536
-        }
3537
-        $universal_query_params = array();
3538
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3539
-            $universal_query_params = $this->_get_default_where_conditions();
3540
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3541
-            $universal_query_params = $this->_get_minimum_where_conditions();
3542
-        }
3543
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3544
-            $related_model = $this->get_related_model_obj($model_name);
3545
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3546
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3547
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3548
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3549
-            } else {
3550
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3551
-                continue;
3552
-            }
3553
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3554
-                $related_model_universal_where_params,
3555
-                $where_query_params,
3556
-                $related_model,
3557
-                $model_relation_path
3558
-            );
3559
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3560
-                $universal_query_params,
3561
-                $overrides
3562
-            );
3563
-        }
3564
-        return $universal_query_params;
3565
-    }
3566
-
3567
-
3568
-
3569
-    /**
3570
-     * Determines whether or not we should use default where conditions for the model in question
3571
-     * (this model, or other related models).
3572
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3573
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3574
-     * We should use default where conditions on related models when they requested to use default where conditions
3575
-     * on all models, or specifically just on other related models
3576
-     * @param      $default_where_conditions_value
3577
-     * @param bool $for_this_model false means this is for OTHER related models
3578
-     * @return bool
3579
-     */
3580
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3581
-    {
3582
-        return (
3583
-                   $for_this_model
3584
-                   && in_array(
3585
-                       $default_where_conditions_value,
3586
-                       array(
3587
-                           EEM_Base::default_where_conditions_all,
3588
-                           EEM_Base::default_where_conditions_this_only,
3589
-                           EEM_Base::default_where_conditions_minimum_others,
3590
-                       ),
3591
-                       true
3592
-                   )
3593
-               )
3594
-               || (
3595
-                   ! $for_this_model
3596
-                   && in_array(
3597
-                       $default_where_conditions_value,
3598
-                       array(
3599
-                           EEM_Base::default_where_conditions_all,
3600
-                           EEM_Base::default_where_conditions_others_only,
3601
-                       ),
3602
-                       true
3603
-                   )
3604
-               );
3605
-    }
3606
-
3607
-    /**
3608
-     * Determines whether or not we should use default minimum conditions for the model in question
3609
-     * (this model, or other related models).
3610
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3611
-     * where conditions.
3612
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3613
-     * on this model or others
3614
-     * @param      $default_where_conditions_value
3615
-     * @param bool $for_this_model false means this is for OTHER related models
3616
-     * @return bool
3617
-     */
3618
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3619
-    {
3620
-        return (
3621
-                   $for_this_model
3622
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3623
-               )
3624
-               || (
3625
-                   ! $for_this_model
3626
-                   && in_array(
3627
-                       $default_where_conditions_value,
3628
-                       array(
3629
-                           EEM_Base::default_where_conditions_minimum_others,
3630
-                           EEM_Base::default_where_conditions_minimum_all,
3631
-                       ),
3632
-                       true
3633
-                   )
3634
-               );
3635
-    }
3636
-
3637
-
3638
-    /**
3639
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3640
-     * then we also add a special where condition which allows for that model's primary key
3641
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3642
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3643
-     *
3644
-     * @param array    $default_where_conditions
3645
-     * @param array    $provided_where_conditions
3646
-     * @param EEM_Base $model
3647
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3648
-     * @return array like EEM_Base::get_all's $query_params[0]
3649
-     * @throws EE_Error
3650
-     */
3651
-    private function _override_defaults_or_make_null_friendly(
3652
-        $default_where_conditions,
3653
-        $provided_where_conditions,
3654
-        $model,
3655
-        $model_relation_path
3656
-    ) {
3657
-        $null_friendly_where_conditions = array();
3658
-        $none_overridden = true;
3659
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3660
-        foreach ($default_where_conditions as $key => $val) {
3661
-            if (isset($provided_where_conditions[$key])) {
3662
-                $none_overridden = false;
3663
-            } else {
3664
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3665
-            }
3666
-        }
3667
-        if ($none_overridden && $default_where_conditions) {
3668
-            if ($model->has_primary_key_field()) {
3669
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3670
-                                                                                . "."
3671
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3672
-            }/*else{
35
+	//admin posty
36
+	//basic -> grants access to mine -> if they don't have it, select none
37
+	//*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
38
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
39
+	//*_published -> grants access to published -> if they dont have it, select non-published
40
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
41
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
42
+	//frontend posty
43
+	//by default has access to published
44
+	//basic -> grants access to mine that aren't published, and all published
45
+	//*_others ->grants access to others that aren't private, all mine
46
+	//*_private -> grants full access
47
+	//frontend non-posty
48
+	//like admin posty
49
+	//category-y
50
+	//assign -> grants access to join-table
51
+	//(delete, edit)
52
+	//payment-method-y
53
+	//for each registered payment method,
54
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
55
+	/**
56
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
57
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
58
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
59
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
60
+	 *
61
+	 * @var boolean
62
+	 */
63
+	private $_values_already_prepared_by_model_object = 0;
64
+
65
+	/**
66
+	 * when $_values_already_prepared_by_model_object equals this, we assume
67
+	 * the data is just like form input that needs to have the model fields'
68
+	 * prepare_for_set and prepare_for_use_in_db called on it
69
+	 */
70
+	const not_prepared_by_model_object = 0;
71
+
72
+	/**
73
+	 * when $_values_already_prepared_by_model_object equals this, we
74
+	 * assume this value is coming from a model object and doesn't need to have
75
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
76
+	 */
77
+	const prepared_by_model_object = 1;
78
+
79
+	/**
80
+	 * when $_values_already_prepared_by_model_object equals this, we assume
81
+	 * the values are already to be used in the database (ie no processing is done
82
+	 * on them by the model's fields)
83
+	 */
84
+	const prepared_for_use_in_db = 2;
85
+
86
+
87
+	protected $singular_item = 'Item';
88
+
89
+	protected $plural_item   = 'Items';
90
+
91
+	/**
92
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
93
+	 */
94
+	protected $_tables;
95
+
96
+	/**
97
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
98
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
99
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
100
+	 *
101
+	 * @var \EE_Model_Field_Base[] $_fields
102
+	 */
103
+	protected $_fields;
104
+
105
+	/**
106
+	 * array of different kinds of relations
107
+	 *
108
+	 * @var \EE_Model_Relation_Base[] $_model_relations
109
+	 */
110
+	protected $_model_relations;
111
+
112
+	/**
113
+	 * @var \EE_Index[] $_indexes
114
+	 */
115
+	protected $_indexes = array();
116
+
117
+	/**
118
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
119
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
120
+	 * by setting the same columns as used in these queries in the query yourself.
121
+	 *
122
+	 * @var EE_Default_Where_Conditions
123
+	 */
124
+	protected $_default_where_conditions_strategy;
125
+
126
+	/**
127
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
128
+	 * This is particularly useful when you want something between 'none' and 'default'
129
+	 *
130
+	 * @var EE_Default_Where_Conditions
131
+	 */
132
+	protected $_minimum_where_conditions_strategy;
133
+
134
+	/**
135
+	 * String describing how to find the "owner" of this model's objects.
136
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
137
+	 * But when there isn't, this indicates which related model, or transiently-related model,
138
+	 * has the foreign key to the wp_users table.
139
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
140
+	 * related to events, and events have a foreign key to wp_users.
141
+	 * On EEM_Transaction, this would be 'Transaction.Event'
142
+	 *
143
+	 * @var string
144
+	 */
145
+	protected $_model_chain_to_wp_user = '';
146
+
147
+	/**
148
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
149
+	 * don't need it (particularly CPT models)
150
+	 *
151
+	 * @var bool
152
+	 */
153
+	protected $_ignore_where_strategy = false;
154
+
155
+	/**
156
+	 * String used in caps relating to this model. Eg, if the caps relating to this
157
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
158
+	 *
159
+	 * @var string. If null it hasn't been initialized yet. If false then we
160
+	 * have indicated capabilities don't apply to this
161
+	 */
162
+	protected $_caps_slug = null;
163
+
164
+	/**
165
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
166
+	 * and next-level keys are capability names, and each's value is a
167
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
168
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
169
+	 * and then each capability in the corresponding sub-array that they're missing
170
+	 * adds the where conditions onto the query.
171
+	 *
172
+	 * @var array
173
+	 */
174
+	protected $_cap_restrictions = array(
175
+		self::caps_read       => array(),
176
+		self::caps_read_admin => array(),
177
+		self::caps_edit       => array(),
178
+		self::caps_delete     => array(),
179
+	);
180
+
181
+	/**
182
+	 * Array defining which cap restriction generators to use to create default
183
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
184
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
185
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
186
+	 * automatically set this to false (not just null).
187
+	 *
188
+	 * @var EE_Restriction_Generator_Base[]
189
+	 */
190
+	protected $_cap_restriction_generators = array();
191
+
192
+	/**
193
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
194
+	 */
195
+	const caps_read       = 'read';
196
+
197
+	const caps_read_admin = 'read_admin';
198
+
199
+	const caps_edit       = 'edit';
200
+
201
+	const caps_delete     = 'delete';
202
+
203
+	/**
204
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
205
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
206
+	 * maps to 'read' because when looking for relevant permissions we're going to use
207
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
208
+	 *
209
+	 * @var array
210
+	 */
211
+	protected $_cap_contexts_to_cap_action_map = array(
212
+		self::caps_read       => 'read',
213
+		self::caps_read_admin => 'read',
214
+		self::caps_edit       => 'edit',
215
+		self::caps_delete     => 'delete',
216
+	);
217
+
218
+	/**
219
+	 * Timezone
220
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
221
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
222
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
223
+	 * EE_Datetime_Field data type will have access to it.
224
+	 *
225
+	 * @var string
226
+	 */
227
+	protected $_timezone;
228
+
229
+
230
+	/**
231
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
232
+	 * multisite.
233
+	 *
234
+	 * @var int
235
+	 */
236
+	protected static $_model_query_blog_id;
237
+
238
+	/**
239
+	 * A copy of _fields, except the array keys are the model names pointed to by
240
+	 * the field
241
+	 *
242
+	 * @var EE_Model_Field_Base[]
243
+	 */
244
+	private $_cache_foreign_key_to_fields = array();
245
+
246
+	/**
247
+	 * Cached list of all the fields on the model, indexed by their name
248
+	 *
249
+	 * @var EE_Model_Field_Base[]
250
+	 */
251
+	private $_cached_fields = null;
252
+
253
+	/**
254
+	 * Cached list of all the fields on the model, except those that are
255
+	 * marked as only pertinent to the database
256
+	 *
257
+	 * @var EE_Model_Field_Base[]
258
+	 */
259
+	private $_cached_fields_non_db_only = null;
260
+
261
+	/**
262
+	 * A cached reference to the primary key for quick lookup
263
+	 *
264
+	 * @var EE_Model_Field_Base
265
+	 */
266
+	private $_primary_key_field = null;
267
+
268
+	/**
269
+	 * Flag indicating whether this model has a primary key or not
270
+	 *
271
+	 * @var boolean
272
+	 */
273
+	protected $_has_primary_key_field = null;
274
+
275
+	/**
276
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
277
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
278
+	 *
279
+	 * @var boolean
280
+	 */
281
+	protected $_wp_core_model = false;
282
+
283
+	/**
284
+	 *    List of valid operators that can be used for querying.
285
+	 * The keys are all operators we'll accept, the values are the real SQL
286
+	 * operators used
287
+	 *
288
+	 * @var array
289
+	 */
290
+	protected $_valid_operators = array(
291
+		'='           => '=',
292
+		'<='          => '<=',
293
+		'<'           => '<',
294
+		'>='          => '>=',
295
+		'>'           => '>',
296
+		'!='          => '!=',
297
+		'LIKE'        => 'LIKE',
298
+		'like'        => 'LIKE',
299
+		'NOT_LIKE'    => 'NOT LIKE',
300
+		'not_like'    => 'NOT LIKE',
301
+		'NOT LIKE'    => 'NOT LIKE',
302
+		'not like'    => 'NOT LIKE',
303
+		'IN'          => 'IN',
304
+		'in'          => 'IN',
305
+		'NOT_IN'      => 'NOT IN',
306
+		'not_in'      => 'NOT IN',
307
+		'NOT IN'      => 'NOT IN',
308
+		'not in'      => 'NOT IN',
309
+		'between'     => 'BETWEEN',
310
+		'BETWEEN'     => 'BETWEEN',
311
+		'IS_NOT_NULL' => 'IS NOT NULL',
312
+		'is_not_null' => 'IS NOT NULL',
313
+		'IS NOT NULL' => 'IS NOT NULL',
314
+		'is not null' => 'IS NOT NULL',
315
+		'IS_NULL'     => 'IS NULL',
316
+		'is_null'     => 'IS NULL',
317
+		'IS NULL'     => 'IS NULL',
318
+		'is null'     => 'IS NULL',
319
+		'REGEXP'      => 'REGEXP',
320
+		'regexp'      => 'REGEXP',
321
+		'NOT_REGEXP'  => 'NOT REGEXP',
322
+		'not_regexp'  => 'NOT REGEXP',
323
+		'NOT REGEXP'  => 'NOT REGEXP',
324
+		'not regexp'  => 'NOT REGEXP',
325
+	);
326
+
327
+	/**
328
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
329
+	 *
330
+	 * @var array
331
+	 */
332
+	protected $_in_style_operators = array('IN', 'NOT IN');
333
+
334
+	/**
335
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
336
+	 * '12-31-2012'"
337
+	 *
338
+	 * @var array
339
+	 */
340
+	protected $_between_style_operators = array('BETWEEN');
341
+
342
+	/**
343
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
344
+	 * on a join table.
345
+	 *
346
+	 * @var array
347
+	 */
348
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
349
+
350
+	/**
351
+	 * Allowed values for $query_params['order'] for ordering in queries
352
+	 *
353
+	 * @var array
354
+	 */
355
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
356
+
357
+	/**
358
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
359
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
360
+	 *
361
+	 * @var array
362
+	 */
363
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
364
+
365
+	/**
366
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
367
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
368
+	 *
369
+	 * @var array
370
+	 */
371
+	private $_allowed_query_params = array(
372
+		0,
373
+		'limit',
374
+		'order_by',
375
+		'group_by',
376
+		'having',
377
+		'force_join',
378
+		'order',
379
+		'on_join_limit',
380
+		'default_where_conditions',
381
+		'caps',
382
+	);
383
+
384
+	/**
385
+	 * All the data types that can be used in $wpdb->prepare statements.
386
+	 *
387
+	 * @var array
388
+	 */
389
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
390
+
391
+	/**
392
+	 *    EE_Registry Object
393
+	 *
394
+	 * @var    object
395
+	 * @access    protected
396
+	 */
397
+	protected $EE = null;
398
+
399
+
400
+	/**
401
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
402
+	 *
403
+	 * @var int
404
+	 */
405
+	protected $_show_next_x_db_queries = 0;
406
+
407
+	/**
408
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
409
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
410
+	 *
411
+	 * @var array
412
+	 */
413
+	protected $_custom_selections = array();
414
+
415
+	/**
416
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
417
+	 * caches every model object we've fetched from the DB on this request
418
+	 *
419
+	 * @var array
420
+	 */
421
+	protected $_entity_map;
422
+
423
+	/**
424
+	 * constant used to show EEM_Base has not yet verified the db on this http request
425
+	 */
426
+	const db_verified_none = 0;
427
+
428
+	/**
429
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
430
+	 * but not the addons' dbs
431
+	 */
432
+	const db_verified_core = 1;
433
+
434
+	/**
435
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
436
+	 * the EE core db too)
437
+	 */
438
+	const db_verified_addons = 2;
439
+
440
+	/**
441
+	 * indicates whether an EEM_Base child has already re-verified the DB
442
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
443
+	 * looking like EEM_Base::db_verified_*
444
+	 *
445
+	 * @var int - 0 = none, 1 = core, 2 = addons
446
+	 */
447
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
448
+
449
+	/**
450
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
451
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
452
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
453
+	 */
454
+	const default_where_conditions_all = 'all';
455
+
456
+	/**
457
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
458
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
459
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
460
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
461
+	 *        models which share tables with other models, this can return data for the wrong model.
462
+	 */
463
+	const default_where_conditions_this_only = 'this_model_only';
464
+
465
+	/**
466
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
467
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
468
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
469
+	 */
470
+	const default_where_conditions_others_only = 'other_models_only';
471
+
472
+	/**
473
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
474
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
475
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
476
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
477
+	 *        (regardless of whether those events and venues are trashed)
478
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
479
+	 *        events.
480
+	 */
481
+	const default_where_conditions_minimum_all = 'minimum';
482
+
483
+	/**
484
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
485
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
486
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
487
+	 *        not)
488
+	 */
489
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
490
+
491
+	/**
492
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
493
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
494
+	 *        it's possible it will return table entries for other models. You should use
495
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
496
+	 */
497
+	const default_where_conditions_none = 'none';
498
+
499
+
500
+
501
+	/**
502
+	 * About all child constructors:
503
+	 * they should define the _tables, _fields and _model_relations arrays.
504
+	 * Should ALWAYS be called after child constructor.
505
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
506
+	 * finalizes constructing all the object's attributes.
507
+	 * Generally, rather than requiring a child to code
508
+	 * $this->_tables = array(
509
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
510
+	 *        ...);
511
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
512
+	 * each EE_Table has a function to set the table's alias after the constructor, using
513
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
514
+	 * do something similar.
515
+	 *
516
+	 * @param null $timezone
517
+	 * @throws EE_Error
518
+	 */
519
+	protected function __construct($timezone = null)
520
+	{
521
+		// check that the model has not been loaded too soon
522
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
523
+			throw new EE_Error (
524
+				sprintf(
525
+					__('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.',
526
+						'event_espresso'),
527
+					get_class($this)
528
+				)
529
+			);
530
+		}
531
+		/**
532
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
533
+		 */
534
+		if (empty(EEM_Base::$_model_query_blog_id)) {
535
+			EEM_Base::set_model_query_blog_id();
536
+		}
537
+		/**
538
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
539
+		 * just use EE_Register_Model_Extension
540
+		 *
541
+		 * @var EE_Table_Base[] $_tables
542
+		 */
543
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
544
+		foreach ($this->_tables as $table_alias => $table_obj) {
545
+			/** @var $table_obj EE_Table_Base */
546
+			$table_obj->_construct_finalize_with_alias($table_alias);
547
+			if ($table_obj instanceof EE_Secondary_Table) {
548
+				/** @var $table_obj EE_Secondary_Table */
549
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
550
+			}
551
+		}
552
+		/**
553
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
554
+		 * EE_Register_Model_Extension
555
+		 *
556
+		 * @param EE_Model_Field_Base[] $_fields
557
+		 */
558
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
559
+		$this->_invalidate_field_caches();
560
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
561
+			if (! array_key_exists($table_alias, $this->_tables)) {
562
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
563
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
564
+			}
565
+			foreach ($fields_for_table as $field_name => $field_obj) {
566
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
567
+				//primary key field base has a slightly different _construct_finalize
568
+				/** @var $field_obj EE_Model_Field_Base */
569
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
570
+			}
571
+		}
572
+		// everything is related to Extra_Meta
573
+		if (get_class($this) !== 'EEM_Extra_Meta') {
574
+			//make extra meta related to everything, but don't block deleting things just
575
+			//because they have related extra meta info. For now just orphan those extra meta
576
+			//in the future we should automatically delete them
577
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		//and change logs
580
+		if (get_class($this) !== 'EEM_Change_Log') {
581
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
582
+		}
583
+		/**
584
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
585
+		 * EE_Register_Model_Extension
586
+		 *
587
+		 * @param EE_Model_Relation_Base[] $_model_relations
588
+		 */
589
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
590
+			$this->_model_relations);
591
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
592
+			/** @var $relation_obj EE_Model_Relation_Base */
593
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
594
+		}
595
+		foreach ($this->_indexes as $index_name => $index_obj) {
596
+			/** @var $index_obj EE_Index */
597
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
598
+		}
599
+		$this->set_timezone($timezone);
600
+		//finalize default where condition strategy, or set default
601
+		if (! $this->_default_where_conditions_strategy) {
602
+			//nothing was set during child constructor, so set default
603
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
604
+		}
605
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
606
+		if (! $this->_minimum_where_conditions_strategy) {
607
+			//nothing was set during child constructor, so set default
608
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
609
+		}
610
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
611
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
612
+		//to indicate to NOT set it, set it to the logical default
613
+		if ($this->_caps_slug === null) {
614
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
615
+		}
616
+		//initialize the standard cap restriction generators if none were specified by the child constructor
617
+		if ($this->_cap_restriction_generators !== false) {
618
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
619
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
620
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
621
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
622
+						new EE_Restriction_Generator_Protected(),
623
+						$cap_context,
624
+						$this
625
+					);
626
+				}
627
+			}
628
+		}
629
+		//if there are cap restriction generators, use them to make the default cap restrictions
630
+		if ($this->_cap_restriction_generators !== false) {
631
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
632
+				if (! $generator_object) {
633
+					continue;
634
+				}
635
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
636
+					throw new EE_Error(
637
+						sprintf(
638
+							__('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.',
639
+								'event_espresso'),
640
+							$context,
641
+							$this->get_this_model_name()
642
+						)
643
+					);
644
+				}
645
+				$action = $this->cap_action_for_context($context);
646
+				if (! $generator_object->construction_finalized()) {
647
+					$generator_object->_construct_finalize($this, $action);
648
+				}
649
+			}
650
+		}
651
+		do_action('AHEE__' . get_class($this) . '__construct__end');
652
+	}
653
+
654
+
655
+
656
+	/**
657
+	 * Generates the cap restrictions for the given context, or if they were
658
+	 * already generated just gets what's cached
659
+	 *
660
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
661
+	 * @return EE_Default_Where_Conditions[]
662
+	 */
663
+	protected function _generate_cap_restrictions($context)
664
+	{
665
+		if (isset($this->_cap_restriction_generators[$context])
666
+			&& $this->_cap_restriction_generators[$context]
667
+			   instanceof
668
+			   EE_Restriction_Generator_Base
669
+		) {
670
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
671
+		} else {
672
+			return array();
673
+		}
674
+	}
675
+
676
+
677
+
678
+	/**
679
+	 * Used to set the $_model_query_blog_id static property.
680
+	 *
681
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
682
+	 *                      value for get_current_blog_id() will be used.
683
+	 */
684
+	public static function set_model_query_blog_id($blog_id = 0)
685
+	{
686
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
687
+	}
688
+
689
+
690
+
691
+	/**
692
+	 * Returns whatever is set as the internal $model_query_blog_id.
693
+	 *
694
+	 * @return int
695
+	 */
696
+	public static function get_model_query_blog_id()
697
+	{
698
+		return EEM_Base::$_model_query_blog_id;
699
+	}
700
+
701
+
702
+
703
+	/**
704
+	 * This function is a singleton method used to instantiate the Espresso_model object
705
+	 *
706
+	 * @param string            $timezone string representing the timezone we want to set for returned Date Time Strings
707
+	 *                                    (and any incoming timezone data that gets saved).
708
+	 *                                    Note this just sends the timezone info to the date time model field objects.
709
+	 *                                    Default is NULL
710
+	 *                                    (and will be assumed using the set timezone in the 'timezone_string' wp option)
711
+	 * @param ModelFieldFactory $model_field_factory
712
+	 * @return static (as in the concrete child class)
713
+	 * @throws InvalidArgumentException
714
+	 * @throws InvalidInterfaceException
715
+	 * @throws InvalidDataTypeException
716
+	 * @throws EE_Error
717
+	 */
718
+	public static function instance($timezone = null, ModelFieldFactory $model_field_factory = null)
719
+	{
720
+		// check if instance of Espresso_model already exists
721
+		if (! static::$_instance instanceof static) {
722
+			$model_field_factory = self::getModelFieldFactory($model_field_factory);
723
+			// instantiate Espresso_model
724
+			static::$_instance = new static($timezone, $model_field_factory);
725
+		}
726
+		//we might have a timezone set, let set_timezone decide what to do with it
727
+		static::$_instance->set_timezone($timezone);
728
+		// Espresso_model object
729
+		return static::$_instance;
730
+	}
731
+
732
+
733
+
734
+	/**
735
+	 * @param $model_field_factory
736
+	 * @return ModelFieldFactory
737
+	 * @throws InvalidArgumentException
738
+	 * @throws InvalidDataTypeException
739
+	 * @throws InvalidInterfaceException
740
+	 */
741
+	private static function getModelFieldFactory($model_field_factory)
742
+	{
743
+		return $model_field_factory instanceof ModelFieldFactory
744
+			? $model_field_factory
745
+			: LoaderFactory::getLoader()->load('EventEspresso\core\services\database\ModelFieldFactory');
746
+	}
747
+
748
+
749
+
750
+	/**
751
+	 * resets the model and returns it
752
+	 *
753
+	 * @param null | string          $timezone
754
+	 * @param ModelFieldFactory|null $model_field_factory
755
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
756
+	 * @throws ReflectionException
757
+	 * all its properties reset; if it wasn't instantiated, returns null)
758
+	 * @throws EE_Error
759
+	 * @throws InvalidArgumentException
760
+	 * @throws InvalidDataTypeException
761
+	 * @throws InvalidInterfaceException
762
+	 */
763
+	public static function reset($timezone = null, ModelFieldFactory $model_field_factory = null)
764
+	{
765
+		if (static::$_instance instanceof EEM_Base) {
766
+			//let's try to NOT swap out the current instance for a new one
767
+			//because if someone has a reference to it, we can't remove their reference
768
+			//so it's best to keep using the same reference, but change the original object
769
+			//reset all its properties to their original values as defined in the class
770
+			$r = new ReflectionClass(get_class(static::$_instance));
771
+			$static_properties = $r->getStaticProperties();
772
+			foreach ($r->getDefaultProperties() as $property => $value) {
773
+				//don't set instance to null like it was originally,
774
+				//but it's static anyways, and we're ignoring static properties (for now at least)
775
+				if (! isset($static_properties[$property])) {
776
+					static::$_instance->{$property} = $value;
777
+				}
778
+			}
779
+			//and then directly call its constructor again, like we would if we were creating a new one
780
+			$model_field_factory = self::getModelFieldFactory($model_field_factory);
781
+			static::$_instance->__construct($timezone, $model_field_factory);
782
+			return self::instance();
783
+		}
784
+		return null;
785
+	}
786
+
787
+
788
+
789
+	/**
790
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
791
+	 *
792
+	 * @param  boolean $translated return localized strings or JUST the array.
793
+	 * @return array
794
+	 * @throws EE_Error
795
+	 */
796
+	public function status_array($translated = false)
797
+	{
798
+		if (! array_key_exists('Status', $this->_model_relations)) {
799
+			return array();
800
+		}
801
+		$model_name = $this->get_this_model_name();
802
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
803
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
804
+		$status_array = array();
805
+		foreach ($stati as $status) {
806
+			$status_array[$status->ID()] = $status->get('STS_code');
807
+		}
808
+		return $translated
809
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
810
+			: $status_array;
811
+	}
812
+
813
+
814
+
815
+	/**
816
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
817
+	 *
818
+	 * @param array $query_params             {
819
+	 * @var array $0 (where) array {
820
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
821
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
822
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
823
+	 *                                        conditions based on related models (and even
824
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
825
+	 *                                        name. Eg,
826
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
827
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
828
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
829
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
830
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
831
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
832
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
833
+	 *                                        to Venues (even when each of those models actually consisted of two
834
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
835
+	 *                                        just having
836
+	 *                                        "Venue.VNU_ID", you could have
837
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
838
+	 *                                        events are related to Registrations, which are related to Attendees). You
839
+	 *                                        can take it even further with
840
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
841
+	 *                                        (from the default of '='), change the value to an numerically-indexed
842
+	 *                                        array, where the first item in the list is the operator. eg: array(
843
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
844
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
845
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
846
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
847
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
848
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
849
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
850
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
851
+	 *                                        the value is a field, simply provide a third array item (true) to the
852
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
853
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
854
+	 *                                        Note: you can also use related model field names like you would any other
855
+	 *                                        field name. eg:
856
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
857
+	 *                                        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__>' =>
858
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
859
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
860
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
861
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
862
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
863
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
864
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
865
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
866
+	 *                                        "stick" until you specify an AND. eg
867
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
868
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
869
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
870
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
871
+	 *                                        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 >>
872
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
873
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
874
+	 *                                        too, eg:
875
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
876
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
877
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
878
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
879
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
880
+	 *                                        the OFFSET, the 2nd is the LIMIT
881
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
882
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
883
+	 *                                        following format array('on_join_limit'
884
+	 *                                        => array( 'table_alias', array(1,2) ) ).
885
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
886
+	 *                                        values are either 'ASC' or 'DESC'.
887
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
888
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
889
+	 *                                        DESC..." respectively. Like the
890
+	 *                                        'where' conditions, these fields can be on related models. Eg
891
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
892
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
893
+	 *                                        Attendee, Price, Datetime, etc.)
894
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
895
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
896
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
897
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
898
+	 *                                        order by the primary key. Eg,
899
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
900
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
901
+	 *                                        DTT_EVT_start) or
902
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
903
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
904
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
905
+	 *                                        'group_by'=>'VNU_ID', or
906
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
907
+	 *                                        if no
908
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
909
+	 *                                        model's primary key (or combined primary keys). This avoids some
910
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
911
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
912
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
913
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
914
+	 *                                        results)
915
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
916
+	 *                                        array where values are models to be joined in the query.Eg
917
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
918
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
919
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
920
+	 *                                        related models which belongs to the current model
921
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
922
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
923
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
924
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
925
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
926
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
927
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
928
+	 *                                        this model's default where conditions added to the query, use
929
+	 *                                        'this_model_only'. If you want to use all default where conditions
930
+	 *                                        (default), set to 'all'.
931
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
932
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
933
+	 *                                        everything? Or should we only show the current user items they should be
934
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
935
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
936
+	 *                                        }
937
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
938
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
939
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
940
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
941
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
942
+	 *                                        array( array(
943
+	 *                                        'OR'=>array(
944
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
945
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
946
+	 *                                        )
947
+	 *                                        ),
948
+	 *                                        'limit'=>10,
949
+	 *                                        'group_by'=>'TXN_ID'
950
+	 *                                        ));
951
+	 *                                        get all the answers to the question titled "shirt size" for event with id
952
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
953
+	 *                                        'Question.QST_display_text'=>'shirt size',
954
+	 *                                        'Registration.Event.EVT_ID'=>12
955
+	 *                                        ),
956
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
957
+	 *                                        ));
958
+	 * @throws EE_Error
959
+	 */
960
+	public function get_all($query_params = array())
961
+	{
962
+		if (isset($query_params['limit'])
963
+			&& ! isset($query_params['group_by'])
964
+		) {
965
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
966
+		}
967
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
968
+	}
969
+
970
+
971
+
972
+	/**
973
+	 * Modifies the query parameters so we only get back model objects
974
+	 * that "belong" to the current user
975
+	 *
976
+	 * @param array $query_params @see EEM_Base::get_all()
977
+	 * @return array like EEM_Base::get_all
978
+	 */
979
+	public function alter_query_params_to_only_include_mine($query_params = array())
980
+	{
981
+		$wp_user_field_name = $this->wp_user_field_name();
982
+		if ($wp_user_field_name) {
983
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
984
+		}
985
+		return $query_params;
986
+	}
987
+
988
+
989
+
990
+	/**
991
+	 * Returns the name of the field's name that points to the WP_User table
992
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
993
+	 * foreign key to the WP_User table)
994
+	 *
995
+	 * @return string|boolean string on success, boolean false when there is no
996
+	 * foreign key to the WP_User table
997
+	 */
998
+	public function wp_user_field_name()
999
+	{
1000
+		try {
1001
+			if (! empty($this->_model_chain_to_wp_user)) {
1002
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
1003
+				$last_model_name = end($models_to_follow_to_wp_users);
1004
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
1005
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
1006
+			} else {
1007
+				$model_with_fk_to_wp_users = $this;
1008
+				$model_chain_to_wp_user = '';
1009
+			}
1010
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
1011
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
1012
+		} catch (EE_Error $e) {
1013
+			return false;
1014
+		}
1015
+	}
1016
+
1017
+
1018
+
1019
+	/**
1020
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
1021
+	 * (or transiently-related model) has a foreign key to the wp_users table;
1022
+	 * useful for finding if model objects of this type are 'owned' by the current user.
1023
+	 * This is an empty string when the foreign key is on this model and when it isn't,
1024
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
1025
+	 * (or transiently-related model)
1026
+	 *
1027
+	 * @return string
1028
+	 */
1029
+	public function model_chain_to_wp_user()
1030
+	{
1031
+		return $this->_model_chain_to_wp_user;
1032
+	}
1033
+
1034
+
1035
+
1036
+	/**
1037
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1038
+	 * like how registrations don't have a foreign key to wp_users, but the
1039
+	 * events they are for are), or is unrelated to wp users.
1040
+	 * generally available
1041
+	 *
1042
+	 * @return boolean
1043
+	 */
1044
+	public function is_owned()
1045
+	{
1046
+		if ($this->model_chain_to_wp_user()) {
1047
+			return true;
1048
+		}
1049
+		try {
1050
+			$this->get_foreign_key_to('WP_User');
1051
+			return true;
1052
+		} catch (EE_Error $e) {
1053
+			return false;
1054
+		}
1055
+	}
1056
+
1057
+
1058
+
1059
+	/**
1060
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1061
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1062
+	 * the model)
1063
+	 *
1064
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1065
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1066
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1067
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1068
+	 *                                  override this and set the select to "*", or a specific column name, like
1069
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1070
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1071
+	 *                                  the aliases used to refer to this selection, and values are to be
1072
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1073
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1074
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1075
+	 * @throws EE_Error
1076
+	 */
1077
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1078
+	{
1079
+		// remember the custom selections, if any, and type cast as array
1080
+		// (unless $columns_to_select is an object, then just set as an empty array)
1081
+		// Note: (array) 'some string' === array( 'some string' )
1082
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1083
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1084
+		$select_expressions = $columns_to_select !== null
1085
+			? $this->_construct_select_from_input($columns_to_select)
1086
+			: $this->_construct_default_select_sql($model_query_info);
1087
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1088
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1089
+	}
1090
+
1091
+
1092
+
1093
+	/**
1094
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1095
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1096
+	 * take care of joins, field preparation etc.
1097
+	 *
1098
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1099
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1100
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1101
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1102
+	 *                                  override this and set the select to "*", or a specific column name, like
1103
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1104
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1105
+	 *                                  the aliases used to refer to this selection, and values are to be
1106
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1107
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1108
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1109
+	 * @throws EE_Error
1110
+	 */
1111
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1112
+	{
1113
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1114
+	}
1115
+
1116
+
1117
+
1118
+	/**
1119
+	 * For creating a custom select statement
1120
+	 *
1121
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1122
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1123
+	 *                                 SQL, and 1=>is the datatype
1124
+	 * @throws EE_Error
1125
+	 * @return string
1126
+	 */
1127
+	private function _construct_select_from_input($columns_to_select)
1128
+	{
1129
+		if (is_array($columns_to_select)) {
1130
+			$select_sql_array = array();
1131
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1132
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1133
+					throw new EE_Error(
1134
+						sprintf(
1135
+							__(
1136
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1137
+								"event_espresso"
1138
+							),
1139
+							$selection_and_datatype,
1140
+							$alias
1141
+						)
1142
+					);
1143
+				}
1144
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1145
+					throw new EE_Error(
1146
+						sprintf(
1147
+							__(
1148
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1149
+								"event_espresso"
1150
+							),
1151
+							$selection_and_datatype[1],
1152
+							$selection_and_datatype[0],
1153
+							$alias,
1154
+							implode(",", $this->_valid_wpdb_data_types)
1155
+						)
1156
+					);
1157
+				}
1158
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1159
+			}
1160
+			$columns_to_select_string = implode(", ", $select_sql_array);
1161
+		} else {
1162
+			$columns_to_select_string = $columns_to_select;
1163
+		}
1164
+		return $columns_to_select_string;
1165
+	}
1166
+
1167
+
1168
+
1169
+	/**
1170
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1171
+	 *
1172
+	 * @return string
1173
+	 * @throws EE_Error
1174
+	 */
1175
+	public function primary_key_name()
1176
+	{
1177
+		return $this->get_primary_key_field()->get_name();
1178
+	}
1179
+
1180
+
1181
+
1182
+	/**
1183
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1184
+	 * If there is no primary key on this model, $id is treated as primary key string
1185
+	 *
1186
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1187
+	 * @return EE_Base_Class
1188
+	 */
1189
+	public function get_one_by_ID($id)
1190
+	{
1191
+		if ($this->get_from_entity_map($id)) {
1192
+			return $this->get_from_entity_map($id);
1193
+		}
1194
+		return $this->get_one(
1195
+			$this->alter_query_params_to_restrict_by_ID(
1196
+				$id,
1197
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1198
+			)
1199
+		);
1200
+	}
1201
+
1202
+
1203
+
1204
+	/**
1205
+	 * Alters query parameters to only get items with this ID are returned.
1206
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1207
+	 * or could just be a simple primary key ID
1208
+	 *
1209
+	 * @param int   $id
1210
+	 * @param array $query_params
1211
+	 * @return array of normal query params, @see EEM_Base::get_all
1212
+	 * @throws EE_Error
1213
+	 */
1214
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1215
+	{
1216
+		if (! isset($query_params[0])) {
1217
+			$query_params[0] = array();
1218
+		}
1219
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1220
+		if ($conditions_from_id === null) {
1221
+			$query_params[0][$this->primary_key_name()] = $id;
1222
+		} else {
1223
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1224
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1225
+		}
1226
+		return $query_params;
1227
+	}
1228
+
1229
+
1230
+
1231
+	/**
1232
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1233
+	 * array. If no item is found, null is returned.
1234
+	 *
1235
+	 * @param array $query_params like EEM_Base's $query_params variable.
1236
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1237
+	 * @throws EE_Error
1238
+	 */
1239
+	public function get_one($query_params = array())
1240
+	{
1241
+		if (! is_array($query_params)) {
1242
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1243
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1244
+					gettype($query_params)), '4.6.0');
1245
+			$query_params = array();
1246
+		}
1247
+		$query_params['limit'] = 1;
1248
+		$items = $this->get_all($query_params);
1249
+		if (empty($items)) {
1250
+			return null;
1251
+		}
1252
+		return array_shift($items);
1253
+	}
1254
+
1255
+
1256
+
1257
+	/**
1258
+	 * Returns the next x number of items in sequence from the given value as
1259
+	 * found in the database matching the given query conditions.
1260
+	 *
1261
+	 * @param mixed $current_field_value    Value used for the reference point.
1262
+	 * @param null  $field_to_order_by      What field is used for the
1263
+	 *                                      reference point.
1264
+	 * @param int   $limit                  How many to return.
1265
+	 * @param array $query_params           Extra conditions on the query.
1266
+	 * @param null  $columns_to_select      If left null, then an array of
1267
+	 *                                      EE_Base_Class objects is returned,
1268
+	 *                                      otherwise you can indicate just the
1269
+	 *                                      columns you want returned.
1270
+	 * @return EE_Base_Class[]|array
1271
+	 * @throws EE_Error
1272
+	 */
1273
+	public function next_x(
1274
+		$current_field_value,
1275
+		$field_to_order_by = null,
1276
+		$limit = 1,
1277
+		$query_params = array(),
1278
+		$columns_to_select = null
1279
+	) {
1280
+		return $this->_get_consecutive(
1281
+			$current_field_value,
1282
+			'>',
1283
+			$field_to_order_by,
1284
+			$limit,
1285
+			$query_params,
1286
+			$columns_to_select
1287
+		);
1288
+	}
1289
+
1290
+
1291
+
1292
+	/**
1293
+	 * Returns the previous x number of items in sequence from the given value
1294
+	 * as found in the database matching the given query conditions.
1295
+	 *
1296
+	 * @param mixed $current_field_value    Value used for the reference point.
1297
+	 * @param null  $field_to_order_by      What field is used for the
1298
+	 *                                      reference point.
1299
+	 * @param int   $limit                  How many to return.
1300
+	 * @param array $query_params           Extra conditions on the query.
1301
+	 * @param null  $columns_to_select      If left null, then an array of
1302
+	 *                                      EE_Base_Class objects is returned,
1303
+	 *                                      otherwise you can indicate just the
1304
+	 *                                      columns you want returned.
1305
+	 * @return EE_Base_Class[]|array
1306
+	 * @throws EE_Error
1307
+	 */
1308
+	public function previous_x(
1309
+		$current_field_value,
1310
+		$field_to_order_by = null,
1311
+		$limit = 1,
1312
+		$query_params = array(),
1313
+		$columns_to_select = null
1314
+	) {
1315
+		return $this->_get_consecutive(
1316
+			$current_field_value,
1317
+			'<',
1318
+			$field_to_order_by,
1319
+			$limit,
1320
+			$query_params,
1321
+			$columns_to_select
1322
+		);
1323
+	}
1324
+
1325
+
1326
+
1327
+	/**
1328
+	 * Returns the next item in sequence from the given value as found in the
1329
+	 * database matching the given query conditions.
1330
+	 *
1331
+	 * @param mixed $current_field_value    Value used for the reference point.
1332
+	 * @param null  $field_to_order_by      What field is used for the
1333
+	 *                                      reference point.
1334
+	 * @param array $query_params           Extra conditions on the query.
1335
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1336
+	 *                                      object is returned, otherwise you
1337
+	 *                                      can indicate just the columns you
1338
+	 *                                      want and a single array indexed by
1339
+	 *                                      the columns will be returned.
1340
+	 * @return EE_Base_Class|null|array()
1341
+	 * @throws EE_Error
1342
+	 */
1343
+	public function next(
1344
+		$current_field_value,
1345
+		$field_to_order_by = null,
1346
+		$query_params = array(),
1347
+		$columns_to_select = null
1348
+	) {
1349
+		$results = $this->_get_consecutive(
1350
+			$current_field_value,
1351
+			'>',
1352
+			$field_to_order_by,
1353
+			1,
1354
+			$query_params,
1355
+			$columns_to_select
1356
+		);
1357
+		return empty($results) ? null : reset($results);
1358
+	}
1359
+
1360
+
1361
+
1362
+	/**
1363
+	 * Returns the previous item in sequence from the given value as found in
1364
+	 * the database matching the given query conditions.
1365
+	 *
1366
+	 * @param mixed $current_field_value    Value used for the reference point.
1367
+	 * @param null  $field_to_order_by      What field is used for the
1368
+	 *                                      reference point.
1369
+	 * @param array $query_params           Extra conditions on the query.
1370
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1371
+	 *                                      object is returned, otherwise you
1372
+	 *                                      can indicate just the columns you
1373
+	 *                                      want and a single array indexed by
1374
+	 *                                      the columns will be returned.
1375
+	 * @return EE_Base_Class|null|array()
1376
+	 * @throws EE_Error
1377
+	 */
1378
+	public function previous(
1379
+		$current_field_value,
1380
+		$field_to_order_by = null,
1381
+		$query_params = array(),
1382
+		$columns_to_select = null
1383
+	) {
1384
+		$results = $this->_get_consecutive(
1385
+			$current_field_value,
1386
+			'<',
1387
+			$field_to_order_by,
1388
+			1,
1389
+			$query_params,
1390
+			$columns_to_select
1391
+		);
1392
+		return empty($results) ? null : reset($results);
1393
+	}
1394
+
1395
+
1396
+
1397
+	/**
1398
+	 * Returns the a consecutive number of items in sequence from the given
1399
+	 * value as found in the database matching the given query conditions.
1400
+	 *
1401
+	 * @param mixed  $current_field_value   Value used for the reference point.
1402
+	 * @param string $operand               What operand is used for the sequence.
1403
+	 * @param string $field_to_order_by     What field is used for the reference point.
1404
+	 * @param int    $limit                 How many to return.
1405
+	 * @param array  $query_params          Extra conditions on the query.
1406
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1407
+	 *                                      otherwise you can indicate just the columns you want returned.
1408
+	 * @return EE_Base_Class[]|array
1409
+	 * @throws EE_Error
1410
+	 */
1411
+	protected function _get_consecutive(
1412
+		$current_field_value,
1413
+		$operand = '>',
1414
+		$field_to_order_by = null,
1415
+		$limit = 1,
1416
+		$query_params = array(),
1417
+		$columns_to_select = null
1418
+	) {
1419
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1420
+		if (empty($field_to_order_by)) {
1421
+			if ($this->has_primary_key_field()) {
1422
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1423
+			} else {
1424
+				if (WP_DEBUG) {
1425
+					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).',
1426
+						'event_espresso'));
1427
+				}
1428
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1429
+				return array();
1430
+			}
1431
+		}
1432
+		if (! is_array($query_params)) {
1433
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1434
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1435
+					gettype($query_params)), '4.6.0');
1436
+			$query_params = array();
1437
+		}
1438
+		//let's add the where query param for consecutive look up.
1439
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1440
+		$query_params['limit'] = $limit;
1441
+		//set direction
1442
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1443
+		$query_params['order_by'] = $operand === '>'
1444
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1445
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1446
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1447
+		if (empty($columns_to_select)) {
1448
+			return $this->get_all($query_params);
1449
+		}
1450
+		//getting just the fields
1451
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1452
+	}
1453
+
1454
+
1455
+
1456
+	/**
1457
+	 * This sets the _timezone property after model object has been instantiated.
1458
+	 *
1459
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1460
+	 */
1461
+	public function set_timezone($timezone)
1462
+	{
1463
+		if ($timezone !== null) {
1464
+			$this->_timezone = $timezone;
1465
+		}
1466
+		//note we need to loop through relations and set the timezone on those objects as well.
1467
+		foreach ($this->_model_relations as $relation) {
1468
+			$relation->set_timezone($timezone);
1469
+		}
1470
+		//and finally we do the same for any datetime fields
1471
+		foreach ($this->_fields as $field) {
1472
+			if ($field instanceof EE_Datetime_Field) {
1473
+				$field->set_timezone($timezone);
1474
+			}
1475
+		}
1476
+	}
1477
+
1478
+
1479
+
1480
+	/**
1481
+	 * This just returns whatever is set for the current timezone.
1482
+	 *
1483
+	 * @access public
1484
+	 * @return string
1485
+	 */
1486
+	public function get_timezone()
1487
+	{
1488
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1489
+		if (empty($this->_timezone)) {
1490
+			foreach ($this->_fields as $field) {
1491
+				if ($field instanceof EE_Datetime_Field) {
1492
+					$this->set_timezone($field->get_timezone());
1493
+					break;
1494
+				}
1495
+			}
1496
+		}
1497
+		//if timezone STILL empty then return the default timezone for the site.
1498
+		if (empty($this->_timezone)) {
1499
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1500
+		}
1501
+		return $this->_timezone;
1502
+	}
1503
+
1504
+
1505
+
1506
+	/**
1507
+	 * This returns the date formats set for the given field name and also ensures that
1508
+	 * $this->_timezone property is set correctly.
1509
+	 *
1510
+	 * @since 4.6.x
1511
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1512
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1513
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1514
+	 * @return array formats in an array with the date format first, and the time format last.
1515
+	 */
1516
+	public function get_formats_for($field_name, $pretty = false)
1517
+	{
1518
+		$field_settings = $this->field_settings_for($field_name);
1519
+		//if not a valid EE_Datetime_Field then throw error
1520
+		if (! $field_settings instanceof EE_Datetime_Field) {
1521
+			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.',
1522
+				'event_espresso'), $field_name));
1523
+		}
1524
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1525
+		//the field.
1526
+		$this->_timezone = $field_settings->get_timezone();
1527
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1528
+	}
1529
+
1530
+
1531
+
1532
+	/**
1533
+	 * This returns the current time in a format setup for a query on this model.
1534
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1535
+	 * it will return:
1536
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1537
+	 *  NOW
1538
+	 *  - or a unix timestamp (equivalent to time())
1539
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1540
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1541
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1542
+	 * @since 4.6.x
1543
+	 * @param string $field_name       The field the current time is needed for.
1544
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1545
+	 *                                 formatted string matching the set format for the field in the set timezone will
1546
+	 *                                 be returned.
1547
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1548
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1549
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1550
+	 *                                 exception is triggered.
1551
+	 */
1552
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1553
+	{
1554
+		$formats = $this->get_formats_for($field_name);
1555
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1556
+		if ($timestamp) {
1557
+			return $DateTime->format('U');
1558
+		}
1559
+		//not returning timestamp, so return formatted string in timezone.
1560
+		switch ($what) {
1561
+			case 'time' :
1562
+				return $DateTime->format($formats[1]);
1563
+				break;
1564
+			case 'date' :
1565
+				return $DateTime->format($formats[0]);
1566
+				break;
1567
+			default :
1568
+				return $DateTime->format(implode(' ', $formats));
1569
+				break;
1570
+		}
1571
+	}
1572
+
1573
+
1574
+
1575
+	/**
1576
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1577
+	 * for the model are.  Returns a DateTime object.
1578
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1579
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1580
+	 * ignored.
1581
+	 *
1582
+	 * @param string $field_name      The field being setup.
1583
+	 * @param string $timestring      The date time string being used.
1584
+	 * @param string $incoming_format The format for the time string.
1585
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1586
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1587
+	 *                                format is
1588
+	 *                                'U', this is ignored.
1589
+	 * @return DateTime
1590
+	 * @throws EE_Error
1591
+	 */
1592
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1593
+	{
1594
+		//just using this to ensure the timezone is set correctly internally
1595
+		$this->get_formats_for($field_name);
1596
+		//load EEH_DTT_Helper
1597
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1598
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1599
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1600
+	}
1601
+
1602
+
1603
+
1604
+	/**
1605
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1606
+	 *
1607
+	 * @return EE_Table_Base[]
1608
+	 */
1609
+	public function get_tables()
1610
+	{
1611
+		return $this->_tables;
1612
+	}
1613
+
1614
+
1615
+
1616
+	/**
1617
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1618
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1619
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1620
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1621
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1622
+	 * model object with EVT_ID = 1
1623
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1624
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1625
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1626
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1627
+	 * are not specified)
1628
+	 *
1629
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1630
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1631
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1632
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1633
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1634
+	 *                                         ID=34, we'd use this method as follows:
1635
+	 *                                         EEM_Transaction::instance()->update(
1636
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1637
+	 *                                         array(array('TXN_ID'=>34)));
1638
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1639
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1640
+	 *                                         consider updating Question's QST_admin_label field is of type
1641
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1642
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1643
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1644
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1645
+	 *                                         TRUE, it is assumed that you've already called
1646
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1647
+	 *                                         malicious javascript. However, if
1648
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1649
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1650
+	 *                                         and every other field, before insertion. We provide this parameter
1651
+	 *                                         because model objects perform their prepare_for_set function on all
1652
+	 *                                         their values, and so don't need to be called again (and in many cases,
1653
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1654
+	 *                                         prepare_for_set method...)
1655
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1656
+	 *                                         in this model's entity map according to $fields_n_values that match
1657
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1658
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1659
+	 *                                         could get out-of-sync with the database
1660
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1661
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1662
+	 *                                         bad)
1663
+	 * @throws EE_Error
1664
+	 */
1665
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1666
+	{
1667
+		if (! is_array($query_params)) {
1668
+			EE_Error::doing_it_wrong('EEM_Base::update',
1669
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1670
+					gettype($query_params)), '4.6.0');
1671
+			$query_params = array();
1672
+		}
1673
+		/**
1674
+		 * Action called before a model update call has been made.
1675
+		 *
1676
+		 * @param EEM_Base $model
1677
+		 * @param array    $fields_n_values the updated fields and their new values
1678
+		 * @param array    $query_params    @see EEM_Base::get_all()
1679
+		 */
1680
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1681
+		/**
1682
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1683
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1684
+		 *
1685
+		 * @param array    $fields_n_values fields and their new values
1686
+		 * @param EEM_Base $model           the model being queried
1687
+		 * @param array    $query_params    see EEM_Base::get_all()
1688
+		 */
1689
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1690
+			$query_params);
1691
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1692
+		//to do that, for each table, verify that it's PK isn't null.
1693
+		$tables = $this->get_tables();
1694
+		//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
1695
+		//NOTE: we should make this code more efficient by NOT querying twice
1696
+		//before the real update, but that needs to first go through ALPHA testing
1697
+		//as it's dangerous. says Mike August 8 2014
1698
+		//we want to make sure the default_where strategy is ignored
1699
+		$this->_ignore_where_strategy = true;
1700
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1701
+		foreach ($wpdb_select_results as $wpdb_result) {
1702
+			// type cast stdClass as array
1703
+			$wpdb_result = (array)$wpdb_result;
1704
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1705
+			if ($this->has_primary_key_field()) {
1706
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1707
+			} else {
1708
+				//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)
1709
+				$main_table_pk_value = null;
1710
+			}
1711
+			//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
1712
+			//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
1713
+			if (count($tables) > 1) {
1714
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1715
+				//in that table, and so we'll want to insert one
1716
+				foreach ($tables as $table_obj) {
1717
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1718
+					//if there is no private key for this table on the results, it means there's no entry
1719
+					//in this table, right? so insert a row in the current table, using any fields available
1720
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1721
+						   && $wpdb_result[$this_table_pk_column])
1722
+					) {
1723
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1724
+							$main_table_pk_value);
1725
+						//if we died here, report the error
1726
+						if (! $success) {
1727
+							return false;
1728
+						}
1729
+					}
1730
+				}
1731
+			}
1732
+			//				//and now check that if we have cached any models by that ID on the model, that
1733
+			//				//they also get updated properly
1734
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1735
+			//				if( $model_object ){
1736
+			//					foreach( $fields_n_values as $field => $value ){
1737
+			//						$model_object->set($field, $value);
1738
+			//let's make sure default_where strategy is followed now
1739
+			$this->_ignore_where_strategy = false;
1740
+		}
1741
+		//if we want to keep model objects in sync, AND
1742
+		//if this wasn't called from a model object (to update itself)
1743
+		//then we want to make sure we keep all the existing
1744
+		//model objects in sync with the db
1745
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1746
+			if ($this->has_primary_key_field()) {
1747
+				$model_objs_affected_ids = $this->get_col($query_params);
1748
+			} else {
1749
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1750
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1751
+				$model_objs_affected_ids = array();
1752
+				foreach ($models_affected_key_columns as $row) {
1753
+					$combined_index_key = $this->get_index_primary_key_string($row);
1754
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1755
+				}
1756
+			}
1757
+			if (! $model_objs_affected_ids) {
1758
+				//wait wait wait- if nothing was affected let's stop here
1759
+				return 0;
1760
+			}
1761
+			foreach ($model_objs_affected_ids as $id) {
1762
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1763
+				if ($model_obj_in_entity_map) {
1764
+					foreach ($fields_n_values as $field => $new_value) {
1765
+						$model_obj_in_entity_map->set($field, $new_value);
1766
+					}
1767
+				}
1768
+			}
1769
+			//if there is a primary key on this model, we can now do a slight optimization
1770
+			if ($this->has_primary_key_field()) {
1771
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1772
+				$query_params = array(
1773
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1774
+					'limit'                    => count($model_objs_affected_ids),
1775
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1776
+				);
1777
+			}
1778
+		}
1779
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1780
+		$SQL = "UPDATE "
1781
+			   . $model_query_info->get_full_join_sql()
1782
+			   . " SET "
1783
+			   . $this->_construct_update_sql($fields_n_values)
1784
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1785
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1786
+		/**
1787
+		 * Action called after a model update call has been made.
1788
+		 *
1789
+		 * @param EEM_Base $model
1790
+		 * @param array    $fields_n_values the updated fields and their new values
1791
+		 * @param array    $query_params    @see EEM_Base::get_all()
1792
+		 * @param int      $rows_affected
1793
+		 */
1794
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1795
+		return $rows_affected;//how many supposedly got updated
1796
+	}
1797
+
1798
+
1799
+
1800
+	/**
1801
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1802
+	 * are teh values of the field specified (or by default the primary key field)
1803
+	 * that matched the query params. Note that you should pass the name of the
1804
+	 * model FIELD, not the database table's column name.
1805
+	 *
1806
+	 * @param array  $query_params @see EEM_Base::get_all()
1807
+	 * @param string $field_to_select
1808
+	 * @return array just like $wpdb->get_col()
1809
+	 * @throws EE_Error
1810
+	 */
1811
+	public function get_col($query_params = array(), $field_to_select = null)
1812
+	{
1813
+		if ($field_to_select) {
1814
+			$field = $this->field_settings_for($field_to_select);
1815
+		} elseif ($this->has_primary_key_field()) {
1816
+			$field = $this->get_primary_key_field();
1817
+		} else {
1818
+			//no primary key, just grab the first column
1819
+			$field = reset($this->field_settings());
1820
+		}
1821
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1822
+		$select_expressions = $field->get_qualified_column();
1823
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1824
+		return $this->_do_wpdb_query('get_col', array($SQL));
1825
+	}
1826
+
1827
+
1828
+
1829
+	/**
1830
+	 * Returns a single column value for a single row from the database
1831
+	 *
1832
+	 * @param array  $query_params    @see EEM_Base::get_all()
1833
+	 * @param string $field_to_select @see EEM_Base::get_col()
1834
+	 * @return string
1835
+	 * @throws EE_Error
1836
+	 */
1837
+	public function get_var($query_params = array(), $field_to_select = null)
1838
+	{
1839
+		$query_params['limit'] = 1;
1840
+		$col = $this->get_col($query_params, $field_to_select);
1841
+		if (! empty($col)) {
1842
+			return reset($col);
1843
+		}
1844
+		return null;
1845
+	}
1846
+
1847
+
1848
+
1849
+	/**
1850
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1851
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1852
+	 * injection, but currently no further filtering is done
1853
+	 *
1854
+	 * @global      $wpdb
1855
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1856
+	 *                               be updated to in the DB
1857
+	 * @return string of SQL
1858
+	 * @throws EE_Error
1859
+	 */
1860
+	public function _construct_update_sql($fields_n_values)
1861
+	{
1862
+		/** @type WPDB $wpdb */
1863
+		global $wpdb;
1864
+		$cols_n_values = array();
1865
+		foreach ($fields_n_values as $field_name => $value) {
1866
+			$field_obj = $this->field_settings_for($field_name);
1867
+			//if the value is NULL, we want to assign the value to that.
1868
+			//wpdb->prepare doesn't really handle that properly
1869
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1870
+			$value_sql = $prepared_value === null ? 'NULL'
1871
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1872
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1873
+		}
1874
+		return implode(",", $cols_n_values);
1875
+	}
1876
+
1877
+
1878
+
1879
+	/**
1880
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1881
+	 * Performs a HARD delete, meaning the database row should always be removed,
1882
+	 * not just have a flag field on it switched
1883
+	 * Wrapper for EEM_Base::delete_permanently()
1884
+	 *
1885
+	 * @param mixed $id
1886
+	 * @return boolean whether the row got deleted or not
1887
+	 * @throws EE_Error
1888
+	 */
1889
+	public function delete_permanently_by_ID($id)
1890
+	{
1891
+		return $this->delete_permanently(
1892
+			array(
1893
+				array($this->get_primary_key_field()->get_name() => $id),
1894
+				'limit' => 1,
1895
+			)
1896
+		);
1897
+	}
1898
+
1899
+
1900
+
1901
+	/**
1902
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1903
+	 * Wrapper for EEM_Base::delete()
1904
+	 *
1905
+	 * @param mixed $id
1906
+	 * @return boolean whether the row got deleted or not
1907
+	 * @throws EE_Error
1908
+	 */
1909
+	public function delete_by_ID($id)
1910
+	{
1911
+		return $this->delete(
1912
+			array(
1913
+				array($this->get_primary_key_field()->get_name() => $id),
1914
+				'limit' => 1,
1915
+			)
1916
+		);
1917
+	}
1918
+
1919
+
1920
+
1921
+	/**
1922
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1923
+	 * meaning if the model has a field that indicates its been "trashed" or
1924
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1925
+	 *
1926
+	 * @see EEM_Base::delete_permanently
1927
+	 * @param array   $query_params
1928
+	 * @param boolean $allow_blocking
1929
+	 * @return int how many rows got deleted
1930
+	 * @throws EE_Error
1931
+	 */
1932
+	public function delete($query_params, $allow_blocking = true)
1933
+	{
1934
+		return $this->delete_permanently($query_params, $allow_blocking);
1935
+	}
1936
+
1937
+
1938
+
1939
+	/**
1940
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1941
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1942
+	 * as archived, not actually deleted
1943
+	 *
1944
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1945
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1946
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1947
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1948
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1949
+	 *                                DB
1950
+	 * @return int how many rows got deleted
1951
+	 * @throws EE_Error
1952
+	 */
1953
+	public function delete_permanently($query_params, $allow_blocking = true)
1954
+	{
1955
+		/**
1956
+		 * Action called just before performing a real deletion query. You can use the
1957
+		 * model and its $query_params to find exactly which items will be deleted
1958
+		 *
1959
+		 * @param EEM_Base $model
1960
+		 * @param array    $query_params   @see EEM_Base::get_all()
1961
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1962
+		 *                                 to block (prevent) this deletion
1963
+		 */
1964
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1965
+		//some MySQL databases may be running safe mode, which may restrict
1966
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1967
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1968
+		//to delete them
1969
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1970
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1971
+		if ($deletion_where) {
1972
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1973
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1974
+			$table_aliases = array_keys($this->_tables);
1975
+			$SQL = "DELETE "
1976
+				   . implode(", ", $table_aliases)
1977
+				   . " FROM "
1978
+				   . $model_query_info->get_full_join_sql()
1979
+				   . " WHERE "
1980
+				   . $deletion_where;
1981
+			//		/echo "delete sql:$SQL";
1982
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1983
+		} else {
1984
+			$rows_deleted = 0;
1985
+		}
1986
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1987
+		if ($this->has_primary_key_field()) {
1988
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1989
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1990
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1991
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1992
+				}
1993
+			}
1994
+		}
1995
+		/**
1996
+		 * Action called just after performing a real deletion query. Although at this point the
1997
+		 * items should have been deleted
1998
+		 *
1999
+		 * @param EEM_Base $model
2000
+		 * @param array    $query_params @see EEM_Base::get_all()
2001
+		 * @param int      $rows_deleted
2002
+		 */
2003
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
2004
+		return $rows_deleted;//how many supposedly got deleted
2005
+	}
2006
+
2007
+
2008
+
2009
+	/**
2010
+	 * Checks all the relations that throw error messages when there are blocking related objects
2011
+	 * for related model objects. If there are any related model objects on those relations,
2012
+	 * adds an EE_Error, and return true
2013
+	 *
2014
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2015
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2016
+	 *                                                 should be ignored when determining whether there are related
2017
+	 *                                                 model objects which block this model object's deletion. Useful
2018
+	 *                                                 if you know A is related to B and are considering deleting A,
2019
+	 *                                                 but want to see if A has any other objects blocking its deletion
2020
+	 *                                                 before removing the relation between A and B
2021
+	 * @return boolean
2022
+	 * @throws EE_Error
2023
+	 */
2024
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2025
+	{
2026
+		//first, if $ignore_this_model_obj was supplied, get its model
2027
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2028
+			$ignored_model = $ignore_this_model_obj->get_model();
2029
+		} else {
2030
+			$ignored_model = null;
2031
+		}
2032
+		//now check all the relations of $this_model_obj_or_id and see if there
2033
+		//are any related model objects blocking it?
2034
+		$is_blocked = false;
2035
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2036
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2037
+				//if $ignore_this_model_obj was supplied, then for the query
2038
+				//on that model needs to be told to ignore $ignore_this_model_obj
2039
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2040
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2041
+						array(
2042
+							$ignored_model->get_primary_key_field()->get_name() => array(
2043
+								'!=',
2044
+								$ignore_this_model_obj->ID(),
2045
+							),
2046
+						),
2047
+					));
2048
+				} else {
2049
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2050
+				}
2051
+				if ($related_model_objects) {
2052
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2053
+					$is_blocked = true;
2054
+				}
2055
+			}
2056
+		}
2057
+		return $is_blocked;
2058
+	}
2059
+
2060
+
2061
+
2062
+	/**
2063
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2064
+	 * well.
2065
+	 *
2066
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2067
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2068
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
2069
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
2070
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
2071
+	 *                                      easily corrupt your DB
2072
+	 * @throws EE_Error
2073
+	 * @return string    everything that comes after the WHERE statement.
2074
+	 */
2075
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2076
+	{
2077
+		if ($this->has_primary_key_field()) {
2078
+			$primary_table = $this->_get_main_table();
2079
+			$other_tables = $this->_get_other_tables();
2080
+			$deletes = $query = array();
2081
+			foreach ($objects_for_deletion as $delete_object) {
2082
+				//before we mark this object for deletion,
2083
+				//make sure there's no related objects blocking its deletion (if we're checking)
2084
+				if (
2085
+					$allow_blocking
2086
+					&& $this->delete_is_blocked_by_related_models(
2087
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
2088
+					)
2089
+				) {
2090
+					continue;
2091
+				}
2092
+				//primary table deletes
2093
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2094
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2095
+				}
2096
+				//other tables
2097
+				if (! empty($other_tables)) {
2098
+					foreach ($other_tables as $ot) {
2099
+						//first check if we've got the foreign key column here.
2100
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2101
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2102
+						}
2103
+						// wait! it's entirely possible that we'll have a the primary key
2104
+						// for this table in here, if it's a foreign key for one of the other secondary tables
2105
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2106
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2107
+						}
2108
+						// finally, it is possible that the fk for this table is found
2109
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
2110
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2111
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2112
+						}
2113
+					}
2114
+				}
2115
+			}
2116
+			//we should have deletes now, so let's just go through and setup the where statement
2117
+			foreach ($deletes as $column => $values) {
2118
+				//make sure we have unique $values;
2119
+				$values = array_unique($values);
2120
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
2121
+			}
2122
+			return ! empty($query) ? implode(' AND ', $query) : '';
2123
+		}
2124
+		if (count($this->get_combined_primary_key_fields()) > 1) {
2125
+			$ways_to_identify_a_row = array();
2126
+			$fields = $this->get_combined_primary_key_fields();
2127
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2128
+			foreach ($objects_for_deletion as $delete_object) {
2129
+				$values_for_each_cpk_for_a_row = array();
2130
+				foreach ($fields as $cpk_field) {
2131
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2132
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2133
+														   . "="
2134
+														   . $delete_object[$cpk_field->get_qualified_column()];
2135
+					}
2136
+				}
2137
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2138
+			}
2139
+			return implode(" OR ", $ways_to_identify_a_row);
2140
+		}
2141
+		//so there's no primary key and no combined key...
2142
+		//sorry, can't help you
2143
+		throw new EE_Error(
2144
+			sprintf(
2145
+				__(
2146
+					"Cannot delete objects of type %s because there is no primary key NOR combined key",
2147
+					"event_espresso"
2148
+				), get_class($this)
2149
+			)
2150
+		);
2151
+	}
2152
+
2153
+
2154
+
2155
+	/**
2156
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2157
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2158
+	 * column
2159
+	 *
2160
+	 * @param array  $query_params   like EEM_Base::get_all's
2161
+	 * @param string $field_to_count field on model to count by (not column name)
2162
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2163
+	 *                               that by the setting $distinct to TRUE;
2164
+	 * @return int
2165
+	 * @throws EE_Error
2166
+	 */
2167
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2168
+	{
2169
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2170
+		if ($field_to_count) {
2171
+			$field_obj = $this->field_settings_for($field_to_count);
2172
+			$column_to_count = $field_obj->get_qualified_column();
2173
+		} elseif ($this->has_primary_key_field()) {
2174
+			$pk_field_obj = $this->get_primary_key_field();
2175
+			$column_to_count = $pk_field_obj->get_qualified_column();
2176
+		} else {
2177
+			//there's no primary key
2178
+			//if we're counting distinct items, and there's no primary key,
2179
+			//we need to list out the columns for distinction;
2180
+			//otherwise we can just use star
2181
+			if ($distinct) {
2182
+				$columns_to_use = array();
2183
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2184
+					$columns_to_use[] = $field_obj->get_qualified_column();
2185
+				}
2186
+				$column_to_count = implode(',', $columns_to_use);
2187
+			} else {
2188
+				$column_to_count = '*';
2189
+			}
2190
+		}
2191
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2192
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2193
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2194
+	}
2195
+
2196
+
2197
+
2198
+	/**
2199
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2200
+	 *
2201
+	 * @param array  $query_params like EEM_Base::get_all
2202
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2203
+	 * @return float
2204
+	 * @throws EE_Error
2205
+	 */
2206
+	public function sum($query_params, $field_to_sum = null)
2207
+	{
2208
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2209
+		if ($field_to_sum) {
2210
+			$field_obj = $this->field_settings_for($field_to_sum);
2211
+		} else {
2212
+			$field_obj = $this->get_primary_key_field();
2213
+		}
2214
+		$column_to_count = $field_obj->get_qualified_column();
2215
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2216
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2217
+		$data_type = $field_obj->get_wpdb_data_type();
2218
+		if ($data_type === '%d' || $data_type === '%s') {
2219
+			return (float)$return_value;
2220
+		}
2221
+		//must be %f
2222
+		return (float)$return_value;
2223
+	}
2224
+
2225
+
2226
+
2227
+	/**
2228
+	 * Just calls the specified method on $wpdb with the given arguments
2229
+	 * Consolidates a little extra error handling code
2230
+	 *
2231
+	 * @param string $wpdb_method
2232
+	 * @param array  $arguments_to_provide
2233
+	 * @throws EE_Error
2234
+	 * @global wpdb  $wpdb
2235
+	 * @return mixed
2236
+	 */
2237
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2238
+	{
2239
+		//if we're in maintenance mode level 2, DON'T run any queries
2240
+		//because level 2 indicates the database needs updating and
2241
+		//is probably out of sync with the code
2242
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2243
+			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.",
2244
+				"event_espresso")));
2245
+		}
2246
+		/** @type WPDB $wpdb */
2247
+		global $wpdb;
2248
+		if (! method_exists($wpdb, $wpdb_method)) {
2249
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2250
+				'event_espresso'), $wpdb_method));
2251
+		}
2252
+		if (WP_DEBUG) {
2253
+			$old_show_errors_value = $wpdb->show_errors;
2254
+			$wpdb->show_errors(false);
2255
+		}
2256
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2257
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2258
+		if (WP_DEBUG) {
2259
+			$wpdb->show_errors($old_show_errors_value);
2260
+			if (! empty($wpdb->last_error)) {
2261
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2262
+			}
2263
+			if ($result === false) {
2264
+				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"',
2265
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2266
+			}
2267
+		} elseif ($result === false) {
2268
+			EE_Error::add_error(
2269
+				sprintf(
2270
+					__('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"',
2271
+						'event_espresso'),
2272
+					$wpdb_method,
2273
+					var_export($arguments_to_provide, true),
2274
+					$wpdb->last_error
2275
+				),
2276
+				__FILE__,
2277
+				__FUNCTION__,
2278
+				__LINE__
2279
+			);
2280
+		}
2281
+		return $result;
2282
+	}
2283
+
2284
+
2285
+
2286
+	/**
2287
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2288
+	 * and if there's an error tries to verify the DB is correct. Uses
2289
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2290
+	 * we should try to fix the EE core db, the addons, or just give up
2291
+	 *
2292
+	 * @param string $wpdb_method
2293
+	 * @param array  $arguments_to_provide
2294
+	 * @return mixed
2295
+	 */
2296
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2297
+	{
2298
+		/** @type WPDB $wpdb */
2299
+		global $wpdb;
2300
+		$wpdb->last_error = null;
2301
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2302
+		// was there an error running the query? but we don't care on new activations
2303
+		// (we're going to setup the DB anyway on new activations)
2304
+		if (($result === false || ! empty($wpdb->last_error))
2305
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2306
+		) {
2307
+			switch (EEM_Base::$_db_verification_level) {
2308
+				case EEM_Base::db_verified_none :
2309
+					// let's double-check core's DB
2310
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2311
+					break;
2312
+				case EEM_Base::db_verified_core :
2313
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2314
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2315
+					break;
2316
+				case EEM_Base::db_verified_addons :
2317
+					// ummmm... you in trouble
2318
+					return $result;
2319
+					break;
2320
+			}
2321
+			if (! empty($error_message)) {
2322
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2323
+				trigger_error($error_message);
2324
+			}
2325
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2326
+		}
2327
+		return $result;
2328
+	}
2329
+
2330
+
2331
+
2332
+	/**
2333
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2334
+	 * EEM_Base::$_db_verification_level
2335
+	 *
2336
+	 * @param string $wpdb_method
2337
+	 * @param array  $arguments_to_provide
2338
+	 * @return string
2339
+	 */
2340
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2341
+	{
2342
+		/** @type WPDB $wpdb */
2343
+		global $wpdb;
2344
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2345
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2346
+		$error_message = sprintf(
2347
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2348
+				'event_espresso'),
2349
+			$wpdb->last_error,
2350
+			$wpdb_method,
2351
+			wp_json_encode($arguments_to_provide)
2352
+		);
2353
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2354
+		return $error_message;
2355
+	}
2356
+
2357
+
2358
+
2359
+	/**
2360
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2361
+	 * EEM_Base::$_db_verification_level
2362
+	 *
2363
+	 * @param $wpdb_method
2364
+	 * @param $arguments_to_provide
2365
+	 * @return string
2366
+	 */
2367
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2368
+	{
2369
+		/** @type WPDB $wpdb */
2370
+		global $wpdb;
2371
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2372
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2373
+		$error_message = sprintf(
2374
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2375
+				'event_espresso'),
2376
+			$wpdb->last_error,
2377
+			$wpdb_method,
2378
+			wp_json_encode($arguments_to_provide)
2379
+		);
2380
+		EE_System::instance()->initialize_addons();
2381
+		return $error_message;
2382
+	}
2383
+
2384
+
2385
+
2386
+	/**
2387
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2388
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2389
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2390
+	 * ..."
2391
+	 *
2392
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2393
+	 * @return string
2394
+	 */
2395
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2396
+	{
2397
+		return " FROM " . $model_query_info->get_full_join_sql() .
2398
+			   $model_query_info->get_where_sql() .
2399
+			   $model_query_info->get_group_by_sql() .
2400
+			   $model_query_info->get_having_sql() .
2401
+			   $model_query_info->get_order_by_sql() .
2402
+			   $model_query_info->get_limit_sql();
2403
+	}
2404
+
2405
+
2406
+
2407
+	/**
2408
+	 * Set to easily debug the next X queries ran from this model.
2409
+	 *
2410
+	 * @param int $count
2411
+	 */
2412
+	public function show_next_x_db_queries($count = 1)
2413
+	{
2414
+		$this->_show_next_x_db_queries = $count;
2415
+	}
2416
+
2417
+
2418
+
2419
+	/**
2420
+	 * @param $sql_query
2421
+	 */
2422
+	public function show_db_query_if_previously_requested($sql_query)
2423
+	{
2424
+		if ($this->_show_next_x_db_queries > 0) {
2425
+			echo $sql_query;
2426
+			$this->_show_next_x_db_queries--;
2427
+		}
2428
+	}
2429
+
2430
+
2431
+
2432
+	/**
2433
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2434
+	 * There are the 3 cases:
2435
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2436
+	 * $otherModelObject has no ID, it is first saved.
2437
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2438
+	 * has no ID, it is first saved.
2439
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2440
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2441
+	 * join table
2442
+	 *
2443
+	 * @param        EE_Base_Class                     /int $thisModelObject
2444
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2445
+	 * @param string $relationName                     , key in EEM_Base::_relations
2446
+	 *                                                 an attendee to a group, you also want to specify which role they
2447
+	 *                                                 will have in that group. So you would use this parameter to
2448
+	 *                                                 specify array('role-column-name'=>'role-id')
2449
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2450
+	 *                                                 to for relation to methods that allow you to further specify
2451
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2452
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2453
+	 *                                                 because these will be inserted in any new rows created as well.
2454
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2455
+	 * @throws EE_Error
2456
+	 */
2457
+	public function add_relationship_to(
2458
+		$id_or_obj,
2459
+		$other_model_id_or_obj,
2460
+		$relationName,
2461
+		$extra_join_model_fields_n_values = array()
2462
+	) {
2463
+		$relation_obj = $this->related_settings_for($relationName);
2464
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2465
+	}
2466
+
2467
+
2468
+
2469
+	/**
2470
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2471
+	 * There are the 3 cases:
2472
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2473
+	 * error
2474
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2475
+	 * an error
2476
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2477
+	 *
2478
+	 * @param        EE_Base_Class /int $id_or_obj
2479
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2480
+	 * @param string $relationName key in EEM_Base::_relations
2481
+	 * @return boolean of success
2482
+	 * @throws EE_Error
2483
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2484
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2485
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2486
+	 *                             because these will be inserted in any new rows created as well.
2487
+	 */
2488
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2489
+	{
2490
+		$relation_obj = $this->related_settings_for($relationName);
2491
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2492
+	}
2493
+
2494
+
2495
+
2496
+	/**
2497
+	 * @param mixed           $id_or_obj
2498
+	 * @param string          $relationName
2499
+	 * @param array           $where_query_params
2500
+	 * @param EE_Base_Class[] objects to which relations were removed
2501
+	 * @return \EE_Base_Class[]
2502
+	 * @throws EE_Error
2503
+	 */
2504
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2505
+	{
2506
+		$relation_obj = $this->related_settings_for($relationName);
2507
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2508
+	}
2509
+
2510
+
2511
+
2512
+	/**
2513
+	 * Gets all the related items of the specified $model_name, using $query_params.
2514
+	 * Note: by default, we remove the "default query params"
2515
+	 * because we want to get even deleted items etc.
2516
+	 *
2517
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2518
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2519
+	 * @param array  $query_params like EEM_Base::get_all
2520
+	 * @return EE_Base_Class[]
2521
+	 * @throws EE_Error
2522
+	 */
2523
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2524
+	{
2525
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2526
+		$relation_settings = $this->related_settings_for($model_name);
2527
+		return $relation_settings->get_all_related($model_obj, $query_params);
2528
+	}
2529
+
2530
+
2531
+
2532
+	/**
2533
+	 * Deletes all the model objects across the relation indicated by $model_name
2534
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2535
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2536
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2537
+	 *
2538
+	 * @param EE_Base_Class|int|string $id_or_obj
2539
+	 * @param string                   $model_name
2540
+	 * @param array                    $query_params
2541
+	 * @return int how many deleted
2542
+	 * @throws EE_Error
2543
+	 */
2544
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2545
+	{
2546
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2547
+		$relation_settings = $this->related_settings_for($model_name);
2548
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2549
+	}
2550
+
2551
+
2552
+
2553
+	/**
2554
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2555
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2556
+	 * the model objects can't be hard deleted because of blocking related model objects,
2557
+	 * just does a soft-delete on them instead.
2558
+	 *
2559
+	 * @param EE_Base_Class|int|string $id_or_obj
2560
+	 * @param string                   $model_name
2561
+	 * @param array                    $query_params
2562
+	 * @return int how many deleted
2563
+	 * @throws EE_Error
2564
+	 */
2565
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2566
+	{
2567
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2568
+		$relation_settings = $this->related_settings_for($model_name);
2569
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2570
+	}
2571
+
2572
+
2573
+
2574
+	/**
2575
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2576
+	 * unless otherwise specified in the $query_params
2577
+	 *
2578
+	 * @param        int             /EE_Base_Class $id_or_obj
2579
+	 * @param string $model_name     like 'Event', or 'Registration'
2580
+	 * @param array  $query_params   like EEM_Base::get_all's
2581
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2582
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2583
+	 *                               that by the setting $distinct to TRUE;
2584
+	 * @return int
2585
+	 * @throws EE_Error
2586
+	 */
2587
+	public function count_related(
2588
+		$id_or_obj,
2589
+		$model_name,
2590
+		$query_params = array(),
2591
+		$field_to_count = null,
2592
+		$distinct = false
2593
+	) {
2594
+		$related_model = $this->get_related_model_obj($model_name);
2595
+		//we're just going to use the query params on the related model's normal get_all query,
2596
+		//except add a condition to say to match the current mod
2597
+		if (! isset($query_params['default_where_conditions'])) {
2598
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2599
+		}
2600
+		$this_model_name = $this->get_this_model_name();
2601
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2602
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2603
+		return $related_model->count($query_params, $field_to_count, $distinct);
2604
+	}
2605
+
2606
+
2607
+
2608
+	/**
2609
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2610
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2611
+	 *
2612
+	 * @param        int           /EE_Base_Class $id_or_obj
2613
+	 * @param string $model_name   like 'Event', or 'Registration'
2614
+	 * @param array  $query_params like EEM_Base::get_all's
2615
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2616
+	 * @return float
2617
+	 * @throws EE_Error
2618
+	 */
2619
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2620
+	{
2621
+		$related_model = $this->get_related_model_obj($model_name);
2622
+		if (! is_array($query_params)) {
2623
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2624
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2625
+					gettype($query_params)), '4.6.0');
2626
+			$query_params = array();
2627
+		}
2628
+		//we're just going to use the query params on the related model's normal get_all query,
2629
+		//except add a condition to say to match the current mod
2630
+		if (! isset($query_params['default_where_conditions'])) {
2631
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2632
+		}
2633
+		$this_model_name = $this->get_this_model_name();
2634
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2635
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2636
+		return $related_model->sum($query_params, $field_to_sum);
2637
+	}
2638
+
2639
+
2640
+
2641
+	/**
2642
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2643
+	 * $modelObject
2644
+	 *
2645
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2646
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2647
+	 * @param array               $query_params     like EEM_Base::get_all's
2648
+	 * @return EE_Base_Class
2649
+	 * @throws EE_Error
2650
+	 */
2651
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2652
+	{
2653
+		$query_params['limit'] = 1;
2654
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2655
+		if ($results) {
2656
+			return array_shift($results);
2657
+		}
2658
+		return null;
2659
+	}
2660
+
2661
+
2662
+
2663
+	/**
2664
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2665
+	 *
2666
+	 * @return string
2667
+	 */
2668
+	public function get_this_model_name()
2669
+	{
2670
+		return str_replace("EEM_", "", get_class($this));
2671
+	}
2672
+
2673
+
2674
+
2675
+	/**
2676
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2677
+	 *
2678
+	 * @return EE_Any_Foreign_Model_Name_Field
2679
+	 * @throws EE_Error
2680
+	 */
2681
+	public function get_field_containing_related_model_name()
2682
+	{
2683
+		foreach ($this->field_settings(true) as $field) {
2684
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2685
+				$field_with_model_name = $field;
2686
+			}
2687
+		}
2688
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2689
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2690
+				$this->get_this_model_name()));
2691
+		}
2692
+		return $field_with_model_name;
2693
+	}
2694
+
2695
+
2696
+
2697
+	/**
2698
+	 * Inserts a new entry into the database, for each table.
2699
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2700
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2701
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2702
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2703
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2704
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2705
+	 *
2706
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2707
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2708
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2709
+	 *                              of EEM_Base)
2710
+	 * @return int new primary key on main table that got inserted
2711
+	 * @throws EE_Error
2712
+	 */
2713
+	public function insert($field_n_values)
2714
+	{
2715
+		/**
2716
+		 * Filters the fields and their values before inserting an item using the models
2717
+		 *
2718
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2719
+		 * @param EEM_Base $model           the model used
2720
+		 */
2721
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2722
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2723
+			$main_table = $this->_get_main_table();
2724
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2725
+			if ($new_id !== false) {
2726
+				foreach ($this->_get_other_tables() as $other_table) {
2727
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2728
+				}
2729
+			}
2730
+			/**
2731
+			 * Done just after attempting to insert a new model object
2732
+			 *
2733
+			 * @param EEM_Base   $model           used
2734
+			 * @param array      $fields_n_values fields and their values
2735
+			 * @param int|string the              ID of the newly-inserted model object
2736
+			 */
2737
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2738
+			return $new_id;
2739
+		}
2740
+		return false;
2741
+	}
2742
+
2743
+
2744
+
2745
+	/**
2746
+	 * Checks that the result would satisfy the unique indexes on this model
2747
+	 *
2748
+	 * @param array  $field_n_values
2749
+	 * @param string $action
2750
+	 * @return boolean
2751
+	 * @throws EE_Error
2752
+	 */
2753
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2754
+	{
2755
+		foreach ($this->unique_indexes() as $index_name => $index) {
2756
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2757
+			if ($this->exists(array($uniqueness_where_params))) {
2758
+				EE_Error::add_error(
2759
+					sprintf(
2760
+						__(
2761
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2762
+							"event_espresso"
2763
+						),
2764
+						$action,
2765
+						$this->_get_class_name(),
2766
+						$index_name,
2767
+						implode(",", $index->field_names()),
2768
+						http_build_query($uniqueness_where_params)
2769
+					),
2770
+					__FILE__,
2771
+					__FUNCTION__,
2772
+					__LINE__
2773
+				);
2774
+				return false;
2775
+			}
2776
+		}
2777
+		return true;
2778
+	}
2779
+
2780
+
2781
+
2782
+	/**
2783
+	 * Checks the database for an item that conflicts (ie, if this item were
2784
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2785
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2786
+	 * can be either an EE_Base_Class or an array of fields n values
2787
+	 *
2788
+	 * @param EE_Base_Class|array $obj_or_fields_array
2789
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2790
+	 *                                                 when looking for conflicts
2791
+	 *                                                 (ie, if false, we ignore the model object's primary key
2792
+	 *                                                 when finding "conflicts". If true, it's also considered).
2793
+	 *                                                 Only works for INT primary key,
2794
+	 *                                                 STRING primary keys cannot be ignored
2795
+	 * @throws EE_Error
2796
+	 * @return EE_Base_Class|array
2797
+	 */
2798
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2799
+	{
2800
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2801
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2802
+		} elseif (is_array($obj_or_fields_array)) {
2803
+			$fields_n_values = $obj_or_fields_array;
2804
+		} else {
2805
+			throw new EE_Error(
2806
+				sprintf(
2807
+					__(
2808
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2809
+						"event_espresso"
2810
+					),
2811
+					get_class($this),
2812
+					$obj_or_fields_array
2813
+				)
2814
+			);
2815
+		}
2816
+		$query_params = array();
2817
+		if ($this->has_primary_key_field()
2818
+			&& ($include_primary_key
2819
+				|| $this->get_primary_key_field()
2820
+				   instanceof
2821
+				   EE_Primary_Key_String_Field)
2822
+			&& isset($fields_n_values[$this->primary_key_name()])
2823
+		) {
2824
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2825
+		}
2826
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2827
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2828
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2829
+		}
2830
+		//if there is nothing to base this search on, then we shouldn't find anything
2831
+		if (empty($query_params)) {
2832
+			return array();
2833
+		}
2834
+		return $this->get_one($query_params);
2835
+	}
2836
+
2837
+
2838
+
2839
+	/**
2840
+	 * Like count, but is optimized and returns a boolean instead of an int
2841
+	 *
2842
+	 * @param array $query_params
2843
+	 * @return boolean
2844
+	 * @throws EE_Error
2845
+	 */
2846
+	public function exists($query_params)
2847
+	{
2848
+		$query_params['limit'] = 1;
2849
+		return $this->count($query_params) > 0;
2850
+	}
2851
+
2852
+
2853
+
2854
+	/**
2855
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2856
+	 *
2857
+	 * @param int|string $id
2858
+	 * @return boolean
2859
+	 * @throws EE_Error
2860
+	 */
2861
+	public function exists_by_ID($id)
2862
+	{
2863
+		return $this->exists(
2864
+			array(
2865
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2866
+				array(
2867
+					$this->primary_key_name() => $id,
2868
+				),
2869
+			)
2870
+		);
2871
+	}
2872
+
2873
+
2874
+
2875
+	/**
2876
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2877
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2878
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2879
+	 * on the main table)
2880
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2881
+	 * cases where we want to call it directly rather than via insert().
2882
+	 *
2883
+	 * @access   protected
2884
+	 * @param EE_Table_Base $table
2885
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2886
+	 *                                       float
2887
+	 * @param int           $new_id          for now we assume only int keys
2888
+	 * @throws EE_Error
2889
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2890
+	 * @return int ID of new row inserted, or FALSE on failure
2891
+	 */
2892
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2893
+	{
2894
+		global $wpdb;
2895
+		$insertion_col_n_values = array();
2896
+		$format_for_insertion = array();
2897
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2898
+		foreach ($fields_on_table as $field_name => $field_obj) {
2899
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2900
+			if ($field_obj->is_auto_increment()) {
2901
+				continue;
2902
+			}
2903
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2904
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2905
+			if ($prepared_value !== null) {
2906
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2907
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2908
+			}
2909
+		}
2910
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2911
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2912
+			//so add the fk to the main table as a column
2913
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2914
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2915
+		}
2916
+		//insert the new entry
2917
+		$result = $this->_do_wpdb_query('insert',
2918
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2919
+		if ($result === false) {
2920
+			return false;
2921
+		}
2922
+		//ok, now what do we return for the ID of the newly-inserted thing?
2923
+		if ($this->has_primary_key_field()) {
2924
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2925
+				return $wpdb->insert_id;
2926
+			}
2927
+			//it's not an auto-increment primary key, so
2928
+			//it must have been supplied
2929
+			return $fields_n_values[$this->get_primary_key_field()->get_name()];
2930
+		}
2931
+		//we can't return a  primary key because there is none. instead return
2932
+		//a unique string indicating this model
2933
+		return $this->get_index_primary_key_string($fields_n_values);
2934
+	}
2935
+
2936
+
2937
+
2938
+	/**
2939
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2940
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2941
+	 * and there is no default, we pass it along. WPDB will take care of it)
2942
+	 *
2943
+	 * @param EE_Model_Field_Base $field_obj
2944
+	 * @param array               $fields_n_values
2945
+	 * @return mixed string|int|float depending on what the table column will be expecting
2946
+	 * @throws EE_Error
2947
+	 */
2948
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2949
+	{
2950
+		//if this field doesn't allow nullable, don't allow it
2951
+		if (
2952
+			! $field_obj->is_nullable()
2953
+			&& (
2954
+				! isset($fields_n_values[$field_obj->get_name()])
2955
+				|| $fields_n_values[$field_obj->get_name()] === null
2956
+			)
2957
+		) {
2958
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2959
+		}
2960
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2961
+			? $fields_n_values[$field_obj->get_name()]
2962
+			: null;
2963
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2964
+	}
2965
+
2966
+
2967
+
2968
+	/**
2969
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2970
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2971
+	 * the field's prepare_for_set() method.
2972
+	 *
2973
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2974
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2975
+	 *                                   top of file)
2976
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2977
+	 *                                   $value is a custom selection
2978
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2979
+	 */
2980
+	private function _prepare_value_for_use_in_db($value, $field)
2981
+	{
2982
+		if ($field && $field instanceof EE_Model_Field_Base) {
2983
+			switch ($this->_values_already_prepared_by_model_object) {
2984
+				/** @noinspection PhpMissingBreakStatementInspection */
2985
+				case self::not_prepared_by_model_object:
2986
+					$value = $field->prepare_for_set($value);
2987
+				//purposefully left out "return"
2988
+				case self::prepared_by_model_object:
2989
+					/** @noinspection SuspiciousAssignmentsInspection */
2990
+					$value = $field->prepare_for_use_in_db($value);
2991
+				case self::prepared_for_use_in_db:
2992
+					//leave the value alone
2993
+			}
2994
+			return $value;
2995
+		}
2996
+		return $value;
2997
+	}
2998
+
2999
+
3000
+
3001
+	/**
3002
+	 * Returns the main table on this model
3003
+	 *
3004
+	 * @return EE_Primary_Table
3005
+	 * @throws EE_Error
3006
+	 */
3007
+	protected function _get_main_table()
3008
+	{
3009
+		foreach ($this->_tables as $table) {
3010
+			if ($table instanceof EE_Primary_Table) {
3011
+				return $table;
3012
+			}
3013
+		}
3014
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3015
+			'event_espresso'), get_class($this)));
3016
+	}
3017
+
3018
+
3019
+
3020
+	/**
3021
+	 * table
3022
+	 * returns EE_Primary_Table table name
3023
+	 *
3024
+	 * @return string
3025
+	 * @throws EE_Error
3026
+	 */
3027
+	public function table()
3028
+	{
3029
+		return $this->_get_main_table()->get_table_name();
3030
+	}
3031
+
3032
+
3033
+
3034
+	/**
3035
+	 * table
3036
+	 * returns first EE_Secondary_Table table name
3037
+	 *
3038
+	 * @return string
3039
+	 */
3040
+	public function second_table()
3041
+	{
3042
+		// grab second table from tables array
3043
+		$second_table = end($this->_tables);
3044
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3045
+	}
3046
+
3047
+
3048
+
3049
+	/**
3050
+	 * get_table_obj_by_alias
3051
+	 * returns table name given it's alias
3052
+	 *
3053
+	 * @param string $table_alias
3054
+	 * @return EE_Primary_Table | EE_Secondary_Table
3055
+	 */
3056
+	public function get_table_obj_by_alias($table_alias = '')
3057
+	{
3058
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3059
+	}
3060
+
3061
+
3062
+
3063
+	/**
3064
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3065
+	 *
3066
+	 * @return EE_Secondary_Table[]
3067
+	 */
3068
+	protected function _get_other_tables()
3069
+	{
3070
+		$other_tables = array();
3071
+		foreach ($this->_tables as $table_alias => $table) {
3072
+			if ($table instanceof EE_Secondary_Table) {
3073
+				$other_tables[$table_alias] = $table;
3074
+			}
3075
+		}
3076
+		return $other_tables;
3077
+	}
3078
+
3079
+
3080
+
3081
+	/**
3082
+	 * Finds all the fields that correspond to the given table
3083
+	 *
3084
+	 * @param string $table_alias , array key in EEM_Base::_tables
3085
+	 * @return EE_Model_Field_Base[]
3086
+	 */
3087
+	public function _get_fields_for_table($table_alias)
3088
+	{
3089
+		return $this->_fields[$table_alias];
3090
+	}
3091
+
3092
+
3093
+
3094
+	/**
3095
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3096
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3097
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3098
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3099
+	 * related Registration, Transaction, and Payment models.
3100
+	 *
3101
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3102
+	 * @return EE_Model_Query_Info_Carrier
3103
+	 * @throws EE_Error
3104
+	 */
3105
+	public function _extract_related_models_from_query($query_params)
3106
+	{
3107
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3108
+		if (array_key_exists(0, $query_params)) {
3109
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3110
+		}
3111
+		if (array_key_exists('group_by', $query_params)) {
3112
+			if (is_array($query_params['group_by'])) {
3113
+				$this->_extract_related_models_from_sub_params_array_values(
3114
+					$query_params['group_by'],
3115
+					$query_info_carrier,
3116
+					'group_by'
3117
+				);
3118
+			} elseif (! empty ($query_params['group_by'])) {
3119
+				$this->_extract_related_model_info_from_query_param(
3120
+					$query_params['group_by'],
3121
+					$query_info_carrier,
3122
+					'group_by'
3123
+				);
3124
+			}
3125
+		}
3126
+		if (array_key_exists('having', $query_params)) {
3127
+			$this->_extract_related_models_from_sub_params_array_keys(
3128
+				$query_params[0],
3129
+				$query_info_carrier,
3130
+				'having'
3131
+			);
3132
+		}
3133
+		if (array_key_exists('order_by', $query_params)) {
3134
+			if (is_array($query_params['order_by'])) {
3135
+				$this->_extract_related_models_from_sub_params_array_keys(
3136
+					$query_params['order_by'],
3137
+					$query_info_carrier,
3138
+					'order_by'
3139
+				);
3140
+			} elseif (! empty($query_params['order_by'])) {
3141
+				$this->_extract_related_model_info_from_query_param(
3142
+					$query_params['order_by'],
3143
+					$query_info_carrier,
3144
+					'order_by'
3145
+				);
3146
+			}
3147
+		}
3148
+		if (array_key_exists('force_join', $query_params)) {
3149
+			$this->_extract_related_models_from_sub_params_array_values(
3150
+				$query_params['force_join'],
3151
+				$query_info_carrier,
3152
+				'force_join'
3153
+			);
3154
+		}
3155
+		return $query_info_carrier;
3156
+	}
3157
+
3158
+
3159
+
3160
+	/**
3161
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3162
+	 *
3163
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3164
+	 *                                                      $query_params['having']
3165
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3166
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3167
+	 * @throws EE_Error
3168
+	 * @return \EE_Model_Query_Info_Carrier
3169
+	 */
3170
+	private function _extract_related_models_from_sub_params_array_keys(
3171
+		$sub_query_params,
3172
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3173
+		$query_param_type
3174
+	) {
3175
+		if (! empty($sub_query_params)) {
3176
+			$sub_query_params = (array)$sub_query_params;
3177
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3178
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3179
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3180
+					$query_param_type);
3181
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3182
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3183
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3184
+				//of array('Registration.TXN_ID'=>23)
3185
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3186
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3187
+					if (! is_array($possibly_array_of_params)) {
3188
+						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'))",
3189
+							"event_espresso"),
3190
+							$param, $possibly_array_of_params));
3191
+					}
3192
+					$this->_extract_related_models_from_sub_params_array_keys(
3193
+						$possibly_array_of_params,
3194
+						$model_query_info_carrier, $query_param_type
3195
+					);
3196
+				} elseif ($query_param_type === 0 //ie WHERE
3197
+						  && is_array($possibly_array_of_params)
3198
+						  && isset($possibly_array_of_params[2])
3199
+						  && $possibly_array_of_params[2] == true
3200
+				) {
3201
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3202
+					//indicating that $possible_array_of_params[1] is actually a field name,
3203
+					//from which we should extract query parameters!
3204
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3205
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3206
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3207
+					}
3208
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3209
+						$model_query_info_carrier, $query_param_type);
3210
+				}
3211
+			}
3212
+		}
3213
+		return $model_query_info_carrier;
3214
+	}
3215
+
3216
+
3217
+
3218
+	/**
3219
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3220
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3221
+	 *
3222
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3223
+	 *                                                      $query_params['having']
3224
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3225
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3226
+	 * @throws EE_Error
3227
+	 * @return \EE_Model_Query_Info_Carrier
3228
+	 */
3229
+	private function _extract_related_models_from_sub_params_array_values(
3230
+		$sub_query_params,
3231
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3232
+		$query_param_type
3233
+	) {
3234
+		if (! empty($sub_query_params)) {
3235
+			if (! is_array($sub_query_params)) {
3236
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3237
+					$sub_query_params));
3238
+			}
3239
+			foreach ($sub_query_params as $param) {
3240
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3241
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3242
+					$query_param_type);
3243
+			}
3244
+		}
3245
+		return $model_query_info_carrier;
3246
+	}
3247
+
3248
+
3249
+
3250
+	/**
3251
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3252
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3253
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3254
+	 * but use them in a different order. Eg, we need to know what models we are querying
3255
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3256
+	 * other models before we can finalize the where clause SQL.
3257
+	 *
3258
+	 * @param array $query_params
3259
+	 * @throws EE_Error
3260
+	 * @return EE_Model_Query_Info_Carrier
3261
+	 */
3262
+	public function _create_model_query_info_carrier($query_params)
3263
+	{
3264
+		if (! is_array($query_params)) {
3265
+			EE_Error::doing_it_wrong(
3266
+				'EEM_Base::_create_model_query_info_carrier',
3267
+				sprintf(
3268
+					__(
3269
+						'$query_params should be an array, you passed a variable of type %s',
3270
+						'event_espresso'
3271
+					),
3272
+					gettype($query_params)
3273
+				),
3274
+				'4.6.0'
3275
+			);
3276
+			$query_params = array();
3277
+		}
3278
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3279
+		//first check if we should alter the query to account for caps or not
3280
+		//because the caps might require us to do extra joins
3281
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3282
+			$query_params[0] = $where_query_params = array_replace_recursive(
3283
+				$where_query_params,
3284
+				$this->caps_where_conditions(
3285
+					$query_params['caps']
3286
+				)
3287
+			);
3288
+		}
3289
+		$query_object = $this->_extract_related_models_from_query($query_params);
3290
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3291
+		foreach ($where_query_params as $key => $value) {
3292
+			if (is_int($key)) {
3293
+				throw new EE_Error(
3294
+					sprintf(
3295
+						__(
3296
+							"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.",
3297
+							"event_espresso"
3298
+						),
3299
+						$key,
3300
+						var_export($value, true),
3301
+						var_export($query_params, true),
3302
+						get_class($this)
3303
+					)
3304
+				);
3305
+			}
3306
+		}
3307
+		if (
3308
+			array_key_exists('default_where_conditions', $query_params)
3309
+			&& ! empty($query_params['default_where_conditions'])
3310
+		) {
3311
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3312
+		} else {
3313
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3314
+		}
3315
+		$where_query_params = array_merge(
3316
+			$this->_get_default_where_conditions_for_models_in_query(
3317
+				$query_object,
3318
+				$use_default_where_conditions,
3319
+				$where_query_params
3320
+			),
3321
+			$where_query_params
3322
+		);
3323
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3324
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3325
+		// So we need to setup a subquery and use that for the main join.
3326
+		// Note for now this only works on the primary table for the model.
3327
+		// So for instance, you could set the limit array like this:
3328
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3329
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3330
+			$query_object->set_main_model_join_sql(
3331
+				$this->_construct_limit_join_select(
3332
+					$query_params['on_join_limit'][0],
3333
+					$query_params['on_join_limit'][1]
3334
+				)
3335
+			);
3336
+		}
3337
+		//set limit
3338
+		if (array_key_exists('limit', $query_params)) {
3339
+			if (is_array($query_params['limit'])) {
3340
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3341
+					$e = sprintf(
3342
+						__(
3343
+							"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)",
3344
+							"event_espresso"
3345
+						),
3346
+						http_build_query($query_params['limit'])
3347
+					);
3348
+					throw new EE_Error($e . "|" . $e);
3349
+				}
3350
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3351
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3352
+			} elseif (! empty ($query_params['limit'])) {
3353
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3354
+			}
3355
+		}
3356
+		//set order by
3357
+		if (array_key_exists('order_by', $query_params)) {
3358
+			if (is_array($query_params['order_by'])) {
3359
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3360
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3361
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3362
+				if (array_key_exists('order', $query_params)) {
3363
+					throw new EE_Error(
3364
+						sprintf(
3365
+							__(
3366
+								"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 ",
3367
+								"event_espresso"
3368
+							),
3369
+							get_class($this),
3370
+							implode(", ", array_keys($query_params['order_by'])),
3371
+							implode(", ", $query_params['order_by']),
3372
+							$query_params['order']
3373
+						)
3374
+					);
3375
+				}
3376
+				$this->_extract_related_models_from_sub_params_array_keys(
3377
+					$query_params['order_by'],
3378
+					$query_object,
3379
+					'order_by'
3380
+				);
3381
+				//assume it's an array of fields to order by
3382
+				$order_array = array();
3383
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3384
+					$order = $this->_extract_order($order);
3385
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3386
+				}
3387
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3388
+			} elseif (! empty ($query_params['order_by'])) {
3389
+				$this->_extract_related_model_info_from_query_param(
3390
+					$query_params['order_by'],
3391
+					$query_object,
3392
+					'order',
3393
+					$query_params['order_by']
3394
+				);
3395
+				$order = isset($query_params['order'])
3396
+					? $this->_extract_order($query_params['order'])
3397
+					: 'DESC';
3398
+				$query_object->set_order_by_sql(
3399
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3400
+				);
3401
+			}
3402
+		}
3403
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3404
+		if (! array_key_exists('order_by', $query_params)
3405
+			&& array_key_exists('order', $query_params)
3406
+			&& ! empty($query_params['order'])
3407
+		) {
3408
+			$pk_field = $this->get_primary_key_field();
3409
+			$order = $this->_extract_order($query_params['order']);
3410
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3411
+		}
3412
+		//set group by
3413
+		if (array_key_exists('group_by', $query_params)) {
3414
+			if (is_array($query_params['group_by'])) {
3415
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3416
+				$group_by_array = array();
3417
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3418
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3419
+				}
3420
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3421
+			} elseif (! empty ($query_params['group_by'])) {
3422
+				$query_object->set_group_by_sql(
3423
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3424
+				);
3425
+			}
3426
+		}
3427
+		//set having
3428
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3429
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3430
+		}
3431
+		//now, just verify they didn't pass anything wack
3432
+		foreach ($query_params as $query_key => $query_value) {
3433
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3434
+				throw new EE_Error(
3435
+					sprintf(
3436
+						__(
3437
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3438
+							'event_espresso'
3439
+						),
3440
+						$query_key,
3441
+						get_class($this),
3442
+						//						print_r( $this->_allowed_query_params, TRUE )
3443
+						implode(',', $this->_allowed_query_params)
3444
+					)
3445
+				);
3446
+			}
3447
+		}
3448
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3449
+		if (empty($main_model_join_sql)) {
3450
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3451
+		}
3452
+		return $query_object;
3453
+	}
3454
+
3455
+
3456
+
3457
+	/**
3458
+	 * Gets the where conditions that should be imposed on the query based on the
3459
+	 * context (eg reading frontend, backend, edit or delete).
3460
+	 *
3461
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3462
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3463
+	 * @throws EE_Error
3464
+	 */
3465
+	public function caps_where_conditions($context = self::caps_read)
3466
+	{
3467
+		EEM_Base::verify_is_valid_cap_context($context);
3468
+		$cap_where_conditions = array();
3469
+		$cap_restrictions = $this->caps_missing($context);
3470
+		/**
3471
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3472
+		 */
3473
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3474
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3475
+				$restriction_if_no_cap->get_default_where_conditions());
3476
+		}
3477
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3478
+			$cap_restrictions);
3479
+	}
3480
+
3481
+
3482
+
3483
+	/**
3484
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3485
+	 * otherwise throws an exception
3486
+	 *
3487
+	 * @param string $should_be_order_string
3488
+	 * @return string either ASC, asc, DESC or desc
3489
+	 * @throws EE_Error
3490
+	 */
3491
+	private function _extract_order($should_be_order_string)
3492
+	{
3493
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3494
+			return $should_be_order_string;
3495
+		}
3496
+		throw new EE_Error(
3497
+			sprintf(
3498
+				__(
3499
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3500
+					"event_espresso"
3501
+				), get_class($this), $should_be_order_string
3502
+			)
3503
+		);
3504
+	}
3505
+
3506
+
3507
+
3508
+	/**
3509
+	 * Looks at all the models which are included in this query, and asks each
3510
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3511
+	 * so they can be merged
3512
+	 *
3513
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3514
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3515
+	 *                                                                  'none' means NO default where conditions will
3516
+	 *                                                                  be used AT ALL during this query.
3517
+	 *                                                                  'other_models_only' means default where
3518
+	 *                                                                  conditions from other models will be used, but
3519
+	 *                                                                  not for this primary model. 'all', the default,
3520
+	 *                                                                  means default where conditions will apply as
3521
+	 *                                                                  normal
3522
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3523
+	 * @throws EE_Error
3524
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3525
+	 */
3526
+	private function _get_default_where_conditions_for_models_in_query(
3527
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3528
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3529
+		$where_query_params = array()
3530
+	) {
3531
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3532
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3533
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3534
+				"event_espresso"), $use_default_where_conditions,
3535
+				implode(", ", $allowed_used_default_where_conditions_values)));
3536
+		}
3537
+		$universal_query_params = array();
3538
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3539
+			$universal_query_params = $this->_get_default_where_conditions();
3540
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3541
+			$universal_query_params = $this->_get_minimum_where_conditions();
3542
+		}
3543
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3544
+			$related_model = $this->get_related_model_obj($model_name);
3545
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3546
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3547
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3548
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3549
+			} else {
3550
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3551
+				continue;
3552
+			}
3553
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3554
+				$related_model_universal_where_params,
3555
+				$where_query_params,
3556
+				$related_model,
3557
+				$model_relation_path
3558
+			);
3559
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3560
+				$universal_query_params,
3561
+				$overrides
3562
+			);
3563
+		}
3564
+		return $universal_query_params;
3565
+	}
3566
+
3567
+
3568
+
3569
+	/**
3570
+	 * Determines whether or not we should use default where conditions for the model in question
3571
+	 * (this model, or other related models).
3572
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3573
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3574
+	 * We should use default where conditions on related models when they requested to use default where conditions
3575
+	 * on all models, or specifically just on other related models
3576
+	 * @param      $default_where_conditions_value
3577
+	 * @param bool $for_this_model false means this is for OTHER related models
3578
+	 * @return bool
3579
+	 */
3580
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3581
+	{
3582
+		return (
3583
+				   $for_this_model
3584
+				   && in_array(
3585
+					   $default_where_conditions_value,
3586
+					   array(
3587
+						   EEM_Base::default_where_conditions_all,
3588
+						   EEM_Base::default_where_conditions_this_only,
3589
+						   EEM_Base::default_where_conditions_minimum_others,
3590
+					   ),
3591
+					   true
3592
+				   )
3593
+			   )
3594
+			   || (
3595
+				   ! $for_this_model
3596
+				   && in_array(
3597
+					   $default_where_conditions_value,
3598
+					   array(
3599
+						   EEM_Base::default_where_conditions_all,
3600
+						   EEM_Base::default_where_conditions_others_only,
3601
+					   ),
3602
+					   true
3603
+				   )
3604
+			   );
3605
+	}
3606
+
3607
+	/**
3608
+	 * Determines whether or not we should use default minimum conditions for the model in question
3609
+	 * (this model, or other related models).
3610
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3611
+	 * where conditions.
3612
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3613
+	 * on this model or others
3614
+	 * @param      $default_where_conditions_value
3615
+	 * @param bool $for_this_model false means this is for OTHER related models
3616
+	 * @return bool
3617
+	 */
3618
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3619
+	{
3620
+		return (
3621
+				   $for_this_model
3622
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3623
+			   )
3624
+			   || (
3625
+				   ! $for_this_model
3626
+				   && in_array(
3627
+					   $default_where_conditions_value,
3628
+					   array(
3629
+						   EEM_Base::default_where_conditions_minimum_others,
3630
+						   EEM_Base::default_where_conditions_minimum_all,
3631
+					   ),
3632
+					   true
3633
+				   )
3634
+			   );
3635
+	}
3636
+
3637
+
3638
+	/**
3639
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3640
+	 * then we also add a special where condition which allows for that model's primary key
3641
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3642
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3643
+	 *
3644
+	 * @param array    $default_where_conditions
3645
+	 * @param array    $provided_where_conditions
3646
+	 * @param EEM_Base $model
3647
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3648
+	 * @return array like EEM_Base::get_all's $query_params[0]
3649
+	 * @throws EE_Error
3650
+	 */
3651
+	private function _override_defaults_or_make_null_friendly(
3652
+		$default_where_conditions,
3653
+		$provided_where_conditions,
3654
+		$model,
3655
+		$model_relation_path
3656
+	) {
3657
+		$null_friendly_where_conditions = array();
3658
+		$none_overridden = true;
3659
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3660
+		foreach ($default_where_conditions as $key => $val) {
3661
+			if (isset($provided_where_conditions[$key])) {
3662
+				$none_overridden = false;
3663
+			} else {
3664
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3665
+			}
3666
+		}
3667
+		if ($none_overridden && $default_where_conditions) {
3668
+			if ($model->has_primary_key_field()) {
3669
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3670
+																				. "."
3671
+																				. $model->primary_key_name()] = array('IS NULL');
3672
+			}/*else{
3673 3673
 				//@todo NO PK, use other defaults
3674 3674
 			}*/
3675
-        }
3676
-        return $null_friendly_where_conditions;
3677
-    }
3678
-
3679
-
3680
-
3681
-    /**
3682
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3683
-     * default where conditions on all get_all, update, and delete queries done by this model.
3684
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3685
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3686
-     *
3687
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3688
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3689
-     */
3690
-    private function _get_default_where_conditions($model_relation_path = null)
3691
-    {
3692
-        if ($this->_ignore_where_strategy) {
3693
-            return array();
3694
-        }
3695
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3696
-    }
3697
-
3698
-
3699
-
3700
-    /**
3701
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3702
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3703
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3704
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3705
-     * Similar to _get_default_where_conditions
3706
-     *
3707
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3708
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3709
-     */
3710
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3711
-    {
3712
-        if ($this->_ignore_where_strategy) {
3713
-            return array();
3714
-        }
3715
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3716
-    }
3717
-
3718
-
3719
-
3720
-    /**
3721
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3722
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3723
-     *
3724
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3725
-     * @return string
3726
-     * @throws EE_Error
3727
-     */
3728
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3729
-    {
3730
-        $selects = $this->_get_columns_to_select_for_this_model();
3731
-        foreach (
3732
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3733
-            $name_of_other_model_included
3734
-        ) {
3735
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3736
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3737
-            foreach ($other_model_selects as $key => $value) {
3738
-                $selects[] = $value;
3739
-            }
3740
-        }
3741
-        return implode(", ", $selects);
3742
-    }
3743
-
3744
-
3745
-
3746
-    /**
3747
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3748
-     * So that's going to be the columns for all the fields on the model
3749
-     *
3750
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3751
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3752
-     */
3753
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3754
-    {
3755
-        $fields = $this->field_settings();
3756
-        $selects = array();
3757
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3758
-            $this->get_this_model_name());
3759
-        foreach ($fields as $field_obj) {
3760
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3761
-                         . $field_obj->get_table_alias()
3762
-                         . "."
3763
-                         . $field_obj->get_table_column()
3764
-                         . " AS '"
3765
-                         . $table_alias_with_model_relation_chain_prefix
3766
-                         . $field_obj->get_table_alias()
3767
-                         . "."
3768
-                         . $field_obj->get_table_column()
3769
-                         . "'";
3770
-        }
3771
-        //make sure we are also getting the PKs of each table
3772
-        $tables = $this->get_tables();
3773
-        if (count($tables) > 1) {
3774
-            foreach ($tables as $table_obj) {
3775
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3776
-                                       . $table_obj->get_fully_qualified_pk_column();
3777
-                if (! in_array($qualified_pk_column, $selects)) {
3778
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3779
-                }
3780
-            }
3781
-        }
3782
-        return $selects;
3783
-    }
3784
-
3785
-
3786
-
3787
-    /**
3788
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3789
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3790
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3791
-     * SQL for joining, and the data types
3792
-     *
3793
-     * @param null|string                 $original_query_param
3794
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3795
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3796
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3797
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3798
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3799
-     *                                                          or 'Registration's
3800
-     * @param string                      $original_query_param what it originally was (eg
3801
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3802
-     *                                                          matches $query_param
3803
-     * @throws EE_Error
3804
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3805
-     */
3806
-    private function _extract_related_model_info_from_query_param(
3807
-        $query_param,
3808
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3809
-        $query_param_type,
3810
-        $original_query_param = null
3811
-    ) {
3812
-        if ($original_query_param === null) {
3813
-            $original_query_param = $query_param;
3814
-        }
3815
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3816
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3817
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3818
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3819
-        //check to see if we have a field on this model
3820
-        $this_model_fields = $this->field_settings(true);
3821
-        if (array_key_exists($query_param, $this_model_fields)) {
3822
-            if ($allow_fields) {
3823
-                return;
3824
-            }
3825
-            throw new EE_Error(
3826
-                sprintf(
3827
-                    __(
3828
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3829
-                        "event_espresso"
3830
-                    ),
3831
-                    $query_param, get_class($this), $query_param_type, $original_query_param
3832
-                )
3833
-            );
3834
-        }
3835
-        //check if this is a special logic query param
3836
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3837
-            if ($allow_logic_query_params) {
3838
-                return;
3839
-            }
3840
-            throw new EE_Error(
3841
-                sprintf(
3842
-                    __(
3843
-                        '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',
3844
-                        'event_espresso'
3845
-                    ),
3846
-                    implode('", "', $this->_logic_query_param_keys),
3847
-                    $query_param,
3848
-                    get_class($this),
3849
-                    '<br />',
3850
-                    "\t"
3851
-                    . ' $passed_in_query_info = <pre>'
3852
-                    . print_r($passed_in_query_info, true)
3853
-                    . '</pre>'
3854
-                    . "\n\t"
3855
-                    . ' $query_param_type = '
3856
-                    . $query_param_type
3857
-                    . "\n\t"
3858
-                    . ' $original_query_param = '
3859
-                    . $original_query_param
3860
-                )
3861
-            );
3862
-        }
3863
-        //check if it's a custom selection
3864
-        if (array_key_exists($query_param, $this->_custom_selections)) {
3865
-            return;
3866
-        }
3867
-        //check if has a model name at the beginning
3868
-        //and
3869
-        //check if it's a field on a related model
3870
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3871
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3872
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3873
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3874
-                if ($query_param === '') {
3875
-                    //nothing left to $query_param
3876
-                    //we should actually end in a field name, not a model like this!
3877
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3878
-                        "event_espresso"),
3879
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3880
-                }
3881
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3882
-                $related_model_obj->_extract_related_model_info_from_query_param(
3883
-                    $query_param,
3884
-                    $passed_in_query_info, $query_param_type, $original_query_param
3885
-                );
3886
-                return;
3887
-            }
3888
-            if ($query_param === $valid_related_model_name) {
3889
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3890
-                return;
3891
-            }
3892
-        }
3893
-        //ok so $query_param didn't start with a model name
3894
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3895
-        //it's wack, that's what it is
3896
-        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",
3897
-            "event_espresso"),
3898
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3899
-    }
3900
-
3901
-
3902
-
3903
-    /**
3904
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3905
-     * and store it on $passed_in_query_info
3906
-     *
3907
-     * @param string                      $model_name
3908
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3909
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3910
-     *                                                          model and $model_name. Eg, if we are querying Event,
3911
-     *                                                          and are adding a join to 'Payment' with the original
3912
-     *                                                          query param key
3913
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3914
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3915
-     *                                                          Payment wants to add default query params so that it
3916
-     *                                                          will know what models to prepend onto its default query
3917
-     *                                                          params or in case it wants to rename tables (in case
3918
-     *                                                          there are multiple joins to the same table)
3919
-     * @return void
3920
-     * @throws EE_Error
3921
-     */
3922
-    private function _add_join_to_model(
3923
-        $model_name,
3924
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3925
-        $original_query_param
3926
-    ) {
3927
-        $relation_obj = $this->related_settings_for($model_name);
3928
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3929
-        //check if the relation is HABTM, because then we're essentially doing two joins
3930
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3931
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3932
-            $join_model_obj = $relation_obj->get_join_model();
3933
-            //replace the model specified with the join model for this relation chain, whi
3934
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3935
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3936
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3937
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3938
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3939
-            $passed_in_query_info->merge($new_query_info);
3940
-        }
3941
-        //now just join to the other table pointed to by the relation object, and add its data types
3942
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3943
-            array($model_relation_chain => $model_name),
3944
-            $relation_obj->get_join_statement($model_relation_chain));
3945
-        $passed_in_query_info->merge($new_query_info);
3946
-    }
3947
-
3948
-
3949
-
3950
-    /**
3951
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3952
-     *
3953
-     * @param array $where_params like EEM_Base::get_all
3954
-     * @return string of SQL
3955
-     * @throws EE_Error
3956
-     */
3957
-    private function _construct_where_clause($where_params)
3958
-    {
3959
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3960
-        if ($SQL) {
3961
-            return " WHERE " . $SQL;
3962
-        }
3963
-        return '';
3964
-    }
3965
-
3966
-
3967
-
3968
-    /**
3969
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3970
-     * and should be passed HAVING parameters, not WHERE parameters
3971
-     *
3972
-     * @param array $having_params
3973
-     * @return string
3974
-     * @throws EE_Error
3975
-     */
3976
-    private function _construct_having_clause($having_params)
3977
-    {
3978
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3979
-        if ($SQL) {
3980
-            return " HAVING " . $SQL;
3981
-        }
3982
-        return '';
3983
-    }
3984
-
3985
-
3986
-
3987
-    /**
3988
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3989
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3990
-     * EEM_Attendee.
3991
-     *
3992
-     * @param string $field_name
3993
-     * @param string $model_name
3994
-     * @return EE_Model_Field_Base
3995
-     * @throws EE_Error
3996
-     */
3997
-    protected function _get_field_on_model($field_name, $model_name)
3998
-    {
3999
-        $model_class = 'EEM_' . $model_name;
4000
-        $model_filepath = $model_class . ".model.php";
4001
-        if (is_readable($model_filepath)) {
4002
-            require_once($model_filepath);
4003
-            $model_instance = call_user_func($model_name . "::instance");
4004
-            /* @var $model_instance EEM_Base */
4005
-            return $model_instance->field_settings_for($field_name);
4006
-        }
4007
-        throw new EE_Error(
4008
-            sprintf(
4009
-                __(
4010
-                    'No model named %s exists, with classname %s and filepath %s',
4011
-                    'event_espresso'
4012
-                ), $model_name, $model_class, $model_filepath
4013
-            )
4014
-        );
4015
-    }
4016
-
4017
-
4018
-
4019
-    /**
4020
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4021
-     * Event_Meta.meta_value = 'foo'))"
4022
-     *
4023
-     * @param array  $where_params see EEM_Base::get_all for documentation
4024
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4025
-     * @throws EE_Error
4026
-     * @return string of SQL
4027
-     */
4028
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4029
-    {
4030
-        $where_clauses = array();
4031
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4032
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4033
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4034
-                switch ($query_param) {
4035
-                    case 'not':
4036
-                    case 'NOT':
4037
-                        $where_clauses[] = "! ("
4038
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4039
-                                $glue)
4040
-                                           . ")";
4041
-                        break;
4042
-                    case 'and':
4043
-                    case 'AND':
4044
-                        $where_clauses[] = " ("
4045
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4046
-                                ' AND ')
4047
-                                           . ")";
4048
-                        break;
4049
-                    case 'or':
4050
-                    case 'OR':
4051
-                        $where_clauses[] = " ("
4052
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4053
-                                ' OR ')
4054
-                                           . ")";
4055
-                        break;
4056
-                }
4057
-            } else {
4058
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4059
-                //if it's not a normal field, maybe it's a custom selection?
4060
-                if (! $field_obj) {
4061
-                    if (isset($this->_custom_selections[$query_param][1])) {
4062
-                        $field_obj = $this->_custom_selections[$query_param][1];
4063
-                    } else {
4064
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4065
-                            "event_espresso"), $query_param));
4066
-                    }
4067
-                }
4068
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4069
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4070
-            }
4071
-        }
4072
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4073
-    }
4074
-
4075
-
4076
-
4077
-    /**
4078
-     * Takes the input parameter and extract the table name (alias) and column name
4079
-     *
4080
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4081
-     * @throws EE_Error
4082
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4083
-     */
4084
-    private function _deduce_column_name_from_query_param($query_param)
4085
-    {
4086
-        $field = $this->_deduce_field_from_query_param($query_param);
4087
-        if ($field) {
4088
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4089
-                $query_param);
4090
-            return $table_alias_prefix . $field->get_qualified_column();
4091
-        }
4092
-        if (array_key_exists($query_param, $this->_custom_selections)) {
4093
-            //maybe it's custom selection item?
4094
-            //if so, just use it as the "column name"
4095
-            return $query_param;
4096
-        }
4097
-        throw new EE_Error(
4098
-            sprintf(
4099
-                __(
4100
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4101
-                    "event_espresso"
4102
-                ), $query_param, implode(",", $this->_custom_selections)
4103
-            )
4104
-        );
4105
-    }
4106
-
4107
-
4108
-
4109
-    /**
4110
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4111
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4112
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4113
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4114
-     *
4115
-     * @param string $condition_query_param_key
4116
-     * @return string
4117
-     */
4118
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4119
-    {
4120
-        $pos_of_star = strpos($condition_query_param_key, '*');
4121
-        if ($pos_of_star === false) {
4122
-            return $condition_query_param_key;
4123
-        }
4124
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4125
-        return $condition_query_param_sans_star;
4126
-    }
4127
-
4128
-
4129
-
4130
-    /**
4131
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4132
-     *
4133
-     * @param                            mixed      array | string    $op_and_value
4134
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4135
-     * @throws EE_Error
4136
-     * @return string
4137
-     */
4138
-    private function _construct_op_and_value($op_and_value, $field_obj)
4139
-    {
4140
-        if (is_array($op_and_value)) {
4141
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4142
-            if (! $operator) {
4143
-                $php_array_like_string = array();
4144
-                foreach ($op_and_value as $key => $value) {
4145
-                    $php_array_like_string[] = "$key=>$value";
4146
-                }
4147
-                throw new EE_Error(
4148
-                    sprintf(
4149
-                        __(
4150
-                            "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))",
4151
-                            "event_espresso"
4152
-                        ),
4153
-                        implode(",", $php_array_like_string)
4154
-                    )
4155
-                );
4156
-            }
4157
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4158
-        } else {
4159
-            $operator = '=';
4160
-            $value = $op_and_value;
4161
-        }
4162
-        //check to see if the value is actually another field
4163
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4164
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4165
-        }
4166
-        if (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4167
-            //in this case, the value should be an array, or at least a comma-separated list
4168
-            //it will need to handle a little differently
4169
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4170
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4171
-            return $operator . SP . $cleaned_value;
4172
-        }
4173
-        if (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4174
-            //the value should be an array with count of two.
4175
-            if (count($value) !== 2) {
4176
-                throw new EE_Error(
4177
-                    sprintf(
4178
-                        __(
4179
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4180
-                            'event_espresso'
4181
-                        ),
4182
-                        "BETWEEN"
4183
-                    )
4184
-                );
4185
-            }
4186
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4187
-            return $operator . SP . $cleaned_value;
4188
-        }
4189
-        if (in_array($operator, $this->_null_style_operators)) {
4190
-            if ($value !== null) {
4191
-                throw new EE_Error(
4192
-                    sprintf(
4193
-                        __(
4194
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4195
-                            "event_espresso"
4196
-                        ),
4197
-                        $value,
4198
-                        $operator
4199
-                    )
4200
-                );
4201
-            }
4202
-            return $operator;
4203
-        }
4204
-        if ($operator === 'LIKE' && ! is_array($value)) {
4205
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4206
-            //remove other junk. So just treat it as a string.
4207
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4208
-        }
4209
-        if (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4210
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4211
-        }
4212
-        if (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4213
-            throw new EE_Error(
4214
-                sprintf(
4215
-                    __(
4216
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4217
-                        'event_espresso'
4218
-                    ),
4219
-                    $operator,
4220
-                    $operator
4221
-                )
4222
-            );
4223
-        }
4224
-        if (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4225
-            throw new EE_Error(
4226
-                sprintf(
4227
-                    __(
4228
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4229
-                        'event_espresso'
4230
-                    ),
4231
-                    $operator,
4232
-                    $operator
4233
-                )
4234
-            );
4235
-        }
4236
-        throw new EE_Error(
4237
-            sprintf(
4238
-                __(
4239
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4240
-                    "event_espresso"
4241
-                ),
4242
-                http_build_query($op_and_value)
4243
-            )
4244
-        );
4245
-    }
4246
-
4247
-
4248
-
4249
-    /**
4250
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4251
-     *
4252
-     * @param array                      $values
4253
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4254
-     *                                              '%s'
4255
-     * @return string
4256
-     * @throws EE_Error
4257
-     */
4258
-    public function _construct_between_value($values, $field_obj)
4259
-    {
4260
-        $cleaned_values = array();
4261
-        foreach ($values as $value) {
4262
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4263
-        }
4264
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4265
-    }
4266
-
4267
-
4268
-
4269
-    /**
4270
-     * Takes an array or a comma-separated list of $values and cleans them
4271
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4272
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4273
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4274
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4275
-     *
4276
-     * @param mixed                      $values    array or comma-separated string
4277
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4278
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4279
-     * @throws EE_Error
4280
-     */
4281
-    public function _construct_in_value($values, $field_obj)
4282
-    {
4283
-        //check if the value is a CSV list
4284
-        if (is_string($values)) {
4285
-            //in which case, turn it into an array
4286
-            $values = explode(",", $values);
4287
-        }
4288
-        $cleaned_values = array();
4289
-        foreach ($values as $value) {
4290
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4291
-        }
4292
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4293
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4294
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4295
-        if (empty($cleaned_values)) {
4296
-            $all_fields = $this->field_settings();
4297
-            $a_field = array_shift($all_fields);
4298
-            $main_table = $this->_get_main_table();
4299
-            $cleaned_values[] = "SELECT "
4300
-                                . $a_field->get_table_column()
4301
-                                . " FROM "
4302
-                                . $main_table->get_table_name()
4303
-                                . " WHERE FALSE";
4304
-        }
4305
-        return "(" . implode(",", $cleaned_values) . ")";
4306
-    }
4307
-
4308
-
4309
-
4310
-    /**
4311
-     * @param mixed                      $value
4312
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4313
-     * @throws EE_Error
4314
-     * @return false|null|string
4315
-     */
4316
-    private function _wpdb_prepare_using_field($value, $field_obj)
4317
-    {
4318
-        /** @type WPDB $wpdb */
4319
-        global $wpdb;
4320
-        if ($field_obj instanceof EE_Model_Field_Base) {
4321
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4322
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4323
-        } //$field_obj should really just be a data type
4324
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4325
-            throw new EE_Error(
4326
-                sprintf(
4327
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4328
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4329
-                )
4330
-            );
4331
-        }
4332
-        return $wpdb->prepare($field_obj, $value);
4333
-    }
4334
-
4335
-
4336
-
4337
-    /**
4338
-     * Takes the input parameter and finds the model field that it indicates.
4339
-     *
4340
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4341
-     * @throws EE_Error
4342
-     * @return EE_Model_Field_Base
4343
-     */
4344
-    protected function _deduce_field_from_query_param($query_param_name)
4345
-    {
4346
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4347
-        //which will help us find the database table and column
4348
-        $query_param_parts = explode(".", $query_param_name);
4349
-        if (empty($query_param_parts)) {
4350
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4351
-                'event_espresso'), $query_param_name));
4352
-        }
4353
-        $number_of_parts = count($query_param_parts);
4354
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4355
-        if ($number_of_parts === 1) {
4356
-            $field_name = $last_query_param_part;
4357
-            $model_obj = $this;
4358
-        } else {// $number_of_parts >= 2
4359
-            //the last part is the column name, and there are only 2parts. therefore...
4360
-            $field_name = $last_query_param_part;
4361
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4362
-        }
4363
-        try {
4364
-            return $model_obj->field_settings_for($field_name);
4365
-        } catch (EE_Error $e) {
4366
-            return null;
4367
-        }
4368
-    }
4369
-
4370
-
4371
-
4372
-    /**
4373
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4374
-     * alias and column which corresponds to it
4375
-     *
4376
-     * @param string $field_name
4377
-     * @throws EE_Error
4378
-     * @return string
4379
-     */
4380
-    public function _get_qualified_column_for_field($field_name)
4381
-    {
4382
-        $all_fields = $this->field_settings();
4383
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4384
-        if ($field) {
4385
-            return $field->get_qualified_column();
4386
-        }
4387
-        throw new EE_Error(
4388
-            sprintf(
4389
-                __(
4390
-                    "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.",
4391
-                    'event_espresso'
4392
-                ), $field_name, get_class($this)
4393
-            )
4394
-        );
4395
-    }
4396
-
4397
-
4398
-
4399
-    /**
4400
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4401
-     * Example usage:
4402
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4403
-     *      array(),
4404
-     *      ARRAY_A,
4405
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4406
-     *  );
4407
-     * is equivalent to
4408
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4409
-     * and
4410
-     *  EEM_Event::instance()->get_all_wpdb_results(
4411
-     *      array(
4412
-     *          array(
4413
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4414
-     *          ),
4415
-     *          ARRAY_A,
4416
-     *          implode(
4417
-     *              ', ',
4418
-     *              array_merge(
4419
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4420
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4421
-     *              )
4422
-     *          )
4423
-     *      )
4424
-     *  );
4425
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4426
-     *
4427
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4428
-     *                                            and the one whose fields you are selecting for example: when querying
4429
-     *                                            tickets model and selecting fields from the tickets model you would
4430
-     *                                            leave this parameter empty, because no models are needed to join
4431
-     *                                            between the queried model and the selected one. Likewise when
4432
-     *                                            querying the datetime model and selecting fields from the tickets
4433
-     *                                            model, it would also be left empty, because there is a direct
4434
-     *                                            relation from datetimes to tickets, so no model is needed to join
4435
-     *                                            them together. However, when querying from the event model and
4436
-     *                                            selecting fields from the ticket model, you should provide the string
4437
-     *                                            'Datetime', indicating that the event model must first join to the
4438
-     *                                            datetime model in order to find its relation to ticket model.
4439
-     *                                            Also, when querying from the venue model and selecting fields from
4440
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4441
-     *                                            indicating you need to join the venue model to the event model,
4442
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4443
-     *                                            This string is used to deduce the prefix that gets added onto the
4444
-     *                                            models' tables qualified columns
4445
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4446
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4447
-     *                                            qualified column names
4448
-     * @return array|string
4449
-     */
4450
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4451
-    {
4452
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4453
-        $qualified_columns = array();
4454
-        foreach ($this->field_settings() as $field_name => $field) {
4455
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4456
-        }
4457
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4458
-    }
4459
-
4460
-
4461
-
4462
-    /**
4463
-     * constructs the select use on special limit joins
4464
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4465
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4466
-     * (as that is typically where the limits would be set).
4467
-     *
4468
-     * @param  string       $table_alias The table the select is being built for
4469
-     * @param  mixed|string $limit       The limit for this select
4470
-     * @return string                The final select join element for the query.
4471
-     */
4472
-    public function _construct_limit_join_select($table_alias, $limit)
4473
-    {
4474
-        $SQL = '';
4475
-        foreach ($this->_tables as $table_obj) {
4476
-            if ($table_obj instanceof EE_Primary_Table) {
4477
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4478
-                    ? $table_obj->get_select_join_limit($limit)
4479
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4480
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4481
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4482
-                    ? $table_obj->get_select_join_limit_join($limit)
4483
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4484
-            }
4485
-        }
4486
-        return $SQL;
4487
-    }
4488
-
4489
-
4490
-
4491
-    /**
4492
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4493
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4494
-     *
4495
-     * @return string SQL
4496
-     * @throws EE_Error
4497
-     */
4498
-    public function _construct_internal_join()
4499
-    {
4500
-        $SQL = $this->_get_main_table()->get_table_sql();
4501
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4502
-        return $SQL;
4503
-    }
4504
-
4505
-
4506
-
4507
-    /**
4508
-     * Constructs the SQL for joining all the tables on this model.
4509
-     * Normally $alias should be the primary table's alias, but in cases where
4510
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4511
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4512
-     * alias, this will construct SQL like:
4513
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4514
-     * With $alias being a secondary table's alias, this will construct SQL like:
4515
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4516
-     *
4517
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4518
-     * @return string
4519
-     */
4520
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4521
-    {
4522
-        $SQL = '';
4523
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4524
-        foreach ($this->_tables as $table_obj) {
4525
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4526
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4527
-                    //so we're joining to this table, meaning the table is already in
4528
-                    //the FROM statement, BUT the primary table isn't. So we want
4529
-                    //to add the inverse join sql
4530
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4531
-                } else {
4532
-                    //just add a regular JOIN to this table from the primary table
4533
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4534
-                }
4535
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4536
-        }
4537
-        return $SQL;
4538
-    }
4539
-
4540
-
4541
-
4542
-    /**
4543
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4544
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4545
-     * their data type (eg, '%s', '%d', etc)
4546
-     *
4547
-     * @return array
4548
-     */
4549
-    public function _get_data_types()
4550
-    {
4551
-        $data_types = array();
4552
-        foreach ($this->field_settings() as $field_obj) {
4553
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4554
-            /** @var $field_obj EE_Model_Field_Base */
4555
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4556
-        }
4557
-        return $data_types;
4558
-    }
4559
-
4560
-
4561
-
4562
-    /**
4563
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4564
-     *
4565
-     * @param string $model_name
4566
-     * @throws EE_Error
4567
-     * @return EEM_Base
4568
-     */
4569
-    public function get_related_model_obj($model_name)
4570
-    {
4571
-        $model_classname = "EEM_" . $model_name;
4572
-        if (! class_exists($model_classname)) {
4573
-            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",
4574
-                'event_espresso'), $model_name, $model_classname));
4575
-        }
4576
-        return call_user_func($model_classname . "::instance");
4577
-    }
4578
-
4579
-
4580
-
4581
-    /**
4582
-     * Returns the array of EE_ModelRelations for this model.
4583
-     *
4584
-     * @return EE_Model_Relation_Base[]
4585
-     */
4586
-    public function relation_settings()
4587
-    {
4588
-        return $this->_model_relations;
4589
-    }
4590
-
4591
-
4592
-
4593
-    /**
4594
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4595
-     * because without THOSE models, this model probably doesn't have much purpose.
4596
-     * (Eg, without an event, datetimes have little purpose.)
4597
-     *
4598
-     * @return EE_Belongs_To_Relation[]
4599
-     */
4600
-    public function belongs_to_relations()
4601
-    {
4602
-        $belongs_to_relations = array();
4603
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4604
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4605
-                $belongs_to_relations[$model_name] = $relation_obj;
4606
-            }
4607
-        }
4608
-        return $belongs_to_relations;
4609
-    }
4610
-
4611
-
4612
-
4613
-    /**
4614
-     * Returns the specified EE_Model_Relation, or throws an exception
4615
-     *
4616
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4617
-     * @throws EE_Error
4618
-     * @return EE_Model_Relation_Base
4619
-     */
4620
-    public function related_settings_for($relation_name)
4621
-    {
4622
-        $relatedModels = $this->relation_settings();
4623
-        if (! array_key_exists($relation_name, $relatedModels)) {
4624
-            throw new EE_Error(
4625
-                sprintf(
4626
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4627
-                        'event_espresso'),
4628
-                    $relation_name,
4629
-                    $this->_get_class_name(),
4630
-                    implode(', ', array_keys($relatedModels))
4631
-                )
4632
-            );
4633
-        }
4634
-        return $relatedModels[$relation_name];
4635
-    }
4636
-
4637
-
4638
-
4639
-    /**
4640
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4641
-     * fields
4642
-     *
4643
-     * @param string $fieldName
4644
-     * @throws EE_Error
4645
-     * @return EE_Model_Field_Base
4646
-     */
4647
-    public function field_settings_for($fieldName)
4648
-    {
4649
-        $fieldSettings = $this->field_settings(true);
4650
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4651
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4652
-                get_class($this)));
4653
-        }
4654
-        return $fieldSettings[$fieldName];
4655
-    }
4656
-
4657
-
4658
-
4659
-    /**
4660
-     * Checks if this field exists on this model
4661
-     *
4662
-     * @param string $fieldName a key in the model's _field_settings array
4663
-     * @return boolean
4664
-     */
4665
-    public function has_field($fieldName)
4666
-    {
4667
-        $fieldSettings = $this->field_settings(true);
4668
-        if (isset($fieldSettings[$fieldName])) {
4669
-            return true;
4670
-        }
4671
-        return false;
4672
-    }
4673
-
4674
-
4675
-
4676
-    /**
4677
-     * Returns whether or not this model has a relation to the specified model
4678
-     *
4679
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4680
-     * @return boolean
4681
-     */
4682
-    public function has_relation($relation_name)
4683
-    {
4684
-        $relations = $this->relation_settings();
4685
-        if (isset($relations[$relation_name])) {
4686
-            return true;
4687
-        }
4688
-        return false;
4689
-    }
4690
-
4691
-
4692
-
4693
-    /**
4694
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4695
-     * Eg, on EE_Answer that would be ANS_ID field object
4696
-     *
4697
-     * @param $field_obj
4698
-     * @return boolean
4699
-     */
4700
-    public function is_primary_key_field($field_obj)
4701
-    {
4702
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4703
-    }
4704
-
4705
-
4706
-
4707
-    /**
4708
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4709
-     * Eg, on EE_Answer that would be ANS_ID field object
4710
-     *
4711
-     * @return EE_Model_Field_Base
4712
-     * @throws EE_Error
4713
-     */
4714
-    public function get_primary_key_field()
4715
-    {
4716
-        if ($this->_primary_key_field === null) {
4717
-            foreach ($this->field_settings(true) as $field_obj) {
4718
-                if ($this->is_primary_key_field($field_obj)) {
4719
-                    $this->_primary_key_field = $field_obj;
4720
-                    break;
4721
-                }
4722
-            }
4723
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4724
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4725
-                    get_class($this)));
4726
-            }
4727
-        }
4728
-        return $this->_primary_key_field;
4729
-    }
4730
-
4731
-
4732
-
4733
-    /**
4734
-     * Returns whether or not not there is a primary key on this model.
4735
-     * Internally does some caching.
4736
-     *
4737
-     * @return boolean
4738
-     */
4739
-    public function has_primary_key_field()
4740
-    {
4741
-        if ($this->_has_primary_key_field === null) {
4742
-            try {
4743
-                $this->get_primary_key_field();
4744
-                $this->_has_primary_key_field = true;
4745
-            } catch (EE_Error $e) {
4746
-                $this->_has_primary_key_field = false;
4747
-            }
4748
-        }
4749
-        return $this->_has_primary_key_field;
4750
-    }
4751
-
4752
-
4753
-
4754
-    /**
4755
-     * Finds the first field of type $field_class_name.
4756
-     *
4757
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4758
-     *                                 EE_Foreign_Key_Field, etc
4759
-     * @return EE_Model_Field_Base or null if none is found
4760
-     */
4761
-    public function get_a_field_of_type($field_class_name)
4762
-    {
4763
-        foreach ($this->field_settings() as $field) {
4764
-            if ($field instanceof $field_class_name) {
4765
-                return $field;
4766
-            }
4767
-        }
4768
-        return null;
4769
-    }
4770
-
4771
-
4772
-
4773
-    /**
4774
-     * Gets a foreign key field pointing to model.
4775
-     *
4776
-     * @param string $model_name eg Event, Registration, not EEM_Event
4777
-     * @return EE_Foreign_Key_Field_Base
4778
-     * @throws EE_Error
4779
-     */
4780
-    public function get_foreign_key_to($model_name)
4781
-    {
4782
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4783
-            foreach ($this->field_settings() as $field) {
4784
-                if (
4785
-                    $field instanceof EE_Foreign_Key_Field_Base
4786
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4787
-                ) {
4788
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4789
-                    break;
4790
-                }
4791
-            }
4792
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4793
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4794
-                    'event_espresso'), $model_name, get_class($this)));
4795
-            }
4796
-        }
4797
-        return $this->_cache_foreign_key_to_fields[$model_name];
4798
-    }
4799
-
4800
-
4801
-
4802
-    /**
4803
-     * Gets the actual table for the table alias
4804
-     *
4805
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4806
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4807
-     *                            Either one works
4808
-     * @return EE_Table_Base
4809
-     */
4810
-    public function get_table_for_alias($table_alias)
4811
-    {
4812
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4813
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4814
-    }
4815
-
4816
-
4817
-
4818
-    /**
4819
-     * Returns a flat array of all field son this model, instead of organizing them
4820
-     * by table_alias as they are in the constructor.
4821
-     *
4822
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4823
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4824
-     */
4825
-    public function field_settings($include_db_only_fields = false)
4826
-    {
4827
-        if ($include_db_only_fields) {
4828
-            if ($this->_cached_fields === null) {
4829
-                $this->_cached_fields = array();
4830
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4831
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4832
-                        $this->_cached_fields[$field_name] = $field_obj;
4833
-                    }
4834
-                }
4835
-            }
4836
-            return $this->_cached_fields;
4837
-        }
4838
-        if ($this->_cached_fields_non_db_only === null) {
4839
-            $this->_cached_fields_non_db_only = array();
4840
-            foreach ($this->_fields as $fields_corresponding_to_table) {
4841
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4842
-                    /** @var $field_obj EE_Model_Field_Base */
4843
-                    if (! $field_obj->is_db_only_field()) {
4844
-                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4845
-                    }
4846
-                }
4847
-            }
4848
-        }
4849
-        return $this->_cached_fields_non_db_only;
4850
-    }
4851
-
4852
-
4853
-
4854
-    /**
4855
-     *        cycle though array of attendees and create objects out of each item
4856
-     *
4857
-     * @access        private
4858
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4859
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4860
-     *                           numerically indexed)
4861
-     * @throws EE_Error
4862
-     */
4863
-    protected function _create_objects($rows = array())
4864
-    {
4865
-        $array_of_objects = array();
4866
-        if (empty($rows)) {
4867
-            return array();
4868
-        }
4869
-        $count_if_model_has_no_primary_key = 0;
4870
-        $has_primary_key = $this->has_primary_key_field();
4871
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4872
-        foreach ((array)$rows as $row) {
4873
-            if (empty($row)) {
4874
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4875
-                return array();
4876
-            }
4877
-            //check if we've already set this object in the results array,
4878
-            //in which case there's no need to process it further (again)
4879
-            if ($has_primary_key) {
4880
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4881
-                    $row,
4882
-                    $primary_key_field->get_qualified_column(),
4883
-                    $primary_key_field->get_table_column()
4884
-                );
4885
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4886
-                    continue;
4887
-                }
4888
-            }
4889
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4890
-            if (! $classInstance) {
4891
-                throw new EE_Error(
4892
-                    sprintf(
4893
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4894
-                        $this->get_this_model_name(),
4895
-                        http_build_query($row)
4896
-                    )
4897
-                );
4898
-            }
4899
-            //set the timezone on the instantiated objects
4900
-            $classInstance->set_timezone($this->_timezone);
4901
-            //make sure if there is any timezone setting present that we set the timezone for the object
4902
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4903
-            $array_of_objects[$key] = $classInstance;
4904
-            //also, for all the relations of type BelongsTo, see if we can cache
4905
-            //those related models
4906
-            //(we could do this for other relations too, but if there are conditions
4907
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4908
-            //so it requires a little more thought than just caching them immediately...)
4909
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4910
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4911
-                    //check if this model's INFO is present. If so, cache it on the model
4912
-                    $other_model = $relation_obj->get_other_model();
4913
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4914
-                    //if we managed to make a model object from the results, cache it on the main model object
4915
-                    if ($other_model_obj_maybe) {
4916
-                        //set timezone on these other model objects if they are present
4917
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4918
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4919
-                    }
4920
-                }
4921
-            }
4922
-        }
4923
-        return $array_of_objects;
4924
-    }
4925
-
4926
-
4927
-
4928
-    /**
4929
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4930
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4931
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4932
-     * object (as set in the model_field!).
4933
-     *
4934
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4935
-     */
4936
-    public function create_default_object()
4937
-    {
4938
-        $this_model_fields_and_values = array();
4939
-        //setup the row using default values;
4940
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4941
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4942
-        }
4943
-        $className = $this->_get_class_name();
4944
-        $classInstance = EE_Registry::instance()
4945
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4946
-        return $classInstance;
4947
-    }
4948
-
4949
-
4950
-
4951
-    /**
4952
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4953
-     *                             or an stdClass where each property is the name of a column,
4954
-     * @return EE_Base_Class
4955
-     * @throws EE_Error
4956
-     */
4957
-    public function instantiate_class_from_array_or_object($cols_n_values)
4958
-    {
4959
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4960
-            $cols_n_values = get_object_vars($cols_n_values);
4961
-        }
4962
-        $primary_key = null;
4963
-        //make sure the array only has keys that are fields/columns on this model
4964
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4965
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4966
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4967
-        }
4968
-        $className = $this->_get_class_name();
4969
-        //check we actually found results that we can use to build our model object
4970
-        //if not, return null
4971
-        if ($this->has_primary_key_field()) {
4972
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4973
-                return null;
4974
-            }
4975
-        } else if ($this->unique_indexes()) {
4976
-            $first_column = reset($this_model_fields_n_values);
4977
-            if (empty($first_column)) {
4978
-                return null;
4979
-            }
4980
-        }
4981
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4982
-        if ($primary_key) {
4983
-            $classInstance = $this->get_from_entity_map($primary_key);
4984
-            if (! $classInstance) {
4985
-                $classInstance = EE_Registry::instance()
4986
-                                            ->load_class($className,
4987
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4988
-                // add this new object to the entity map
4989
-                $classInstance = $this->add_to_entity_map($classInstance);
4990
-            }
4991
-        } else {
4992
-            $classInstance = EE_Registry::instance()
4993
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4994
-                                            true, false);
4995
-        }
4996
-        //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.
4997
-        $this->set_timezone($classInstance->get_timezone());
4998
-        return $classInstance;
4999
-    }
5000
-
5001
-
5002
-
5003
-    /**
5004
-     * Gets the model object from the  entity map if it exists
5005
-     *
5006
-     * @param int|string $id the ID of the model object
5007
-     * @return EE_Base_Class
5008
-     */
5009
-    public function get_from_entity_map($id)
5010
-    {
5011
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5012
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5013
-    }
5014
-
5015
-
5016
-
5017
-    /**
5018
-     * add_to_entity_map
5019
-     * Adds the object to the model's entity mappings
5020
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5021
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5022
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5023
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5024
-     *        then this method should be called immediately after the update query
5025
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5026
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5027
-     *
5028
-     * @param    EE_Base_Class $object
5029
-     * @throws EE_Error
5030
-     * @return \EE_Base_Class
5031
-     */
5032
-    public function add_to_entity_map(EE_Base_Class $object)
5033
-    {
5034
-        $className = $this->_get_class_name();
5035
-        if (! $object instanceof $className) {
5036
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5037
-                is_object($object) ? get_class($object) : $object, $className));
5038
-        }
5039
-        /** @var $object EE_Base_Class */
5040
-        if (! $object->ID()) {
5041
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5042
-                "event_espresso"), get_class($this)));
5043
-        }
5044
-        // double check it's not already there
5045
-        $classInstance = $this->get_from_entity_map($object->ID());
5046
-        if ($classInstance) {
5047
-            return $classInstance;
5048
-        }
5049
-        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5050
-        return $object;
5051
-    }
5052
-
5053
-
5054
-
5055
-    /**
5056
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5057
-     * if no identifier is provided, then the entire entity map is emptied
5058
-     *
5059
-     * @param int|string $id the ID of the model object
5060
-     * @return boolean
5061
-     */
5062
-    public function clear_entity_map($id = null)
5063
-    {
5064
-        if (empty($id)) {
5065
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5066
-            return true;
5067
-        }
5068
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5069
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5070
-            return true;
5071
-        }
5072
-        return false;
5073
-    }
5074
-
5075
-
5076
-
5077
-    /**
5078
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5079
-     * Given an array where keys are column (or column alias) names and values,
5080
-     * returns an array of their corresponding field names and database values
5081
-     *
5082
-     * @param array $cols_n_values
5083
-     * @return array
5084
-     */
5085
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5086
-    {
5087
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5088
-    }
5089
-
5090
-
5091
-
5092
-    /**
5093
-     * _deduce_fields_n_values_from_cols_n_values
5094
-     * Given an array where keys are column (or column alias) names and values,
5095
-     * returns an array of their corresponding field names and database values
5096
-     *
5097
-     * @param string $cols_n_values
5098
-     * @return array
5099
-     */
5100
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5101
-    {
5102
-        $this_model_fields_n_values = array();
5103
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5104
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5105
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5106
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5107
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5108
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5109
-                    if (! $field_obj->is_db_only_field()) {
5110
-                        //prepare field as if its coming from db
5111
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5112
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5113
-                    }
5114
-                }
5115
-            } else {
5116
-                //the table's rows existed. Use their values
5117
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5118
-                    if (! $field_obj->is_db_only_field()) {
5119
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5120
-                            $cols_n_values, $field_obj->get_qualified_column(),
5121
-                            $field_obj->get_table_column()
5122
-                        );
5123
-                    }
5124
-                }
5125
-            }
5126
-        }
5127
-        return $this_model_fields_n_values;
5128
-    }
5129
-
5130
-
5131
-
5132
-    /**
5133
-     * @param $cols_n_values
5134
-     * @param $qualified_column
5135
-     * @param $regular_column
5136
-     * @return null
5137
-     */
5138
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5139
-    {
5140
-        $value = null;
5141
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5142
-        //does the field on the model relate to this column retrieved from the db?
5143
-        //or is it a db-only field? (not relating to the model)
5144
-        if (isset($cols_n_values[$qualified_column])) {
5145
-            $value = $cols_n_values[$qualified_column];
5146
-        } elseif (isset($cols_n_values[$regular_column])) {
5147
-            $value = $cols_n_values[$regular_column];
5148
-        }
5149
-        return $value;
5150
-    }
5151
-
5152
-
5153
-
5154
-    /**
5155
-     * refresh_entity_map_from_db
5156
-     * Makes sure the model object in the entity map at $id assumes the values
5157
-     * of the database (opposite of EE_base_Class::save())
5158
-     *
5159
-     * @param int|string $id
5160
-     * @return EE_Base_Class
5161
-     * @throws EE_Error
5162
-     */
5163
-    public function refresh_entity_map_from_db($id)
5164
-    {
5165
-        $obj_in_map = $this->get_from_entity_map($id);
5166
-        if ($obj_in_map) {
5167
-            $wpdb_results = $this->_get_all_wpdb_results(
5168
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5169
-            );
5170
-            if ($wpdb_results && is_array($wpdb_results)) {
5171
-                $one_row = reset($wpdb_results);
5172
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5173
-                    $obj_in_map->set_from_db($field_name, $db_value);
5174
-                }
5175
-                //clear the cache of related model objects
5176
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5177
-                    $obj_in_map->clear_cache($relation_name, null, true);
5178
-                }
5179
-            }
5180
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5181
-            return $obj_in_map;
5182
-        }
5183
-        return $this->get_one_by_ID($id);
5184
-    }
5185
-
5186
-
5187
-
5188
-    /**
5189
-     * refresh_entity_map_with
5190
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5191
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5192
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5193
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5194
-     *
5195
-     * @param int|string    $id
5196
-     * @param EE_Base_Class $replacing_model_obj
5197
-     * @return \EE_Base_Class
5198
-     * @throws EE_Error
5199
-     */
5200
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5201
-    {
5202
-        $obj_in_map = $this->get_from_entity_map($id);
5203
-        if ($obj_in_map) {
5204
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5205
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5206
-                    $obj_in_map->set($field_name, $value);
5207
-                }
5208
-                //make the model object in the entity map's cache match the $replacing_model_obj
5209
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5210
-                    $obj_in_map->clear_cache($relation_name, null, true);
5211
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5212
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5213
-                    }
5214
-                }
5215
-            }
5216
-            return $obj_in_map;
5217
-        }
5218
-        $this->add_to_entity_map($replacing_model_obj);
5219
-        return $replacing_model_obj;
5220
-    }
5221
-
5222
-
5223
-
5224
-    /**
5225
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5226
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5227
-     * require_once($this->_getClassName().".class.php");
5228
-     *
5229
-     * @return string
5230
-     */
5231
-    private function _get_class_name()
5232
-    {
5233
-        return "EE_" . $this->get_this_model_name();
5234
-    }
5235
-
5236
-
5237
-
5238
-    /**
5239
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5240
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5241
-     * it would be 'Events'.
5242
-     *
5243
-     * @param int $quantity
5244
-     * @return string
5245
-     */
5246
-    public function item_name($quantity = 1)
5247
-    {
5248
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5249
-    }
5250
-
5251
-
5252
-
5253
-    /**
5254
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5255
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5256
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5257
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5258
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5259
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5260
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5261
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5262
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5263
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5264
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5265
-     *        return $previousReturnValue.$returnString;
5266
-     * }
5267
-     * require('EEM_Answer.model.php');
5268
-     * $answer=EEM_Answer::instance();
5269
-     * echo $answer->my_callback('monkeys',100);
5270
-     * //will output "you called my_callback! and passed args:monkeys,100"
5271
-     *
5272
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5273
-     * @param array  $args       array of original arguments passed to the function
5274
-     * @throws EE_Error
5275
-     * @return mixed whatever the plugin which calls add_filter decides
5276
-     */
5277
-    public function __call($methodName, $args)
5278
-    {
5279
-        $className = get_class($this);
5280
-        $tagName = "FHEE__{$className}__{$methodName}";
5281
-        if (! has_filter($tagName)) {
5282
-            throw new EE_Error(
5283
-                sprintf(
5284
-                    __('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 );',
5285
-                        'event_espresso'),
5286
-                    $methodName,
5287
-                    $className,
5288
-                    $tagName,
5289
-                    '<br />'
5290
-                )
5291
-            );
5292
-        }
5293
-        return apply_filters($tagName, null, $this, $args);
5294
-    }
5295
-
5296
-
5297
-
5298
-    /**
5299
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5300
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5301
-     *
5302
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5303
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5304
-     *                                                       the object's class name
5305
-     *                                                       or object's ID
5306
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5307
-     *                                                       exists in the database. If it does not, we add it
5308
-     * @throws EE_Error
5309
-     * @return EE_Base_Class
5310
-     */
5311
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5312
-    {
5313
-        $className = $this->_get_class_name();
5314
-        if ($base_class_obj_or_id instanceof $className) {
5315
-            $model_object = $base_class_obj_or_id;
5316
-        } else {
5317
-            $primary_key_field = $this->get_primary_key_field();
5318
-            if (
5319
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5320
-                && (
5321
-                    is_int($base_class_obj_or_id)
5322
-                    || is_string($base_class_obj_or_id)
5323
-                )
5324
-            ) {
5325
-                // assume it's an ID.
5326
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5327
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5328
-            } else if (
5329
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5330
-                && is_string($base_class_obj_or_id)
5331
-            ) {
5332
-                // assume its a string representation of the object
5333
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5334
-            } else {
5335
-                throw new EE_Error(
5336
-                    sprintf(
5337
-                        __(
5338
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5339
-                            'event_espresso'
5340
-                        ),
5341
-                        $base_class_obj_or_id,
5342
-                        $this->_get_class_name(),
5343
-                        print_r($base_class_obj_or_id, true)
5344
-                    )
5345
-                );
5346
-            }
5347
-        }
5348
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5349
-            $model_object->save();
5350
-        }
5351
-        return $model_object;
5352
-    }
5353
-
5354
-
5355
-
5356
-    /**
5357
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5358
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5359
-     * returns it ID.
5360
-     *
5361
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5362
-     * @return int|string depending on the type of this model object's ID
5363
-     * @throws EE_Error
5364
-     */
5365
-    public function ensure_is_ID($base_class_obj_or_id)
5366
-    {
5367
-        $className = $this->_get_class_name();
5368
-        if ($base_class_obj_or_id instanceof $className) {
5369
-            /** @var $base_class_obj_or_id EE_Base_Class */
5370
-            $id = $base_class_obj_or_id->ID();
5371
-        } elseif (is_int($base_class_obj_or_id)) {
5372
-            //assume it's an ID
5373
-            $id = $base_class_obj_or_id;
5374
-        } elseif (is_string($base_class_obj_or_id)) {
5375
-            //assume its a string representation of the object
5376
-            $id = $base_class_obj_or_id;
5377
-        } else {
5378
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5379
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5380
-                print_r($base_class_obj_or_id, true)));
5381
-        }
5382
-        return $id;
5383
-    }
5384
-
5385
-
5386
-
5387
-    /**
5388
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5389
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5390
-     * been sanitized and converted into the appropriate domain.
5391
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5392
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5393
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5394
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5395
-     * $EVT = EEM_Event::instance(); $old_setting =
5396
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5397
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5398
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5399
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5400
-     *
5401
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5402
-     * @return void
5403
-     */
5404
-    public function assume_values_already_prepared_by_model_object(
5405
-        $values_already_prepared = self::not_prepared_by_model_object
5406
-    ) {
5407
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5408
-    }
5409
-
5410
-
5411
-
5412
-    /**
5413
-     * Read comments for assume_values_already_prepared_by_model_object()
5414
-     *
5415
-     * @return int
5416
-     */
5417
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5418
-    {
5419
-        return $this->_values_already_prepared_by_model_object;
5420
-    }
5421
-
5422
-
5423
-
5424
-    /**
5425
-     * Gets all the indexes on this model
5426
-     *
5427
-     * @return EE_Index[]
5428
-     */
5429
-    public function indexes()
5430
-    {
5431
-        return $this->_indexes;
5432
-    }
5433
-
5434
-
5435
-
5436
-    /**
5437
-     * Gets all the Unique Indexes on this model
5438
-     *
5439
-     * @return EE_Unique_Index[]
5440
-     */
5441
-    public function unique_indexes()
5442
-    {
5443
-        $unique_indexes = array();
5444
-        foreach ($this->_indexes as $name => $index) {
5445
-            if ($index instanceof EE_Unique_Index) {
5446
-                $unique_indexes [$name] = $index;
5447
-            }
5448
-        }
5449
-        return $unique_indexes;
5450
-    }
5451
-
5452
-
5453
-
5454
-    /**
5455
-     * Gets all the fields which, when combined, make the primary key.
5456
-     * This is usually just an array with 1 element (the primary key), but in cases
5457
-     * where there is no primary key, it's a combination of fields as defined
5458
-     * on a primary index
5459
-     *
5460
-     * @return EE_Model_Field_Base[] indexed by the field's name
5461
-     * @throws EE_Error
5462
-     */
5463
-    public function get_combined_primary_key_fields()
5464
-    {
5465
-        foreach ($this->indexes() as $index) {
5466
-            if ($index instanceof EE_Primary_Key_Index) {
5467
-                return $index->fields();
5468
-            }
5469
-        }
5470
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5471
-    }
5472
-
5473
-
5474
-
5475
-    /**
5476
-     * Used to build a primary key string (when the model has no primary key),
5477
-     * which can be used a unique string to identify this model object.
5478
-     *
5479
-     * @param array $cols_n_values keys are field names, values are their values
5480
-     * @return string
5481
-     * @throws EE_Error
5482
-     */
5483
-    public function get_index_primary_key_string($cols_n_values)
5484
-    {
5485
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5486
-            $this->get_combined_primary_key_fields());
5487
-        return http_build_query($cols_n_values_for_primary_key_index);
5488
-    }
5489
-
5490
-
5491
-
5492
-    /**
5493
-     * Gets the field values from the primary key string
5494
-     *
5495
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5496
-     * @param string $index_primary_key_string
5497
-     * @return null|array
5498
-     * @throws EE_Error
5499
-     */
5500
-    public function parse_index_primary_key_string($index_primary_key_string)
5501
-    {
5502
-        $key_fields = $this->get_combined_primary_key_fields();
5503
-        //check all of them are in the $id
5504
-        $key_vals_in_combined_pk = array();
5505
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5506
-        foreach ($key_fields as $key_field_name => $field_obj) {
5507
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5508
-                return null;
5509
-            }
5510
-        }
5511
-        return $key_vals_in_combined_pk;
5512
-    }
5513
-
5514
-
5515
-
5516
-    /**
5517
-     * verifies that an array of key-value pairs for model fields has a key
5518
-     * for each field comprising the primary key index
5519
-     *
5520
-     * @param array $key_vals
5521
-     * @return boolean
5522
-     * @throws EE_Error
5523
-     */
5524
-    public function has_all_combined_primary_key_fields($key_vals)
5525
-    {
5526
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5527
-        foreach ($keys_it_should_have as $key) {
5528
-            if (! isset($key_vals[$key])) {
5529
-                return false;
5530
-            }
5531
-        }
5532
-        return true;
5533
-    }
5534
-
5535
-
5536
-
5537
-    /**
5538
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5539
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5540
-     *
5541
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5542
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5543
-     * @throws EE_Error
5544
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5545
-     *                                                              indexed)
5546
-     */
5547
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5548
-    {
5549
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5550
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5551
-        } elseif (is_array($model_object_or_attributes_array)) {
5552
-            $attributes_array = $model_object_or_attributes_array;
5553
-        } else {
5554
-            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",
5555
-                "event_espresso"), $model_object_or_attributes_array));
5556
-        }
5557
-        //even copies obviously won't have the same ID, so remove the primary key
5558
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5559
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5560
-            unset($attributes_array[$this->primary_key_name()]);
5561
-        }
5562
-        if (isset($query_params[0])) {
5563
-            $query_params[0] = array_merge($attributes_array, $query_params);
5564
-        } else {
5565
-            $query_params[0] = $attributes_array;
5566
-        }
5567
-        return $this->get_all($query_params);
5568
-    }
5569
-
5570
-
5571
-
5572
-    /**
5573
-     * Gets the first copy we find. See get_all_copies for more details
5574
-     *
5575
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5576
-     * @param array $query_params
5577
-     * @return EE_Base_Class
5578
-     * @throws EE_Error
5579
-     */
5580
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5581
-    {
5582
-        if (! is_array($query_params)) {
5583
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5584
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5585
-                    gettype($query_params)), '4.6.0');
5586
-            $query_params = array();
5587
-        }
5588
-        $query_params['limit'] = 1;
5589
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5590
-        if (is_array($copies)) {
5591
-            return array_shift($copies);
5592
-        }
5593
-        return null;
5594
-    }
5595
-
5596
-
5597
-
5598
-    /**
5599
-     * Updates the item with the specified id. Ignores default query parameters because
5600
-     * we have specified the ID, and its assumed we KNOW what we're doing
5601
-     *
5602
-     * @param array      $fields_n_values keys are field names, values are their new values
5603
-     * @param int|string $id              the value of the primary key to update
5604
-     * @return int number of rows updated
5605
-     * @throws EE_Error
5606
-     */
5607
-    public function update_by_ID($fields_n_values, $id)
5608
-    {
5609
-        $query_params = array(
5610
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5611
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5612
-        );
5613
-        return $this->update($fields_n_values, $query_params);
5614
-    }
5615
-
5616
-
5617
-
5618
-    /**
5619
-     * Changes an operator which was supplied to the models into one usable in SQL
5620
-     *
5621
-     * @param string $operator_supplied
5622
-     * @return string an operator which can be used in SQL
5623
-     * @throws EE_Error
5624
-     */
5625
-    private function _prepare_operator_for_sql($operator_supplied)
5626
-    {
5627
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5628
-            : null;
5629
-        if ($sql_operator) {
5630
-            return $sql_operator;
5631
-        }
5632
-        throw new EE_Error(
5633
-            sprintf(
5634
-                __(
5635
-                    "The operator '%s' is not in the list of valid operators: %s",
5636
-                    "event_espresso"
5637
-                ), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5638
-            )
5639
-        );
5640
-    }
5641
-
5642
-
5643
-
5644
-    /**
5645
-     * Gets an array where keys are the primary keys and values are their 'names'
5646
-     * (as determined by the model object's name() function, which is often overridden)
5647
-     *
5648
-     * @param array $query_params like get_all's
5649
-     * @return string[]
5650
-     * @throws EE_Error
5651
-     */
5652
-    public function get_all_names($query_params = array())
5653
-    {
5654
-        $objs = $this->get_all($query_params);
5655
-        $names = array();
5656
-        foreach ($objs as $obj) {
5657
-            $names[$obj->ID()] = $obj->name();
5658
-        }
5659
-        return $names;
5660
-    }
5661
-
5662
-
5663
-
5664
-    /**
5665
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5666
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5667
-     * this is duplicated effort and reduces efficiency) you would be better to use
5668
-     * array_keys() on $model_objects.
5669
-     *
5670
-     * @param \EE_Base_Class[] $model_objects
5671
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5672
-     *                                               in the returned array
5673
-     * @return array
5674
-     * @throws EE_Error
5675
-     */
5676
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5677
-    {
5678
-        if (! $this->has_primary_key_field()) {
5679
-            if (WP_DEBUG) {
5680
-                EE_Error::add_error(
5681
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5682
-                    __FILE__,
5683
-                    __FUNCTION__,
5684
-                    __LINE__
5685
-                );
5686
-            }
5687
-        }
5688
-        $IDs = array();
5689
-        foreach ($model_objects as $model_object) {
5690
-            $id = $model_object->ID();
5691
-            if (! $id) {
5692
-                if ($filter_out_empty_ids) {
5693
-                    continue;
5694
-                }
5695
-                if (WP_DEBUG) {
5696
-                    EE_Error::add_error(
5697
-                        __(
5698
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5699
-                            'event_espresso'
5700
-                        ),
5701
-                        __FILE__,
5702
-                        __FUNCTION__,
5703
-                        __LINE__
5704
-                    );
5705
-                }
5706
-            }
5707
-            $IDs[] = $id;
5708
-        }
5709
-        return $IDs;
5710
-    }
5711
-
5712
-
5713
-
5714
-    /**
5715
-     * Returns the string used in capabilities relating to this model. If there
5716
-     * are no capabilities that relate to this model returns false
5717
-     *
5718
-     * @return string|false
5719
-     */
5720
-    public function cap_slug()
5721
-    {
5722
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5723
-    }
5724
-
5725
-
5726
-
5727
-    /**
5728
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5729
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5730
-     * only returns the cap restrictions array in that context (ie, the array
5731
-     * at that key)
5732
-     *
5733
-     * @param string $context
5734
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5735
-     * @throws EE_Error
5736
-     */
5737
-    public function cap_restrictions($context = EEM_Base::caps_read)
5738
-    {
5739
-        EEM_Base::verify_is_valid_cap_context($context);
5740
-        //check if we ought to run the restriction generator first
5741
-        if (
5742
-            isset($this->_cap_restriction_generators[$context])
5743
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5744
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5745
-        ) {
5746
-            $this->_cap_restrictions[$context] = array_merge(
5747
-                $this->_cap_restrictions[$context],
5748
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5749
-            );
5750
-        }
5751
-        //and make sure we've finalized the construction of each restriction
5752
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5753
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5754
-                $where_conditions_obj->_finalize_construct($this);
5755
-            }
5756
-        }
5757
-        return $this->_cap_restrictions[$context];
5758
-    }
5759
-
5760
-
5761
-
5762
-    /**
5763
-     * Indicating whether or not this model thinks its a wp core model
5764
-     *
5765
-     * @return boolean
5766
-     */
5767
-    public function is_wp_core_model()
5768
-    {
5769
-        return $this->_wp_core_model;
5770
-    }
5771
-
5772
-
5773
-
5774
-    /**
5775
-     * Gets all the caps that are missing which impose a restriction on
5776
-     * queries made in this context
5777
-     *
5778
-     * @param string $context one of EEM_Base::caps_ constants
5779
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5780
-     * @throws EE_Error
5781
-     */
5782
-    public function caps_missing($context = EEM_Base::caps_read)
5783
-    {
5784
-        $missing_caps = array();
5785
-        $cap_restrictions = $this->cap_restrictions($context);
5786
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5787
-            if (! EE_Capabilities::instance()
5788
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5789
-            ) {
5790
-                $missing_caps[$cap] = $restriction_if_no_cap;
5791
-            }
5792
-        }
5793
-        return $missing_caps;
5794
-    }
5795
-
5796
-
5797
-
5798
-    /**
5799
-     * Gets the mapping from capability contexts to action strings used in capability names
5800
-     *
5801
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5802
-     * one of 'read', 'edit', or 'delete'
5803
-     */
5804
-    public function cap_contexts_to_cap_action_map()
5805
-    {
5806
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5807
-            $this);
5808
-    }
5809
-
5810
-
5811
-
5812
-    /**
5813
-     * Gets the action string for the specified capability context
5814
-     *
5815
-     * @param string $context
5816
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5817
-     * @throws EE_Error
5818
-     */
5819
-    public function cap_action_for_context($context)
5820
-    {
5821
-        $mapping = $this->cap_contexts_to_cap_action_map();
5822
-        if (isset($mapping[$context])) {
5823
-            return $mapping[$context];
5824
-        }
5825
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5826
-            return $action;
5827
-        }
5828
-        throw new EE_Error(
5829
-            sprintf(
5830
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5831
-                $context,
5832
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5833
-            )
5834
-        );
5835
-    }
5836
-
5837
-
5838
-
5839
-    /**
5840
-     * Returns all the capability contexts which are valid when querying models
5841
-     *
5842
-     * @return array
5843
-     */
5844
-    public static function valid_cap_contexts()
5845
-    {
5846
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5847
-            self::caps_read,
5848
-            self::caps_read_admin,
5849
-            self::caps_edit,
5850
-            self::caps_delete,
5851
-        ));
5852
-    }
5853
-
5854
-
5855
-
5856
-    /**
5857
-     * Returns all valid options for 'default_where_conditions'
5858
-     *
5859
-     * @return array
5860
-     */
5861
-    public static function valid_default_where_conditions()
5862
-    {
5863
-        return array(
5864
-            EEM_Base::default_where_conditions_all,
5865
-            EEM_Base::default_where_conditions_this_only,
5866
-            EEM_Base::default_where_conditions_others_only,
5867
-            EEM_Base::default_where_conditions_minimum_all,
5868
-            EEM_Base::default_where_conditions_minimum_others,
5869
-            EEM_Base::default_where_conditions_none
5870
-        );
5871
-    }
5872
-
5873
-    // public static function default_where_conditions_full
5874
-    /**
5875
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5876
-     *
5877
-     * @param string $context
5878
-     * @return bool
5879
-     * @throws EE_Error
5880
-     */
5881
-    static public function verify_is_valid_cap_context($context)
5882
-    {
5883
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5884
-        if (in_array($context, $valid_cap_contexts)) {
5885
-            return true;
5886
-        }
5887
-        throw new EE_Error(
5888
-            sprintf(
5889
-                __(
5890
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5891
-                    'event_espresso'
5892
-                ),
5893
-                $context,
5894
-                'EEM_Base',
5895
-                implode(',', $valid_cap_contexts)
5896
-            )
5897
-        );
5898
-    }
5899
-
5900
-
5901
-
5902
-    /**
5903
-     * Clears all the models field caches. This is only useful when a sub-class
5904
-     * might have added a field or something and these caches might be invalidated
5905
-     */
5906
-    protected function _invalidate_field_caches()
5907
-    {
5908
-        $this->_cache_foreign_key_to_fields = array();
5909
-        $this->_cached_fields = null;
5910
-        $this->_cached_fields_non_db_only = null;
5911
-    }
5912
-
5913
-
5914
-
5915
-    /**
5916
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5917
-     * (eg "and", "or", "not").
5918
-     *
5919
-     * @return array
5920
-     */
5921
-    public function logic_query_param_keys()
5922
-    {
5923
-        return $this->_logic_query_param_keys;
5924
-    }
5925
-
5926
-
5927
-
5928
-    /**
5929
-     * Determines whether or not the where query param array key is for a logic query param.
5930
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
5931
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5932
-     *
5933
-     * @param $query_param_key
5934
-     * @return bool
5935
-     */
5936
-    public function is_logic_query_param_key($query_param_key)
5937
-    {
5938
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5939
-            if ($query_param_key === $logic_query_param_key
5940
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5941
-            ) {
5942
-                return true;
5943
-            }
5944
-        }
5945
-        return false;
5946
-    }
3675
+		}
3676
+		return $null_friendly_where_conditions;
3677
+	}
3678
+
3679
+
3680
+
3681
+	/**
3682
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3683
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3684
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3685
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3686
+	 *
3687
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3688
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3689
+	 */
3690
+	private function _get_default_where_conditions($model_relation_path = null)
3691
+	{
3692
+		if ($this->_ignore_where_strategy) {
3693
+			return array();
3694
+		}
3695
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3696
+	}
3697
+
3698
+
3699
+
3700
+	/**
3701
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3702
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3703
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3704
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3705
+	 * Similar to _get_default_where_conditions
3706
+	 *
3707
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3708
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3709
+	 */
3710
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3711
+	{
3712
+		if ($this->_ignore_where_strategy) {
3713
+			return array();
3714
+		}
3715
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3716
+	}
3717
+
3718
+
3719
+
3720
+	/**
3721
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3722
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3723
+	 *
3724
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3725
+	 * @return string
3726
+	 * @throws EE_Error
3727
+	 */
3728
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3729
+	{
3730
+		$selects = $this->_get_columns_to_select_for_this_model();
3731
+		foreach (
3732
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3733
+			$name_of_other_model_included
3734
+		) {
3735
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3736
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3737
+			foreach ($other_model_selects as $key => $value) {
3738
+				$selects[] = $value;
3739
+			}
3740
+		}
3741
+		return implode(", ", $selects);
3742
+	}
3743
+
3744
+
3745
+
3746
+	/**
3747
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3748
+	 * So that's going to be the columns for all the fields on the model
3749
+	 *
3750
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3751
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3752
+	 */
3753
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3754
+	{
3755
+		$fields = $this->field_settings();
3756
+		$selects = array();
3757
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3758
+			$this->get_this_model_name());
3759
+		foreach ($fields as $field_obj) {
3760
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3761
+						 . $field_obj->get_table_alias()
3762
+						 . "."
3763
+						 . $field_obj->get_table_column()
3764
+						 . " AS '"
3765
+						 . $table_alias_with_model_relation_chain_prefix
3766
+						 . $field_obj->get_table_alias()
3767
+						 . "."
3768
+						 . $field_obj->get_table_column()
3769
+						 . "'";
3770
+		}
3771
+		//make sure we are also getting the PKs of each table
3772
+		$tables = $this->get_tables();
3773
+		if (count($tables) > 1) {
3774
+			foreach ($tables as $table_obj) {
3775
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3776
+									   . $table_obj->get_fully_qualified_pk_column();
3777
+				if (! in_array($qualified_pk_column, $selects)) {
3778
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3779
+				}
3780
+			}
3781
+		}
3782
+		return $selects;
3783
+	}
3784
+
3785
+
3786
+
3787
+	/**
3788
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3789
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3790
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3791
+	 * SQL for joining, and the data types
3792
+	 *
3793
+	 * @param null|string                 $original_query_param
3794
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3795
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3796
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3797
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3798
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3799
+	 *                                                          or 'Registration's
3800
+	 * @param string                      $original_query_param what it originally was (eg
3801
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3802
+	 *                                                          matches $query_param
3803
+	 * @throws EE_Error
3804
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3805
+	 */
3806
+	private function _extract_related_model_info_from_query_param(
3807
+		$query_param,
3808
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3809
+		$query_param_type,
3810
+		$original_query_param = null
3811
+	) {
3812
+		if ($original_query_param === null) {
3813
+			$original_query_param = $query_param;
3814
+		}
3815
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3816
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3817
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3818
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3819
+		//check to see if we have a field on this model
3820
+		$this_model_fields = $this->field_settings(true);
3821
+		if (array_key_exists($query_param, $this_model_fields)) {
3822
+			if ($allow_fields) {
3823
+				return;
3824
+			}
3825
+			throw new EE_Error(
3826
+				sprintf(
3827
+					__(
3828
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3829
+						"event_espresso"
3830
+					),
3831
+					$query_param, get_class($this), $query_param_type, $original_query_param
3832
+				)
3833
+			);
3834
+		}
3835
+		//check if this is a special logic query param
3836
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3837
+			if ($allow_logic_query_params) {
3838
+				return;
3839
+			}
3840
+			throw new EE_Error(
3841
+				sprintf(
3842
+					__(
3843
+						'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',
3844
+						'event_espresso'
3845
+					),
3846
+					implode('", "', $this->_logic_query_param_keys),
3847
+					$query_param,
3848
+					get_class($this),
3849
+					'<br />',
3850
+					"\t"
3851
+					. ' $passed_in_query_info = <pre>'
3852
+					. print_r($passed_in_query_info, true)
3853
+					. '</pre>'
3854
+					. "\n\t"
3855
+					. ' $query_param_type = '
3856
+					. $query_param_type
3857
+					. "\n\t"
3858
+					. ' $original_query_param = '
3859
+					. $original_query_param
3860
+				)
3861
+			);
3862
+		}
3863
+		//check if it's a custom selection
3864
+		if (array_key_exists($query_param, $this->_custom_selections)) {
3865
+			return;
3866
+		}
3867
+		//check if has a model name at the beginning
3868
+		//and
3869
+		//check if it's a field on a related model
3870
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3871
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3872
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3873
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3874
+				if ($query_param === '') {
3875
+					//nothing left to $query_param
3876
+					//we should actually end in a field name, not a model like this!
3877
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3878
+						"event_espresso"),
3879
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3880
+				}
3881
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3882
+				$related_model_obj->_extract_related_model_info_from_query_param(
3883
+					$query_param,
3884
+					$passed_in_query_info, $query_param_type, $original_query_param
3885
+				);
3886
+				return;
3887
+			}
3888
+			if ($query_param === $valid_related_model_name) {
3889
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3890
+				return;
3891
+			}
3892
+		}
3893
+		//ok so $query_param didn't start with a model name
3894
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3895
+		//it's wack, that's what it is
3896
+		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",
3897
+			"event_espresso"),
3898
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3899
+	}
3900
+
3901
+
3902
+
3903
+	/**
3904
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3905
+	 * and store it on $passed_in_query_info
3906
+	 *
3907
+	 * @param string                      $model_name
3908
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3909
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3910
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3911
+	 *                                                          and are adding a join to 'Payment' with the original
3912
+	 *                                                          query param key
3913
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3914
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3915
+	 *                                                          Payment wants to add default query params so that it
3916
+	 *                                                          will know what models to prepend onto its default query
3917
+	 *                                                          params or in case it wants to rename tables (in case
3918
+	 *                                                          there are multiple joins to the same table)
3919
+	 * @return void
3920
+	 * @throws EE_Error
3921
+	 */
3922
+	private function _add_join_to_model(
3923
+		$model_name,
3924
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3925
+		$original_query_param
3926
+	) {
3927
+		$relation_obj = $this->related_settings_for($model_name);
3928
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3929
+		//check if the relation is HABTM, because then we're essentially doing two joins
3930
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3931
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3932
+			$join_model_obj = $relation_obj->get_join_model();
3933
+			//replace the model specified with the join model for this relation chain, whi
3934
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3935
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3936
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3937
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3938
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3939
+			$passed_in_query_info->merge($new_query_info);
3940
+		}
3941
+		//now just join to the other table pointed to by the relation object, and add its data types
3942
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3943
+			array($model_relation_chain => $model_name),
3944
+			$relation_obj->get_join_statement($model_relation_chain));
3945
+		$passed_in_query_info->merge($new_query_info);
3946
+	}
3947
+
3948
+
3949
+
3950
+	/**
3951
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3952
+	 *
3953
+	 * @param array $where_params like EEM_Base::get_all
3954
+	 * @return string of SQL
3955
+	 * @throws EE_Error
3956
+	 */
3957
+	private function _construct_where_clause($where_params)
3958
+	{
3959
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3960
+		if ($SQL) {
3961
+			return " WHERE " . $SQL;
3962
+		}
3963
+		return '';
3964
+	}
3965
+
3966
+
3967
+
3968
+	/**
3969
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3970
+	 * and should be passed HAVING parameters, not WHERE parameters
3971
+	 *
3972
+	 * @param array $having_params
3973
+	 * @return string
3974
+	 * @throws EE_Error
3975
+	 */
3976
+	private function _construct_having_clause($having_params)
3977
+	{
3978
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3979
+		if ($SQL) {
3980
+			return " HAVING " . $SQL;
3981
+		}
3982
+		return '';
3983
+	}
3984
+
3985
+
3986
+
3987
+	/**
3988
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3989
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3990
+	 * EEM_Attendee.
3991
+	 *
3992
+	 * @param string $field_name
3993
+	 * @param string $model_name
3994
+	 * @return EE_Model_Field_Base
3995
+	 * @throws EE_Error
3996
+	 */
3997
+	protected function _get_field_on_model($field_name, $model_name)
3998
+	{
3999
+		$model_class = 'EEM_' . $model_name;
4000
+		$model_filepath = $model_class . ".model.php";
4001
+		if (is_readable($model_filepath)) {
4002
+			require_once($model_filepath);
4003
+			$model_instance = call_user_func($model_name . "::instance");
4004
+			/* @var $model_instance EEM_Base */
4005
+			return $model_instance->field_settings_for($field_name);
4006
+		}
4007
+		throw new EE_Error(
4008
+			sprintf(
4009
+				__(
4010
+					'No model named %s exists, with classname %s and filepath %s',
4011
+					'event_espresso'
4012
+				), $model_name, $model_class, $model_filepath
4013
+			)
4014
+		);
4015
+	}
4016
+
4017
+
4018
+
4019
+	/**
4020
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4021
+	 * Event_Meta.meta_value = 'foo'))"
4022
+	 *
4023
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4024
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4025
+	 * @throws EE_Error
4026
+	 * @return string of SQL
4027
+	 */
4028
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4029
+	{
4030
+		$where_clauses = array();
4031
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4032
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4033
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4034
+				switch ($query_param) {
4035
+					case 'not':
4036
+					case 'NOT':
4037
+						$where_clauses[] = "! ("
4038
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4039
+								$glue)
4040
+										   . ")";
4041
+						break;
4042
+					case 'and':
4043
+					case 'AND':
4044
+						$where_clauses[] = " ("
4045
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4046
+								' AND ')
4047
+										   . ")";
4048
+						break;
4049
+					case 'or':
4050
+					case 'OR':
4051
+						$where_clauses[] = " ("
4052
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4053
+								' OR ')
4054
+										   . ")";
4055
+						break;
4056
+				}
4057
+			} else {
4058
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4059
+				//if it's not a normal field, maybe it's a custom selection?
4060
+				if (! $field_obj) {
4061
+					if (isset($this->_custom_selections[$query_param][1])) {
4062
+						$field_obj = $this->_custom_selections[$query_param][1];
4063
+					} else {
4064
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4065
+							"event_espresso"), $query_param));
4066
+					}
4067
+				}
4068
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4069
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4070
+			}
4071
+		}
4072
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4073
+	}
4074
+
4075
+
4076
+
4077
+	/**
4078
+	 * Takes the input parameter and extract the table name (alias) and column name
4079
+	 *
4080
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4081
+	 * @throws EE_Error
4082
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4083
+	 */
4084
+	private function _deduce_column_name_from_query_param($query_param)
4085
+	{
4086
+		$field = $this->_deduce_field_from_query_param($query_param);
4087
+		if ($field) {
4088
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4089
+				$query_param);
4090
+			return $table_alias_prefix . $field->get_qualified_column();
4091
+		}
4092
+		if (array_key_exists($query_param, $this->_custom_selections)) {
4093
+			//maybe it's custom selection item?
4094
+			//if so, just use it as the "column name"
4095
+			return $query_param;
4096
+		}
4097
+		throw new EE_Error(
4098
+			sprintf(
4099
+				__(
4100
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4101
+					"event_espresso"
4102
+				), $query_param, implode(",", $this->_custom_selections)
4103
+			)
4104
+		);
4105
+	}
4106
+
4107
+
4108
+
4109
+	/**
4110
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4111
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4112
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4113
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4114
+	 *
4115
+	 * @param string $condition_query_param_key
4116
+	 * @return string
4117
+	 */
4118
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4119
+	{
4120
+		$pos_of_star = strpos($condition_query_param_key, '*');
4121
+		if ($pos_of_star === false) {
4122
+			return $condition_query_param_key;
4123
+		}
4124
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4125
+		return $condition_query_param_sans_star;
4126
+	}
4127
+
4128
+
4129
+
4130
+	/**
4131
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4132
+	 *
4133
+	 * @param                            mixed      array | string    $op_and_value
4134
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4135
+	 * @throws EE_Error
4136
+	 * @return string
4137
+	 */
4138
+	private function _construct_op_and_value($op_and_value, $field_obj)
4139
+	{
4140
+		if (is_array($op_and_value)) {
4141
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4142
+			if (! $operator) {
4143
+				$php_array_like_string = array();
4144
+				foreach ($op_and_value as $key => $value) {
4145
+					$php_array_like_string[] = "$key=>$value";
4146
+				}
4147
+				throw new EE_Error(
4148
+					sprintf(
4149
+						__(
4150
+							"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))",
4151
+							"event_espresso"
4152
+						),
4153
+						implode(",", $php_array_like_string)
4154
+					)
4155
+				);
4156
+			}
4157
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4158
+		} else {
4159
+			$operator = '=';
4160
+			$value = $op_and_value;
4161
+		}
4162
+		//check to see if the value is actually another field
4163
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4164
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4165
+		}
4166
+		if (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4167
+			//in this case, the value should be an array, or at least a comma-separated list
4168
+			//it will need to handle a little differently
4169
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4170
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4171
+			return $operator . SP . $cleaned_value;
4172
+		}
4173
+		if (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4174
+			//the value should be an array with count of two.
4175
+			if (count($value) !== 2) {
4176
+				throw new EE_Error(
4177
+					sprintf(
4178
+						__(
4179
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4180
+							'event_espresso'
4181
+						),
4182
+						"BETWEEN"
4183
+					)
4184
+				);
4185
+			}
4186
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4187
+			return $operator . SP . $cleaned_value;
4188
+		}
4189
+		if (in_array($operator, $this->_null_style_operators)) {
4190
+			if ($value !== null) {
4191
+				throw new EE_Error(
4192
+					sprintf(
4193
+						__(
4194
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4195
+							"event_espresso"
4196
+						),
4197
+						$value,
4198
+						$operator
4199
+					)
4200
+				);
4201
+			}
4202
+			return $operator;
4203
+		}
4204
+		if ($operator === 'LIKE' && ! is_array($value)) {
4205
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4206
+			//remove other junk. So just treat it as a string.
4207
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4208
+		}
4209
+		if (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4210
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4211
+		}
4212
+		if (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4213
+			throw new EE_Error(
4214
+				sprintf(
4215
+					__(
4216
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4217
+						'event_espresso'
4218
+					),
4219
+					$operator,
4220
+					$operator
4221
+				)
4222
+			);
4223
+		}
4224
+		if (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4225
+			throw new EE_Error(
4226
+				sprintf(
4227
+					__(
4228
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4229
+						'event_espresso'
4230
+					),
4231
+					$operator,
4232
+					$operator
4233
+				)
4234
+			);
4235
+		}
4236
+		throw new EE_Error(
4237
+			sprintf(
4238
+				__(
4239
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4240
+					"event_espresso"
4241
+				),
4242
+				http_build_query($op_and_value)
4243
+			)
4244
+		);
4245
+	}
4246
+
4247
+
4248
+
4249
+	/**
4250
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4251
+	 *
4252
+	 * @param array                      $values
4253
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4254
+	 *                                              '%s'
4255
+	 * @return string
4256
+	 * @throws EE_Error
4257
+	 */
4258
+	public function _construct_between_value($values, $field_obj)
4259
+	{
4260
+		$cleaned_values = array();
4261
+		foreach ($values as $value) {
4262
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4263
+		}
4264
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4265
+	}
4266
+
4267
+
4268
+
4269
+	/**
4270
+	 * Takes an array or a comma-separated list of $values and cleans them
4271
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4272
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4273
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4274
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4275
+	 *
4276
+	 * @param mixed                      $values    array or comma-separated string
4277
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4278
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4279
+	 * @throws EE_Error
4280
+	 */
4281
+	public function _construct_in_value($values, $field_obj)
4282
+	{
4283
+		//check if the value is a CSV list
4284
+		if (is_string($values)) {
4285
+			//in which case, turn it into an array
4286
+			$values = explode(",", $values);
4287
+		}
4288
+		$cleaned_values = array();
4289
+		foreach ($values as $value) {
4290
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4291
+		}
4292
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4293
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4294
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4295
+		if (empty($cleaned_values)) {
4296
+			$all_fields = $this->field_settings();
4297
+			$a_field = array_shift($all_fields);
4298
+			$main_table = $this->_get_main_table();
4299
+			$cleaned_values[] = "SELECT "
4300
+								. $a_field->get_table_column()
4301
+								. " FROM "
4302
+								. $main_table->get_table_name()
4303
+								. " WHERE FALSE";
4304
+		}
4305
+		return "(" . implode(",", $cleaned_values) . ")";
4306
+	}
4307
+
4308
+
4309
+
4310
+	/**
4311
+	 * @param mixed                      $value
4312
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4313
+	 * @throws EE_Error
4314
+	 * @return false|null|string
4315
+	 */
4316
+	private function _wpdb_prepare_using_field($value, $field_obj)
4317
+	{
4318
+		/** @type WPDB $wpdb */
4319
+		global $wpdb;
4320
+		if ($field_obj instanceof EE_Model_Field_Base) {
4321
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4322
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4323
+		} //$field_obj should really just be a data type
4324
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4325
+			throw new EE_Error(
4326
+				sprintf(
4327
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4328
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)
4329
+				)
4330
+			);
4331
+		}
4332
+		return $wpdb->prepare($field_obj, $value);
4333
+	}
4334
+
4335
+
4336
+
4337
+	/**
4338
+	 * Takes the input parameter and finds the model field that it indicates.
4339
+	 *
4340
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4341
+	 * @throws EE_Error
4342
+	 * @return EE_Model_Field_Base
4343
+	 */
4344
+	protected function _deduce_field_from_query_param($query_param_name)
4345
+	{
4346
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4347
+		//which will help us find the database table and column
4348
+		$query_param_parts = explode(".", $query_param_name);
4349
+		if (empty($query_param_parts)) {
4350
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4351
+				'event_espresso'), $query_param_name));
4352
+		}
4353
+		$number_of_parts = count($query_param_parts);
4354
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4355
+		if ($number_of_parts === 1) {
4356
+			$field_name = $last_query_param_part;
4357
+			$model_obj = $this;
4358
+		} else {// $number_of_parts >= 2
4359
+			//the last part is the column name, and there are only 2parts. therefore...
4360
+			$field_name = $last_query_param_part;
4361
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4362
+		}
4363
+		try {
4364
+			return $model_obj->field_settings_for($field_name);
4365
+		} catch (EE_Error $e) {
4366
+			return null;
4367
+		}
4368
+	}
4369
+
4370
+
4371
+
4372
+	/**
4373
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4374
+	 * alias and column which corresponds to it
4375
+	 *
4376
+	 * @param string $field_name
4377
+	 * @throws EE_Error
4378
+	 * @return string
4379
+	 */
4380
+	public function _get_qualified_column_for_field($field_name)
4381
+	{
4382
+		$all_fields = $this->field_settings();
4383
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4384
+		if ($field) {
4385
+			return $field->get_qualified_column();
4386
+		}
4387
+		throw new EE_Error(
4388
+			sprintf(
4389
+				__(
4390
+					"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.",
4391
+					'event_espresso'
4392
+				), $field_name, get_class($this)
4393
+			)
4394
+		);
4395
+	}
4396
+
4397
+
4398
+
4399
+	/**
4400
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4401
+	 * Example usage:
4402
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4403
+	 *      array(),
4404
+	 *      ARRAY_A,
4405
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4406
+	 *  );
4407
+	 * is equivalent to
4408
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4409
+	 * and
4410
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4411
+	 *      array(
4412
+	 *          array(
4413
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4414
+	 *          ),
4415
+	 *          ARRAY_A,
4416
+	 *          implode(
4417
+	 *              ', ',
4418
+	 *              array_merge(
4419
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4420
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4421
+	 *              )
4422
+	 *          )
4423
+	 *      )
4424
+	 *  );
4425
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4426
+	 *
4427
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4428
+	 *                                            and the one whose fields you are selecting for example: when querying
4429
+	 *                                            tickets model and selecting fields from the tickets model you would
4430
+	 *                                            leave this parameter empty, because no models are needed to join
4431
+	 *                                            between the queried model and the selected one. Likewise when
4432
+	 *                                            querying the datetime model and selecting fields from the tickets
4433
+	 *                                            model, it would also be left empty, because there is a direct
4434
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4435
+	 *                                            them together. However, when querying from the event model and
4436
+	 *                                            selecting fields from the ticket model, you should provide the string
4437
+	 *                                            'Datetime', indicating that the event model must first join to the
4438
+	 *                                            datetime model in order to find its relation to ticket model.
4439
+	 *                                            Also, when querying from the venue model and selecting fields from
4440
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4441
+	 *                                            indicating you need to join the venue model to the event model,
4442
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4443
+	 *                                            This string is used to deduce the prefix that gets added onto the
4444
+	 *                                            models' tables qualified columns
4445
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4446
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4447
+	 *                                            qualified column names
4448
+	 * @return array|string
4449
+	 */
4450
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4451
+	{
4452
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4453
+		$qualified_columns = array();
4454
+		foreach ($this->field_settings() as $field_name => $field) {
4455
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4456
+		}
4457
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4458
+	}
4459
+
4460
+
4461
+
4462
+	/**
4463
+	 * constructs the select use on special limit joins
4464
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4465
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4466
+	 * (as that is typically where the limits would be set).
4467
+	 *
4468
+	 * @param  string       $table_alias The table the select is being built for
4469
+	 * @param  mixed|string $limit       The limit for this select
4470
+	 * @return string                The final select join element for the query.
4471
+	 */
4472
+	public function _construct_limit_join_select($table_alias, $limit)
4473
+	{
4474
+		$SQL = '';
4475
+		foreach ($this->_tables as $table_obj) {
4476
+			if ($table_obj instanceof EE_Primary_Table) {
4477
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4478
+					? $table_obj->get_select_join_limit($limit)
4479
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4480
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4481
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4482
+					? $table_obj->get_select_join_limit_join($limit)
4483
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4484
+			}
4485
+		}
4486
+		return $SQL;
4487
+	}
4488
+
4489
+
4490
+
4491
+	/**
4492
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4493
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4494
+	 *
4495
+	 * @return string SQL
4496
+	 * @throws EE_Error
4497
+	 */
4498
+	public function _construct_internal_join()
4499
+	{
4500
+		$SQL = $this->_get_main_table()->get_table_sql();
4501
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4502
+		return $SQL;
4503
+	}
4504
+
4505
+
4506
+
4507
+	/**
4508
+	 * Constructs the SQL for joining all the tables on this model.
4509
+	 * Normally $alias should be the primary table's alias, but in cases where
4510
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4511
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4512
+	 * alias, this will construct SQL like:
4513
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4514
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4515
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4516
+	 *
4517
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4518
+	 * @return string
4519
+	 */
4520
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4521
+	{
4522
+		$SQL = '';
4523
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4524
+		foreach ($this->_tables as $table_obj) {
4525
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4526
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4527
+					//so we're joining to this table, meaning the table is already in
4528
+					//the FROM statement, BUT the primary table isn't. So we want
4529
+					//to add the inverse join sql
4530
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4531
+				} else {
4532
+					//just add a regular JOIN to this table from the primary table
4533
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4534
+				}
4535
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4536
+		}
4537
+		return $SQL;
4538
+	}
4539
+
4540
+
4541
+
4542
+	/**
4543
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4544
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4545
+	 * their data type (eg, '%s', '%d', etc)
4546
+	 *
4547
+	 * @return array
4548
+	 */
4549
+	public function _get_data_types()
4550
+	{
4551
+		$data_types = array();
4552
+		foreach ($this->field_settings() as $field_obj) {
4553
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4554
+			/** @var $field_obj EE_Model_Field_Base */
4555
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4556
+		}
4557
+		return $data_types;
4558
+	}
4559
+
4560
+
4561
+
4562
+	/**
4563
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4564
+	 *
4565
+	 * @param string $model_name
4566
+	 * @throws EE_Error
4567
+	 * @return EEM_Base
4568
+	 */
4569
+	public function get_related_model_obj($model_name)
4570
+	{
4571
+		$model_classname = "EEM_" . $model_name;
4572
+		if (! class_exists($model_classname)) {
4573
+			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",
4574
+				'event_espresso'), $model_name, $model_classname));
4575
+		}
4576
+		return call_user_func($model_classname . "::instance");
4577
+	}
4578
+
4579
+
4580
+
4581
+	/**
4582
+	 * Returns the array of EE_ModelRelations for this model.
4583
+	 *
4584
+	 * @return EE_Model_Relation_Base[]
4585
+	 */
4586
+	public function relation_settings()
4587
+	{
4588
+		return $this->_model_relations;
4589
+	}
4590
+
4591
+
4592
+
4593
+	/**
4594
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4595
+	 * because without THOSE models, this model probably doesn't have much purpose.
4596
+	 * (Eg, without an event, datetimes have little purpose.)
4597
+	 *
4598
+	 * @return EE_Belongs_To_Relation[]
4599
+	 */
4600
+	public function belongs_to_relations()
4601
+	{
4602
+		$belongs_to_relations = array();
4603
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4604
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4605
+				$belongs_to_relations[$model_name] = $relation_obj;
4606
+			}
4607
+		}
4608
+		return $belongs_to_relations;
4609
+	}
4610
+
4611
+
4612
+
4613
+	/**
4614
+	 * Returns the specified EE_Model_Relation, or throws an exception
4615
+	 *
4616
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4617
+	 * @throws EE_Error
4618
+	 * @return EE_Model_Relation_Base
4619
+	 */
4620
+	public function related_settings_for($relation_name)
4621
+	{
4622
+		$relatedModels = $this->relation_settings();
4623
+		if (! array_key_exists($relation_name, $relatedModels)) {
4624
+			throw new EE_Error(
4625
+				sprintf(
4626
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4627
+						'event_espresso'),
4628
+					$relation_name,
4629
+					$this->_get_class_name(),
4630
+					implode(', ', array_keys($relatedModels))
4631
+				)
4632
+			);
4633
+		}
4634
+		return $relatedModels[$relation_name];
4635
+	}
4636
+
4637
+
4638
+
4639
+	/**
4640
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4641
+	 * fields
4642
+	 *
4643
+	 * @param string $fieldName
4644
+	 * @throws EE_Error
4645
+	 * @return EE_Model_Field_Base
4646
+	 */
4647
+	public function field_settings_for($fieldName)
4648
+	{
4649
+		$fieldSettings = $this->field_settings(true);
4650
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4651
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4652
+				get_class($this)));
4653
+		}
4654
+		return $fieldSettings[$fieldName];
4655
+	}
4656
+
4657
+
4658
+
4659
+	/**
4660
+	 * Checks if this field exists on this model
4661
+	 *
4662
+	 * @param string $fieldName a key in the model's _field_settings array
4663
+	 * @return boolean
4664
+	 */
4665
+	public function has_field($fieldName)
4666
+	{
4667
+		$fieldSettings = $this->field_settings(true);
4668
+		if (isset($fieldSettings[$fieldName])) {
4669
+			return true;
4670
+		}
4671
+		return false;
4672
+	}
4673
+
4674
+
4675
+
4676
+	/**
4677
+	 * Returns whether or not this model has a relation to the specified model
4678
+	 *
4679
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4680
+	 * @return boolean
4681
+	 */
4682
+	public function has_relation($relation_name)
4683
+	{
4684
+		$relations = $this->relation_settings();
4685
+		if (isset($relations[$relation_name])) {
4686
+			return true;
4687
+		}
4688
+		return false;
4689
+	}
4690
+
4691
+
4692
+
4693
+	/**
4694
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4695
+	 * Eg, on EE_Answer that would be ANS_ID field object
4696
+	 *
4697
+	 * @param $field_obj
4698
+	 * @return boolean
4699
+	 */
4700
+	public function is_primary_key_field($field_obj)
4701
+	{
4702
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4703
+	}
4704
+
4705
+
4706
+
4707
+	/**
4708
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4709
+	 * Eg, on EE_Answer that would be ANS_ID field object
4710
+	 *
4711
+	 * @return EE_Model_Field_Base
4712
+	 * @throws EE_Error
4713
+	 */
4714
+	public function get_primary_key_field()
4715
+	{
4716
+		if ($this->_primary_key_field === null) {
4717
+			foreach ($this->field_settings(true) as $field_obj) {
4718
+				if ($this->is_primary_key_field($field_obj)) {
4719
+					$this->_primary_key_field = $field_obj;
4720
+					break;
4721
+				}
4722
+			}
4723
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4724
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4725
+					get_class($this)));
4726
+			}
4727
+		}
4728
+		return $this->_primary_key_field;
4729
+	}
4730
+
4731
+
4732
+
4733
+	/**
4734
+	 * Returns whether or not not there is a primary key on this model.
4735
+	 * Internally does some caching.
4736
+	 *
4737
+	 * @return boolean
4738
+	 */
4739
+	public function has_primary_key_field()
4740
+	{
4741
+		if ($this->_has_primary_key_field === null) {
4742
+			try {
4743
+				$this->get_primary_key_field();
4744
+				$this->_has_primary_key_field = true;
4745
+			} catch (EE_Error $e) {
4746
+				$this->_has_primary_key_field = false;
4747
+			}
4748
+		}
4749
+		return $this->_has_primary_key_field;
4750
+	}
4751
+
4752
+
4753
+
4754
+	/**
4755
+	 * Finds the first field of type $field_class_name.
4756
+	 *
4757
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4758
+	 *                                 EE_Foreign_Key_Field, etc
4759
+	 * @return EE_Model_Field_Base or null if none is found
4760
+	 */
4761
+	public function get_a_field_of_type($field_class_name)
4762
+	{
4763
+		foreach ($this->field_settings() as $field) {
4764
+			if ($field instanceof $field_class_name) {
4765
+				return $field;
4766
+			}
4767
+		}
4768
+		return null;
4769
+	}
4770
+
4771
+
4772
+
4773
+	/**
4774
+	 * Gets a foreign key field pointing to model.
4775
+	 *
4776
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4777
+	 * @return EE_Foreign_Key_Field_Base
4778
+	 * @throws EE_Error
4779
+	 */
4780
+	public function get_foreign_key_to($model_name)
4781
+	{
4782
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4783
+			foreach ($this->field_settings() as $field) {
4784
+				if (
4785
+					$field instanceof EE_Foreign_Key_Field_Base
4786
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4787
+				) {
4788
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4789
+					break;
4790
+				}
4791
+			}
4792
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4793
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4794
+					'event_espresso'), $model_name, get_class($this)));
4795
+			}
4796
+		}
4797
+		return $this->_cache_foreign_key_to_fields[$model_name];
4798
+	}
4799
+
4800
+
4801
+
4802
+	/**
4803
+	 * Gets the actual table for the table alias
4804
+	 *
4805
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4806
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4807
+	 *                            Either one works
4808
+	 * @return EE_Table_Base
4809
+	 */
4810
+	public function get_table_for_alias($table_alias)
4811
+	{
4812
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4813
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4814
+	}
4815
+
4816
+
4817
+
4818
+	/**
4819
+	 * Returns a flat array of all field son this model, instead of organizing them
4820
+	 * by table_alias as they are in the constructor.
4821
+	 *
4822
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4823
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4824
+	 */
4825
+	public function field_settings($include_db_only_fields = false)
4826
+	{
4827
+		if ($include_db_only_fields) {
4828
+			if ($this->_cached_fields === null) {
4829
+				$this->_cached_fields = array();
4830
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4831
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4832
+						$this->_cached_fields[$field_name] = $field_obj;
4833
+					}
4834
+				}
4835
+			}
4836
+			return $this->_cached_fields;
4837
+		}
4838
+		if ($this->_cached_fields_non_db_only === null) {
4839
+			$this->_cached_fields_non_db_only = array();
4840
+			foreach ($this->_fields as $fields_corresponding_to_table) {
4841
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4842
+					/** @var $field_obj EE_Model_Field_Base */
4843
+					if (! $field_obj->is_db_only_field()) {
4844
+						$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4845
+					}
4846
+				}
4847
+			}
4848
+		}
4849
+		return $this->_cached_fields_non_db_only;
4850
+	}
4851
+
4852
+
4853
+
4854
+	/**
4855
+	 *        cycle though array of attendees and create objects out of each item
4856
+	 *
4857
+	 * @access        private
4858
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4859
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4860
+	 *                           numerically indexed)
4861
+	 * @throws EE_Error
4862
+	 */
4863
+	protected function _create_objects($rows = array())
4864
+	{
4865
+		$array_of_objects = array();
4866
+		if (empty($rows)) {
4867
+			return array();
4868
+		}
4869
+		$count_if_model_has_no_primary_key = 0;
4870
+		$has_primary_key = $this->has_primary_key_field();
4871
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4872
+		foreach ((array)$rows as $row) {
4873
+			if (empty($row)) {
4874
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4875
+				return array();
4876
+			}
4877
+			//check if we've already set this object in the results array,
4878
+			//in which case there's no need to process it further (again)
4879
+			if ($has_primary_key) {
4880
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4881
+					$row,
4882
+					$primary_key_field->get_qualified_column(),
4883
+					$primary_key_field->get_table_column()
4884
+				);
4885
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4886
+					continue;
4887
+				}
4888
+			}
4889
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4890
+			if (! $classInstance) {
4891
+				throw new EE_Error(
4892
+					sprintf(
4893
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4894
+						$this->get_this_model_name(),
4895
+						http_build_query($row)
4896
+					)
4897
+				);
4898
+			}
4899
+			//set the timezone on the instantiated objects
4900
+			$classInstance->set_timezone($this->_timezone);
4901
+			//make sure if there is any timezone setting present that we set the timezone for the object
4902
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4903
+			$array_of_objects[$key] = $classInstance;
4904
+			//also, for all the relations of type BelongsTo, see if we can cache
4905
+			//those related models
4906
+			//(we could do this for other relations too, but if there are conditions
4907
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4908
+			//so it requires a little more thought than just caching them immediately...)
4909
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4910
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4911
+					//check if this model's INFO is present. If so, cache it on the model
4912
+					$other_model = $relation_obj->get_other_model();
4913
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4914
+					//if we managed to make a model object from the results, cache it on the main model object
4915
+					if ($other_model_obj_maybe) {
4916
+						//set timezone on these other model objects if they are present
4917
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4918
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4919
+					}
4920
+				}
4921
+			}
4922
+		}
4923
+		return $array_of_objects;
4924
+	}
4925
+
4926
+
4927
+
4928
+	/**
4929
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4930
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4931
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4932
+	 * object (as set in the model_field!).
4933
+	 *
4934
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4935
+	 */
4936
+	public function create_default_object()
4937
+	{
4938
+		$this_model_fields_and_values = array();
4939
+		//setup the row using default values;
4940
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4941
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4942
+		}
4943
+		$className = $this->_get_class_name();
4944
+		$classInstance = EE_Registry::instance()
4945
+									->load_class($className, array($this_model_fields_and_values), false, false);
4946
+		return $classInstance;
4947
+	}
4948
+
4949
+
4950
+
4951
+	/**
4952
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4953
+	 *                             or an stdClass where each property is the name of a column,
4954
+	 * @return EE_Base_Class
4955
+	 * @throws EE_Error
4956
+	 */
4957
+	public function instantiate_class_from_array_or_object($cols_n_values)
4958
+	{
4959
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4960
+			$cols_n_values = get_object_vars($cols_n_values);
4961
+		}
4962
+		$primary_key = null;
4963
+		//make sure the array only has keys that are fields/columns on this model
4964
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4965
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4966
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4967
+		}
4968
+		$className = $this->_get_class_name();
4969
+		//check we actually found results that we can use to build our model object
4970
+		//if not, return null
4971
+		if ($this->has_primary_key_field()) {
4972
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4973
+				return null;
4974
+			}
4975
+		} else if ($this->unique_indexes()) {
4976
+			$first_column = reset($this_model_fields_n_values);
4977
+			if (empty($first_column)) {
4978
+				return null;
4979
+			}
4980
+		}
4981
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4982
+		if ($primary_key) {
4983
+			$classInstance = $this->get_from_entity_map($primary_key);
4984
+			if (! $classInstance) {
4985
+				$classInstance = EE_Registry::instance()
4986
+											->load_class($className,
4987
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4988
+				// add this new object to the entity map
4989
+				$classInstance = $this->add_to_entity_map($classInstance);
4990
+			}
4991
+		} else {
4992
+			$classInstance = EE_Registry::instance()
4993
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4994
+											true, false);
4995
+		}
4996
+		//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.
4997
+		$this->set_timezone($classInstance->get_timezone());
4998
+		return $classInstance;
4999
+	}
5000
+
5001
+
5002
+
5003
+	/**
5004
+	 * Gets the model object from the  entity map if it exists
5005
+	 *
5006
+	 * @param int|string $id the ID of the model object
5007
+	 * @return EE_Base_Class
5008
+	 */
5009
+	public function get_from_entity_map($id)
5010
+	{
5011
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5012
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5013
+	}
5014
+
5015
+
5016
+
5017
+	/**
5018
+	 * add_to_entity_map
5019
+	 * Adds the object to the model's entity mappings
5020
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5021
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5022
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5023
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5024
+	 *        then this method should be called immediately after the update query
5025
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5026
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5027
+	 *
5028
+	 * @param    EE_Base_Class $object
5029
+	 * @throws EE_Error
5030
+	 * @return \EE_Base_Class
5031
+	 */
5032
+	public function add_to_entity_map(EE_Base_Class $object)
5033
+	{
5034
+		$className = $this->_get_class_name();
5035
+		if (! $object instanceof $className) {
5036
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5037
+				is_object($object) ? get_class($object) : $object, $className));
5038
+		}
5039
+		/** @var $object EE_Base_Class */
5040
+		if (! $object->ID()) {
5041
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5042
+				"event_espresso"), get_class($this)));
5043
+		}
5044
+		// double check it's not already there
5045
+		$classInstance = $this->get_from_entity_map($object->ID());
5046
+		if ($classInstance) {
5047
+			return $classInstance;
5048
+		}
5049
+		$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5050
+		return $object;
5051
+	}
5052
+
5053
+
5054
+
5055
+	/**
5056
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5057
+	 * if no identifier is provided, then the entire entity map is emptied
5058
+	 *
5059
+	 * @param int|string $id the ID of the model object
5060
+	 * @return boolean
5061
+	 */
5062
+	public function clear_entity_map($id = null)
5063
+	{
5064
+		if (empty($id)) {
5065
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5066
+			return true;
5067
+		}
5068
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5069
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5070
+			return true;
5071
+		}
5072
+		return false;
5073
+	}
5074
+
5075
+
5076
+
5077
+	/**
5078
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5079
+	 * Given an array where keys are column (or column alias) names and values,
5080
+	 * returns an array of their corresponding field names and database values
5081
+	 *
5082
+	 * @param array $cols_n_values
5083
+	 * @return array
5084
+	 */
5085
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5086
+	{
5087
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5088
+	}
5089
+
5090
+
5091
+
5092
+	/**
5093
+	 * _deduce_fields_n_values_from_cols_n_values
5094
+	 * Given an array where keys are column (or column alias) names and values,
5095
+	 * returns an array of their corresponding field names and database values
5096
+	 *
5097
+	 * @param string $cols_n_values
5098
+	 * @return array
5099
+	 */
5100
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5101
+	{
5102
+		$this_model_fields_n_values = array();
5103
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5104
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5105
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5106
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5107
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5108
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5109
+					if (! $field_obj->is_db_only_field()) {
5110
+						//prepare field as if its coming from db
5111
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5112
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5113
+					}
5114
+				}
5115
+			} else {
5116
+				//the table's rows existed. Use their values
5117
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5118
+					if (! $field_obj->is_db_only_field()) {
5119
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5120
+							$cols_n_values, $field_obj->get_qualified_column(),
5121
+							$field_obj->get_table_column()
5122
+						);
5123
+					}
5124
+				}
5125
+			}
5126
+		}
5127
+		return $this_model_fields_n_values;
5128
+	}
5129
+
5130
+
5131
+
5132
+	/**
5133
+	 * @param $cols_n_values
5134
+	 * @param $qualified_column
5135
+	 * @param $regular_column
5136
+	 * @return null
5137
+	 */
5138
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5139
+	{
5140
+		$value = null;
5141
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5142
+		//does the field on the model relate to this column retrieved from the db?
5143
+		//or is it a db-only field? (not relating to the model)
5144
+		if (isset($cols_n_values[$qualified_column])) {
5145
+			$value = $cols_n_values[$qualified_column];
5146
+		} elseif (isset($cols_n_values[$regular_column])) {
5147
+			$value = $cols_n_values[$regular_column];
5148
+		}
5149
+		return $value;
5150
+	}
5151
+
5152
+
5153
+
5154
+	/**
5155
+	 * refresh_entity_map_from_db
5156
+	 * Makes sure the model object in the entity map at $id assumes the values
5157
+	 * of the database (opposite of EE_base_Class::save())
5158
+	 *
5159
+	 * @param int|string $id
5160
+	 * @return EE_Base_Class
5161
+	 * @throws EE_Error
5162
+	 */
5163
+	public function refresh_entity_map_from_db($id)
5164
+	{
5165
+		$obj_in_map = $this->get_from_entity_map($id);
5166
+		if ($obj_in_map) {
5167
+			$wpdb_results = $this->_get_all_wpdb_results(
5168
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5169
+			);
5170
+			if ($wpdb_results && is_array($wpdb_results)) {
5171
+				$one_row = reset($wpdb_results);
5172
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5173
+					$obj_in_map->set_from_db($field_name, $db_value);
5174
+				}
5175
+				//clear the cache of related model objects
5176
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5177
+					$obj_in_map->clear_cache($relation_name, null, true);
5178
+				}
5179
+			}
5180
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5181
+			return $obj_in_map;
5182
+		}
5183
+		return $this->get_one_by_ID($id);
5184
+	}
5185
+
5186
+
5187
+
5188
+	/**
5189
+	 * refresh_entity_map_with
5190
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5191
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5192
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5193
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5194
+	 *
5195
+	 * @param int|string    $id
5196
+	 * @param EE_Base_Class $replacing_model_obj
5197
+	 * @return \EE_Base_Class
5198
+	 * @throws EE_Error
5199
+	 */
5200
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5201
+	{
5202
+		$obj_in_map = $this->get_from_entity_map($id);
5203
+		if ($obj_in_map) {
5204
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5205
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5206
+					$obj_in_map->set($field_name, $value);
5207
+				}
5208
+				//make the model object in the entity map's cache match the $replacing_model_obj
5209
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5210
+					$obj_in_map->clear_cache($relation_name, null, true);
5211
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5212
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5213
+					}
5214
+				}
5215
+			}
5216
+			return $obj_in_map;
5217
+		}
5218
+		$this->add_to_entity_map($replacing_model_obj);
5219
+		return $replacing_model_obj;
5220
+	}
5221
+
5222
+
5223
+
5224
+	/**
5225
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5226
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5227
+	 * require_once($this->_getClassName().".class.php");
5228
+	 *
5229
+	 * @return string
5230
+	 */
5231
+	private function _get_class_name()
5232
+	{
5233
+		return "EE_" . $this->get_this_model_name();
5234
+	}
5235
+
5236
+
5237
+
5238
+	/**
5239
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5240
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5241
+	 * it would be 'Events'.
5242
+	 *
5243
+	 * @param int $quantity
5244
+	 * @return string
5245
+	 */
5246
+	public function item_name($quantity = 1)
5247
+	{
5248
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5249
+	}
5250
+
5251
+
5252
+
5253
+	/**
5254
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5255
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5256
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5257
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5258
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5259
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5260
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5261
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5262
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5263
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5264
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5265
+	 *        return $previousReturnValue.$returnString;
5266
+	 * }
5267
+	 * require('EEM_Answer.model.php');
5268
+	 * $answer=EEM_Answer::instance();
5269
+	 * echo $answer->my_callback('monkeys',100);
5270
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5271
+	 *
5272
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5273
+	 * @param array  $args       array of original arguments passed to the function
5274
+	 * @throws EE_Error
5275
+	 * @return mixed whatever the plugin which calls add_filter decides
5276
+	 */
5277
+	public function __call($methodName, $args)
5278
+	{
5279
+		$className = get_class($this);
5280
+		$tagName = "FHEE__{$className}__{$methodName}";
5281
+		if (! has_filter($tagName)) {
5282
+			throw new EE_Error(
5283
+				sprintf(
5284
+					__('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 );',
5285
+						'event_espresso'),
5286
+					$methodName,
5287
+					$className,
5288
+					$tagName,
5289
+					'<br />'
5290
+				)
5291
+			);
5292
+		}
5293
+		return apply_filters($tagName, null, $this, $args);
5294
+	}
5295
+
5296
+
5297
+
5298
+	/**
5299
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5300
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5301
+	 *
5302
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5303
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5304
+	 *                                                       the object's class name
5305
+	 *                                                       or object's ID
5306
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5307
+	 *                                                       exists in the database. If it does not, we add it
5308
+	 * @throws EE_Error
5309
+	 * @return EE_Base_Class
5310
+	 */
5311
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5312
+	{
5313
+		$className = $this->_get_class_name();
5314
+		if ($base_class_obj_or_id instanceof $className) {
5315
+			$model_object = $base_class_obj_or_id;
5316
+		} else {
5317
+			$primary_key_field = $this->get_primary_key_field();
5318
+			if (
5319
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5320
+				&& (
5321
+					is_int($base_class_obj_or_id)
5322
+					|| is_string($base_class_obj_or_id)
5323
+				)
5324
+			) {
5325
+				// assume it's an ID.
5326
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5327
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5328
+			} else if (
5329
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5330
+				&& is_string($base_class_obj_or_id)
5331
+			) {
5332
+				// assume its a string representation of the object
5333
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5334
+			} else {
5335
+				throw new EE_Error(
5336
+					sprintf(
5337
+						__(
5338
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5339
+							'event_espresso'
5340
+						),
5341
+						$base_class_obj_or_id,
5342
+						$this->_get_class_name(),
5343
+						print_r($base_class_obj_or_id, true)
5344
+					)
5345
+				);
5346
+			}
5347
+		}
5348
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5349
+			$model_object->save();
5350
+		}
5351
+		return $model_object;
5352
+	}
5353
+
5354
+
5355
+
5356
+	/**
5357
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5358
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5359
+	 * returns it ID.
5360
+	 *
5361
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5362
+	 * @return int|string depending on the type of this model object's ID
5363
+	 * @throws EE_Error
5364
+	 */
5365
+	public function ensure_is_ID($base_class_obj_or_id)
5366
+	{
5367
+		$className = $this->_get_class_name();
5368
+		if ($base_class_obj_or_id instanceof $className) {
5369
+			/** @var $base_class_obj_or_id EE_Base_Class */
5370
+			$id = $base_class_obj_or_id->ID();
5371
+		} elseif (is_int($base_class_obj_or_id)) {
5372
+			//assume it's an ID
5373
+			$id = $base_class_obj_or_id;
5374
+		} elseif (is_string($base_class_obj_or_id)) {
5375
+			//assume its a string representation of the object
5376
+			$id = $base_class_obj_or_id;
5377
+		} else {
5378
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5379
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5380
+				print_r($base_class_obj_or_id, true)));
5381
+		}
5382
+		return $id;
5383
+	}
5384
+
5385
+
5386
+
5387
+	/**
5388
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5389
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5390
+	 * been sanitized and converted into the appropriate domain.
5391
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5392
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5393
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5394
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5395
+	 * $EVT = EEM_Event::instance(); $old_setting =
5396
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5397
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5398
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5399
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5400
+	 *
5401
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5402
+	 * @return void
5403
+	 */
5404
+	public function assume_values_already_prepared_by_model_object(
5405
+		$values_already_prepared = self::not_prepared_by_model_object
5406
+	) {
5407
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5408
+	}
5409
+
5410
+
5411
+
5412
+	/**
5413
+	 * Read comments for assume_values_already_prepared_by_model_object()
5414
+	 *
5415
+	 * @return int
5416
+	 */
5417
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5418
+	{
5419
+		return $this->_values_already_prepared_by_model_object;
5420
+	}
5421
+
5422
+
5423
+
5424
+	/**
5425
+	 * Gets all the indexes on this model
5426
+	 *
5427
+	 * @return EE_Index[]
5428
+	 */
5429
+	public function indexes()
5430
+	{
5431
+		return $this->_indexes;
5432
+	}
5433
+
5434
+
5435
+
5436
+	/**
5437
+	 * Gets all the Unique Indexes on this model
5438
+	 *
5439
+	 * @return EE_Unique_Index[]
5440
+	 */
5441
+	public function unique_indexes()
5442
+	{
5443
+		$unique_indexes = array();
5444
+		foreach ($this->_indexes as $name => $index) {
5445
+			if ($index instanceof EE_Unique_Index) {
5446
+				$unique_indexes [$name] = $index;
5447
+			}
5448
+		}
5449
+		return $unique_indexes;
5450
+	}
5451
+
5452
+
5453
+
5454
+	/**
5455
+	 * Gets all the fields which, when combined, make the primary key.
5456
+	 * This is usually just an array with 1 element (the primary key), but in cases
5457
+	 * where there is no primary key, it's a combination of fields as defined
5458
+	 * on a primary index
5459
+	 *
5460
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5461
+	 * @throws EE_Error
5462
+	 */
5463
+	public function get_combined_primary_key_fields()
5464
+	{
5465
+		foreach ($this->indexes() as $index) {
5466
+			if ($index instanceof EE_Primary_Key_Index) {
5467
+				return $index->fields();
5468
+			}
5469
+		}
5470
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5471
+	}
5472
+
5473
+
5474
+
5475
+	/**
5476
+	 * Used to build a primary key string (when the model has no primary key),
5477
+	 * which can be used a unique string to identify this model object.
5478
+	 *
5479
+	 * @param array $cols_n_values keys are field names, values are their values
5480
+	 * @return string
5481
+	 * @throws EE_Error
5482
+	 */
5483
+	public function get_index_primary_key_string($cols_n_values)
5484
+	{
5485
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5486
+			$this->get_combined_primary_key_fields());
5487
+		return http_build_query($cols_n_values_for_primary_key_index);
5488
+	}
5489
+
5490
+
5491
+
5492
+	/**
5493
+	 * Gets the field values from the primary key string
5494
+	 *
5495
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5496
+	 * @param string $index_primary_key_string
5497
+	 * @return null|array
5498
+	 * @throws EE_Error
5499
+	 */
5500
+	public function parse_index_primary_key_string($index_primary_key_string)
5501
+	{
5502
+		$key_fields = $this->get_combined_primary_key_fields();
5503
+		//check all of them are in the $id
5504
+		$key_vals_in_combined_pk = array();
5505
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5506
+		foreach ($key_fields as $key_field_name => $field_obj) {
5507
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5508
+				return null;
5509
+			}
5510
+		}
5511
+		return $key_vals_in_combined_pk;
5512
+	}
5513
+
5514
+
5515
+
5516
+	/**
5517
+	 * verifies that an array of key-value pairs for model fields has a key
5518
+	 * for each field comprising the primary key index
5519
+	 *
5520
+	 * @param array $key_vals
5521
+	 * @return boolean
5522
+	 * @throws EE_Error
5523
+	 */
5524
+	public function has_all_combined_primary_key_fields($key_vals)
5525
+	{
5526
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5527
+		foreach ($keys_it_should_have as $key) {
5528
+			if (! isset($key_vals[$key])) {
5529
+				return false;
5530
+			}
5531
+		}
5532
+		return true;
5533
+	}
5534
+
5535
+
5536
+
5537
+	/**
5538
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5539
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5540
+	 *
5541
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5542
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5543
+	 * @throws EE_Error
5544
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5545
+	 *                                                              indexed)
5546
+	 */
5547
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5548
+	{
5549
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5550
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5551
+		} elseif (is_array($model_object_or_attributes_array)) {
5552
+			$attributes_array = $model_object_or_attributes_array;
5553
+		} else {
5554
+			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",
5555
+				"event_espresso"), $model_object_or_attributes_array));
5556
+		}
5557
+		//even copies obviously won't have the same ID, so remove the primary key
5558
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5559
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5560
+			unset($attributes_array[$this->primary_key_name()]);
5561
+		}
5562
+		if (isset($query_params[0])) {
5563
+			$query_params[0] = array_merge($attributes_array, $query_params);
5564
+		} else {
5565
+			$query_params[0] = $attributes_array;
5566
+		}
5567
+		return $this->get_all($query_params);
5568
+	}
5569
+
5570
+
5571
+
5572
+	/**
5573
+	 * Gets the first copy we find. See get_all_copies for more details
5574
+	 *
5575
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5576
+	 * @param array $query_params
5577
+	 * @return EE_Base_Class
5578
+	 * @throws EE_Error
5579
+	 */
5580
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5581
+	{
5582
+		if (! is_array($query_params)) {
5583
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5584
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5585
+					gettype($query_params)), '4.6.0');
5586
+			$query_params = array();
5587
+		}
5588
+		$query_params['limit'] = 1;
5589
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5590
+		if (is_array($copies)) {
5591
+			return array_shift($copies);
5592
+		}
5593
+		return null;
5594
+	}
5595
+
5596
+
5597
+
5598
+	/**
5599
+	 * Updates the item with the specified id. Ignores default query parameters because
5600
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5601
+	 *
5602
+	 * @param array      $fields_n_values keys are field names, values are their new values
5603
+	 * @param int|string $id              the value of the primary key to update
5604
+	 * @return int number of rows updated
5605
+	 * @throws EE_Error
5606
+	 */
5607
+	public function update_by_ID($fields_n_values, $id)
5608
+	{
5609
+		$query_params = array(
5610
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5611
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5612
+		);
5613
+		return $this->update($fields_n_values, $query_params);
5614
+	}
5615
+
5616
+
5617
+
5618
+	/**
5619
+	 * Changes an operator which was supplied to the models into one usable in SQL
5620
+	 *
5621
+	 * @param string $operator_supplied
5622
+	 * @return string an operator which can be used in SQL
5623
+	 * @throws EE_Error
5624
+	 */
5625
+	private function _prepare_operator_for_sql($operator_supplied)
5626
+	{
5627
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5628
+			: null;
5629
+		if ($sql_operator) {
5630
+			return $sql_operator;
5631
+		}
5632
+		throw new EE_Error(
5633
+			sprintf(
5634
+				__(
5635
+					"The operator '%s' is not in the list of valid operators: %s",
5636
+					"event_espresso"
5637
+				), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5638
+			)
5639
+		);
5640
+	}
5641
+
5642
+
5643
+
5644
+	/**
5645
+	 * Gets an array where keys are the primary keys and values are their 'names'
5646
+	 * (as determined by the model object's name() function, which is often overridden)
5647
+	 *
5648
+	 * @param array $query_params like get_all's
5649
+	 * @return string[]
5650
+	 * @throws EE_Error
5651
+	 */
5652
+	public function get_all_names($query_params = array())
5653
+	{
5654
+		$objs = $this->get_all($query_params);
5655
+		$names = array();
5656
+		foreach ($objs as $obj) {
5657
+			$names[$obj->ID()] = $obj->name();
5658
+		}
5659
+		return $names;
5660
+	}
5661
+
5662
+
5663
+
5664
+	/**
5665
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5666
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5667
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5668
+	 * array_keys() on $model_objects.
5669
+	 *
5670
+	 * @param \EE_Base_Class[] $model_objects
5671
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5672
+	 *                                               in the returned array
5673
+	 * @return array
5674
+	 * @throws EE_Error
5675
+	 */
5676
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5677
+	{
5678
+		if (! $this->has_primary_key_field()) {
5679
+			if (WP_DEBUG) {
5680
+				EE_Error::add_error(
5681
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5682
+					__FILE__,
5683
+					__FUNCTION__,
5684
+					__LINE__
5685
+				);
5686
+			}
5687
+		}
5688
+		$IDs = array();
5689
+		foreach ($model_objects as $model_object) {
5690
+			$id = $model_object->ID();
5691
+			if (! $id) {
5692
+				if ($filter_out_empty_ids) {
5693
+					continue;
5694
+				}
5695
+				if (WP_DEBUG) {
5696
+					EE_Error::add_error(
5697
+						__(
5698
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5699
+							'event_espresso'
5700
+						),
5701
+						__FILE__,
5702
+						__FUNCTION__,
5703
+						__LINE__
5704
+					);
5705
+				}
5706
+			}
5707
+			$IDs[] = $id;
5708
+		}
5709
+		return $IDs;
5710
+	}
5711
+
5712
+
5713
+
5714
+	/**
5715
+	 * Returns the string used in capabilities relating to this model. If there
5716
+	 * are no capabilities that relate to this model returns false
5717
+	 *
5718
+	 * @return string|false
5719
+	 */
5720
+	public function cap_slug()
5721
+	{
5722
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5723
+	}
5724
+
5725
+
5726
+
5727
+	/**
5728
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5729
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5730
+	 * only returns the cap restrictions array in that context (ie, the array
5731
+	 * at that key)
5732
+	 *
5733
+	 * @param string $context
5734
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5735
+	 * @throws EE_Error
5736
+	 */
5737
+	public function cap_restrictions($context = EEM_Base::caps_read)
5738
+	{
5739
+		EEM_Base::verify_is_valid_cap_context($context);
5740
+		//check if we ought to run the restriction generator first
5741
+		if (
5742
+			isset($this->_cap_restriction_generators[$context])
5743
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5744
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5745
+		) {
5746
+			$this->_cap_restrictions[$context] = array_merge(
5747
+				$this->_cap_restrictions[$context],
5748
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5749
+			);
5750
+		}
5751
+		//and make sure we've finalized the construction of each restriction
5752
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5753
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5754
+				$where_conditions_obj->_finalize_construct($this);
5755
+			}
5756
+		}
5757
+		return $this->_cap_restrictions[$context];
5758
+	}
5759
+
5760
+
5761
+
5762
+	/**
5763
+	 * Indicating whether or not this model thinks its a wp core model
5764
+	 *
5765
+	 * @return boolean
5766
+	 */
5767
+	public function is_wp_core_model()
5768
+	{
5769
+		return $this->_wp_core_model;
5770
+	}
5771
+
5772
+
5773
+
5774
+	/**
5775
+	 * Gets all the caps that are missing which impose a restriction on
5776
+	 * queries made in this context
5777
+	 *
5778
+	 * @param string $context one of EEM_Base::caps_ constants
5779
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5780
+	 * @throws EE_Error
5781
+	 */
5782
+	public function caps_missing($context = EEM_Base::caps_read)
5783
+	{
5784
+		$missing_caps = array();
5785
+		$cap_restrictions = $this->cap_restrictions($context);
5786
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5787
+			if (! EE_Capabilities::instance()
5788
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5789
+			) {
5790
+				$missing_caps[$cap] = $restriction_if_no_cap;
5791
+			}
5792
+		}
5793
+		return $missing_caps;
5794
+	}
5795
+
5796
+
5797
+
5798
+	/**
5799
+	 * Gets the mapping from capability contexts to action strings used in capability names
5800
+	 *
5801
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5802
+	 * one of 'read', 'edit', or 'delete'
5803
+	 */
5804
+	public function cap_contexts_to_cap_action_map()
5805
+	{
5806
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5807
+			$this);
5808
+	}
5809
+
5810
+
5811
+
5812
+	/**
5813
+	 * Gets the action string for the specified capability context
5814
+	 *
5815
+	 * @param string $context
5816
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5817
+	 * @throws EE_Error
5818
+	 */
5819
+	public function cap_action_for_context($context)
5820
+	{
5821
+		$mapping = $this->cap_contexts_to_cap_action_map();
5822
+		if (isset($mapping[$context])) {
5823
+			return $mapping[$context];
5824
+		}
5825
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5826
+			return $action;
5827
+		}
5828
+		throw new EE_Error(
5829
+			sprintf(
5830
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5831
+				$context,
5832
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5833
+			)
5834
+		);
5835
+	}
5836
+
5837
+
5838
+
5839
+	/**
5840
+	 * Returns all the capability contexts which are valid when querying models
5841
+	 *
5842
+	 * @return array
5843
+	 */
5844
+	public static function valid_cap_contexts()
5845
+	{
5846
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5847
+			self::caps_read,
5848
+			self::caps_read_admin,
5849
+			self::caps_edit,
5850
+			self::caps_delete,
5851
+		));
5852
+	}
5853
+
5854
+
5855
+
5856
+	/**
5857
+	 * Returns all valid options for 'default_where_conditions'
5858
+	 *
5859
+	 * @return array
5860
+	 */
5861
+	public static function valid_default_where_conditions()
5862
+	{
5863
+		return array(
5864
+			EEM_Base::default_where_conditions_all,
5865
+			EEM_Base::default_where_conditions_this_only,
5866
+			EEM_Base::default_where_conditions_others_only,
5867
+			EEM_Base::default_where_conditions_minimum_all,
5868
+			EEM_Base::default_where_conditions_minimum_others,
5869
+			EEM_Base::default_where_conditions_none
5870
+		);
5871
+	}
5872
+
5873
+	// public static function default_where_conditions_full
5874
+	/**
5875
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5876
+	 *
5877
+	 * @param string $context
5878
+	 * @return bool
5879
+	 * @throws EE_Error
5880
+	 */
5881
+	static public function verify_is_valid_cap_context($context)
5882
+	{
5883
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5884
+		if (in_array($context, $valid_cap_contexts)) {
5885
+			return true;
5886
+		}
5887
+		throw new EE_Error(
5888
+			sprintf(
5889
+				__(
5890
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5891
+					'event_espresso'
5892
+				),
5893
+				$context,
5894
+				'EEM_Base',
5895
+				implode(',', $valid_cap_contexts)
5896
+			)
5897
+		);
5898
+	}
5899
+
5900
+
5901
+
5902
+	/**
5903
+	 * Clears all the models field caches. This is only useful when a sub-class
5904
+	 * might have added a field or something and these caches might be invalidated
5905
+	 */
5906
+	protected function _invalidate_field_caches()
5907
+	{
5908
+		$this->_cache_foreign_key_to_fields = array();
5909
+		$this->_cached_fields = null;
5910
+		$this->_cached_fields_non_db_only = null;
5911
+	}
5912
+
5913
+
5914
+
5915
+	/**
5916
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5917
+	 * (eg "and", "or", "not").
5918
+	 *
5919
+	 * @return array
5920
+	 */
5921
+	public function logic_query_param_keys()
5922
+	{
5923
+		return $this->_logic_query_param_keys;
5924
+	}
5925
+
5926
+
5927
+
5928
+	/**
5929
+	 * Determines whether or not the where query param array key is for a logic query param.
5930
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
5931
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5932
+	 *
5933
+	 * @param $query_param_key
5934
+	 * @return bool
5935
+	 */
5936
+	public function is_logic_query_param_key($query_param_key)
5937
+	{
5938
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5939
+			if ($query_param_key === $logic_query_param_key
5940
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5941
+			) {
5942
+				return true;
5943
+			}
5944
+		}
5945
+		return false;
5946
+	}
5947 5947
 
5948 5948
 
5949 5949
 
Please login to merge, or discard this patch.
Spacing   +155 added lines, -155 removed lines patch added patch discarded remove patch
@@ -519,8 +519,8 @@  discard block
 block discarded – undo
519 519
     protected function __construct($timezone = null)
520 520
     {
521 521
         // check that the model has not been loaded too soon
522
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
523
-            throw new EE_Error (
522
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
523
+            throw new EE_Error(
524 524
                 sprintf(
525 525
                     __('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.',
526 526
                         'event_espresso'),
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
          *
541 541
          * @var EE_Table_Base[] $_tables
542 542
          */
543
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
543
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
544 544
         foreach ($this->_tables as $table_alias => $table_obj) {
545 545
             /** @var $table_obj EE_Table_Base */
546 546
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -555,10 +555,10 @@  discard block
 block discarded – undo
555 555
          *
556 556
          * @param EE_Model_Field_Base[] $_fields
557 557
          */
558
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
558
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
559 559
         $this->_invalidate_field_caches();
560 560
         foreach ($this->_fields as $table_alias => $fields_for_table) {
561
-            if (! array_key_exists($table_alias, $this->_tables)) {
561
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
562 562
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
563 563
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
564 564
             }
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
          *
587 587
          * @param EE_Model_Relation_Base[] $_model_relations
588 588
          */
589
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
589
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
590 590
             $this->_model_relations);
591 591
         foreach ($this->_model_relations as $model_name => $relation_obj) {
592 592
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -598,12 +598,12 @@  discard block
 block discarded – undo
598 598
         }
599 599
         $this->set_timezone($timezone);
600 600
         //finalize default where condition strategy, or set default
601
-        if (! $this->_default_where_conditions_strategy) {
601
+        if ( ! $this->_default_where_conditions_strategy) {
602 602
             //nothing was set during child constructor, so set default
603 603
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
604 604
         }
605 605
         $this->_default_where_conditions_strategy->_finalize_construct($this);
606
-        if (! $this->_minimum_where_conditions_strategy) {
606
+        if ( ! $this->_minimum_where_conditions_strategy) {
607 607
             //nothing was set during child constructor, so set default
608 608
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
609 609
         }
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
         //initialize the standard cap restriction generators if none were specified by the child constructor
617 617
         if ($this->_cap_restriction_generators !== false) {
618 618
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
619
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
619
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
620 620
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
621 621
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
622 622
                         new EE_Restriction_Generator_Protected(),
@@ -629,10 +629,10 @@  discard block
 block discarded – undo
629 629
         //if there are cap restriction generators, use them to make the default cap restrictions
630 630
         if ($this->_cap_restriction_generators !== false) {
631 631
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
632
-                if (! $generator_object) {
632
+                if ( ! $generator_object) {
633 633
                     continue;
634 634
                 }
635
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
635
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
636 636
                     throw new EE_Error(
637 637
                         sprintf(
638 638
                             __('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.',
@@ -643,12 +643,12 @@  discard block
 block discarded – undo
643 643
                     );
644 644
                 }
645 645
                 $action = $this->cap_action_for_context($context);
646
-                if (! $generator_object->construction_finalized()) {
646
+                if ( ! $generator_object->construction_finalized()) {
647 647
                     $generator_object->_construct_finalize($this, $action);
648 648
                 }
649 649
             }
650 650
         }
651
-        do_action('AHEE__' . get_class($this) . '__construct__end');
651
+        do_action('AHEE__'.get_class($this).'__construct__end');
652 652
     }
653 653
 
654 654
 
@@ -683,7 +683,7 @@  discard block
 block discarded – undo
683 683
      */
684 684
     public static function set_model_query_blog_id($blog_id = 0)
685 685
     {
686
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
686
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
687 687
     }
688 688
 
689 689
 
@@ -718,7 +718,7 @@  discard block
 block discarded – undo
718 718
     public static function instance($timezone = null, ModelFieldFactory $model_field_factory = null)
719 719
     {
720 720
         // check if instance of Espresso_model already exists
721
-        if (! static::$_instance instanceof static) {
721
+        if ( ! static::$_instance instanceof static) {
722 722
             $model_field_factory = self::getModelFieldFactory($model_field_factory);
723 723
             // instantiate Espresso_model
724 724
             static::$_instance = new static($timezone, $model_field_factory);
@@ -772,7 +772,7 @@  discard block
 block discarded – undo
772 772
             foreach ($r->getDefaultProperties() as $property => $value) {
773 773
                 //don't set instance to null like it was originally,
774 774
                 //but it's static anyways, and we're ignoring static properties (for now at least)
775
-                if (! isset($static_properties[$property])) {
775
+                if ( ! isset($static_properties[$property])) {
776 776
                     static::$_instance->{$property} = $value;
777 777
                 }
778 778
             }
@@ -795,7 +795,7 @@  discard block
 block discarded – undo
795 795
      */
796 796
     public function status_array($translated = false)
797 797
     {
798
-        if (! array_key_exists('Status', $this->_model_relations)) {
798
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
799 799
             return array();
800 800
         }
801 801
         $model_name = $this->get_this_model_name();
@@ -998,17 +998,17 @@  discard block
 block discarded – undo
998 998
     public function wp_user_field_name()
999 999
     {
1000 1000
         try {
1001
-            if (! empty($this->_model_chain_to_wp_user)) {
1001
+            if ( ! empty($this->_model_chain_to_wp_user)) {
1002 1002
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
1003 1003
                 $last_model_name = end($models_to_follow_to_wp_users);
1004 1004
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
1005
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
1005
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
1006 1006
             } else {
1007 1007
                 $model_with_fk_to_wp_users = $this;
1008 1008
                 $model_chain_to_wp_user = '';
1009 1009
             }
1010 1010
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
1011
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
1011
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
1012 1012
         } catch (EE_Error $e) {
1013 1013
             return false;
1014 1014
         }
@@ -1079,12 +1079,12 @@  discard block
 block discarded – undo
1079 1079
         // remember the custom selections, if any, and type cast as array
1080 1080
         // (unless $columns_to_select is an object, then just set as an empty array)
1081 1081
         // Note: (array) 'some string' === array( 'some string' )
1082
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1082
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1083 1083
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1084 1084
         $select_expressions = $columns_to_select !== null
1085 1085
             ? $this->_construct_select_from_input($columns_to_select)
1086 1086
             : $this->_construct_default_select_sql($model_query_info);
1087
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1087
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1088 1088
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1089 1089
     }
1090 1090
 
@@ -1129,7 +1129,7 @@  discard block
 block discarded – undo
1129 1129
         if (is_array($columns_to_select)) {
1130 1130
             $select_sql_array = array();
1131 1131
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1132
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1132
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1133 1133
                     throw new EE_Error(
1134 1134
                         sprintf(
1135 1135
                             __(
@@ -1141,7 +1141,7 @@  discard block
 block discarded – undo
1141 1141
                         )
1142 1142
                     );
1143 1143
                 }
1144
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1144
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1145 1145
                     throw new EE_Error(
1146 1146
                         sprintf(
1147 1147
                             __(
@@ -1213,7 +1213,7 @@  discard block
 block discarded – undo
1213 1213
      */
1214 1214
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1215 1215
     {
1216
-        if (! isset($query_params[0])) {
1216
+        if ( ! isset($query_params[0])) {
1217 1217
             $query_params[0] = array();
1218 1218
         }
1219 1219
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1238,7 +1238,7 @@  discard block
 block discarded – undo
1238 1238
      */
1239 1239
     public function get_one($query_params = array())
1240 1240
     {
1241
-        if (! is_array($query_params)) {
1241
+        if ( ! is_array($query_params)) {
1242 1242
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1243 1243
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1244 1244
                     gettype($query_params)), '4.6.0');
@@ -1429,7 +1429,7 @@  discard block
 block discarded – undo
1429 1429
                 return array();
1430 1430
             }
1431 1431
         }
1432
-        if (! is_array($query_params)) {
1432
+        if ( ! is_array($query_params)) {
1433 1433
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1434 1434
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1435 1435
                     gettype($query_params)), '4.6.0');
@@ -1439,7 +1439,7 @@  discard block
 block discarded – undo
1439 1439
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1440 1440
         $query_params['limit'] = $limit;
1441 1441
         //set direction
1442
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1442
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1443 1443
         $query_params['order_by'] = $operand === '>'
1444 1444
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1445 1445
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1517,7 +1517,7 @@  discard block
 block discarded – undo
1517 1517
     {
1518 1518
         $field_settings = $this->field_settings_for($field_name);
1519 1519
         //if not a valid EE_Datetime_Field then throw error
1520
-        if (! $field_settings instanceof EE_Datetime_Field) {
1520
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1521 1521
             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.',
1522 1522
                 'event_espresso'), $field_name));
1523 1523
         }
@@ -1596,7 +1596,7 @@  discard block
 block discarded – undo
1596 1596
         //load EEH_DTT_Helper
1597 1597
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1598 1598
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1599
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1599
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1600 1600
     }
1601 1601
 
1602 1602
 
@@ -1664,7 +1664,7 @@  discard block
 block discarded – undo
1664 1664
      */
1665 1665
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1666 1666
     {
1667
-        if (! is_array($query_params)) {
1667
+        if ( ! is_array($query_params)) {
1668 1668
             EE_Error::doing_it_wrong('EEM_Base::update',
1669 1669
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1670 1670
                     gettype($query_params)), '4.6.0');
@@ -1686,7 +1686,7 @@  discard block
 block discarded – undo
1686 1686
          * @param EEM_Base $model           the model being queried
1687 1687
          * @param array    $query_params    see EEM_Base::get_all()
1688 1688
          */
1689
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1689
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1690 1690
             $query_params);
1691 1691
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1692 1692
         //to do that, for each table, verify that it's PK isn't null.
@@ -1700,7 +1700,7 @@  discard block
 block discarded – undo
1700 1700
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1701 1701
         foreach ($wpdb_select_results as $wpdb_result) {
1702 1702
             // type cast stdClass as array
1703
-            $wpdb_result = (array)$wpdb_result;
1703
+            $wpdb_result = (array) $wpdb_result;
1704 1704
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1705 1705
             if ($this->has_primary_key_field()) {
1706 1706
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1717,13 +1717,13 @@  discard block
 block discarded – undo
1717 1717
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1718 1718
                     //if there is no private key for this table on the results, it means there's no entry
1719 1719
                     //in this table, right? so insert a row in the current table, using any fields available
1720
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1720
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1721 1721
                            && $wpdb_result[$this_table_pk_column])
1722 1722
                     ) {
1723 1723
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1724 1724
                             $main_table_pk_value);
1725 1725
                         //if we died here, report the error
1726
-                        if (! $success) {
1726
+                        if ( ! $success) {
1727 1727
                             return false;
1728 1728
                         }
1729 1729
                     }
@@ -1754,7 +1754,7 @@  discard block
 block discarded – undo
1754 1754
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1755 1755
                 }
1756 1756
             }
1757
-            if (! $model_objs_affected_ids) {
1757
+            if ( ! $model_objs_affected_ids) {
1758 1758
                 //wait wait wait- if nothing was affected let's stop here
1759 1759
                 return 0;
1760 1760
             }
@@ -1781,7 +1781,7 @@  discard block
 block discarded – undo
1781 1781
                . $model_query_info->get_full_join_sql()
1782 1782
                . " SET "
1783 1783
                . $this->_construct_update_sql($fields_n_values)
1784
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1784
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1785 1785
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1786 1786
         /**
1787 1787
          * Action called after a model update call has been made.
@@ -1792,7 +1792,7 @@  discard block
 block discarded – undo
1792 1792
          * @param int      $rows_affected
1793 1793
          */
1794 1794
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1795
-        return $rows_affected;//how many supposedly got updated
1795
+        return $rows_affected; //how many supposedly got updated
1796 1796
     }
1797 1797
 
1798 1798
 
@@ -1820,7 +1820,7 @@  discard block
 block discarded – undo
1820 1820
         }
1821 1821
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1822 1822
         $select_expressions = $field->get_qualified_column();
1823
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1823
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1824 1824
         return $this->_do_wpdb_query('get_col', array($SQL));
1825 1825
     }
1826 1826
 
@@ -1838,7 +1838,7 @@  discard block
 block discarded – undo
1838 1838
     {
1839 1839
         $query_params['limit'] = 1;
1840 1840
         $col = $this->get_col($query_params, $field_to_select);
1841
-        if (! empty($col)) {
1841
+        if ( ! empty($col)) {
1842 1842
             return reset($col);
1843 1843
         }
1844 1844
         return null;
@@ -1869,7 +1869,7 @@  discard block
 block discarded – undo
1869 1869
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1870 1870
             $value_sql = $prepared_value === null ? 'NULL'
1871 1871
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1872
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1872
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1873 1873
         }
1874 1874
         return implode(",", $cols_n_values);
1875 1875
     }
@@ -2001,7 +2001,7 @@  discard block
 block discarded – undo
2001 2001
          * @param int      $rows_deleted
2002 2002
          */
2003 2003
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
2004
-        return $rows_deleted;//how many supposedly got deleted
2004
+        return $rows_deleted; //how many supposedly got deleted
2005 2005
     }
2006 2006
 
2007 2007
 
@@ -2094,7 +2094,7 @@  discard block
 block discarded – undo
2094 2094
                     $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2095 2095
                 }
2096 2096
                 //other tables
2097
-                if (! empty($other_tables)) {
2097
+                if ( ! empty($other_tables)) {
2098 2098
                     foreach ($other_tables as $ot) {
2099 2099
                         //first check if we've got the foreign key column here.
2100 2100
                         if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
@@ -2117,7 +2117,7 @@  discard block
 block discarded – undo
2117 2117
             foreach ($deletes as $column => $values) {
2118 2118
                 //make sure we have unique $values;
2119 2119
                 $values = array_unique($values);
2120
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2120
+                $query[] = $column.' IN('.implode(",", $values).')';
2121 2121
             }
2122 2122
             return ! empty($query) ? implode(' AND ', $query) : '';
2123 2123
         }
@@ -2134,7 +2134,7 @@  discard block
 block discarded – undo
2134 2134
                                                            . $delete_object[$cpk_field->get_qualified_column()];
2135 2135
                     }
2136 2136
                 }
2137
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2137
+                $ways_to_identify_a_row[] = "(".implode(" AND ", $values_for_each_cpk_for_a_row).")";
2138 2138
             }
2139 2139
             return implode(" OR ", $ways_to_identify_a_row);
2140 2140
         }
@@ -2188,9 +2188,9 @@  discard block
 block discarded – undo
2188 2188
                 $column_to_count = '*';
2189 2189
             }
2190 2190
         }
2191
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2192
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2193
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2191
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2192
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2193
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2194 2194
     }
2195 2195
 
2196 2196
 
@@ -2212,14 +2212,14 @@  discard block
 block discarded – undo
2212 2212
             $field_obj = $this->get_primary_key_field();
2213 2213
         }
2214 2214
         $column_to_count = $field_obj->get_qualified_column();
2215
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2215
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2216 2216
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2217 2217
         $data_type = $field_obj->get_wpdb_data_type();
2218 2218
         if ($data_type === '%d' || $data_type === '%s') {
2219
-            return (float)$return_value;
2219
+            return (float) $return_value;
2220 2220
         }
2221 2221
         //must be %f
2222
-        return (float)$return_value;
2222
+        return (float) $return_value;
2223 2223
     }
2224 2224
 
2225 2225
 
@@ -2239,13 +2239,13 @@  discard block
 block discarded – undo
2239 2239
         //if we're in maintenance mode level 2, DON'T run any queries
2240 2240
         //because level 2 indicates the database needs updating and
2241 2241
         //is probably out of sync with the code
2242
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2242
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2243 2243
             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.",
2244 2244
                 "event_espresso")));
2245 2245
         }
2246 2246
         /** @type WPDB $wpdb */
2247 2247
         global $wpdb;
2248
-        if (! method_exists($wpdb, $wpdb_method)) {
2248
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2249 2249
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2250 2250
                 'event_espresso'), $wpdb_method));
2251 2251
         }
@@ -2257,7 +2257,7 @@  discard block
 block discarded – undo
2257 2257
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2258 2258
         if (WP_DEBUG) {
2259 2259
             $wpdb->show_errors($old_show_errors_value);
2260
-            if (! empty($wpdb->last_error)) {
2260
+            if ( ! empty($wpdb->last_error)) {
2261 2261
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2262 2262
             }
2263 2263
             if ($result === false) {
@@ -2318,7 +2318,7 @@  discard block
 block discarded – undo
2318 2318
                     return $result;
2319 2319
                     break;
2320 2320
             }
2321
-            if (! empty($error_message)) {
2321
+            if ( ! empty($error_message)) {
2322 2322
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2323 2323
                 trigger_error($error_message);
2324 2324
             }
@@ -2394,11 +2394,11 @@  discard block
 block discarded – undo
2394 2394
      */
2395 2395
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2396 2396
     {
2397
-        return " FROM " . $model_query_info->get_full_join_sql() .
2398
-               $model_query_info->get_where_sql() .
2399
-               $model_query_info->get_group_by_sql() .
2400
-               $model_query_info->get_having_sql() .
2401
-               $model_query_info->get_order_by_sql() .
2397
+        return " FROM ".$model_query_info->get_full_join_sql().
2398
+               $model_query_info->get_where_sql().
2399
+               $model_query_info->get_group_by_sql().
2400
+               $model_query_info->get_having_sql().
2401
+               $model_query_info->get_order_by_sql().
2402 2402
                $model_query_info->get_limit_sql();
2403 2403
     }
2404 2404
 
@@ -2594,12 +2594,12 @@  discard block
 block discarded – undo
2594 2594
         $related_model = $this->get_related_model_obj($model_name);
2595 2595
         //we're just going to use the query params on the related model's normal get_all query,
2596 2596
         //except add a condition to say to match the current mod
2597
-        if (! isset($query_params['default_where_conditions'])) {
2597
+        if ( ! isset($query_params['default_where_conditions'])) {
2598 2598
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2599 2599
         }
2600 2600
         $this_model_name = $this->get_this_model_name();
2601 2601
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2602
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2602
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2603 2603
         return $related_model->count($query_params, $field_to_count, $distinct);
2604 2604
     }
2605 2605
 
@@ -2619,7 +2619,7 @@  discard block
 block discarded – undo
2619 2619
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2620 2620
     {
2621 2621
         $related_model = $this->get_related_model_obj($model_name);
2622
-        if (! is_array($query_params)) {
2622
+        if ( ! is_array($query_params)) {
2623 2623
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2624 2624
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2625 2625
                     gettype($query_params)), '4.6.0');
@@ -2627,12 +2627,12 @@  discard block
 block discarded – undo
2627 2627
         }
2628 2628
         //we're just going to use the query params on the related model's normal get_all query,
2629 2629
         //except add a condition to say to match the current mod
2630
-        if (! isset($query_params['default_where_conditions'])) {
2630
+        if ( ! isset($query_params['default_where_conditions'])) {
2631 2631
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2632 2632
         }
2633 2633
         $this_model_name = $this->get_this_model_name();
2634 2634
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2635
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2635
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2636 2636
         return $related_model->sum($query_params, $field_to_sum);
2637 2637
     }
2638 2638
 
@@ -2685,7 +2685,7 @@  discard block
 block discarded – undo
2685 2685
                 $field_with_model_name = $field;
2686 2686
             }
2687 2687
         }
2688
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2688
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2689 2689
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2690 2690
                 $this->get_this_model_name()));
2691 2691
         }
@@ -2718,7 +2718,7 @@  discard block
 block discarded – undo
2718 2718
          * @param array    $fields_n_values keys are the fields and values are their new values
2719 2719
          * @param EEM_Base $model           the model used
2720 2720
          */
2721
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2721
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2722 2722
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2723 2723
             $main_table = $this->_get_main_table();
2724 2724
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2825,7 +2825,7 @@  discard block
 block discarded – undo
2825 2825
         }
2826 2826
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2827 2827
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2828
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2828
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2829 2829
         }
2830 2830
         //if there is nothing to base this search on, then we shouldn't find anything
2831 2831
         if (empty($query_params)) {
@@ -2911,7 +2911,7 @@  discard block
 block discarded – undo
2911 2911
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2912 2912
             //so add the fk to the main table as a column
2913 2913
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2914
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2914
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2915 2915
         }
2916 2916
         //insert the new entry
2917 2917
         $result = $this->_do_wpdb_query('insert',
@@ -3115,7 +3115,7 @@  discard block
 block discarded – undo
3115 3115
                     $query_info_carrier,
3116 3116
                     'group_by'
3117 3117
                 );
3118
-            } elseif (! empty ($query_params['group_by'])) {
3118
+            } elseif ( ! empty ($query_params['group_by'])) {
3119 3119
                 $this->_extract_related_model_info_from_query_param(
3120 3120
                     $query_params['group_by'],
3121 3121
                     $query_info_carrier,
@@ -3137,7 +3137,7 @@  discard block
 block discarded – undo
3137 3137
                     $query_info_carrier,
3138 3138
                     'order_by'
3139 3139
                 );
3140
-            } elseif (! empty($query_params['order_by'])) {
3140
+            } elseif ( ! empty($query_params['order_by'])) {
3141 3141
                 $this->_extract_related_model_info_from_query_param(
3142 3142
                     $query_params['order_by'],
3143 3143
                     $query_info_carrier,
@@ -3172,8 +3172,8 @@  discard block
 block discarded – undo
3172 3172
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3173 3173
         $query_param_type
3174 3174
     ) {
3175
-        if (! empty($sub_query_params)) {
3176
-            $sub_query_params = (array)$sub_query_params;
3175
+        if ( ! empty($sub_query_params)) {
3176
+            $sub_query_params = (array) $sub_query_params;
3177 3177
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3178 3178
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3179 3179
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3184,7 +3184,7 @@  discard block
 block discarded – undo
3184 3184
                 //of array('Registration.TXN_ID'=>23)
3185 3185
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3186 3186
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3187
-                    if (! is_array($possibly_array_of_params)) {
3187
+                    if ( ! is_array($possibly_array_of_params)) {
3188 3188
                         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'))",
3189 3189
                             "event_espresso"),
3190 3190
                             $param, $possibly_array_of_params));
@@ -3201,7 +3201,7 @@  discard block
 block discarded – undo
3201 3201
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3202 3202
                     //indicating that $possible_array_of_params[1] is actually a field name,
3203 3203
                     //from which we should extract query parameters!
3204
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3204
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3205 3205
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3206 3206
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3207 3207
                     }
@@ -3231,8 +3231,8 @@  discard block
 block discarded – undo
3231 3231
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3232 3232
         $query_param_type
3233 3233
     ) {
3234
-        if (! empty($sub_query_params)) {
3235
-            if (! is_array($sub_query_params)) {
3234
+        if ( ! empty($sub_query_params)) {
3235
+            if ( ! is_array($sub_query_params)) {
3236 3236
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3237 3237
                     $sub_query_params));
3238 3238
             }
@@ -3261,7 +3261,7 @@  discard block
 block discarded – undo
3261 3261
      */
3262 3262
     public function _create_model_query_info_carrier($query_params)
3263 3263
     {
3264
-        if (! is_array($query_params)) {
3264
+        if ( ! is_array($query_params)) {
3265 3265
             EE_Error::doing_it_wrong(
3266 3266
                 'EEM_Base::_create_model_query_info_carrier',
3267 3267
                 sprintf(
@@ -3337,7 +3337,7 @@  discard block
 block discarded – undo
3337 3337
         //set limit
3338 3338
         if (array_key_exists('limit', $query_params)) {
3339 3339
             if (is_array($query_params['limit'])) {
3340
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3340
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3341 3341
                     $e = sprintf(
3342 3342
                         __(
3343 3343
                             "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)",
@@ -3345,12 +3345,12 @@  discard block
 block discarded – undo
3345 3345
                         ),
3346 3346
                         http_build_query($query_params['limit'])
3347 3347
                     );
3348
-                    throw new EE_Error($e . "|" . $e);
3348
+                    throw new EE_Error($e."|".$e);
3349 3349
                 }
3350 3350
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3351
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3352
-            } elseif (! empty ($query_params['limit'])) {
3353
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3351
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3352
+            } elseif ( ! empty ($query_params['limit'])) {
3353
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3354 3354
             }
3355 3355
         }
3356 3356
         //set order by
@@ -3382,10 +3382,10 @@  discard block
 block discarded – undo
3382 3382
                 $order_array = array();
3383 3383
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3384 3384
                     $order = $this->_extract_order($order);
3385
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3385
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3386 3386
                 }
3387
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3388
-            } elseif (! empty ($query_params['order_by'])) {
3387
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3388
+            } elseif ( ! empty ($query_params['order_by'])) {
3389 3389
                 $this->_extract_related_model_info_from_query_param(
3390 3390
                     $query_params['order_by'],
3391 3391
                     $query_object,
@@ -3396,18 +3396,18 @@  discard block
 block discarded – undo
3396 3396
                     ? $this->_extract_order($query_params['order'])
3397 3397
                     : 'DESC';
3398 3398
                 $query_object->set_order_by_sql(
3399
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3399
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3400 3400
                 );
3401 3401
             }
3402 3402
         }
3403 3403
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3404
-        if (! array_key_exists('order_by', $query_params)
3404
+        if ( ! array_key_exists('order_by', $query_params)
3405 3405
             && array_key_exists('order', $query_params)
3406 3406
             && ! empty($query_params['order'])
3407 3407
         ) {
3408 3408
             $pk_field = $this->get_primary_key_field();
3409 3409
             $order = $this->_extract_order($query_params['order']);
3410
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3410
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3411 3411
         }
3412 3412
         //set group by
3413 3413
         if (array_key_exists('group_by', $query_params)) {
@@ -3417,10 +3417,10 @@  discard block
 block discarded – undo
3417 3417
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3418 3418
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3419 3419
                 }
3420
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3421
-            } elseif (! empty ($query_params['group_by'])) {
3420
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3421
+            } elseif ( ! empty ($query_params['group_by'])) {
3422 3422
                 $query_object->set_group_by_sql(
3423
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3423
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3424 3424
                 );
3425 3425
             }
3426 3426
         }
@@ -3430,7 +3430,7 @@  discard block
 block discarded – undo
3430 3430
         }
3431 3431
         //now, just verify they didn't pass anything wack
3432 3432
         foreach ($query_params as $query_key => $query_value) {
3433
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3433
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3434 3434
                 throw new EE_Error(
3435 3435
                     sprintf(
3436 3436
                         __(
@@ -3529,22 +3529,22 @@  discard block
 block discarded – undo
3529 3529
         $where_query_params = array()
3530 3530
     ) {
3531 3531
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3532
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3532
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3533 3533
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3534 3534
                 "event_espresso"), $use_default_where_conditions,
3535 3535
                 implode(", ", $allowed_used_default_where_conditions_values)));
3536 3536
         }
3537 3537
         $universal_query_params = array();
3538
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3538
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3539 3539
             $universal_query_params = $this->_get_default_where_conditions();
3540
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3540
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3541 3541
             $universal_query_params = $this->_get_minimum_where_conditions();
3542 3542
         }
3543 3543
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3544 3544
             $related_model = $this->get_related_model_obj($model_name);
3545
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3545
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3546 3546
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3547
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3547
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3548 3548
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3549 3549
             } else {
3550 3550
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3577,7 +3577,7 @@  discard block
 block discarded – undo
3577 3577
      * @param bool $for_this_model false means this is for OTHER related models
3578 3578
      * @return bool
3579 3579
      */
3580
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3580
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3581 3581
     {
3582 3582
         return (
3583 3583
                    $for_this_model
@@ -3656,7 +3656,7 @@  discard block
 block discarded – undo
3656 3656
     ) {
3657 3657
         $null_friendly_where_conditions = array();
3658 3658
         $none_overridden = true;
3659
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3659
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3660 3660
         foreach ($default_where_conditions as $key => $val) {
3661 3661
             if (isset($provided_where_conditions[$key])) {
3662 3662
                 $none_overridden = false;
@@ -3774,7 +3774,7 @@  discard block
 block discarded – undo
3774 3774
             foreach ($tables as $table_obj) {
3775 3775
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3776 3776
                                        . $table_obj->get_fully_qualified_pk_column();
3777
-                if (! in_array($qualified_pk_column, $selects)) {
3777
+                if ( ! in_array($qualified_pk_column, $selects)) {
3778 3778
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3779 3779
                 }
3780 3780
             }
@@ -3868,9 +3868,9 @@  discard block
 block discarded – undo
3868 3868
         //and
3869 3869
         //check if it's a field on a related model
3870 3870
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3871
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3871
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3872 3872
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3873
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3873
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3874 3874
                 if ($query_param === '') {
3875 3875
                     //nothing left to $query_param
3876 3876
                     //we should actually end in a field name, not a model like this!
@@ -3958,7 +3958,7 @@  discard block
 block discarded – undo
3958 3958
     {
3959 3959
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3960 3960
         if ($SQL) {
3961
-            return " WHERE " . $SQL;
3961
+            return " WHERE ".$SQL;
3962 3962
         }
3963 3963
         return '';
3964 3964
     }
@@ -3977,7 +3977,7 @@  discard block
 block discarded – undo
3977 3977
     {
3978 3978
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3979 3979
         if ($SQL) {
3980
-            return " HAVING " . $SQL;
3980
+            return " HAVING ".$SQL;
3981 3981
         }
3982 3982
         return '';
3983 3983
     }
@@ -3996,11 +3996,11 @@  discard block
 block discarded – undo
3996 3996
      */
3997 3997
     protected function _get_field_on_model($field_name, $model_name)
3998 3998
     {
3999
-        $model_class = 'EEM_' . $model_name;
4000
-        $model_filepath = $model_class . ".model.php";
3999
+        $model_class = 'EEM_'.$model_name;
4000
+        $model_filepath = $model_class.".model.php";
4001 4001
         if (is_readable($model_filepath)) {
4002 4002
             require_once($model_filepath);
4003
-            $model_instance = call_user_func($model_name . "::instance");
4003
+            $model_instance = call_user_func($model_name."::instance");
4004 4004
             /* @var $model_instance EEM_Base */
4005 4005
             return $model_instance->field_settings_for($field_name);
4006 4006
         }
@@ -4029,7 +4029,7 @@  discard block
 block discarded – undo
4029 4029
     {
4030 4030
         $where_clauses = array();
4031 4031
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4032
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4032
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
4033 4033
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4034 4034
                 switch ($query_param) {
4035 4035
                     case 'not':
@@ -4057,7 +4057,7 @@  discard block
 block discarded – undo
4057 4057
             } else {
4058 4058
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4059 4059
                 //if it's not a normal field, maybe it's a custom selection?
4060
-                if (! $field_obj) {
4060
+                if ( ! $field_obj) {
4061 4061
                     if (isset($this->_custom_selections[$query_param][1])) {
4062 4062
                         $field_obj = $this->_custom_selections[$query_param][1];
4063 4063
                     } else {
@@ -4066,7 +4066,7 @@  discard block
 block discarded – undo
4066 4066
                     }
4067 4067
                 }
4068 4068
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4069
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4069
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4070 4070
             }
4071 4071
         }
4072 4072
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4087,7 +4087,7 @@  discard block
 block discarded – undo
4087 4087
         if ($field) {
4088 4088
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4089 4089
                 $query_param);
4090
-            return $table_alias_prefix . $field->get_qualified_column();
4090
+            return $table_alias_prefix.$field->get_qualified_column();
4091 4091
         }
4092 4092
         if (array_key_exists($query_param, $this->_custom_selections)) {
4093 4093
             //maybe it's custom selection item?
@@ -4139,7 +4139,7 @@  discard block
 block discarded – undo
4139 4139
     {
4140 4140
         if (is_array($op_and_value)) {
4141 4141
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4142
-            if (! $operator) {
4142
+            if ( ! $operator) {
4143 4143
                 $php_array_like_string = array();
4144 4144
                 foreach ($op_and_value as $key => $value) {
4145 4145
                     $php_array_like_string[] = "$key=>$value";
@@ -4161,14 +4161,14 @@  discard block
 block discarded – undo
4161 4161
         }
4162 4162
         //check to see if the value is actually another field
4163 4163
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4164
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4164
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4165 4165
         }
4166 4166
         if (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4167 4167
             //in this case, the value should be an array, or at least a comma-separated list
4168 4168
             //it will need to handle a little differently
4169 4169
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4170 4170
             //note: $cleaned_value has already been run through $wpdb->prepare()
4171
-            return $operator . SP . $cleaned_value;
4171
+            return $operator.SP.$cleaned_value;
4172 4172
         }
4173 4173
         if (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4174 4174
             //the value should be an array with count of two.
@@ -4184,7 +4184,7 @@  discard block
 block discarded – undo
4184 4184
                 );
4185 4185
             }
4186 4186
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4187
-            return $operator . SP . $cleaned_value;
4187
+            return $operator.SP.$cleaned_value;
4188 4188
         }
4189 4189
         if (in_array($operator, $this->_null_style_operators)) {
4190 4190
             if ($value !== null) {
@@ -4204,10 +4204,10 @@  discard block
 block discarded – undo
4204 4204
         if ($operator === 'LIKE' && ! is_array($value)) {
4205 4205
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4206 4206
             //remove other junk. So just treat it as a string.
4207
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4207
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4208 4208
         }
4209
-        if (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4210
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4209
+        if ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4210
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4211 4211
         }
4212 4212
         if (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4213 4213
             throw new EE_Error(
@@ -4221,7 +4221,7 @@  discard block
 block discarded – undo
4221 4221
                 )
4222 4222
             );
4223 4223
         }
4224
-        if (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4224
+        if ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4225 4225
             throw new EE_Error(
4226 4226
                 sprintf(
4227 4227
                     __(
@@ -4261,7 +4261,7 @@  discard block
 block discarded – undo
4261 4261
         foreach ($values as $value) {
4262 4262
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4263 4263
         }
4264
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4264
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4265 4265
     }
4266 4266
 
4267 4267
 
@@ -4302,7 +4302,7 @@  discard block
 block discarded – undo
4302 4302
                                 . $main_table->get_table_name()
4303 4303
                                 . " WHERE FALSE";
4304 4304
         }
4305
-        return "(" . implode(",", $cleaned_values) . ")";
4305
+        return "(".implode(",", $cleaned_values).")";
4306 4306
     }
4307 4307
 
4308 4308
 
@@ -4321,7 +4321,7 @@  discard block
 block discarded – undo
4321 4321
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4322 4322
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4323 4323
         } //$field_obj should really just be a data type
4324
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4324
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4325 4325
             throw new EE_Error(
4326 4326
                 sprintf(
4327 4327
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4449,10 +4449,10 @@  discard block
 block discarded – undo
4449 4449
      */
4450 4450
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4451 4451
     {
4452
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4452
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4453 4453
         $qualified_columns = array();
4454 4454
         foreach ($this->field_settings() as $field_name => $field) {
4455
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4455
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4456 4456
         }
4457 4457
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4458 4458
     }
@@ -4476,11 +4476,11 @@  discard block
 block discarded – undo
4476 4476
             if ($table_obj instanceof EE_Primary_Table) {
4477 4477
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4478 4478
                     ? $table_obj->get_select_join_limit($limit)
4479
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4479
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4480 4480
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4481 4481
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4482 4482
                     ? $table_obj->get_select_join_limit_join($limit)
4483
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4483
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4484 4484
             }
4485 4485
         }
4486 4486
         return $SQL;
@@ -4568,12 +4568,12 @@  discard block
 block discarded – undo
4568 4568
      */
4569 4569
     public function get_related_model_obj($model_name)
4570 4570
     {
4571
-        $model_classname = "EEM_" . $model_name;
4572
-        if (! class_exists($model_classname)) {
4571
+        $model_classname = "EEM_".$model_name;
4572
+        if ( ! class_exists($model_classname)) {
4573 4573
             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",
4574 4574
                 'event_espresso'), $model_name, $model_classname));
4575 4575
         }
4576
-        return call_user_func($model_classname . "::instance");
4576
+        return call_user_func($model_classname."::instance");
4577 4577
     }
4578 4578
 
4579 4579
 
@@ -4620,7 +4620,7 @@  discard block
 block discarded – undo
4620 4620
     public function related_settings_for($relation_name)
4621 4621
     {
4622 4622
         $relatedModels = $this->relation_settings();
4623
-        if (! array_key_exists($relation_name, $relatedModels)) {
4623
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4624 4624
             throw new EE_Error(
4625 4625
                 sprintf(
4626 4626
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4647,7 +4647,7 @@  discard block
 block discarded – undo
4647 4647
     public function field_settings_for($fieldName)
4648 4648
     {
4649 4649
         $fieldSettings = $this->field_settings(true);
4650
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4650
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4651 4651
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4652 4652
                 get_class($this)));
4653 4653
         }
@@ -4720,7 +4720,7 @@  discard block
 block discarded – undo
4720 4720
                     break;
4721 4721
                 }
4722 4722
             }
4723
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4723
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4724 4724
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4725 4725
                     get_class($this)));
4726 4726
             }
@@ -4779,7 +4779,7 @@  discard block
 block discarded – undo
4779 4779
      */
4780 4780
     public function get_foreign_key_to($model_name)
4781 4781
     {
4782
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4782
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4783 4783
             foreach ($this->field_settings() as $field) {
4784 4784
                 if (
4785 4785
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4789,7 +4789,7 @@  discard block
 block discarded – undo
4789 4789
                     break;
4790 4790
                 }
4791 4791
             }
4792
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4792
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4793 4793
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4794 4794
                     'event_espresso'), $model_name, get_class($this)));
4795 4795
             }
@@ -4840,7 +4840,7 @@  discard block
 block discarded – undo
4840 4840
             foreach ($this->_fields as $fields_corresponding_to_table) {
4841 4841
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4842 4842
                     /** @var $field_obj EE_Model_Field_Base */
4843
-                    if (! $field_obj->is_db_only_field()) {
4843
+                    if ( ! $field_obj->is_db_only_field()) {
4844 4844
                         $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4845 4845
                     }
4846 4846
                 }
@@ -4869,7 +4869,7 @@  discard block
 block discarded – undo
4869 4869
         $count_if_model_has_no_primary_key = 0;
4870 4870
         $has_primary_key = $this->has_primary_key_field();
4871 4871
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4872
-        foreach ((array)$rows as $row) {
4872
+        foreach ((array) $rows as $row) {
4873 4873
             if (empty($row)) {
4874 4874
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4875 4875
                 return array();
@@ -4887,7 +4887,7 @@  discard block
 block discarded – undo
4887 4887
                 }
4888 4888
             }
4889 4889
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4890
-            if (! $classInstance) {
4890
+            if ( ! $classInstance) {
4891 4891
                 throw new EE_Error(
4892 4892
                     sprintf(
4893 4893
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -4956,7 +4956,7 @@  discard block
 block discarded – undo
4956 4956
      */
4957 4957
     public function instantiate_class_from_array_or_object($cols_n_values)
4958 4958
     {
4959
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4959
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4960 4960
             $cols_n_values = get_object_vars($cols_n_values);
4961 4961
         }
4962 4962
         $primary_key = null;
@@ -4981,7 +4981,7 @@  discard block
 block discarded – undo
4981 4981
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4982 4982
         if ($primary_key) {
4983 4983
             $classInstance = $this->get_from_entity_map($primary_key);
4984
-            if (! $classInstance) {
4984
+            if ( ! $classInstance) {
4985 4985
                 $classInstance = EE_Registry::instance()
4986 4986
                                             ->load_class($className,
4987 4987
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -5032,12 +5032,12 @@  discard block
 block discarded – undo
5032 5032
     public function add_to_entity_map(EE_Base_Class $object)
5033 5033
     {
5034 5034
         $className = $this->_get_class_name();
5035
-        if (! $object instanceof $className) {
5035
+        if ( ! $object instanceof $className) {
5036 5036
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5037 5037
                 is_object($object) ? get_class($object) : $object, $className));
5038 5038
         }
5039 5039
         /** @var $object EE_Base_Class */
5040
-        if (! $object->ID()) {
5040
+        if ( ! $object->ID()) {
5041 5041
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5042 5042
                 "event_espresso"), get_class($this)));
5043 5043
         }
@@ -5106,7 +5106,7 @@  discard block
 block discarded – undo
5106 5106
             //there is a primary key on this table and its not set. Use defaults for all its columns
5107 5107
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5108 5108
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5109
-                    if (! $field_obj->is_db_only_field()) {
5109
+                    if ( ! $field_obj->is_db_only_field()) {
5110 5110
                         //prepare field as if its coming from db
5111 5111
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5112 5112
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5115,7 +5115,7 @@  discard block
 block discarded – undo
5115 5115
             } else {
5116 5116
                 //the table's rows existed. Use their values
5117 5117
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5118
-                    if (! $field_obj->is_db_only_field()) {
5118
+                    if ( ! $field_obj->is_db_only_field()) {
5119 5119
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5120 5120
                             $cols_n_values, $field_obj->get_qualified_column(),
5121 5121
                             $field_obj->get_table_column()
@@ -5230,7 +5230,7 @@  discard block
 block discarded – undo
5230 5230
      */
5231 5231
     private function _get_class_name()
5232 5232
     {
5233
-        return "EE_" . $this->get_this_model_name();
5233
+        return "EE_".$this->get_this_model_name();
5234 5234
     }
5235 5235
 
5236 5236
 
@@ -5245,7 +5245,7 @@  discard block
 block discarded – undo
5245 5245
      */
5246 5246
     public function item_name($quantity = 1)
5247 5247
     {
5248
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5248
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5249 5249
     }
5250 5250
 
5251 5251
 
@@ -5278,7 +5278,7 @@  discard block
 block discarded – undo
5278 5278
     {
5279 5279
         $className = get_class($this);
5280 5280
         $tagName = "FHEE__{$className}__{$methodName}";
5281
-        if (! has_filter($tagName)) {
5281
+        if ( ! has_filter($tagName)) {
5282 5282
             throw new EE_Error(
5283 5283
                 sprintf(
5284 5284
                     __('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 );',
@@ -5504,7 +5504,7 @@  discard block
 block discarded – undo
5504 5504
         $key_vals_in_combined_pk = array();
5505 5505
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5506 5506
         foreach ($key_fields as $key_field_name => $field_obj) {
5507
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5507
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5508 5508
                 return null;
5509 5509
             }
5510 5510
         }
@@ -5525,7 +5525,7 @@  discard block
 block discarded – undo
5525 5525
     {
5526 5526
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5527 5527
         foreach ($keys_it_should_have as $key) {
5528
-            if (! isset($key_vals[$key])) {
5528
+            if ( ! isset($key_vals[$key])) {
5529 5529
                 return false;
5530 5530
             }
5531 5531
         }
@@ -5579,7 +5579,7 @@  discard block
 block discarded – undo
5579 5579
      */
5580 5580
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5581 5581
     {
5582
-        if (! is_array($query_params)) {
5582
+        if ( ! is_array($query_params)) {
5583 5583
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5584 5584
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5585 5585
                     gettype($query_params)), '4.6.0');
@@ -5675,7 +5675,7 @@  discard block
 block discarded – undo
5675 5675
      */
5676 5676
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5677 5677
     {
5678
-        if (! $this->has_primary_key_field()) {
5678
+        if ( ! $this->has_primary_key_field()) {
5679 5679
             if (WP_DEBUG) {
5680 5680
                 EE_Error::add_error(
5681 5681
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5688,7 +5688,7 @@  discard block
 block discarded – undo
5688 5688
         $IDs = array();
5689 5689
         foreach ($model_objects as $model_object) {
5690 5690
             $id = $model_object->ID();
5691
-            if (! $id) {
5691
+            if ( ! $id) {
5692 5692
                 if ($filter_out_empty_ids) {
5693 5693
                     continue;
5694 5694
                 }
@@ -5784,8 +5784,8 @@  discard block
 block discarded – undo
5784 5784
         $missing_caps = array();
5785 5785
         $cap_restrictions = $this->cap_restrictions($context);
5786 5786
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5787
-            if (! EE_Capabilities::instance()
5788
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5787
+            if ( ! EE_Capabilities::instance()
5788
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5789 5789
             ) {
5790 5790
                 $missing_caps[$cap] = $restriction_if_no_cap;
5791 5791
             }
@@ -5937,7 +5937,7 @@  discard block
 block discarded – undo
5937 5937
     {
5938 5938
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5939 5939
             if ($query_param_key === $logic_query_param_key
5940
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5940
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
5941 5941
             ) {
5942 5942
                 return true;
5943 5943
             }
Please login to merge, or discard this patch.
core/EE_Dependency_Map.core.php 2 patches
Indentation   +764 added lines, -764 removed lines patch added patch discarded remove patch
@@ -5,7 +5,7 @@  discard block
 block discarded – undo
5 5
 use EventEspresso\core\services\loaders\LoaderInterface;
6 6
 
7 7
 if (! defined('EVENT_ESPRESSO_VERSION')) {
8
-    exit('No direct script access allowed');
8
+	exit('No direct script access allowed');
9 9
 }
10 10
 
11 11
 
@@ -22,769 +22,769 @@  discard block
 block discarded – undo
22 22
 class EE_Dependency_Map
23 23
 {
24 24
 
25
-    /**
26
-     * This means that the requested class dependency is not present in the dependency map
27
-     */
28
-    const not_registered = 0;
29
-
30
-    /**
31
-     * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
32
-     */
33
-    const load_new_object = 1;
34
-
35
-    /**
36
-     * This instructs class loaders to return a previously instantiated and cached object for the requested class.
37
-     * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
38
-     */
39
-    const load_from_cache = 2;
40
-
41
-    /**
42
-     * When registering a dependency,
43
-     * this indicates to keep any existing dependencies that already exist,
44
-     * and simply discard any new dependencies declared in the incoming data
45
-     */
46
-    const KEEP_EXISTING_DEPENDENCIES = 0;
47
-
48
-    /**
49
-     * When registering a dependency,
50
-     * this indicates to overwrite any existing dependencies that already exist using the incoming data
51
-     */
52
-    const OVERWRITE_DEPENDENCIES = 1;
53
-
54
-
55
-
56
-    /**
57
-     * @type EE_Dependency_Map $_instance
58
-     */
59
-    protected static $_instance;
60
-
61
-    /**
62
-     * @type EE_Request $request
63
-     */
64
-    protected $_request;
65
-
66
-    /**
67
-     * @type EE_Response $response
68
-     */
69
-    protected $_response;
70
-
71
-    /**
72
-     * @type LoaderInterface $loader
73
-     */
74
-    protected $loader;
75
-
76
-    /**
77
-     * @type array $_dependency_map
78
-     */
79
-    protected $_dependency_map = array();
80
-
81
-    /**
82
-     * @type array $_class_loaders
83
-     */
84
-    protected $_class_loaders = array();
85
-
86
-    /**
87
-     * @type array $_aliases
88
-     */
89
-    protected $_aliases = array();
90
-
91
-
92
-
93
-    /**
94
-     * EE_Dependency_Map constructor.
95
-     *
96
-     * @param EE_Request  $request
97
-     * @param EE_Response $response
98
-     */
99
-    protected function __construct(EE_Request $request, EE_Response $response)
100
-    {
101
-        $this->_request = $request;
102
-        $this->_response = $response;
103
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
104
-        do_action('EE_Dependency_Map____construct');
105
-    }
106
-
107
-
108
-
109
-    /**
110
-     * @throws InvalidDataTypeException
111
-     * @throws InvalidInterfaceException
112
-     * @throws InvalidArgumentException
113
-     */
114
-    public function initialize()
115
-    {
116
-        $this->_register_core_dependencies();
117
-        $this->_register_core_class_loaders();
118
-        $this->_register_core_aliases();
119
-    }
120
-
121
-
122
-
123
-    /**
124
-     * @singleton method used to instantiate class object
125
-     * @access    public
126
-     * @param EE_Request  $request
127
-     * @param EE_Response $response
128
-     * @return EE_Dependency_Map
129
-     */
130
-    public static function instance(EE_Request $request = null, EE_Response $response = null)
131
-    {
132
-        // check if class object is instantiated, and instantiated properly
133
-        if (! self::$_instance instanceof EE_Dependency_Map) {
134
-            self::$_instance = new EE_Dependency_Map($request, $response);
135
-        }
136
-        return self::$_instance;
137
-    }
138
-
139
-
140
-
141
-    /**
142
-     * @param LoaderInterface $loader
143
-     */
144
-    public function setLoader(LoaderInterface $loader)
145
-    {
146
-        $this->loader = $loader;
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * @param string $class
153
-     * @param array  $dependencies
154
-     * @param int    $overwrite
155
-     * @return bool
156
-     */
157
-    public static function register_dependencies(
158
-        $class,
159
-        array $dependencies,
160
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
161
-    ) {
162
-        return self::$_instance->registerDependencies($class, $dependencies, $overwrite);
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     * Assigns an array of class names and corresponding load sources (new or cached)
169
-     * to the class specified by the first parameter.
170
-     * IMPORTANT !!!
171
-     * The order of elements in the incoming $dependencies array MUST match
172
-     * the order of the constructor parameters for the class in question.
173
-     * This is especially important when overriding any existing dependencies that are registered.
174
-     * the third parameter controls whether any duplicate dependencies are overwritten or not.
175
-     *
176
-     * @param string $class
177
-     * @param array  $dependencies
178
-     * @param int    $overwrite
179
-     * @return bool
180
-     */
181
-    public function registerDependencies(
182
-        $class,
183
-        array $dependencies,
184
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
185
-    ) {
186
-        $class = trim($class, '\\');
187
-        $registered = false;
188
-        if (empty(self::$_instance->_dependency_map[ $class ])) {
189
-            self::$_instance->_dependency_map[ $class ] = array();
190
-        }
191
-        // we need to make sure that any aliases used when registering a dependency
192
-        // get resolved to the correct class name
193
-        foreach ((array)$dependencies as $dependency => $load_source) {
194
-            $alias = self::$_instance->get_alias($dependency);
195
-            if (
196
-                $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
197
-                || ! isset(self::$_instance->_dependency_map[ $class ][ $alias ])
198
-            ) {
199
-                unset($dependencies[$dependency]);
200
-                $dependencies[$alias] = $load_source;
201
-                $registered = true;
202
-            }
203
-        }
204
-        // now add our two lists of dependencies together.
205
-        // using Union (+=) favours the arrays in precedence from left to right,
206
-        // so $dependencies is NOT overwritten because it is listed first
207
-        // ie: with A = B + C, entries in B take precedence over duplicate entries in C
208
-        // Union is way faster than array_merge() but should be used with caution...
209
-        // especially with numerically indexed arrays
210
-        $dependencies += self::$_instance->_dependency_map[ $class ];
211
-        // now we need to ensure that the resulting dependencies
212
-        // array only has the entries that are required for the class
213
-        // so first count how many dependencies were originally registered for the class
214
-        $dependency_count = count(self::$_instance->_dependency_map[ $class ]);
215
-        // if that count is non-zero (meaning dependencies were already registered)
216
-        self::$_instance->_dependency_map[ $class ] = $dependency_count
217
-            // then truncate the  final array to match that count
218
-            ? array_slice($dependencies, 0, $dependency_count)
219
-            // otherwise just take the incoming array because nothing previously existed
220
-            : $dependencies;
221
-        return $registered;
222
-    }
223
-
224
-
225
-
226
-    /**
227
-     * @param string $class_name
228
-     * @param string $loader
229
-     * @return bool
230
-     * @throws DomainException
231
-     */
232
-    public static function register_class_loader($class_name, $loader = 'load_core')
233
-    {
234
-        if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
235
-            throw new DomainException(
236
-                esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
237
-            );
238
-        }
239
-        // check that loader is callable or method starts with "load_" and exists in EE_Registry
240
-        if (
241
-            ! is_callable($loader)
242
-            && (
243
-                strpos($loader, 'load_') !== 0
244
-                || ! method_exists('EE_Registry', $loader)
245
-            )
246
-        ) {
247
-            throw new DomainException(
248
-                sprintf(
249
-                    esc_html__(
250
-                        '"%1$s" is not a valid loader method on EE_Registry.',
251
-                        'event_espresso'
252
-                    ),
253
-                    $loader
254
-                )
255
-            );
256
-        }
257
-        $class_name = self::$_instance->get_alias($class_name);
258
-        if (! isset(self::$_instance->_class_loaders[$class_name])) {
259
-            self::$_instance->_class_loaders[$class_name] = $loader;
260
-            return true;
261
-        }
262
-        return false;
263
-    }
264
-
265
-
266
-
267
-    /**
268
-     * @return array
269
-     */
270
-    public function dependency_map()
271
-    {
272
-        return $this->_dependency_map;
273
-    }
274
-
275
-
276
-
277
-    /**
278
-     * returns TRUE if dependency map contains a listing for the provided class name
279
-     *
280
-     * @param string $class_name
281
-     * @return boolean
282
-     */
283
-    public function has($class_name = '')
284
-    {
285
-        // all legacy models have the same dependencies
286
-        if (strpos($class_name, 'EEM_') === 0) {
287
-            $class_name = 'LEGACY_MODELS';
288
-        }
289
-        return isset($this->_dependency_map[$class_name]) ? true : false;
290
-    }
291
-
292
-
293
-
294
-    /**
295
-     * returns TRUE if dependency map contains a listing for the provided class name AND dependency
296
-     *
297
-     * @param string $class_name
298
-     * @param string $dependency
299
-     * @return bool
300
-     */
301
-    public function has_dependency_for_class($class_name = '', $dependency = '')
302
-    {
303
-        // all legacy models have the same dependencies
304
-        if (strpos($class_name, 'EEM_') === 0) {
305
-            $class_name = 'LEGACY_MODELS';
306
-        }
307
-        $dependency = $this->get_alias($dependency);
308
-        return isset($this->_dependency_map[$class_name], $this->_dependency_map[$class_name][$dependency])
309
-            ? true
310
-            : false;
311
-    }
312
-
313
-
314
-
315
-    /**
316
-     * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
317
-     *
318
-     * @param string $class_name
319
-     * @param string $dependency
320
-     * @return int
321
-     */
322
-    public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
323
-    {
324
-        // all legacy models have the same dependencies
325
-        if (strpos($class_name, 'EEM_') === 0) {
326
-            $class_name = 'LEGACY_MODELS';
327
-        }
328
-        $dependency = $this->get_alias($dependency);
329
-        return $this->has_dependency_for_class($class_name, $dependency)
330
-            ? $this->_dependency_map[$class_name][$dependency]
331
-            : EE_Dependency_Map::not_registered;
332
-    }
333
-
334
-
335
-
336
-    /**
337
-     * @param string $class_name
338
-     * @return string | Closure
339
-     */
340
-    public function class_loader($class_name)
341
-    {
342
-        // all legacy models use load_model()
343
-        if(strpos($class_name, 'EEM_') === 0){
344
-            return 'load_model';
345
-        }
346
-        $class_name = $this->get_alias($class_name);
347
-        return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
348
-    }
349
-
350
-
351
-
352
-    /**
353
-     * @return array
354
-     */
355
-    public function class_loaders()
356
-    {
357
-        return $this->_class_loaders;
358
-    }
359
-
360
-
361
-
362
-    /**
363
-     * adds an alias for a classname
364
-     *
365
-     * @param string $class_name the class name that should be used (concrete class to replace interface)
366
-     * @param string $alias      the class name that would be type hinted for (abstract parent or interface)
367
-     * @param string $for_class  the class that has the dependency (is type hinting for the interface)
368
-     */
369
-    public function add_alias($class_name, $alias, $for_class = '')
370
-    {
371
-        if ($for_class !== '') {
372
-            if (! isset($this->_aliases[$for_class])) {
373
-                $this->_aliases[$for_class] = array();
374
-            }
375
-            $this->_aliases[$for_class][$class_name] = $alias;
376
-        }
377
-        $this->_aliases[$class_name] = $alias;
378
-    }
379
-
380
-
381
-
382
-    /**
383
-     * returns TRUE if the provided class name has an alias
384
-     *
385
-     * @param string $class_name
386
-     * @param string $for_class
387
-     * @return bool
388
-     */
389
-    public function has_alias($class_name = '', $for_class = '')
390
-    {
391
-        return isset($this->_aliases[$for_class], $this->_aliases[$for_class][$class_name])
392
-               || (
393
-                   isset($this->_aliases[$class_name])
394
-                   && ! is_array($this->_aliases[$class_name])
395
-               );
396
-    }
397
-
398
-
399
-
400
-    /**
401
-     * returns alias for class name if one exists, otherwise returns the original classname
402
-     * functions recursively, so that multiple aliases can be used to drill down to a classname
403
-     *  for example:
404
-     *      if the following two entries were added to the _aliases array:
405
-     *          array(
406
-     *              'interface_alias'           => 'some\namespace\interface'
407
-     *              'some\namespace\interface'  => 'some\namespace\classname'
408
-     *          )
409
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
410
-     *      to load an instance of 'some\namespace\classname'
411
-     *
412
-     * @param string $class_name
413
-     * @param string $for_class
414
-     * @return string
415
-     */
416
-    public function get_alias($class_name = '', $for_class = '')
417
-    {
418
-        if (! $this->has_alias($class_name, $for_class)) {
419
-            return $class_name;
420
-        }
421
-        if ($for_class !== '' && isset($this->_aliases[ $for_class ][ $class_name ])) {
422
-            return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
423
-        }
424
-        return $this->get_alias($this->_aliases[$class_name]);
425
-    }
426
-
427
-
428
-
429
-    /**
430
-     * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
431
-     * if one exists, or whether a new object should be generated every time the requested class is loaded.
432
-     * This is done by using the following class constants:
433
-     *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
434
-     *        EE_Dependency_Map::load_new_object - generates a new object every time
435
-     */
436
-    protected function _register_core_dependencies()
437
-    {
438
-        $this->_dependency_map = array(
439
-            'EE_Request_Handler'                                                                                          => array(
440
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
441
-            ),
442
-            'EE_System'                                                                                                   => array(
443
-                'EE_Registry' => EE_Dependency_Map::load_from_cache,
444
-            ),
445
-            'EE_Session'                                                                                                  => array(
446
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
447
-                'EE_Encryption'                                           => EE_Dependency_Map::load_from_cache,
448
-            ),
449
-            'EE_Cart'                                                                                                     => array(
450
-                'EE_Session' => EE_Dependency_Map::load_from_cache,
451
-            ),
452
-            'EE_Front_Controller'                                                                                         => array(
453
-                'EE_Registry'              => EE_Dependency_Map::load_from_cache,
454
-                'EE_Request_Handler'       => EE_Dependency_Map::load_from_cache,
455
-                'EE_Module_Request_Router' => EE_Dependency_Map::load_from_cache,
456
-            ),
457
-            'EE_Messenger_Collection_Loader'                                                                              => array(
458
-                'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
459
-            ),
460
-            'EE_Message_Type_Collection_Loader'                                                                           => array(
461
-                'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
462
-            ),
463
-            'EE_Message_Resource_Manager'                                                                                 => array(
464
-                'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
465
-                'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
466
-                'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
467
-            ),
468
-            'EE_Message_Factory'                                                                                          => array(
469
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
470
-            ),
471
-            'EE_messages'                                                                                                 => array(
472
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
473
-            ),
474
-            'EE_Messages_Generator'                                                                                       => array(
475
-                'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
476
-                'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
477
-                'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
478
-                'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
479
-            ),
480
-            'EE_Messages_Processor'                                                                                       => array(
481
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
482
-            ),
483
-            'EE_Messages_Queue'                                                                                           => array(
484
-                'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
485
-            ),
486
-            'EE_Messages_Template_Defaults'                                                                               => array(
487
-                'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
488
-                'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
489
-            ),
490
-            'EE_Message_To_Generate_From_Request'                                                                         => array(
491
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
492
-                'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
493
-            ),
494
-            'EventEspresso\core\services\commands\CommandBus'                                                             => array(
495
-                'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
496
-            ),
497
-            'EventEspresso\services\commands\CommandHandler'                                                              => array(
498
-                'EE_Registry'         => EE_Dependency_Map::load_from_cache,
499
-                'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
500
-            ),
501
-            'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => array(
502
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
503
-            ),
504
-            'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => array(
505
-                'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
506
-                'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
507
-            ),
508
-            'EventEspresso\core\services\commands\CommandFactory'                                                         => array(
509
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
510
-            ),
511
-            'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => array(
512
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
513
-            ),
514
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => array(
515
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
516
-            ),
517
-            'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => array(
518
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
519
-            ),
520
-            'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => array(
521
-                'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
522
-            ),
523
-            'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => array(
524
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
525
-            ),
526
-            'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => array(
527
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
528
-            ),
529
-            'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => array(
530
-                'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
531
-            ),
532
-            'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => array(
533
-                'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
534
-            ),
535
-            'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => array(
536
-                'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
537
-            ),
538
-            'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => array(
539
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
540
-            ),
541
-            'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => array(
542
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
543
-            ),
544
-            'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => array(
545
-                'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
546
-            ),
547
-            'EventEspresso\core\services\database\TableManager'                                                           => array(
548
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
549
-            ),
550
-            'EE_Data_Migration_Class_Base'                                                                                => array(
551
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
552
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
553
-            ),
554
-            'EE_DMS_Core_4_1_0'                                                                                           => array(
555
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
556
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
557
-            ),
558
-            'EE_DMS_Core_4_2_0'                                                                                           => array(
559
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
560
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
561
-            ),
562
-            'EE_DMS_Core_4_3_0'                                                                                           => array(
563
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
564
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
565
-            ),
566
-            'EE_DMS_Core_4_4_0'                                                                                           => array(
567
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
568
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
569
-            ),
570
-            'EE_DMS_Core_4_5_0'                                                                                           => array(
571
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
572
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
573
-            ),
574
-            'EE_DMS_Core_4_6_0'                                                                                           => array(
575
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
576
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
577
-            ),
578
-            'EE_DMS_Core_4_7_0'                                                                                           => array(
579
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
580
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
581
-            ),
582
-            'EE_DMS_Core_4_8_0'                                                                                           => array(
583
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
584
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
585
-            ),
586
-            'EE_DMS_Core_4_9_0'                                                                                           => array(
587
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
588
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
589
-            ),
590
-            'EventEspresso\core\services\assets\Registry'                                                                 => array(
591
-                'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
592
-                'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
593
-            ),
594
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                             => array(
595
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
596
-            ),
597
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                              => array(
598
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
599
-            ),
600
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                        => array(
601
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
602
-            ),
603
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                => array(
604
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
605
-            ),
606
-            'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                              => array(
607
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
608
-            ),
609
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                        => array(
610
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
611
-            ),
612
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                               => array(
613
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
614
-            ),
615
-            'EventEspresso\core\services\cache\BasicCacheManager'                                                         => array(
616
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
617
-            ),
618
-            'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                   => array(
619
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
620
-            ),
621
-            'EventEspresso\core\services\database\ModelFieldFactory'                                                   => array(
622
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
623
-            ),
624
-            'LEGACY_MODELS'                                                   => array(
625
-                null,
626
-                'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
627
-            ),
628
-        );
629
-    }
630
-
631
-
632
-
633
-    /**
634
-     * Registers how core classes are loaded.
635
-     * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
636
-     *        'EE_Request_Handler' => 'load_core'
637
-     *        'EE_Messages_Queue'  => 'load_lib'
638
-     *        'EEH_Debug_Tools'    => 'load_helper'
639
-     * or, if greater control is required, by providing a custom closure. For example:
640
-     *        'Some_Class' => function () {
641
-     *            return new Some_Class();
642
-     *        },
643
-     * This is required for instantiating dependencies
644
-     * where an interface has been type hinted in a class constructor. For example:
645
-     *        'Required_Interface' => function () {
646
-     *            return new A_Class_That_Implements_Required_Interface();
647
-     *        },
648
-     *
649
-     * @throws InvalidInterfaceException
650
-     * @throws InvalidDataTypeException
651
-     * @throws InvalidArgumentException
652
-     */
653
-    protected function _register_core_class_loaders()
654
-    {
655
-        //for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
656
-        //be used in a closure.
657
-        $request = &$this->_request;
658
-        $response = &$this->_response;
659
-        $loader = &$this->loader;
660
-        $this->_class_loaders = array(
661
-            //load_core
662
-            'EE_Capabilities'                      => 'load_core',
663
-            'EE_Encryption'                        => 'load_core',
664
-            'EE_Front_Controller'                  => 'load_core',
665
-            'EE_Module_Request_Router'             => 'load_core',
666
-            'EE_Registry'                          => 'load_core',
667
-            'EE_Request'                           => function () use (&$request) {
668
-                return $request;
669
-            },
670
-            'EE_Response'                          => function () use (&$response) {
671
-                return $response;
672
-            },
673
-            'EE_Request_Handler'                   => 'load_core',
674
-            'EE_Session'                           => 'load_core',
675
-            'EE_Cron_Tasks'                        => 'load_core',
676
-            //load_lib
677
-            'EE_Message_Resource_Manager'          => 'load_lib',
678
-            'EE_Message_Type_Collection'           => 'load_lib',
679
-            'EE_Message_Type_Collection_Loader'    => 'load_lib',
680
-            'EE_Messenger_Collection'              => 'load_lib',
681
-            'EE_Messenger_Collection_Loader'       => 'load_lib',
682
-            'EE_Messages_Processor'                => 'load_lib',
683
-            'EE_Message_Repository'                => 'load_lib',
684
-            'EE_Messages_Queue'                    => 'load_lib',
685
-            'EE_Messages_Data_Handler_Collection'  => 'load_lib',
686
-            'EE_Message_Template_Group_Collection' => 'load_lib',
687
-            'EE_Messages_Generator'                => function () {
688
-                return EE_Registry::instance()->load_lib(
689
-                    'Messages_Generator',
690
-                    array(),
691
-                    false,
692
-                    false
693
-                );
694
-            },
695
-            'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
696
-                return EE_Registry::instance()->load_lib(
697
-                    'Messages_Template_Defaults',
698
-                    $arguments,
699
-                    false,
700
-                    false
701
-                );
702
-            },
703
-            //load_model
704
-            // 'EEM_Attendee'                         => 'load_model',
705
-            // 'EEM_Message_Template_Group'           => 'load_model',
706
-            // 'EEM_Message_Template'                 => 'load_model',
707
-            //load_helper
708
-            'EEH_Parse_Shortcodes'                 => function () {
709
-                if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
710
-                    return new EEH_Parse_Shortcodes();
711
-                }
712
-                return null;
713
-            },
714
-            'EE_Template_Config'                   => function () {
715
-                return EE_Config::instance()->template_settings;
716
-            },
717
-            'EE_Currency_Config'                   => function () {
718
-                return EE_Config::instance()->currency;
719
-            },
720
-            'EventEspresso\core\services\loaders\Loader' => function () use (&$loader) {
721
-                return $loader;
722
-            },
723
-        );
724
-    }
725
-
726
-
727
-
728
-    /**
729
-     * can be used for supplying alternate names for classes,
730
-     * or for connecting interface names to instantiable classes
731
-     */
732
-    protected function _register_core_aliases()
733
-    {
734
-        $this->_aliases = array(
735
-            'CommandBusInterface'                                                 => 'EventEspresso\core\services\commands\CommandBusInterface',
736
-            'EventEspresso\core\services\commands\CommandBusInterface'            => 'EventEspresso\core\services\commands\CommandBus',
737
-            'CommandHandlerManagerInterface'                                      => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
738
-            'EventEspresso\core\services\commands\CommandHandlerManagerInterface' => 'EventEspresso\core\services\commands\CommandHandlerManager',
739
-            'CapChecker'                                                          => 'EventEspresso\core\services\commands\middleware\CapChecker',
740
-            'AddActionHook'                                                       => 'EventEspresso\core\services\commands\middleware\AddActionHook',
741
-            'CapabilitiesChecker'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
742
-            'CapabilitiesCheckerInterface'                                        => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
743
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
744
-            'CreateRegistrationService'                                           => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
745
-            'CreateRegCodeCommandHandler'                                         => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
746
-            'CreateRegUrlLinkCommandHandler'                                      => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
747
-            'CreateRegistrationCommandHandler'                                    => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
748
-            'CopyRegistrationDetailsCommandHandler'                               => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
749
-            'CopyRegistrationPaymentsCommandHandler'                              => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
750
-            'CancelRegistrationAndTicketLineItemCommandHandler'                   => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
751
-            'UpdateRegistrationAndTransactionAfterChangeCommandHandler'           => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
752
-            'CreateTicketLineItemCommandHandler'                                  => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
753
-            'TableManager'                                                        => 'EventEspresso\core\services\database\TableManager',
754
-            'TableAnalysis'                                                       => 'EventEspresso\core\services\database\TableAnalysis',
755
-            'CreateTransactionCommandHandler'                                     => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
756
-            'CreateAttendeeCommandHandler'                                        => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
757
-            'EspressoShortcode'                                                   => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
758
-            'ShortcodeInterface'                                                  => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
759
-            'EventEspresso\core\services\shortcodes\ShortcodeInterface'           => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
760
-            'EventEspresso\core\services\cache\CacheStorageInterface'             => 'EventEspresso\core\services\cache\TransientCacheStorage',
761
-            'LoaderInterface'                                                     => 'EventEspresso\core\services\loaders\LoaderInterface',
762
-            'EventEspresso\core\services\loaders\LoaderInterface'                 => 'EventEspresso\core\services\loaders\Loader',
763
-            'CommandFactoryInterface'                                             => 'EventEspresso\core\services\commands\CommandFactoryInterface',
764
-            'EventEspresso\core\services\commands\CommandFactoryInterface'        => 'EventEspresso\core\services\commands\CommandFactory',
765
-            'EventEspresso\core\domain\services\session\SessionIdentifierInterface' => 'EE_Session',
766
-            'NoticeConverterInterface'                                            => 'EventEspresso\core\services\notices\NoticeConverterInterface',
767
-            'EventEspresso\core\services\notices\NoticeConverterInterface'        => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
768
-            'NoticesContainerInterface'                                            => 'EventEspresso\core\services\notices\NoticesContainerInterface',
769
-            'EventEspresso\core\services\notices\NoticesContainerInterface'        => 'EventEspresso\core\services\notices\NoticesContainer',
770
-        );
771
-    }
772
-
773
-
774
-
775
-    /**
776
-     * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
777
-     * request Primarily used by unit tests.
778
-     *
779
-     * @throws InvalidDataTypeException
780
-     * @throws InvalidInterfaceException
781
-     * @throws InvalidArgumentException
782
-     */
783
-    public function reset()
784
-    {
785
-        $this->_register_core_class_loaders();
786
-        $this->_register_core_dependencies();
787
-    }
25
+	/**
26
+	 * This means that the requested class dependency is not present in the dependency map
27
+	 */
28
+	const not_registered = 0;
29
+
30
+	/**
31
+	 * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
32
+	 */
33
+	const load_new_object = 1;
34
+
35
+	/**
36
+	 * This instructs class loaders to return a previously instantiated and cached object for the requested class.
37
+	 * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
38
+	 */
39
+	const load_from_cache = 2;
40
+
41
+	/**
42
+	 * When registering a dependency,
43
+	 * this indicates to keep any existing dependencies that already exist,
44
+	 * and simply discard any new dependencies declared in the incoming data
45
+	 */
46
+	const KEEP_EXISTING_DEPENDENCIES = 0;
47
+
48
+	/**
49
+	 * When registering a dependency,
50
+	 * this indicates to overwrite any existing dependencies that already exist using the incoming data
51
+	 */
52
+	const OVERWRITE_DEPENDENCIES = 1;
53
+
54
+
55
+
56
+	/**
57
+	 * @type EE_Dependency_Map $_instance
58
+	 */
59
+	protected static $_instance;
60
+
61
+	/**
62
+	 * @type EE_Request $request
63
+	 */
64
+	protected $_request;
65
+
66
+	/**
67
+	 * @type EE_Response $response
68
+	 */
69
+	protected $_response;
70
+
71
+	/**
72
+	 * @type LoaderInterface $loader
73
+	 */
74
+	protected $loader;
75
+
76
+	/**
77
+	 * @type array $_dependency_map
78
+	 */
79
+	protected $_dependency_map = array();
80
+
81
+	/**
82
+	 * @type array $_class_loaders
83
+	 */
84
+	protected $_class_loaders = array();
85
+
86
+	/**
87
+	 * @type array $_aliases
88
+	 */
89
+	protected $_aliases = array();
90
+
91
+
92
+
93
+	/**
94
+	 * EE_Dependency_Map constructor.
95
+	 *
96
+	 * @param EE_Request  $request
97
+	 * @param EE_Response $response
98
+	 */
99
+	protected function __construct(EE_Request $request, EE_Response $response)
100
+	{
101
+		$this->_request = $request;
102
+		$this->_response = $response;
103
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
104
+		do_action('EE_Dependency_Map____construct');
105
+	}
106
+
107
+
108
+
109
+	/**
110
+	 * @throws InvalidDataTypeException
111
+	 * @throws InvalidInterfaceException
112
+	 * @throws InvalidArgumentException
113
+	 */
114
+	public function initialize()
115
+	{
116
+		$this->_register_core_dependencies();
117
+		$this->_register_core_class_loaders();
118
+		$this->_register_core_aliases();
119
+	}
120
+
121
+
122
+
123
+	/**
124
+	 * @singleton method used to instantiate class object
125
+	 * @access    public
126
+	 * @param EE_Request  $request
127
+	 * @param EE_Response $response
128
+	 * @return EE_Dependency_Map
129
+	 */
130
+	public static function instance(EE_Request $request = null, EE_Response $response = null)
131
+	{
132
+		// check if class object is instantiated, and instantiated properly
133
+		if (! self::$_instance instanceof EE_Dependency_Map) {
134
+			self::$_instance = new EE_Dependency_Map($request, $response);
135
+		}
136
+		return self::$_instance;
137
+	}
138
+
139
+
140
+
141
+	/**
142
+	 * @param LoaderInterface $loader
143
+	 */
144
+	public function setLoader(LoaderInterface $loader)
145
+	{
146
+		$this->loader = $loader;
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * @param string $class
153
+	 * @param array  $dependencies
154
+	 * @param int    $overwrite
155
+	 * @return bool
156
+	 */
157
+	public static function register_dependencies(
158
+		$class,
159
+		array $dependencies,
160
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
161
+	) {
162
+		return self::$_instance->registerDependencies($class, $dependencies, $overwrite);
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 * Assigns an array of class names and corresponding load sources (new or cached)
169
+	 * to the class specified by the first parameter.
170
+	 * IMPORTANT !!!
171
+	 * The order of elements in the incoming $dependencies array MUST match
172
+	 * the order of the constructor parameters for the class in question.
173
+	 * This is especially important when overriding any existing dependencies that are registered.
174
+	 * the third parameter controls whether any duplicate dependencies are overwritten or not.
175
+	 *
176
+	 * @param string $class
177
+	 * @param array  $dependencies
178
+	 * @param int    $overwrite
179
+	 * @return bool
180
+	 */
181
+	public function registerDependencies(
182
+		$class,
183
+		array $dependencies,
184
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
185
+	) {
186
+		$class = trim($class, '\\');
187
+		$registered = false;
188
+		if (empty(self::$_instance->_dependency_map[ $class ])) {
189
+			self::$_instance->_dependency_map[ $class ] = array();
190
+		}
191
+		// we need to make sure that any aliases used when registering a dependency
192
+		// get resolved to the correct class name
193
+		foreach ((array)$dependencies as $dependency => $load_source) {
194
+			$alias = self::$_instance->get_alias($dependency);
195
+			if (
196
+				$overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
197
+				|| ! isset(self::$_instance->_dependency_map[ $class ][ $alias ])
198
+			) {
199
+				unset($dependencies[$dependency]);
200
+				$dependencies[$alias] = $load_source;
201
+				$registered = true;
202
+			}
203
+		}
204
+		// now add our two lists of dependencies together.
205
+		// using Union (+=) favours the arrays in precedence from left to right,
206
+		// so $dependencies is NOT overwritten because it is listed first
207
+		// ie: with A = B + C, entries in B take precedence over duplicate entries in C
208
+		// Union is way faster than array_merge() but should be used with caution...
209
+		// especially with numerically indexed arrays
210
+		$dependencies += self::$_instance->_dependency_map[ $class ];
211
+		// now we need to ensure that the resulting dependencies
212
+		// array only has the entries that are required for the class
213
+		// so first count how many dependencies were originally registered for the class
214
+		$dependency_count = count(self::$_instance->_dependency_map[ $class ]);
215
+		// if that count is non-zero (meaning dependencies were already registered)
216
+		self::$_instance->_dependency_map[ $class ] = $dependency_count
217
+			// then truncate the  final array to match that count
218
+			? array_slice($dependencies, 0, $dependency_count)
219
+			// otherwise just take the incoming array because nothing previously existed
220
+			: $dependencies;
221
+		return $registered;
222
+	}
223
+
224
+
225
+
226
+	/**
227
+	 * @param string $class_name
228
+	 * @param string $loader
229
+	 * @return bool
230
+	 * @throws DomainException
231
+	 */
232
+	public static function register_class_loader($class_name, $loader = 'load_core')
233
+	{
234
+		if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
235
+			throw new DomainException(
236
+				esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
237
+			);
238
+		}
239
+		// check that loader is callable or method starts with "load_" and exists in EE_Registry
240
+		if (
241
+			! is_callable($loader)
242
+			&& (
243
+				strpos($loader, 'load_') !== 0
244
+				|| ! method_exists('EE_Registry', $loader)
245
+			)
246
+		) {
247
+			throw new DomainException(
248
+				sprintf(
249
+					esc_html__(
250
+						'"%1$s" is not a valid loader method on EE_Registry.',
251
+						'event_espresso'
252
+					),
253
+					$loader
254
+				)
255
+			);
256
+		}
257
+		$class_name = self::$_instance->get_alias($class_name);
258
+		if (! isset(self::$_instance->_class_loaders[$class_name])) {
259
+			self::$_instance->_class_loaders[$class_name] = $loader;
260
+			return true;
261
+		}
262
+		return false;
263
+	}
264
+
265
+
266
+
267
+	/**
268
+	 * @return array
269
+	 */
270
+	public function dependency_map()
271
+	{
272
+		return $this->_dependency_map;
273
+	}
274
+
275
+
276
+
277
+	/**
278
+	 * returns TRUE if dependency map contains a listing for the provided class name
279
+	 *
280
+	 * @param string $class_name
281
+	 * @return boolean
282
+	 */
283
+	public function has($class_name = '')
284
+	{
285
+		// all legacy models have the same dependencies
286
+		if (strpos($class_name, 'EEM_') === 0) {
287
+			$class_name = 'LEGACY_MODELS';
288
+		}
289
+		return isset($this->_dependency_map[$class_name]) ? true : false;
290
+	}
291
+
292
+
293
+
294
+	/**
295
+	 * returns TRUE if dependency map contains a listing for the provided class name AND dependency
296
+	 *
297
+	 * @param string $class_name
298
+	 * @param string $dependency
299
+	 * @return bool
300
+	 */
301
+	public function has_dependency_for_class($class_name = '', $dependency = '')
302
+	{
303
+		// all legacy models have the same dependencies
304
+		if (strpos($class_name, 'EEM_') === 0) {
305
+			$class_name = 'LEGACY_MODELS';
306
+		}
307
+		$dependency = $this->get_alias($dependency);
308
+		return isset($this->_dependency_map[$class_name], $this->_dependency_map[$class_name][$dependency])
309
+			? true
310
+			: false;
311
+	}
312
+
313
+
314
+
315
+	/**
316
+	 * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
317
+	 *
318
+	 * @param string $class_name
319
+	 * @param string $dependency
320
+	 * @return int
321
+	 */
322
+	public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
323
+	{
324
+		// all legacy models have the same dependencies
325
+		if (strpos($class_name, 'EEM_') === 0) {
326
+			$class_name = 'LEGACY_MODELS';
327
+		}
328
+		$dependency = $this->get_alias($dependency);
329
+		return $this->has_dependency_for_class($class_name, $dependency)
330
+			? $this->_dependency_map[$class_name][$dependency]
331
+			: EE_Dependency_Map::not_registered;
332
+	}
333
+
334
+
335
+
336
+	/**
337
+	 * @param string $class_name
338
+	 * @return string | Closure
339
+	 */
340
+	public function class_loader($class_name)
341
+	{
342
+		// all legacy models use load_model()
343
+		if(strpos($class_name, 'EEM_') === 0){
344
+			return 'load_model';
345
+		}
346
+		$class_name = $this->get_alias($class_name);
347
+		return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
348
+	}
349
+
350
+
351
+
352
+	/**
353
+	 * @return array
354
+	 */
355
+	public function class_loaders()
356
+	{
357
+		return $this->_class_loaders;
358
+	}
359
+
360
+
361
+
362
+	/**
363
+	 * adds an alias for a classname
364
+	 *
365
+	 * @param string $class_name the class name that should be used (concrete class to replace interface)
366
+	 * @param string $alias      the class name that would be type hinted for (abstract parent or interface)
367
+	 * @param string $for_class  the class that has the dependency (is type hinting for the interface)
368
+	 */
369
+	public function add_alias($class_name, $alias, $for_class = '')
370
+	{
371
+		if ($for_class !== '') {
372
+			if (! isset($this->_aliases[$for_class])) {
373
+				$this->_aliases[$for_class] = array();
374
+			}
375
+			$this->_aliases[$for_class][$class_name] = $alias;
376
+		}
377
+		$this->_aliases[$class_name] = $alias;
378
+	}
379
+
380
+
381
+
382
+	/**
383
+	 * returns TRUE if the provided class name has an alias
384
+	 *
385
+	 * @param string $class_name
386
+	 * @param string $for_class
387
+	 * @return bool
388
+	 */
389
+	public function has_alias($class_name = '', $for_class = '')
390
+	{
391
+		return isset($this->_aliases[$for_class], $this->_aliases[$for_class][$class_name])
392
+			   || (
393
+				   isset($this->_aliases[$class_name])
394
+				   && ! is_array($this->_aliases[$class_name])
395
+			   );
396
+	}
397
+
398
+
399
+
400
+	/**
401
+	 * returns alias for class name if one exists, otherwise returns the original classname
402
+	 * functions recursively, so that multiple aliases can be used to drill down to a classname
403
+	 *  for example:
404
+	 *      if the following two entries were added to the _aliases array:
405
+	 *          array(
406
+	 *              'interface_alias'           => 'some\namespace\interface'
407
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
408
+	 *          )
409
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
410
+	 *      to load an instance of 'some\namespace\classname'
411
+	 *
412
+	 * @param string $class_name
413
+	 * @param string $for_class
414
+	 * @return string
415
+	 */
416
+	public function get_alias($class_name = '', $for_class = '')
417
+	{
418
+		if (! $this->has_alias($class_name, $for_class)) {
419
+			return $class_name;
420
+		}
421
+		if ($for_class !== '' && isset($this->_aliases[ $for_class ][ $class_name ])) {
422
+			return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
423
+		}
424
+		return $this->get_alias($this->_aliases[$class_name]);
425
+	}
426
+
427
+
428
+
429
+	/**
430
+	 * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
431
+	 * if one exists, or whether a new object should be generated every time the requested class is loaded.
432
+	 * This is done by using the following class constants:
433
+	 *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
434
+	 *        EE_Dependency_Map::load_new_object - generates a new object every time
435
+	 */
436
+	protected function _register_core_dependencies()
437
+	{
438
+		$this->_dependency_map = array(
439
+			'EE_Request_Handler'                                                                                          => array(
440
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
441
+			),
442
+			'EE_System'                                                                                                   => array(
443
+				'EE_Registry' => EE_Dependency_Map::load_from_cache,
444
+			),
445
+			'EE_Session'                                                                                                  => array(
446
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
447
+				'EE_Encryption'                                           => EE_Dependency_Map::load_from_cache,
448
+			),
449
+			'EE_Cart'                                                                                                     => array(
450
+				'EE_Session' => EE_Dependency_Map::load_from_cache,
451
+			),
452
+			'EE_Front_Controller'                                                                                         => array(
453
+				'EE_Registry'              => EE_Dependency_Map::load_from_cache,
454
+				'EE_Request_Handler'       => EE_Dependency_Map::load_from_cache,
455
+				'EE_Module_Request_Router' => EE_Dependency_Map::load_from_cache,
456
+			),
457
+			'EE_Messenger_Collection_Loader'                                                                              => array(
458
+				'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
459
+			),
460
+			'EE_Message_Type_Collection_Loader'                                                                           => array(
461
+				'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
462
+			),
463
+			'EE_Message_Resource_Manager'                                                                                 => array(
464
+				'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
465
+				'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
466
+				'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
467
+			),
468
+			'EE_Message_Factory'                                                                                          => array(
469
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
470
+			),
471
+			'EE_messages'                                                                                                 => array(
472
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
473
+			),
474
+			'EE_Messages_Generator'                                                                                       => array(
475
+				'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
476
+				'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
477
+				'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
478
+				'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
479
+			),
480
+			'EE_Messages_Processor'                                                                                       => array(
481
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
482
+			),
483
+			'EE_Messages_Queue'                                                                                           => array(
484
+				'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
485
+			),
486
+			'EE_Messages_Template_Defaults'                                                                               => array(
487
+				'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
488
+				'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
489
+			),
490
+			'EE_Message_To_Generate_From_Request'                                                                         => array(
491
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
492
+				'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
493
+			),
494
+			'EventEspresso\core\services\commands\CommandBus'                                                             => array(
495
+				'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
496
+			),
497
+			'EventEspresso\services\commands\CommandHandler'                                                              => array(
498
+				'EE_Registry'         => EE_Dependency_Map::load_from_cache,
499
+				'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
500
+			),
501
+			'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => array(
502
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
503
+			),
504
+			'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => array(
505
+				'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
506
+				'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
507
+			),
508
+			'EventEspresso\core\services\commands\CommandFactory'                                                         => array(
509
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
510
+			),
511
+			'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => array(
512
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
513
+			),
514
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => array(
515
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
516
+			),
517
+			'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => array(
518
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
519
+			),
520
+			'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => array(
521
+				'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
522
+			),
523
+			'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => array(
524
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
525
+			),
526
+			'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => array(
527
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
528
+			),
529
+			'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => array(
530
+				'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
531
+			),
532
+			'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => array(
533
+				'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
534
+			),
535
+			'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => array(
536
+				'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
537
+			),
538
+			'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => array(
539
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
540
+			),
541
+			'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => array(
542
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
543
+			),
544
+			'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => array(
545
+				'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
546
+			),
547
+			'EventEspresso\core\services\database\TableManager'                                                           => array(
548
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
549
+			),
550
+			'EE_Data_Migration_Class_Base'                                                                                => array(
551
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
552
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
553
+			),
554
+			'EE_DMS_Core_4_1_0'                                                                                           => array(
555
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
556
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
557
+			),
558
+			'EE_DMS_Core_4_2_0'                                                                                           => array(
559
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
560
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
561
+			),
562
+			'EE_DMS_Core_4_3_0'                                                                                           => array(
563
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
564
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
565
+			),
566
+			'EE_DMS_Core_4_4_0'                                                                                           => array(
567
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
568
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
569
+			),
570
+			'EE_DMS_Core_4_5_0'                                                                                           => array(
571
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
572
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
573
+			),
574
+			'EE_DMS_Core_4_6_0'                                                                                           => array(
575
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
576
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
577
+			),
578
+			'EE_DMS_Core_4_7_0'                                                                                           => array(
579
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
580
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
581
+			),
582
+			'EE_DMS_Core_4_8_0'                                                                                           => array(
583
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
584
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
585
+			),
586
+			'EE_DMS_Core_4_9_0'                                                                                           => array(
587
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
588
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
589
+			),
590
+			'EventEspresso\core\services\assets\Registry'                                                                 => array(
591
+				'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
592
+				'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
593
+			),
594
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                             => array(
595
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
596
+			),
597
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                              => array(
598
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
599
+			),
600
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                        => array(
601
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
602
+			),
603
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                => array(
604
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
605
+			),
606
+			'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                              => array(
607
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
608
+			),
609
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                        => array(
610
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
611
+			),
612
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                               => array(
613
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
614
+			),
615
+			'EventEspresso\core\services\cache\BasicCacheManager'                                                         => array(
616
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
617
+			),
618
+			'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                   => array(
619
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
620
+			),
621
+			'EventEspresso\core\services\database\ModelFieldFactory'                                                   => array(
622
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
623
+			),
624
+			'LEGACY_MODELS'                                                   => array(
625
+				null,
626
+				'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
627
+			),
628
+		);
629
+	}
630
+
631
+
632
+
633
+	/**
634
+	 * Registers how core classes are loaded.
635
+	 * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
636
+	 *        'EE_Request_Handler' => 'load_core'
637
+	 *        'EE_Messages_Queue'  => 'load_lib'
638
+	 *        'EEH_Debug_Tools'    => 'load_helper'
639
+	 * or, if greater control is required, by providing a custom closure. For example:
640
+	 *        'Some_Class' => function () {
641
+	 *            return new Some_Class();
642
+	 *        },
643
+	 * This is required for instantiating dependencies
644
+	 * where an interface has been type hinted in a class constructor. For example:
645
+	 *        'Required_Interface' => function () {
646
+	 *            return new A_Class_That_Implements_Required_Interface();
647
+	 *        },
648
+	 *
649
+	 * @throws InvalidInterfaceException
650
+	 * @throws InvalidDataTypeException
651
+	 * @throws InvalidArgumentException
652
+	 */
653
+	protected function _register_core_class_loaders()
654
+	{
655
+		//for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
656
+		//be used in a closure.
657
+		$request = &$this->_request;
658
+		$response = &$this->_response;
659
+		$loader = &$this->loader;
660
+		$this->_class_loaders = array(
661
+			//load_core
662
+			'EE_Capabilities'                      => 'load_core',
663
+			'EE_Encryption'                        => 'load_core',
664
+			'EE_Front_Controller'                  => 'load_core',
665
+			'EE_Module_Request_Router'             => 'load_core',
666
+			'EE_Registry'                          => 'load_core',
667
+			'EE_Request'                           => function () use (&$request) {
668
+				return $request;
669
+			},
670
+			'EE_Response'                          => function () use (&$response) {
671
+				return $response;
672
+			},
673
+			'EE_Request_Handler'                   => 'load_core',
674
+			'EE_Session'                           => 'load_core',
675
+			'EE_Cron_Tasks'                        => 'load_core',
676
+			//load_lib
677
+			'EE_Message_Resource_Manager'          => 'load_lib',
678
+			'EE_Message_Type_Collection'           => 'load_lib',
679
+			'EE_Message_Type_Collection_Loader'    => 'load_lib',
680
+			'EE_Messenger_Collection'              => 'load_lib',
681
+			'EE_Messenger_Collection_Loader'       => 'load_lib',
682
+			'EE_Messages_Processor'                => 'load_lib',
683
+			'EE_Message_Repository'                => 'load_lib',
684
+			'EE_Messages_Queue'                    => 'load_lib',
685
+			'EE_Messages_Data_Handler_Collection'  => 'load_lib',
686
+			'EE_Message_Template_Group_Collection' => 'load_lib',
687
+			'EE_Messages_Generator'                => function () {
688
+				return EE_Registry::instance()->load_lib(
689
+					'Messages_Generator',
690
+					array(),
691
+					false,
692
+					false
693
+				);
694
+			},
695
+			'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
696
+				return EE_Registry::instance()->load_lib(
697
+					'Messages_Template_Defaults',
698
+					$arguments,
699
+					false,
700
+					false
701
+				);
702
+			},
703
+			//load_model
704
+			// 'EEM_Attendee'                         => 'load_model',
705
+			// 'EEM_Message_Template_Group'           => 'load_model',
706
+			// 'EEM_Message_Template'                 => 'load_model',
707
+			//load_helper
708
+			'EEH_Parse_Shortcodes'                 => function () {
709
+				if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
710
+					return new EEH_Parse_Shortcodes();
711
+				}
712
+				return null;
713
+			},
714
+			'EE_Template_Config'                   => function () {
715
+				return EE_Config::instance()->template_settings;
716
+			},
717
+			'EE_Currency_Config'                   => function () {
718
+				return EE_Config::instance()->currency;
719
+			},
720
+			'EventEspresso\core\services\loaders\Loader' => function () use (&$loader) {
721
+				return $loader;
722
+			},
723
+		);
724
+	}
725
+
726
+
727
+
728
+	/**
729
+	 * can be used for supplying alternate names for classes,
730
+	 * or for connecting interface names to instantiable classes
731
+	 */
732
+	protected function _register_core_aliases()
733
+	{
734
+		$this->_aliases = array(
735
+			'CommandBusInterface'                                                 => 'EventEspresso\core\services\commands\CommandBusInterface',
736
+			'EventEspresso\core\services\commands\CommandBusInterface'            => 'EventEspresso\core\services\commands\CommandBus',
737
+			'CommandHandlerManagerInterface'                                      => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
738
+			'EventEspresso\core\services\commands\CommandHandlerManagerInterface' => 'EventEspresso\core\services\commands\CommandHandlerManager',
739
+			'CapChecker'                                                          => 'EventEspresso\core\services\commands\middleware\CapChecker',
740
+			'AddActionHook'                                                       => 'EventEspresso\core\services\commands\middleware\AddActionHook',
741
+			'CapabilitiesChecker'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
742
+			'CapabilitiesCheckerInterface'                                        => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
743
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
744
+			'CreateRegistrationService'                                           => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
745
+			'CreateRegCodeCommandHandler'                                         => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
746
+			'CreateRegUrlLinkCommandHandler'                                      => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
747
+			'CreateRegistrationCommandHandler'                                    => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
748
+			'CopyRegistrationDetailsCommandHandler'                               => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
749
+			'CopyRegistrationPaymentsCommandHandler'                              => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
750
+			'CancelRegistrationAndTicketLineItemCommandHandler'                   => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
751
+			'UpdateRegistrationAndTransactionAfterChangeCommandHandler'           => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
752
+			'CreateTicketLineItemCommandHandler'                                  => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
753
+			'TableManager'                                                        => 'EventEspresso\core\services\database\TableManager',
754
+			'TableAnalysis'                                                       => 'EventEspresso\core\services\database\TableAnalysis',
755
+			'CreateTransactionCommandHandler'                                     => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
756
+			'CreateAttendeeCommandHandler'                                        => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
757
+			'EspressoShortcode'                                                   => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
758
+			'ShortcodeInterface'                                                  => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
759
+			'EventEspresso\core\services\shortcodes\ShortcodeInterface'           => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
760
+			'EventEspresso\core\services\cache\CacheStorageInterface'             => 'EventEspresso\core\services\cache\TransientCacheStorage',
761
+			'LoaderInterface'                                                     => 'EventEspresso\core\services\loaders\LoaderInterface',
762
+			'EventEspresso\core\services\loaders\LoaderInterface'                 => 'EventEspresso\core\services\loaders\Loader',
763
+			'CommandFactoryInterface'                                             => 'EventEspresso\core\services\commands\CommandFactoryInterface',
764
+			'EventEspresso\core\services\commands\CommandFactoryInterface'        => 'EventEspresso\core\services\commands\CommandFactory',
765
+			'EventEspresso\core\domain\services\session\SessionIdentifierInterface' => 'EE_Session',
766
+			'NoticeConverterInterface'                                            => 'EventEspresso\core\services\notices\NoticeConverterInterface',
767
+			'EventEspresso\core\services\notices\NoticeConverterInterface'        => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
768
+			'NoticesContainerInterface'                                            => 'EventEspresso\core\services\notices\NoticesContainerInterface',
769
+			'EventEspresso\core\services\notices\NoticesContainerInterface'        => 'EventEspresso\core\services\notices\NoticesContainer',
770
+		);
771
+	}
772
+
773
+
774
+
775
+	/**
776
+	 * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
777
+	 * request Primarily used by unit tests.
778
+	 *
779
+	 * @throws InvalidDataTypeException
780
+	 * @throws InvalidInterfaceException
781
+	 * @throws InvalidArgumentException
782
+	 */
783
+	public function reset()
784
+	{
785
+		$this->_register_core_class_loaders();
786
+		$this->_register_core_dependencies();
787
+	}
788 788
 
789 789
 
790 790
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\services\loaders\LoaderFactory;
5 5
 use EventEspresso\core\services\loaders\LoaderInterface;
6 6
 
7
-if (! defined('EVENT_ESPRESSO_VERSION')) {
7
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
8 8
     exit('No direct script access allowed');
9 9
 }
10 10
 
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
     public static function instance(EE_Request $request = null, EE_Response $response = null)
131 131
     {
132 132
         // check if class object is instantiated, and instantiated properly
133
-        if (! self::$_instance instanceof EE_Dependency_Map) {
133
+        if ( ! self::$_instance instanceof EE_Dependency_Map) {
134 134
             self::$_instance = new EE_Dependency_Map($request, $response);
135 135
         }
136 136
         return self::$_instance;
@@ -185,16 +185,16 @@  discard block
 block discarded – undo
185 185
     ) {
186 186
         $class = trim($class, '\\');
187 187
         $registered = false;
188
-        if (empty(self::$_instance->_dependency_map[ $class ])) {
189
-            self::$_instance->_dependency_map[ $class ] = array();
188
+        if (empty(self::$_instance->_dependency_map[$class])) {
189
+            self::$_instance->_dependency_map[$class] = array();
190 190
         }
191 191
         // we need to make sure that any aliases used when registering a dependency
192 192
         // get resolved to the correct class name
193
-        foreach ((array)$dependencies as $dependency => $load_source) {
193
+        foreach ((array) $dependencies as $dependency => $load_source) {
194 194
             $alias = self::$_instance->get_alias($dependency);
195 195
             if (
196 196
                 $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
197
-                || ! isset(self::$_instance->_dependency_map[ $class ][ $alias ])
197
+                || ! isset(self::$_instance->_dependency_map[$class][$alias])
198 198
             ) {
199 199
                 unset($dependencies[$dependency]);
200 200
                 $dependencies[$alias] = $load_source;
@@ -207,13 +207,13 @@  discard block
 block discarded – undo
207 207
         // ie: with A = B + C, entries in B take precedence over duplicate entries in C
208 208
         // Union is way faster than array_merge() but should be used with caution...
209 209
         // especially with numerically indexed arrays
210
-        $dependencies += self::$_instance->_dependency_map[ $class ];
210
+        $dependencies += self::$_instance->_dependency_map[$class];
211 211
         // now we need to ensure that the resulting dependencies
212 212
         // array only has the entries that are required for the class
213 213
         // so first count how many dependencies were originally registered for the class
214
-        $dependency_count = count(self::$_instance->_dependency_map[ $class ]);
214
+        $dependency_count = count(self::$_instance->_dependency_map[$class]);
215 215
         // if that count is non-zero (meaning dependencies were already registered)
216
-        self::$_instance->_dependency_map[ $class ] = $dependency_count
216
+        self::$_instance->_dependency_map[$class] = $dependency_count
217 217
             // then truncate the  final array to match that count
218 218
             ? array_slice($dependencies, 0, $dependency_count)
219 219
             // otherwise just take the incoming array because nothing previously existed
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
      */
232 232
     public static function register_class_loader($class_name, $loader = 'load_core')
233 233
     {
234
-        if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
234
+        if ( ! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
235 235
             throw new DomainException(
236 236
                 esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
237 237
             );
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
             );
256 256
         }
257 257
         $class_name = self::$_instance->get_alias($class_name);
258
-        if (! isset(self::$_instance->_class_loaders[$class_name])) {
258
+        if ( ! isset(self::$_instance->_class_loaders[$class_name])) {
259 259
             self::$_instance->_class_loaders[$class_name] = $loader;
260 260
             return true;
261 261
         }
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
     public function class_loader($class_name)
341 341
     {
342 342
         // all legacy models use load_model()
343
-        if(strpos($class_name, 'EEM_') === 0){
343
+        if (strpos($class_name, 'EEM_') === 0) {
344 344
             return 'load_model';
345 345
         }
346 346
         $class_name = $this->get_alias($class_name);
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
     public function add_alias($class_name, $alias, $for_class = '')
370 370
     {
371 371
         if ($for_class !== '') {
372
-            if (! isset($this->_aliases[$for_class])) {
372
+            if ( ! isset($this->_aliases[$for_class])) {
373 373
                 $this->_aliases[$for_class] = array();
374 374
             }
375 375
             $this->_aliases[$for_class][$class_name] = $alias;
@@ -415,10 +415,10 @@  discard block
 block discarded – undo
415 415
      */
416 416
     public function get_alias($class_name = '', $for_class = '')
417 417
     {
418
-        if (! $this->has_alias($class_name, $for_class)) {
418
+        if ( ! $this->has_alias($class_name, $for_class)) {
419 419
             return $class_name;
420 420
         }
421
-        if ($for_class !== '' && isset($this->_aliases[ $for_class ][ $class_name ])) {
421
+        if ($for_class !== '' && isset($this->_aliases[$for_class][$class_name])) {
422 422
             return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
423 423
         }
424 424
         return $this->get_alias($this->_aliases[$class_name]);
@@ -664,10 +664,10 @@  discard block
 block discarded – undo
664 664
             'EE_Front_Controller'                  => 'load_core',
665 665
             'EE_Module_Request_Router'             => 'load_core',
666 666
             'EE_Registry'                          => 'load_core',
667
-            'EE_Request'                           => function () use (&$request) {
667
+            'EE_Request'                           => function() use (&$request) {
668 668
                 return $request;
669 669
             },
670
-            'EE_Response'                          => function () use (&$response) {
670
+            'EE_Response'                          => function() use (&$response) {
671 671
                 return $response;
672 672
             },
673 673
             'EE_Request_Handler'                   => 'load_core',
@@ -684,7 +684,7 @@  discard block
 block discarded – undo
684 684
             'EE_Messages_Queue'                    => 'load_lib',
685 685
             'EE_Messages_Data_Handler_Collection'  => 'load_lib',
686 686
             'EE_Message_Template_Group_Collection' => 'load_lib',
687
-            'EE_Messages_Generator'                => function () {
687
+            'EE_Messages_Generator'                => function() {
688 688
                 return EE_Registry::instance()->load_lib(
689 689
                     'Messages_Generator',
690 690
                     array(),
@@ -692,7 +692,7 @@  discard block
 block discarded – undo
692 692
                     false
693 693
                 );
694 694
             },
695
-            'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
695
+            'EE_Messages_Template_Defaults'        => function($arguments = array()) {
696 696
                 return EE_Registry::instance()->load_lib(
697 697
                     'Messages_Template_Defaults',
698 698
                     $arguments,
@@ -705,19 +705,19 @@  discard block
 block discarded – undo
705 705
             // 'EEM_Message_Template_Group'           => 'load_model',
706 706
             // 'EEM_Message_Template'                 => 'load_model',
707 707
             //load_helper
708
-            'EEH_Parse_Shortcodes'                 => function () {
708
+            'EEH_Parse_Shortcodes'                 => function() {
709 709
                 if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
710 710
                     return new EEH_Parse_Shortcodes();
711 711
                 }
712 712
                 return null;
713 713
             },
714
-            'EE_Template_Config'                   => function () {
714
+            'EE_Template_Config'                   => function() {
715 715
                 return EE_Config::instance()->template_settings;
716 716
             },
717
-            'EE_Currency_Config'                   => function () {
717
+            'EE_Currency_Config'                   => function() {
718 718
                 return EE_Config::instance()->currency;
719 719
             },
720
-            'EventEspresso\core\services\loaders\Loader' => function () use (&$loader) {
720
+            'EventEspresso\core\services\loaders\Loader' => function() use (&$loader) {
721 721
                 return $loader;
722 722
             },
723 723
         );
Please login to merge, or discard this patch.