Completed
Branch FET-10304-welcome-to-vue (2869cd)
by
unknown
12:52
created
admin_pages/messages/help_tabs/messages_templates.help_tab.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@
 block discarded – undo
1 1
 <p><strong><?php esc_html_e('Message Templates', 'event_espresso'); ?></strong></p>
2
-<p><?php printf( esc_html__('Message Templates are the %1$sformat%2$s of the messages going out. Think of them as a “form letter”. Templates tell the Messages system how to style your messages and the content (information) they will have when they are delivered.', 'event_espresso'), '<em>', '</em>'); ?></p>
2
+<p><?php printf(esc_html__('Message Templates are the %1$sformat%2$s of the messages going out. Think of them as a “form letter”. Templates tell the Messages system how to style your messages and the content (information) they will have when they are delivered.', 'event_espresso'), '<em>', '</em>'); ?></p>
3 3
 <p><?php esc_html_e('There is a template created for each Messenger / Message Type and context combination. For example, messages that are sent for Payment Confirmation have a template for Event Administrator and a different one for Primary Registrant.  Whereas, messages that are sent for the Registration confirmation have 3 templates: one for Event Administrator, one for the Primary Registrant, and another for each additional Registrant(s).', 'event_espresso'); ?></p>
4
-<p><?php esc_html_e('With the Event Espresso Messages system, every Messenger, Message Type, and context will have a global template created with some default content on creation. You have the ability to edit the global template that will be used for all events you create. Additionally, you have the ability to create custom templates for each event on the edit event page for the event (in a metabox labelled "Notifications").', 'event_espresso' ); ?></p>
5 4
\ No newline at end of file
5
+<p><?php esc_html_e('With the Event Espresso Messages system, every Messenger, Message Type, and context will have a global template created with some default content on creation. You have the ability to edit the global template that will be used for all events you create. Additionally, you have the ability to create custom templates for each event on the edit event page for the event (in a metabox labelled "Notifications").', 'event_espresso'); ?></p>
6 6
\ No newline at end of file
Please login to merge, or discard this patch.
messages/templates/ee_msg_message_templates_help_tab.template.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@
 block discarded – undo
1 1
 <h2><?php esc_html_e('What are Message Templates', 'event_espresso'); ?></h2>
2
-<p><?php printf( esc_html__('Message Templates are the %1$sformat%2$s of the messages going out. Think of them like a “Form letter”. Templates are used to tell the system what you want your messages to look like and the content they will have when they are delivered.', 'event_espresso'), '<em>', '</em>' ); ?></p>
2
+<p><?php printf(esc_html__('Message Templates are the %1$sformat%2$s of the messages going out. Think of them like a “Form letter”. Templates are used to tell the system what you want your messages to look like and the content they will have when they are delivered.', 'event_espresso'), '<em>', '</em>'); ?></p>
3 3
 <p><?php esc_html_e('There is a template created for each messenger/message type AND context combination. So example, Emails that are sent for the Payment confirmation have a template for Event Administrator and a different one for Primary Registrant.  Whereas, emails that are sent for the Registration confirmation have 3 templates, one for Event Administrator, Primary Registrant, and Registrant.', 'event_espresso'); ?></p>
4
-<p><?php esc_html_e('With the Event Espresso Messages system, every Messenger, Message Type and Context will have a global template created with some default content on creation.  You have the ability to edit this global template that will be used for all events you create.  However, you also have the ability to create custom templates for each event on the edit event page for the event (in a metabox labelled "Notifications").', 'event_espresso' ); ?></p>
5 4
\ No newline at end of file
5
+<p><?php esc_html_e('With the Event Espresso Messages system, every Messenger, Message Type and Context will have a global template created with some default content on creation.  You have the ability to edit this global template that will be used for all events you create.  However, you also have the ability to create custom templates for each event on the edit event page for the event (in a metabox labelled "Notifications").', 'event_espresso'); ?></p>
6 6
\ No newline at end of file
Please login to merge, or discard this patch.
messages/templates/ee_msg_messages_templates_editor_help_tab.template.php 1 patch
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -2,29 +2,29 @@
 block discarded – undo
2 2
 <p><?php _e('Here are a few things that you should know about the Message Template Editor:', 'event_espresso'); ?></p>
3 3
 <p><strong><?php esc_html_e('1. The Event Editor Title', 'event_espresso'); ?></strong></p>
4 4
 <p><?php echo $img1; ?></p>
5
-<p><?php printf( esc_html__( 'The Event Editor title is very helpful in indicating which template you are currently editing.  In the example above, we can see that we are editing the template that for the %1$sEmail%2$s messenger, the %1$sPayment%2$s message type, and the %1$sEvent Admin%2$s context (which for this message type means "recipient").', 'event_espresso'), '<strong>','</strong>' ); ?></p>
5
+<p><?php printf(esc_html__('The Event Editor title is very helpful in indicating which template you are currently editing.  In the example above, we can see that we are editing the template that for the %1$sEmail%2$s messenger, the %1$sPayment%2$s message type, and the %1$sEvent Admin%2$s context (which for this message type means "recipient").', 'event_espresso'), '<strong>', '</strong>'); ?></p>
6 6
 <p><strong><?php esc_html_e('2. "Context Switcher" and Preview Button', 'event_espresso'); ?></strong></p>
7 7
 <p><?php echo $img2; ?></p>
8 8
 <p><?php esc_html_e('The context switcher allows you to quickly switch between templates. The current context you are working on is displayed in the dropdown. You can switch to any other template for contexts available to the messenger and message type template group you are working on.', 'event_espresso'); ?></p>
9 9
 <p><?php esc_html_e('Remember that contexts can represent different things. In this example they represent "recipients" and so they are labelled as such. In this example (for email payment confirmations), you may want Event Administrators to receive different information than Primary Registrants (the other context available to edit).', 'event_espresso'); ?></p>
10
-<p><?php printf( esc_html__('The %sPreview%s button is simply a link to a special view of the current template displayed to give you an idea of how the actual message will look when delivered. More information on what the preview displays is available in the content of the help tab on the preview page.', 'event_espresso'), '<strong>', '</strong>' ); ?>
10
+<p><?php printf(esc_html__('The %sPreview%s button is simply a link to a special view of the current template displayed to give you an idea of how the actual message will look when delivered. More information on what the preview displays is available in the content of the help tab on the preview page.', 'event_espresso'), '<strong>', '</strong>'); ?>
11 11
 </p>
12 12
 <p><strong><?php esc_html_e('3. Template Form Fields', 'event_espresso'); ?></strong></p>
13 13
 <p><?php echo $img3; ?><?php esc_html_e('The middle area of the page is dedicated to all the fields related to the message template. These fields are dynamic in the sense that different messengers may require different fields (and sometimes different message types will add or subtract fields as well.', 'event_espresso'); ?></p>
14
-<p><?php printf( esc_html__('When editing a "Email Payment Template", you will notice that there is a field labelled "Event List" along with "Main Content". The Event List field is a special field that holds the template for whenever the %1$s[EVENT_LIST]%2$s shortcode is used in the "Main Content" field. This is so you can more finely control how each "event" in the event list displays when shown in the Main content. The "Email Registration Template", has an additional field called "Registration List". It functions much the same except that the contents of the "Registration List" field are used to indicate how each registrant is listed in the Main Content when the %1$s[ATTENDEE_LIST]%2$s shortcode is parsed.', 'event_espresso'), '<strong>', '</strong>' ); ?></p>
14
+<p><?php printf(esc_html__('When editing a "Email Payment Template", you will notice that there is a field labelled "Event List" along with "Main Content". The Event List field is a special field that holds the template for whenever the %1$s[EVENT_LIST]%2$s shortcode is used in the "Main Content" field. This is so you can more finely control how each "event" in the event list displays when shown in the Main content. The "Email Registration Template", has an additional field called "Registration List". It functions much the same except that the contents of the "Registration List" field are used to indicate how each registrant is listed in the Main Content when the %1$s[ATTENDEE_LIST]%2$s shortcode is parsed.', 'event_espresso'), '<strong>', '</strong>'); ?></p>
15 15
 <div style="clear:both"></div>
16 16
 <p><strong><?php esc_html_e('4. Valid Shortcodes Metabox', 'event_espresso'); ?></strong></p>
17 17
 <p>
18 18
 	<?php echo $img4; ?><?php esc_html_e('The "Valid Shortcodes" metabox contains a list of all the shortcodes that can be used for the displayed template. This list is dynamic and will vary between templates.', 'event_espresso'); ?>
19 19
 </p>
20 20
 <p><?php _e('This box is at a fixed height, but contents are scrollable. You can click the question mark to find out what the given shortcode will parse to when used in your template.', 'event_espresso'); ?></p>
21
-<p><?php printf( esc_html__('%sAn important note:%s The system has been designed so that when you save the template, checks will be performed on each field to make sure that only valid shortcodes (or values) are used within them.  You will get a warning box with clear instructions if you\'ve tried to use a particular shortcode in a field that does not support it.  Also, you\'ll want to try the Preview button if you\'ve made any changes to the template to see if the changes are as you expected!', 'event_espresso'), '<strong>', '</strong>' ); ?>
21
+<p><?php printf(esc_html__('%sAn important note:%s The system has been designed so that when you save the template, checks will be performed on each field to make sure that only valid shortcodes (or values) are used within them.  You will get a warning box with clear instructions if you\'ve tried to use a particular shortcode in a field that does not support it.  Also, you\'ll want to try the Preview button if you\'ve made any changes to the template to see if the changes are as you expected!', 'event_espresso'), '<strong>', '</strong>'); ?>
22 22
 </p>
23 23
 <div style="clear:both"></div>
24 24
 <p><strong><?php esc_html_e('5. Override All Custom', 'event_espresso'); ?></strong></p>
25 25
 <p>
26 26
 	<?php echo $img5; ?>
27
-	<?php printf( esc_html__( 'When you are editing a template that is a global template (not a custom event template), you\'ll see an option in the Publish metabox in the right column labelled "Override all custom". When this option is selected, custom event templates for that %1$smessenger%2$s, %1$smessage type%2$s, and %1$scontext%2$s will be ignored and the global template will be used. Why would you want to do this? For this given example, you may want to be able to allow custom event templates to be able to modify the looks and content of what goes out to Primary Registrant but to never affect what the Event Administrator receives (as set by the global template).', 'event_espresso'), '<em>', '</em>' ); ?>
27
+	<?php printf(esc_html__('When you are editing a template that is a global template (not a custom event template), you\'ll see an option in the Publish metabox in the right column labelled "Override all custom". When this option is selected, custom event templates for that %1$smessenger%2$s, %1$smessage type%2$s, and %1$scontext%2$s will be ignored and the global template will be used. Why would you want to do this? For this given example, you may want to be able to allow custom event templates to be able to modify the looks and content of what goes out to Primary Registrant but to never affect what the Event Administrator receives (as set by the global template).', 'event_espresso'), '<em>', '</em>'); ?>
28 28
 </p>
29 29
 <p>
30 30
 <strong><?php esc_html_e('Recommendations', 'event_espresso'); ?></strong><br />
Please login to merge, or discard this patch.
admin_pages/messages/templates/ee_msg_overview_help_tab.template.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -41,7 +41,7 @@
 block discarded – undo
41 41
 		</li>
42 42
 		<li>
43 43
 			<?php esc_html_e('Messenger', 'event_espresso'); ?><br />
44
-			<?php printf( esc_html__('This column displays a number of different elements for the listed template.  First is the messenger that this template is delivered by.  The messenger title is linked to the editor for the first %1$scontext%2$s listed (context is labelled "recipients" for payment message types)', 'event_espresso'), '<em>', '</em>'); ?><br />
44
+			<?php printf(esc_html__('This column displays a number of different elements for the listed template.  First is the messenger that this template is delivered by.  The messenger title is linked to the editor for the first %1$scontext%2$s listed (context is labelled "recipients" for payment message types)', 'event_espresso'), '<em>', '</em>'); ?><br />
45 45
 			<?php esc_html_e('Below the Messenger title, is a list of different contexts.  The context label varies for each message type but it is usually labelled "Recipients".  You can click on each context title to go to the specific template for that context and edit it as desired.', 'event_espresso'); ?>
46 46
 		</li>
47 47
 	</ul>
Please login to merge, or discard this patch.
admin_pages/messages/templates/ee_msg_message_type_help_tab.template.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -1,7 +1,7 @@
 block discarded – undo
1 1
 <h2><?php esc_html_e('What are Message Types?', 'event_espresso'); ?></h2>
2
-<p><?php printf( esc_html__('Message Types are the %1$skinds%2$s of messages that get delivered.  Think of them as the "type" of package that is being delivered by the messenger.  For example, Event Espresso comes with two Message Types attached to the Email messenger:  Registration Confirmation (which is triggered by frontend event registrations), and Payment Confirmation (which is triggered by frontend payments).', 'event_espresso'), '<em>', '</em>'); ?></p>
2
+<p><?php printf(esc_html__('Message Types are the %1$skinds%2$s of messages that get delivered.  Think of them as the "type" of package that is being delivered by the messenger.  For example, Event Espresso comes with two Message Types attached to the Email messenger:  Registration Confirmation (which is triggered by frontend event registrations), and Payment Confirmation (which is triggered by frontend payments).', 'event_espresso'), '<em>', '</em>'); ?></p>
3 3
 <p><?php esc_html_e('Future iterations of Event Espresso 4.0 (premium versions), will include more and more different message types that can be attached to the various messengers that are available', 'event_espresso'); ?></p>
4 4
 
5 5
 <h3><?php esc_html_e('Contexts', 'event_espresso'); ?></h3>
6
-<p><?php printf( esc_html__('Each message type (or %1$skind%1$s of message remember!) has different contexts for messages created for that message type. Contexts are dynamic but generally speaking they tend to represent recipients. So for example, Registration Confirmation message type has three types of recipients for every time a registration confirmation is triggered: Event Administrator, Primary Registrant, and Registrant (which may be multiple messages if there are more than one attendee per event). Whereas the Payment Message Type only has two recipients (Event Administrator, Primary Registrant [the one making the payment]).', 'event_espresso' ), '<em>', '</em>'); ?></p>
6
+<p><?php printf(esc_html__('Each message type (or %1$skind%1$s of message remember!) has different contexts for messages created for that message type. Contexts are dynamic but generally speaking they tend to represent recipients. So for example, Registration Confirmation message type has three types of recipients for every time a registration confirmation is triggered: Event Administrator, Primary Registrant, and Registrant (which may be multiple messages if there are more than one attendee per event). Whereas the Payment Message Type only has two recipients (Event Administrator, Primary Registrant [the one making the payment]).', 'event_espresso'), '<em>', '</em>'); ?></p>
7 7
 <p><?php esc_html_e('You will most likely never see the word "context" in any of the Messages system labelling because they are dynamic per message type.  Usually, contexts will be labelled "Recipients" but there may be cases down the road where a message type might use contexts to represent something totally different', 'event_espresso'); ?></p>
8 8
\ No newline at end of file
Please login to merge, or discard this patch.
admin_pages/registrations/Registrations_Admin_Page.core.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1247,7 +1247,7 @@
 block discarded – undo
1247 1247
     /**
1248 1248
      * Sets up the limit for the registrations query.
1249 1249
      *
1250
-     * @param $per_page
1250
+     * @param integer $per_page
1251 1251
      * @return array
1252 1252
      */
1253 1253
     protected function _get_limit($per_page)
Please login to merge, or discard this patch.
Indentation   +2946 added lines, -2946 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
 
@@ -23,1831 +23,1831 @@  discard block
 block discarded – undo
23 23
 class Registrations_Admin_Page extends EE_Admin_Page_CPT
24 24
 {
25 25
 
26
-    /**
27
-     * @var EE_Registration
28
-     */
29
-    private $_registration;
30
-
31
-    /**
32
-     * @var EE_Event
33
-     */
34
-    private $_reg_event;
35
-
36
-    /**
37
-     * @var EE_Session
38
-     */
39
-    private $_session;
40
-
41
-    private static $_reg_status;
42
-
43
-    /**
44
-     * Form for displaying the custom questions for this registration.
45
-     * This gets used a few times throughout the request so its best to cache it
46
-     *
47
-     * @var EE_Registration_Custom_Questions_Form
48
-     */
49
-    protected $_reg_custom_questions_form = null;
50
-
51
-
52
-    /**
53
-     *        constructor
54
-     *
55
-     * @Constructor
56
-     * @access public
57
-     * @param bool $routing
58
-     * @return Registrations_Admin_Page
59
-     */
60
-    public function __construct($routing = true)
61
-    {
62
-        parent::__construct($routing);
63
-        add_action('wp_loaded', array($this, 'wp_loaded'));
64
-    }
65
-
66
-
67
-    public function wp_loaded()
68
-    {
69
-        // when adding a new registration...
70
-        if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
71
-            EE_System::do_not_cache();
72
-            if ( ! isset($this->_req_data['processing_registration'])
73
-                 || absint($this->_req_data['processing_registration']) !== 1
74
-            ) {
75
-                // and it's NOT the attendee information reg step
76
-                // force cookie expiration by setting time to last week
77
-                setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
78
-                // and update the global
79
-                $_COOKIE['ee_registration_added'] = 0;
80
-            }
81
-        }
82
-    }
83
-
84
-
85
-    protected function _init_page_props()
86
-    {
87
-        $this->page_slug        = REG_PG_SLUG;
88
-        $this->_admin_base_url  = REG_ADMIN_URL;
89
-        $this->_admin_base_path = REG_ADMIN;
90
-        $this->page_label       = __('Registrations', 'event_espresso');
91
-        $this->_cpt_routes      = array(
92
-            'add_new_attendee' => 'espresso_attendees',
93
-            'edit_attendee'    => 'espresso_attendees',
94
-            'insert_attendee'  => 'espresso_attendees',
95
-            'update_attendee'  => 'espresso_attendees',
96
-        );
97
-        $this->_cpt_model_names = array(
98
-            'add_new_attendee' => 'EEM_Attendee',
99
-            'edit_attendee'    => 'EEM_Attendee',
100
-        );
101
-        $this->_cpt_edit_routes = array(
102
-            'espresso_attendees' => 'edit_attendee',
103
-        );
104
-        $this->_pagenow_map     = array(
105
-            'add_new_attendee' => 'post-new.php',
106
-            'edit_attendee'    => 'post.php',
107
-            'trash'            => 'post.php',
108
-        );
109
-        add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
110
-        //add filters so that the comment urls don't take users to a confusing 404 page
111
-        add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
112
-    }
113
-
114
-
115
-    public function clear_comment_link($link, $comment, $args)
116
-    {
117
-        //gotta make sure this only happens on this route
118
-        $post_type = get_post_type($comment->comment_post_ID);
119
-        if ($post_type === 'espresso_attendees') {
120
-            return '#commentsdiv';
121
-        }
122
-        return $link;
123
-    }
124
-
125
-
126
-    protected function _ajax_hooks()
127
-    {
128
-        //todo: all hooks for registrations ajax goes in here
129
-        add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
130
-    }
131
-
132
-
133
-    protected function _define_page_props()
134
-    {
135
-        $this->_admin_page_title = $this->page_label;
136
-        $this->_labels           = array(
137
-            'buttons'                      => array(
138
-                'add-registrant'      => __('Add New Registration', 'event_espresso'),
139
-                'add-attendee'        => __('Add Contact', 'event_espresso'),
140
-                'edit'                => __('Edit Contact', 'event_espresso'),
141
-                'report'              => __("Event Registrations CSV Report", "event_espresso"),
142
-                'report_all'          => __('All Registrations CSV Report', 'event_espresso'),
143
-                'report_filtered'     => __('Filtered CSV Report', 'event_espresso'),
144
-                'contact_list_report' => __('Contact List Report', 'event_espresso'),
145
-                'contact_list_export' => __("Export Data", "event_espresso"),
146
-            ),
147
-            'publishbox'                   => array(
148
-                'add_new_attendee' => __("Add Contact Record", 'event_espresso'),
149
-                'edit_attendee'    => __("Update Contact Record", 'event_espresso'),
150
-            ),
151
-            'hide_add_button_on_cpt_route' => array(
152
-                'edit_attendee' => true,
153
-            ),
154
-        );
155
-    }
156
-
157
-
158
-    /**
159
-     *        grab url requests and route them
160
-     *
161
-     * @access private
162
-     * @return void
163
-     */
164
-    public function _set_page_routes()
165
-    {
166
-        $this->_get_registration_status_array();
167
-        $reg_id             = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
168
-            ? $this->_req_data['_REG_ID'] : 0;
169
-        $att_id             = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
170
-            ? $this->_req_data['ATT_ID'] : 0;
171
-        $att_id             = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post']) ? $this->_req_data['post']
172
-            : $att_id;
173
-        $this->_page_routes = array(
174
-            'default'                            => array(
175
-                'func'       => '_registrations_overview_list_table',
176
-                'capability' => 'ee_read_registrations',
177
-            ),
178
-            'view_registration'                  => array(
179
-                'func'       => '_registration_details',
180
-                'capability' => 'ee_read_registration',
181
-                'obj_id'     => $reg_id,
182
-            ),
183
-            'edit_registration'                  => array(
184
-                'func'               => '_update_attendee_registration_form',
185
-                'noheader'           => true,
186
-                'headers_sent_route' => 'view_registration',
187
-                'capability'         => 'ee_edit_registration',
188
-                'obj_id'             => $reg_id,
189
-                '_REG_ID'            => $reg_id,
190
-            ),
191
-            'trash_registrations'                => array(
192
-                'func'       => '_trash_or_restore_registrations',
193
-                'args'       => array('trash' => true),
194
-                'noheader'   => true,
195
-                'capability' => 'ee_delete_registrations',
196
-            ),
197
-            'restore_registrations'              => array(
198
-                'func'       => '_trash_or_restore_registrations',
199
-                'args'       => array('trash' => false),
200
-                'noheader'   => true,
201
-                'capability' => 'ee_delete_registrations',
202
-            ),
203
-            'delete_registrations'               => array(
204
-                'func'       => '_delete_registrations',
205
-                'noheader'   => true,
206
-                'capability' => 'ee_delete_registrations',
207
-            ),
208
-            'new_registration'                   => array(
209
-                'func'       => 'new_registration',
210
-                'capability' => 'ee_edit_registrations',
211
-            ),
212
-            'process_reg_step'                   => array(
213
-                'func'       => 'process_reg_step',
214
-                'noheader'   => true,
215
-                'capability' => 'ee_edit_registrations',
216
-            ),
217
-            'redirect_to_txn'                    => array(
218
-                'func'       => 'redirect_to_txn',
219
-                'noheader'   => true,
220
-                'capability' => 'ee_edit_registrations',
221
-            ),
222
-            'change_reg_status'                  => array(
223
-                'func'       => '_change_reg_status',
224
-                'noheader'   => true,
225
-                'capability' => 'ee_edit_registration',
226
-                'obj_id'     => $reg_id,
227
-            ),
228
-            'approve_registration'               => array(
229
-                'func'       => 'approve_registration',
230
-                'noheader'   => true,
231
-                'capability' => 'ee_edit_registration',
232
-                'obj_id'     => $reg_id,
233
-            ),
234
-            'approve_and_notify_registration'    => array(
235
-                'func'       => 'approve_registration',
236
-                'noheader'   => true,
237
-                'args'       => array(true),
238
-                'capability' => 'ee_edit_registration',
239
-                'obj_id'     => $reg_id,
240
-            ),
241
-            'decline_registration'               => array(
242
-                'func'       => 'decline_registration',
243
-                'noheader'   => true,
244
-                'capability' => 'ee_edit_registration',
245
-                'obj_id'     => $reg_id,
246
-            ),
247
-            'decline_and_notify_registration'    => array(
248
-                'func'       => 'decline_registration',
249
-                'noheader'   => true,
250
-                'args'       => array(true),
251
-                'capability' => 'ee_edit_registration',
252
-                'obj_id'     => $reg_id,
253
-            ),
254
-            'pending_registration'               => array(
255
-                'func'       => 'pending_registration',
256
-                'noheader'   => true,
257
-                'capability' => 'ee_edit_registration',
258
-                'obj_id'     => $reg_id,
259
-            ),
260
-            'pending_and_notify_registration'    => array(
261
-                'func'       => 'pending_registration',
262
-                'noheader'   => true,
263
-                'args'       => array(true),
264
-                'capability' => 'ee_edit_registration',
265
-                'obj_id'     => $reg_id,
266
-            ),
267
-            'no_approve_registration'            => array(
268
-                'func'       => 'not_approve_registration',
269
-                'noheader'   => true,
270
-                'capability' => 'ee_edit_registration',
271
-                'obj_id'     => $reg_id,
272
-            ),
273
-            'no_approve_and_notify_registration' => array(
274
-                'func'       => 'not_approve_registration',
275
-                'noheader'   => true,
276
-                'args'       => array(true),
277
-                'capability' => 'ee_edit_registration',
278
-                'obj_id'     => $reg_id,
279
-            ),
280
-            'cancel_registration'                => array(
281
-                'func'       => 'cancel_registration',
282
-                'noheader'   => true,
283
-                'capability' => 'ee_edit_registration',
284
-                'obj_id'     => $reg_id,
285
-            ),
286
-            'cancel_and_notify_registration'     => array(
287
-                'func'       => 'cancel_registration',
288
-                'noheader'   => true,
289
-                'args'       => array(true),
290
-                'capability' => 'ee_edit_registration',
291
-                'obj_id'     => $reg_id,
292
-            ),
293
-            'contact_list'                       => array(
294
-                'func'       => '_attendee_contact_list_table',
295
-                'capability' => 'ee_read_contacts',
296
-            ),
297
-            'add_new_attendee'                   => array(
298
-                'func' => '_create_new_cpt_item',
299
-                'args' => array(
300
-                    'new_attendee' => true,
301
-                    'capability'   => 'ee_edit_contacts',
302
-                ),
303
-            ),
304
-            'edit_attendee'                      => array(
305
-                'func'       => '_edit_cpt_item',
306
-                'capability' => 'ee_edit_contacts',
307
-                'obj_id'     => $att_id,
308
-            ),
309
-            'duplicate_attendee'                 => array(
310
-                'func'       => '_duplicate_attendee',
311
-                'noheader'   => true,
312
-                'capability' => 'ee_edit_contacts',
313
-                'obj_id'     => $att_id,
314
-            ),
315
-            'insert_attendee'                    => array(
316
-                'func'       => '_insert_or_update_attendee',
317
-                'args'       => array(
318
-                    'new_attendee' => true,
319
-                ),
320
-                'noheader'   => true,
321
-                'capability' => 'ee_edit_contacts',
322
-            ),
323
-            'update_attendee'                    => array(
324
-                'func'       => '_insert_or_update_attendee',
325
-                'args'       => array(
326
-                    'new_attendee' => false,
327
-                ),
328
-                'noheader'   => true,
329
-                'capability' => 'ee_edit_contacts',
330
-                'obj_id'     => $att_id,
331
-            ),
332
-            'trash_attendees'                    => array(
333
-                'func'       => '_trash_or_restore_attendees',
334
-                'args'       => array(
335
-                    'trash' => true,
336
-                ),
337
-                'noheader'   => true,
338
-                'capability' => 'ee_delete_contacts',
339
-                'obj_id'     => $att_id,
340
-            ),
341
-            'restore_attendees'                  => array(
342
-                'func'       => '_trash_or_restore_attendees',
343
-                'args'       => array(
344
-                    'trash' => false,
345
-                ),
346
-                'noheader'   => true,
347
-                'capability' => 'ee_delete_contacts',
348
-                'obj_id'     => $att_id,
349
-            ),
350
-            'resend_registration'                => array(
351
-                'func'       => '_resend_registration',
352
-                'noheader'   => true,
353
-                'capability' => 'ee_send_message',
354
-            ),
355
-            'registrations_report'               => array(
356
-                'func'       => '_registrations_report',
357
-                'noheader'   => true,
358
-                'capability' => 'ee_read_registrations',
359
-            ),
360
-            'contact_list_export'                => array(
361
-                'func'       => '_contact_list_export',
362
-                'noheader'   => true,
363
-                'capability' => 'export',
364
-            ),
365
-            'contact_list_report'                => array(
366
-                'func'       => '_contact_list_report',
367
-                'noheader'   => true,
368
-                'capability' => 'ee_read_contacts',
369
-            ),
370
-        );
371
-    }
372
-
373
-
374
-    protected function _set_page_config()
375
-    {
376
-        $this->_page_config = array(
377
-            'default'           => array(
378
-                'nav'           => array(
379
-                    'label' => __('Overview', 'event_espresso'),
380
-                    'order' => 5,
381
-                ),
382
-                'help_tabs'     => array(
383
-                    'registrations_overview_help_tab'                       => array(
384
-                        'title'    => __('Registrations Overview', 'event_espresso'),
385
-                        'filename' => 'registrations_overview',
386
-                    ),
387
-                    'registrations_overview_table_column_headings_help_tab' => array(
388
-                        'title'    => __('Registrations Table Column Headings', 'event_espresso'),
389
-                        'filename' => 'registrations_overview_table_column_headings',
390
-                    ),
391
-                    'registrations_overview_filters_help_tab'               => array(
392
-                        'title'    => __('Registration Filters', 'event_espresso'),
393
-                        'filename' => 'registrations_overview_filters',
394
-                    ),
395
-                    'registrations_overview_views_help_tab'                 => array(
396
-                        'title'    => __('Registration Views', 'event_espresso'),
397
-                        'filename' => 'registrations_overview_views',
398
-                    ),
399
-                    'registrations_regoverview_other_help_tab'              => array(
400
-                        'title'    => __('Registrations Other', 'event_espresso'),
401
-                        'filename' => 'registrations_overview_other',
402
-                    ),
403
-                ),
404
-                'help_tour'     => array('Registration_Overview_Help_Tour'),
405
-                'qtips'         => array('Registration_List_Table_Tips'),
406
-                'list_table'    => 'EE_Registrations_List_Table',
407
-                'require_nonce' => false,
408
-            ),
409
-            'view_registration' => array(
410
-                'nav'           => array(
411
-                    'label'      => __('REG Details', 'event_espresso'),
412
-                    'order'      => 15,
413
-                    'url'        => isset($this->_req_data['_REG_ID'])
414
-                        ? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
415
-                        : $this->_admin_base_url,
416
-                    'persistent' => false,
417
-                ),
418
-                'help_tabs'     => array(
419
-                    'registrations_details_help_tab'                    => array(
420
-                        'title'    => __('Registration Details', 'event_espresso'),
421
-                        'filename' => 'registrations_details',
422
-                    ),
423
-                    'registrations_details_table_help_tab'              => array(
424
-                        'title'    => __('Registration Details Table', 'event_espresso'),
425
-                        'filename' => 'registrations_details_table',
426
-                    ),
427
-                    'registrations_details_form_answers_help_tab'       => array(
428
-                        'title'    => __('Registration Form Answers', 'event_espresso'),
429
-                        'filename' => 'registrations_details_form_answers',
430
-                    ),
431
-                    'registrations_details_registrant_details_help_tab' => array(
432
-                        'title'    => __('Contact Details', 'event_espresso'),
433
-                        'filename' => 'registrations_details_registrant_details',
434
-                    ),
435
-                ),
436
-                'help_tour'     => array('Registration_Details_Help_Tour'),
437
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes,
438
-                    array('_registration_details_metaboxes')),
439
-                'require_nonce' => false,
440
-            ),
441
-            'new_registration'  => array(
442
-                'nav'           => array(
443
-                    'label'      => __('Add New Registration', 'event_espresso'),
444
-                    'url'        => '#',
445
-                    'order'      => 15,
446
-                    'persistent' => false,
447
-                ),
448
-                'metaboxes'     => $this->_default_espresso_metaboxes,
449
-                'labels'        => array(
450
-                    'publishbox' => __('Save Registration', 'event_espresso'),
451
-                ),
452
-                'require_nonce' => false,
453
-            ),
454
-            'add_new_attendee'  => array(
455
-                'nav'           => array(
456
-                    'label'      => __('Add Contact', 'event_espresso'),
457
-                    'order'      => 15,
458
-                    'persistent' => false,
459
-                ),
460
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes,
461
-                    array('_publish_post_box', 'attendee_editor_metaboxes')),
462
-                'require_nonce' => false,
463
-            ),
464
-            'edit_attendee'     => array(
465
-                'nav'           => array(
466
-                    'label'      => __('Edit Contact', 'event_espresso'),
467
-                    'order'      => 15,
468
-                    'persistent' => false,
469
-                    'url'        => isset($this->_req_data['ATT_ID'])
470
-                        ? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
471
-                        : $this->_admin_base_url,
472
-                ),
473
-                'metaboxes'     => array('attendee_editor_metaboxes'),
474
-                'require_nonce' => false,
475
-            ),
476
-            'contact_list'      => array(
477
-                'nav'           => array(
478
-                    'label' => __('Contact List', 'event_espresso'),
479
-                    'order' => 20,
480
-                ),
481
-                'list_table'    => 'EE_Attendee_Contact_List_Table',
482
-                'help_tabs'     => array(
483
-                    'registrations_contact_list_help_tab'                       => array(
484
-                        'title'    => __('Registrations Contact List', 'event_espresso'),
485
-                        'filename' => 'registrations_contact_list',
486
-                    ),
487
-                    'registrations_contact-list_table_column_headings_help_tab' => array(
488
-                        'title'    => __('Contact List Table Column Headings', 'event_espresso'),
489
-                        'filename' => 'registrations_contact_list_table_column_headings',
490
-                    ),
491
-                    'registrations_contact_list_views_help_tab'                 => array(
492
-                        'title'    => __('Contact List Views', 'event_espresso'),
493
-                        'filename' => 'registrations_contact_list_views',
494
-                    ),
495
-                    'registrations_contact_list_other_help_tab'                 => array(
496
-                        'title'    => __('Contact List Other', 'event_espresso'),
497
-                        'filename' => 'registrations_contact_list_other',
498
-                    ),
499
-                ),
500
-                'help_tour'     => array('Contact_List_Help_Tour'),
501
-                'metaboxes'     => array(),
502
-                'require_nonce' => false,
503
-            ),
504
-            //override default cpt routes
505
-            'create_new'        => '',
506
-            'edit'              => '',
507
-        );
508
-    }
509
-
510
-
511
-    /**
512
-     * The below methods aren't used by this class currently
513
-     */
514
-    protected function _add_screen_options()
515
-    {
516
-    }
517
-
518
-
519
-    protected function _add_feature_pointers()
520
-    {
521
-    }
522
-
523
-
524
-    public function admin_init()
525
-    {
526
-        EE_Registry::$i18n_js_strings['update_att_qstns'] = __('click "Update Registration Questions" to save your changes',
527
-            'event_espresso');
528
-    }
529
-
530
-
531
-    public function admin_notices()
532
-    {
533
-    }
534
-
535
-
536
-    public function admin_footer_scripts()
537
-    {
538
-    }
539
-
540
-
541
-    /**
542
-     *        get list of registration statuses
543
-     *
544
-     * @access private
545
-     * @return void
546
-     */
547
-    private function _get_registration_status_array()
548
-    {
549
-        self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
550
-    }
551
-
552
-
553
-    protected function _add_screen_options_default()
554
-    {
555
-        $this->_per_page_screen_option();
556
-    }
557
-
558
-
559
-    protected function _add_screen_options_contact_list()
560
-    {
561
-        $page_title              = $this->_admin_page_title;
562
-        $this->_admin_page_title = __("Contacts", 'event_espresso');
563
-        $this->_per_page_screen_option();
564
-        $this->_admin_page_title = $page_title;
565
-    }
566
-
567
-
568
-    public function load_scripts_styles()
569
-    {
570
-        //style
571
-        //wp_register_style('espresso_attendees', ATT_ASSETS_URL . 'espresso_attendees_admin.css', array(), EVENT_ESPRESSO_VERSION );
572
-        wp_register_style('espresso_reg', REG_ASSETS_URL . 'espresso_registrations_admin.css', array('ee-admin-css'),
573
-            EVENT_ESPRESSO_VERSION);
574
-        wp_enqueue_style('espresso_reg');
575
-        //script
576
-        wp_register_script('espresso_reg', REG_ASSETS_URL . 'espresso_registrations_admin.js',
577
-            array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'), EVENT_ESPRESSO_VERSION, true);
578
-        wp_enqueue_script('espresso_reg');
579
-    }
580
-
581
-
582
-    public function load_scripts_styles_edit_attendee()
583
-    {
584
-        //stuff to only show up on our attendee edit details page.
585
-        $attendee_details_translations = array(
586
-            'att_publish_text' => sprintf(__('Created on: <b>%1$s</b>', 'event_espresso'),
587
-                $this->_cpt_model_obj->get_datetime('ATT_created')),
588
-        );
589
-        wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
590
-        wp_enqueue_script('jquery-validate');
591
-    }
592
-
593
-
594
-    public function load_scripts_styles_view_registration()
595
-    {
596
-        //styles
597
-        wp_enqueue_style('espresso-ui-theme');
598
-        //scripts
599
-        $this->_get_reg_custom_questions_form($this->_registration->ID());
600
-        $this->_reg_custom_questions_form->wp_enqueue_scripts(true);
601
-    }
602
-
603
-
604
-    public function load_scripts_styles_contact_list()
605
-    {
606
-        wp_deregister_style('espresso_reg');
607
-        wp_register_style('espresso_att', REG_ASSETS_URL . 'espresso_attendees_admin.css', array('ee-admin-css'),
608
-            EVENT_ESPRESSO_VERSION);
609
-        wp_enqueue_style('espresso_att');
610
-    }
611
-
612
-
613
-    public function load_scripts_styles_new_registration()
614
-    {
615
-        wp_register_script('ee-spco-for-admin', REG_ASSETS_URL . 'spco_for_admin.js', array('underscore', 'jquery'),
616
-            EVENT_ESPRESSO_VERSION, true);
617
-        wp_enqueue_script('ee-spco-for-admin');
618
-        add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
619
-        EE_Form_Section_Proper::wp_enqueue_scripts();
620
-        EED_Ticket_Selector::load_tckt_slctr_assets();
621
-        EE_Datepicker_Input::enqueue_styles_and_scripts();
622
-    }
623
-
624
-
625
-    public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
626
-    {
627
-        add_filter('FHEE_load_EE_messages', '__return_true');
628
-    }
629
-
630
-
631
-    public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
632
-    {
633
-        add_filter('FHEE_load_EE_messages', '__return_true');
634
-    }
635
-
636
-
637
-    protected function _set_list_table_views_default()
638
-    {
639
-        //for notification related bulk actions we need to make sure only active messengers have an option.
640
-        EED_Messages::set_autoloaders();
641
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
642
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
643
-        $active_mts               = $message_resource_manager->list_of_active_message_types();
644
-        //key= bulk_action_slug, value= message type.
645
-        $match_array = array(
646
-            'approve_registration'    => 'registration',
647
-            'decline_registration'    => 'declined_registration',
648
-            'pending_registration'    => 'pending_approval',
649
-            'no_approve_registration' => 'not_approved_registration',
650
-            'cancel_registration'     => 'cancelled_registration',
651
-        );
652
-        /** setup reg status bulk actions **/
653
-        $def_reg_status_actions['approve_registration'] = __('Approve Registrations', 'event_espresso');
654
-        if (in_array($match_array['approve_registration'], $active_mts)
655
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
656
-        ) {
657
-            $def_reg_status_actions['approve_and_notify_registration'] = __('Approve and Notify Registrations',
658
-                'event_espresso');
659
-        }
660
-        $def_reg_status_actions['decline_registration'] = __('Decline Registrations', 'event_espresso');
661
-        if (in_array($match_array['decline_registration'], $active_mts)
662
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
663
-        ) {
664
-            $def_reg_status_actions['decline_and_notify_registration'] = __('Decline and Notify Registrations',
665
-                'event_espresso');
666
-        }
667
-        $def_reg_status_actions['pending_registration'] = __('Set Registrations to Pending Payment', 'event_espresso');
668
-        if (in_array($match_array['pending_registration'], $active_mts)
669
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
670
-        ) {
671
-            $def_reg_status_actions['pending_and_notify_registration'] = __('Set Registrations to Pending Payment and Notify',
672
-                'event_espresso');
673
-        }
674
-        $def_reg_status_actions['no_approve_registration'] = __('Set Registrations to Not Approved', 'event_espresso');
675
-        if (in_array($match_array['no_approve_registration'], $active_mts)
676
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
677
-        ) {
678
-            $def_reg_status_actions['no_approve_and_notify_registration'] = __('Set Registrations to Not Approved and Notify',
679
-                'event_espresso');
680
-        }
681
-        $def_reg_status_actions['cancel_registration'] = __('Cancel Registrations', 'event_espresso');
682
-        if (in_array($match_array['cancel_registration'], $active_mts)
683
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
684
-        ) {
685
-            $def_reg_status_actions['cancel_and_notify_registration'] = __('Cancel Registrations and Notify',
686
-                'event_espresso');
687
-        }
688
-        $this->_views = array(
689
-            'all'   => array(
690
-                'slug'        => 'all',
691
-                'label'       => __('View All Registrations', 'event_espresso'),
692
-                'count'       => 0,
693
-                'bulk_action' => array_merge($def_reg_status_actions, array(
694
-                    'trash_registrations' => __('Trash Registrations', 'event_espresso'),
695
-                )),
696
-            ),
697
-            'month' => array(
698
-                'slug'        => 'month',
699
-                'label'       => __('This Month', 'event_espresso'),
700
-                'count'       => 0,
701
-                'bulk_action' => array_merge($def_reg_status_actions, array(
702
-                    'trash_registrations' => __('Trash Registrations', 'event_espresso'),
703
-                )),
704
-            ),
705
-            'today' => array(
706
-                'slug'        => 'today',
707
-                'label'       => sprintf(__('Today - %s', 'event_espresso'), date('M d, Y', current_time('timestamp'))),
708
-                'count'       => 0,
709
-                'bulk_action' => array_merge($def_reg_status_actions, array(
710
-                    'trash_registrations' => __('Trash Registrations', 'event_espresso'),
711
-                )),
712
-            ),
713
-        );
714
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registrations',
715
-            'espresso_registrations_delete_registration')
716
-        ) {
717
-            $this->_views['incomplete'] = array(
718
-                'slug'        => 'incomplete',
719
-                'label'       => __('Incomplete', 'event_espresso'),
720
-                'count'       => 0,
721
-                'bulk_action' => array(
722
-                    'trash_registrations' => __('Trash Registrations', 'event_espresso'),
723
-                ),
724
-            );
725
-            $this->_views['trash']      = array(
726
-                'slug'        => 'trash',
727
-                'label'       => __('Trash', 'event_espresso'),
728
-                'count'       => 0,
729
-                'bulk_action' => array(
730
-                    'restore_registrations' => __('Restore Registrations', 'event_espresso'),
731
-                    'delete_registrations'  => __('Delete Registrations Permanently', 'event_espresso'),
732
-                ),
733
-            );
734
-        }
735
-    }
736
-
737
-
738
-    protected function _set_list_table_views_contact_list()
739
-    {
740
-        $this->_views = array(
741
-            'in_use' => array(
742
-                'slug'        => 'in_use',
743
-                'label'       => __('In Use', 'event_espresso'),
744
-                'count'       => 0,
745
-                'bulk_action' => array(
746
-                    'trash_attendees' => __('Move to Trash', 'event_espresso'),
747
-                ),
748
-            ),
749
-        );
750
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_contacts',
751
-            'espresso_registrations_trash_attendees')
752
-        ) {
753
-            $this->_views['trash'] = array(
754
-                'slug'        => 'trash',
755
-                'label'       => __('Trash', 'event_espresso'),
756
-                'count'       => 0,
757
-                'bulk_action' => array(
758
-                    'restore_attendees' => __('Restore from Trash', 'event_espresso'),
759
-                ),
760
-            );
761
-        }
762
-    }
763
-
764
-
765
-    protected function _registration_legend_items()
766
-    {
767
-        $fc_items = array(
768
-            'star-icon'        => array(
769
-                'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
770
-                'desc'  => __('This is the Primary Registrant', 'event_espresso'),
771
-            ),
772
-            'view_details'     => array(
773
-                'class' => 'dashicons dashicons-clipboard',
774
-                'desc'  => __('View Registration Details', 'event_espresso'),
775
-            ),
776
-            'edit_attendee'    => array(
777
-                'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
778
-                'desc'  => __('Edit Contact Details', 'event_espresso'),
779
-            ),
780
-            'view_transaction' => array(
781
-                'class' => 'dashicons dashicons-cart',
782
-                'desc'  => __('View Transaction Details', 'event_espresso'),
783
-            ),
784
-            'view_invoice'     => array(
785
-                'class' => 'dashicons dashicons-media-spreadsheet',
786
-                'desc'  => __('View Transaction Invoice', 'event_espresso'),
787
-            ),
788
-        );
789
-        if (EE_Registry::instance()->CAP->current_user_can('ee_send_message',
790
-            'espresso_registrations_resend_registration')
791
-        ) {
792
-            $fc_items['resend_registration'] = array(
793
-                'class' => 'dashicons dashicons-email-alt',
794
-                'desc'  => __('Resend Registration Details', 'event_espresso'),
795
-            );
796
-        } else {
797
-            $fc_items['blank'] = array('class' => 'blank', 'desc' => '');
798
-        }
799
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
800
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
801
-            if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
802
-                $fc_items['view_related_messages'] = array(
803
-                    'class' => $related_for_icon['css_class'],
804
-                    'desc'  => $related_for_icon['label'],
805
-                );
806
-            }
807
-        }
808
-        $sc_items = array(
809
-            'approved_status'   => array(
810
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
811
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
812
-            ),
813
-            'pending_status'    => array(
814
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
815
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
816
-            ),
817
-            'wait_list'         => array(
818
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
819
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
820
-            ),
821
-            'incomplete_status' => array(
822
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
823
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_incomplete, false, 'sentence'),
824
-            ),
825
-            'not_approved'      => array(
826
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
827
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
828
-            ),
829
-            'declined_status'   => array(
830
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
831
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
832
-            ),
833
-            'cancelled_status'  => array(
834
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
835
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
836
-            ),
837
-        );
838
-        return array_merge($fc_items, $sc_items);
839
-    }
840
-
841
-
842
-
843
-    /***************************************        REGISTRATION OVERVIEW        **************************************/
844
-    /**
845
-     * @throws \EE_Error
846
-     */
847
-    protected function _registrations_overview_list_table()
848
-    {
849
-        $this->_template_args['admin_page_header'] = '';
850
-        $EVT_ID                                    = ! empty($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : 0;
851
-        if ($EVT_ID) {
852
-            if (EE_Registry::instance()->CAP->current_user_can('ee_edit_registrations',
853
-                'espresso_registrations_new_registration', $EVT_ID)
854
-            ) {
855
-                $this->_admin_page_title .= ' ' . $this->get_action_link_or_button('new_registration', 'add-registrant',
856
-                        array('event_id' => $EVT_ID), 'add-new-h2');
857
-            }
858
-            $event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
859
-            if ($event instanceof EE_Event) {
860
-                $this->_template_args['admin_page_header'] = sprintf(__('%s Viewing registrations for the event: %s%s',
861
-                    'event_espresso'), '<h3 style="line-height:1.5em;">',
862
-                    '<br /><a href="' . EE_Admin_Page::add_query_args_and_nonce(array(
863
-                        'action' => 'edit',
864
-                        'post'   => $event->ID(),
865
-                    ), EVENTS_ADMIN_URL) . '">&nbsp;' . $event->get('EVT_name') . '&nbsp;</a>&nbsp;', '</h3>');
866
-            }
867
-            $DTT_ID   = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
868
-            $datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
869
-            if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
870
-                $this->_template_args['admin_page_header'] = substr($this->_template_args['admin_page_header'], 0, -5);
871
-                $this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
872
-                $this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
873
-                $this->_template_args['admin_page_header'] .= $datetime->name();
874
-                $this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
875
-                $this->_template_args['admin_page_header'] .= '</span></h3>';
876
-            }
877
-        }
878
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
879
-        $this->display_admin_list_table_page_with_no_sidebar();
880
-    }
881
-
882
-
883
-    /**
884
-     * This sets the _registration property for the registration details screen
885
-     *
886
-     * @access private
887
-     * @return bool
888
-     */
889
-    private function _set_registration_object()
890
-    {
891
-        //get out if we've already set the object
892
-        if (is_object($this->_registration)) {
893
-            return true;
894
-        }
895
-        $REG    = EEM_Registration::instance();
896
-        $REG_ID = ( ! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
897
-        if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
898
-            return true;
899
-        } else {
900
-            $error_msg = sprintf(__('An error occurred and the details for Registration ID #%s could not be retrieved.',
901
-                'event_espresso'), $REG_ID);
902
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
903
-            $this->_registration = null;
904
-            return false;
905
-        }
906
-    }
907
-
908
-
909
-    /**
910
-     * Used to retrieve registrations for the list table.
911
-     *
912
-     * @param int    $per_page
913
-     * @param bool   $count
914
-     * @param bool   $this_month 
915
-     * @param bool   $today
916
-     * @return \EE_Registration[]|int
917
-     */
918
-    public function get_registrations(
919
-        $per_page = 10,
920
-        $count = false,
921
-        $this_month = false,
922
-        $today = false
923
-    ) {
924
-        if( $this_month ) {
925
-            $this->_req_data['status'] = 'month';
926
-        }
927
-        if( $today ) {
928
-            $this->_req_data['status'] = 'today';
929
-        }
930
-        $query_params = $this->_get_registration_query_parameters($this->_req_data, $per_page, $count);
931
-        return $count
932
-            ? EEM_Registration::instance()->count($query_params)
933
-            /** @type EE_Registration[] */
934
-            : EEM_Registration::instance()->get_all($query_params);
935
-    }
936
-
937
-
938
-
939
-    /**
940
-     * Retrieves the query parameters to be used by the Registration model for getting registrations.
941
-     * Note: this listens to values on the request for some of the query parameters.
942
-     *
943
-     * @param array $request
944
-     * @param int    $per_page
945
-     * @param bool   $count
946
-     * @return array
947
-     */
948
-    protected function _get_registration_query_parameters(
949
-        $request = array(),
950
-        $per_page = 10,
951
-        $count = false
952
-    ) {
953
-
954
-        $query_params = array(
955
-            0                          => $this->_get_where_conditions_for_registrations_query(
956
-                $request
957
-            ),
958
-            'caps'                     => EEM_Registration::caps_read_admin,
959
-            'default_where_conditions' => 'this_model_only',
960
-        );
961
-        if ( ! $count) {
962
-            $query_params = array_merge(
963
-                $query_params,
964
-                $this->_get_orderby_for_registrations_query(),
965
-                $this->_get_limit($per_page)
966
-            );
967
-        }
968
-
969
-        return $query_params;
970
-    }
971
-
972
-
973
-    /**
974
-     * This will add EVT_ID to the provided $where array for EE model query parameters.
975
-     *
976
-     * @param array $request usually the same as $this->_req_data but not necessarily
977
-     * @return array
978
-     */
979
-    protected function _add_event_id_to_where_conditions(array $request)
980
-    {
981
-        $where = array();
982
-        if ( ! empty($request['event_id'])) {
983
-            $where['EVT_ID'] = absint($request['event_id']);
984
-        }
985
-        return $where;
986
-    }
987
-
988
-
989
-    /**
990
-     * Adds category ID if it exists in the request to the where conditions for the registrations query.
991
-     *
992
-     * @param array $request usually the same as $this->_req_data but not necessarily
993
-     * @return array
994
-     */
995
-    protected function _add_category_id_to_where_conditions(array $request)
996
-    {
997
-        $where = array();
998
-        if ( ! empty($request['EVT_CAT']) && (int)$request['EVT_CAT'] !== -1) {
999
-            $where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1000
-        }
1001
-        return $where;
1002
-    }
1003
-
1004
-
1005
-    /**
1006
-     * Adds the datetime ID if it exists in the request to the where conditions for the registrations query.
1007
-     *
1008
-     * @param array $request usually the same as $this->_req_data but not necessarily
1009
-     * @return array
1010
-     */
1011
-    protected function _add_datetime_id_to_where_conditions(array $request)
1012
-    {
1013
-        $where = array();
1014
-        if ( ! empty($request['datetime_id'])) {
1015
-            $where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1016
-        }
1017
-        if( ! empty($request['DTT_ID'])){
1018
-            $where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1019
-        }
1020
-        return $where;
1021
-    }
1022
-
1023
-
1024
-    /**
1025
-     * Adds the correct registration status to the where conditions for the registrations query.
1026
-     *
1027
-     * @param array $request usually the same as $this->_req_data but not necessarily
1028
-     * @return array
1029
-     */
1030
-    protected function _add_registration_status_to_where_conditions(array $request)
1031
-    {
1032
-        $where = array();
1033
-        $view  = EEH_Array::is_set( $request, 'status', '' );
1034
-        $registration_status = ! empty($request['_reg_status'])
1035
-            ? sanitize_text_field($request['_reg_status'])
1036
-            : '';
1037
-
1038
-        /*
26
+	/**
27
+	 * @var EE_Registration
28
+	 */
29
+	private $_registration;
30
+
31
+	/**
32
+	 * @var EE_Event
33
+	 */
34
+	private $_reg_event;
35
+
36
+	/**
37
+	 * @var EE_Session
38
+	 */
39
+	private $_session;
40
+
41
+	private static $_reg_status;
42
+
43
+	/**
44
+	 * Form for displaying the custom questions for this registration.
45
+	 * This gets used a few times throughout the request so its best to cache it
46
+	 *
47
+	 * @var EE_Registration_Custom_Questions_Form
48
+	 */
49
+	protected $_reg_custom_questions_form = null;
50
+
51
+
52
+	/**
53
+	 *        constructor
54
+	 *
55
+	 * @Constructor
56
+	 * @access public
57
+	 * @param bool $routing
58
+	 * @return Registrations_Admin_Page
59
+	 */
60
+	public function __construct($routing = true)
61
+	{
62
+		parent::__construct($routing);
63
+		add_action('wp_loaded', array($this, 'wp_loaded'));
64
+	}
65
+
66
+
67
+	public function wp_loaded()
68
+	{
69
+		// when adding a new registration...
70
+		if (isset($this->_req_data['action']) && $this->_req_data['action'] === 'new_registration') {
71
+			EE_System::do_not_cache();
72
+			if ( ! isset($this->_req_data['processing_registration'])
73
+				 || absint($this->_req_data['processing_registration']) !== 1
74
+			) {
75
+				// and it's NOT the attendee information reg step
76
+				// force cookie expiration by setting time to last week
77
+				setcookie('ee_registration_added', 0, time() - WEEK_IN_SECONDS, '/');
78
+				// and update the global
79
+				$_COOKIE['ee_registration_added'] = 0;
80
+			}
81
+		}
82
+	}
83
+
84
+
85
+	protected function _init_page_props()
86
+	{
87
+		$this->page_slug        = REG_PG_SLUG;
88
+		$this->_admin_base_url  = REG_ADMIN_URL;
89
+		$this->_admin_base_path = REG_ADMIN;
90
+		$this->page_label       = __('Registrations', 'event_espresso');
91
+		$this->_cpt_routes      = array(
92
+			'add_new_attendee' => 'espresso_attendees',
93
+			'edit_attendee'    => 'espresso_attendees',
94
+			'insert_attendee'  => 'espresso_attendees',
95
+			'update_attendee'  => 'espresso_attendees',
96
+		);
97
+		$this->_cpt_model_names = array(
98
+			'add_new_attendee' => 'EEM_Attendee',
99
+			'edit_attendee'    => 'EEM_Attendee',
100
+		);
101
+		$this->_cpt_edit_routes = array(
102
+			'espresso_attendees' => 'edit_attendee',
103
+		);
104
+		$this->_pagenow_map     = array(
105
+			'add_new_attendee' => 'post-new.php',
106
+			'edit_attendee'    => 'post.php',
107
+			'trash'            => 'post.php',
108
+		);
109
+		add_action('edit_form_after_title', array($this, 'after_title_form_fields'), 10);
110
+		//add filters so that the comment urls don't take users to a confusing 404 page
111
+		add_filter('get_comment_link', array($this, 'clear_comment_link'), 10, 3);
112
+	}
113
+
114
+
115
+	public function clear_comment_link($link, $comment, $args)
116
+	{
117
+		//gotta make sure this only happens on this route
118
+		$post_type = get_post_type($comment->comment_post_ID);
119
+		if ($post_type === 'espresso_attendees') {
120
+			return '#commentsdiv';
121
+		}
122
+		return $link;
123
+	}
124
+
125
+
126
+	protected function _ajax_hooks()
127
+	{
128
+		//todo: all hooks for registrations ajax goes in here
129
+		add_action('wp_ajax_toggle_checkin_status', array($this, 'toggle_checkin_status'));
130
+	}
131
+
132
+
133
+	protected function _define_page_props()
134
+	{
135
+		$this->_admin_page_title = $this->page_label;
136
+		$this->_labels           = array(
137
+			'buttons'                      => array(
138
+				'add-registrant'      => __('Add New Registration', 'event_espresso'),
139
+				'add-attendee'        => __('Add Contact', 'event_espresso'),
140
+				'edit'                => __('Edit Contact', 'event_espresso'),
141
+				'report'              => __("Event Registrations CSV Report", "event_espresso"),
142
+				'report_all'          => __('All Registrations CSV Report', 'event_espresso'),
143
+				'report_filtered'     => __('Filtered CSV Report', 'event_espresso'),
144
+				'contact_list_report' => __('Contact List Report', 'event_espresso'),
145
+				'contact_list_export' => __("Export Data", "event_espresso"),
146
+			),
147
+			'publishbox'                   => array(
148
+				'add_new_attendee' => __("Add Contact Record", 'event_espresso'),
149
+				'edit_attendee'    => __("Update Contact Record", 'event_espresso'),
150
+			),
151
+			'hide_add_button_on_cpt_route' => array(
152
+				'edit_attendee' => true,
153
+			),
154
+		);
155
+	}
156
+
157
+
158
+	/**
159
+	 *        grab url requests and route them
160
+	 *
161
+	 * @access private
162
+	 * @return void
163
+	 */
164
+	public function _set_page_routes()
165
+	{
166
+		$this->_get_registration_status_array();
167
+		$reg_id             = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
168
+			? $this->_req_data['_REG_ID'] : 0;
169
+		$att_id             = ! empty($this->_req_data['ATT_ID']) && ! is_array($this->_req_data['ATT_ID'])
170
+			? $this->_req_data['ATT_ID'] : 0;
171
+		$att_id             = ! empty($this->_req_data['post']) && ! is_array($this->_req_data['post']) ? $this->_req_data['post']
172
+			: $att_id;
173
+		$this->_page_routes = array(
174
+			'default'                            => array(
175
+				'func'       => '_registrations_overview_list_table',
176
+				'capability' => 'ee_read_registrations',
177
+			),
178
+			'view_registration'                  => array(
179
+				'func'       => '_registration_details',
180
+				'capability' => 'ee_read_registration',
181
+				'obj_id'     => $reg_id,
182
+			),
183
+			'edit_registration'                  => array(
184
+				'func'               => '_update_attendee_registration_form',
185
+				'noheader'           => true,
186
+				'headers_sent_route' => 'view_registration',
187
+				'capability'         => 'ee_edit_registration',
188
+				'obj_id'             => $reg_id,
189
+				'_REG_ID'            => $reg_id,
190
+			),
191
+			'trash_registrations'                => array(
192
+				'func'       => '_trash_or_restore_registrations',
193
+				'args'       => array('trash' => true),
194
+				'noheader'   => true,
195
+				'capability' => 'ee_delete_registrations',
196
+			),
197
+			'restore_registrations'              => array(
198
+				'func'       => '_trash_or_restore_registrations',
199
+				'args'       => array('trash' => false),
200
+				'noheader'   => true,
201
+				'capability' => 'ee_delete_registrations',
202
+			),
203
+			'delete_registrations'               => array(
204
+				'func'       => '_delete_registrations',
205
+				'noheader'   => true,
206
+				'capability' => 'ee_delete_registrations',
207
+			),
208
+			'new_registration'                   => array(
209
+				'func'       => 'new_registration',
210
+				'capability' => 'ee_edit_registrations',
211
+			),
212
+			'process_reg_step'                   => array(
213
+				'func'       => 'process_reg_step',
214
+				'noheader'   => true,
215
+				'capability' => 'ee_edit_registrations',
216
+			),
217
+			'redirect_to_txn'                    => array(
218
+				'func'       => 'redirect_to_txn',
219
+				'noheader'   => true,
220
+				'capability' => 'ee_edit_registrations',
221
+			),
222
+			'change_reg_status'                  => array(
223
+				'func'       => '_change_reg_status',
224
+				'noheader'   => true,
225
+				'capability' => 'ee_edit_registration',
226
+				'obj_id'     => $reg_id,
227
+			),
228
+			'approve_registration'               => array(
229
+				'func'       => 'approve_registration',
230
+				'noheader'   => true,
231
+				'capability' => 'ee_edit_registration',
232
+				'obj_id'     => $reg_id,
233
+			),
234
+			'approve_and_notify_registration'    => array(
235
+				'func'       => 'approve_registration',
236
+				'noheader'   => true,
237
+				'args'       => array(true),
238
+				'capability' => 'ee_edit_registration',
239
+				'obj_id'     => $reg_id,
240
+			),
241
+			'decline_registration'               => array(
242
+				'func'       => 'decline_registration',
243
+				'noheader'   => true,
244
+				'capability' => 'ee_edit_registration',
245
+				'obj_id'     => $reg_id,
246
+			),
247
+			'decline_and_notify_registration'    => array(
248
+				'func'       => 'decline_registration',
249
+				'noheader'   => true,
250
+				'args'       => array(true),
251
+				'capability' => 'ee_edit_registration',
252
+				'obj_id'     => $reg_id,
253
+			),
254
+			'pending_registration'               => array(
255
+				'func'       => 'pending_registration',
256
+				'noheader'   => true,
257
+				'capability' => 'ee_edit_registration',
258
+				'obj_id'     => $reg_id,
259
+			),
260
+			'pending_and_notify_registration'    => array(
261
+				'func'       => 'pending_registration',
262
+				'noheader'   => true,
263
+				'args'       => array(true),
264
+				'capability' => 'ee_edit_registration',
265
+				'obj_id'     => $reg_id,
266
+			),
267
+			'no_approve_registration'            => array(
268
+				'func'       => 'not_approve_registration',
269
+				'noheader'   => true,
270
+				'capability' => 'ee_edit_registration',
271
+				'obj_id'     => $reg_id,
272
+			),
273
+			'no_approve_and_notify_registration' => array(
274
+				'func'       => 'not_approve_registration',
275
+				'noheader'   => true,
276
+				'args'       => array(true),
277
+				'capability' => 'ee_edit_registration',
278
+				'obj_id'     => $reg_id,
279
+			),
280
+			'cancel_registration'                => array(
281
+				'func'       => 'cancel_registration',
282
+				'noheader'   => true,
283
+				'capability' => 'ee_edit_registration',
284
+				'obj_id'     => $reg_id,
285
+			),
286
+			'cancel_and_notify_registration'     => array(
287
+				'func'       => 'cancel_registration',
288
+				'noheader'   => true,
289
+				'args'       => array(true),
290
+				'capability' => 'ee_edit_registration',
291
+				'obj_id'     => $reg_id,
292
+			),
293
+			'contact_list'                       => array(
294
+				'func'       => '_attendee_contact_list_table',
295
+				'capability' => 'ee_read_contacts',
296
+			),
297
+			'add_new_attendee'                   => array(
298
+				'func' => '_create_new_cpt_item',
299
+				'args' => array(
300
+					'new_attendee' => true,
301
+					'capability'   => 'ee_edit_contacts',
302
+				),
303
+			),
304
+			'edit_attendee'                      => array(
305
+				'func'       => '_edit_cpt_item',
306
+				'capability' => 'ee_edit_contacts',
307
+				'obj_id'     => $att_id,
308
+			),
309
+			'duplicate_attendee'                 => array(
310
+				'func'       => '_duplicate_attendee',
311
+				'noheader'   => true,
312
+				'capability' => 'ee_edit_contacts',
313
+				'obj_id'     => $att_id,
314
+			),
315
+			'insert_attendee'                    => array(
316
+				'func'       => '_insert_or_update_attendee',
317
+				'args'       => array(
318
+					'new_attendee' => true,
319
+				),
320
+				'noheader'   => true,
321
+				'capability' => 'ee_edit_contacts',
322
+			),
323
+			'update_attendee'                    => array(
324
+				'func'       => '_insert_or_update_attendee',
325
+				'args'       => array(
326
+					'new_attendee' => false,
327
+				),
328
+				'noheader'   => true,
329
+				'capability' => 'ee_edit_contacts',
330
+				'obj_id'     => $att_id,
331
+			),
332
+			'trash_attendees'                    => array(
333
+				'func'       => '_trash_or_restore_attendees',
334
+				'args'       => array(
335
+					'trash' => true,
336
+				),
337
+				'noheader'   => true,
338
+				'capability' => 'ee_delete_contacts',
339
+				'obj_id'     => $att_id,
340
+			),
341
+			'restore_attendees'                  => array(
342
+				'func'       => '_trash_or_restore_attendees',
343
+				'args'       => array(
344
+					'trash' => false,
345
+				),
346
+				'noheader'   => true,
347
+				'capability' => 'ee_delete_contacts',
348
+				'obj_id'     => $att_id,
349
+			),
350
+			'resend_registration'                => array(
351
+				'func'       => '_resend_registration',
352
+				'noheader'   => true,
353
+				'capability' => 'ee_send_message',
354
+			),
355
+			'registrations_report'               => array(
356
+				'func'       => '_registrations_report',
357
+				'noheader'   => true,
358
+				'capability' => 'ee_read_registrations',
359
+			),
360
+			'contact_list_export'                => array(
361
+				'func'       => '_contact_list_export',
362
+				'noheader'   => true,
363
+				'capability' => 'export',
364
+			),
365
+			'contact_list_report'                => array(
366
+				'func'       => '_contact_list_report',
367
+				'noheader'   => true,
368
+				'capability' => 'ee_read_contacts',
369
+			),
370
+		);
371
+	}
372
+
373
+
374
+	protected function _set_page_config()
375
+	{
376
+		$this->_page_config = array(
377
+			'default'           => array(
378
+				'nav'           => array(
379
+					'label' => __('Overview', 'event_espresso'),
380
+					'order' => 5,
381
+				),
382
+				'help_tabs'     => array(
383
+					'registrations_overview_help_tab'                       => array(
384
+						'title'    => __('Registrations Overview', 'event_espresso'),
385
+						'filename' => 'registrations_overview',
386
+					),
387
+					'registrations_overview_table_column_headings_help_tab' => array(
388
+						'title'    => __('Registrations Table Column Headings', 'event_espresso'),
389
+						'filename' => 'registrations_overview_table_column_headings',
390
+					),
391
+					'registrations_overview_filters_help_tab'               => array(
392
+						'title'    => __('Registration Filters', 'event_espresso'),
393
+						'filename' => 'registrations_overview_filters',
394
+					),
395
+					'registrations_overview_views_help_tab'                 => array(
396
+						'title'    => __('Registration Views', 'event_espresso'),
397
+						'filename' => 'registrations_overview_views',
398
+					),
399
+					'registrations_regoverview_other_help_tab'              => array(
400
+						'title'    => __('Registrations Other', 'event_espresso'),
401
+						'filename' => 'registrations_overview_other',
402
+					),
403
+				),
404
+				'help_tour'     => array('Registration_Overview_Help_Tour'),
405
+				'qtips'         => array('Registration_List_Table_Tips'),
406
+				'list_table'    => 'EE_Registrations_List_Table',
407
+				'require_nonce' => false,
408
+			),
409
+			'view_registration' => array(
410
+				'nav'           => array(
411
+					'label'      => __('REG Details', 'event_espresso'),
412
+					'order'      => 15,
413
+					'url'        => isset($this->_req_data['_REG_ID'])
414
+						? add_query_arg(array('_REG_ID' => $this->_req_data['_REG_ID']), $this->_current_page_view_url)
415
+						: $this->_admin_base_url,
416
+					'persistent' => false,
417
+				),
418
+				'help_tabs'     => array(
419
+					'registrations_details_help_tab'                    => array(
420
+						'title'    => __('Registration Details', 'event_espresso'),
421
+						'filename' => 'registrations_details',
422
+					),
423
+					'registrations_details_table_help_tab'              => array(
424
+						'title'    => __('Registration Details Table', 'event_espresso'),
425
+						'filename' => 'registrations_details_table',
426
+					),
427
+					'registrations_details_form_answers_help_tab'       => array(
428
+						'title'    => __('Registration Form Answers', 'event_espresso'),
429
+						'filename' => 'registrations_details_form_answers',
430
+					),
431
+					'registrations_details_registrant_details_help_tab' => array(
432
+						'title'    => __('Contact Details', 'event_espresso'),
433
+						'filename' => 'registrations_details_registrant_details',
434
+					),
435
+				),
436
+				'help_tour'     => array('Registration_Details_Help_Tour'),
437
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes,
438
+					array('_registration_details_metaboxes')),
439
+				'require_nonce' => false,
440
+			),
441
+			'new_registration'  => array(
442
+				'nav'           => array(
443
+					'label'      => __('Add New Registration', 'event_espresso'),
444
+					'url'        => '#',
445
+					'order'      => 15,
446
+					'persistent' => false,
447
+				),
448
+				'metaboxes'     => $this->_default_espresso_metaboxes,
449
+				'labels'        => array(
450
+					'publishbox' => __('Save Registration', 'event_espresso'),
451
+				),
452
+				'require_nonce' => false,
453
+			),
454
+			'add_new_attendee'  => array(
455
+				'nav'           => array(
456
+					'label'      => __('Add Contact', 'event_espresso'),
457
+					'order'      => 15,
458
+					'persistent' => false,
459
+				),
460
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes,
461
+					array('_publish_post_box', 'attendee_editor_metaboxes')),
462
+				'require_nonce' => false,
463
+			),
464
+			'edit_attendee'     => array(
465
+				'nav'           => array(
466
+					'label'      => __('Edit Contact', 'event_espresso'),
467
+					'order'      => 15,
468
+					'persistent' => false,
469
+					'url'        => isset($this->_req_data['ATT_ID'])
470
+						? add_query_arg(array('ATT_ID' => $this->_req_data['ATT_ID']), $this->_current_page_view_url)
471
+						: $this->_admin_base_url,
472
+				),
473
+				'metaboxes'     => array('attendee_editor_metaboxes'),
474
+				'require_nonce' => false,
475
+			),
476
+			'contact_list'      => array(
477
+				'nav'           => array(
478
+					'label' => __('Contact List', 'event_espresso'),
479
+					'order' => 20,
480
+				),
481
+				'list_table'    => 'EE_Attendee_Contact_List_Table',
482
+				'help_tabs'     => array(
483
+					'registrations_contact_list_help_tab'                       => array(
484
+						'title'    => __('Registrations Contact List', 'event_espresso'),
485
+						'filename' => 'registrations_contact_list',
486
+					),
487
+					'registrations_contact-list_table_column_headings_help_tab' => array(
488
+						'title'    => __('Contact List Table Column Headings', 'event_espresso'),
489
+						'filename' => 'registrations_contact_list_table_column_headings',
490
+					),
491
+					'registrations_contact_list_views_help_tab'                 => array(
492
+						'title'    => __('Contact List Views', 'event_espresso'),
493
+						'filename' => 'registrations_contact_list_views',
494
+					),
495
+					'registrations_contact_list_other_help_tab'                 => array(
496
+						'title'    => __('Contact List Other', 'event_espresso'),
497
+						'filename' => 'registrations_contact_list_other',
498
+					),
499
+				),
500
+				'help_tour'     => array('Contact_List_Help_Tour'),
501
+				'metaboxes'     => array(),
502
+				'require_nonce' => false,
503
+			),
504
+			//override default cpt routes
505
+			'create_new'        => '',
506
+			'edit'              => '',
507
+		);
508
+	}
509
+
510
+
511
+	/**
512
+	 * The below methods aren't used by this class currently
513
+	 */
514
+	protected function _add_screen_options()
515
+	{
516
+	}
517
+
518
+
519
+	protected function _add_feature_pointers()
520
+	{
521
+	}
522
+
523
+
524
+	public function admin_init()
525
+	{
526
+		EE_Registry::$i18n_js_strings['update_att_qstns'] = __('click "Update Registration Questions" to save your changes',
527
+			'event_espresso');
528
+	}
529
+
530
+
531
+	public function admin_notices()
532
+	{
533
+	}
534
+
535
+
536
+	public function admin_footer_scripts()
537
+	{
538
+	}
539
+
540
+
541
+	/**
542
+	 *        get list of registration statuses
543
+	 *
544
+	 * @access private
545
+	 * @return void
546
+	 */
547
+	private function _get_registration_status_array()
548
+	{
549
+		self::$_reg_status = EEM_Registration::reg_status_array(array(), true);
550
+	}
551
+
552
+
553
+	protected function _add_screen_options_default()
554
+	{
555
+		$this->_per_page_screen_option();
556
+	}
557
+
558
+
559
+	protected function _add_screen_options_contact_list()
560
+	{
561
+		$page_title              = $this->_admin_page_title;
562
+		$this->_admin_page_title = __("Contacts", 'event_espresso');
563
+		$this->_per_page_screen_option();
564
+		$this->_admin_page_title = $page_title;
565
+	}
566
+
567
+
568
+	public function load_scripts_styles()
569
+	{
570
+		//style
571
+		//wp_register_style('espresso_attendees', ATT_ASSETS_URL . 'espresso_attendees_admin.css', array(), EVENT_ESPRESSO_VERSION );
572
+		wp_register_style('espresso_reg', REG_ASSETS_URL . 'espresso_registrations_admin.css', array('ee-admin-css'),
573
+			EVENT_ESPRESSO_VERSION);
574
+		wp_enqueue_style('espresso_reg');
575
+		//script
576
+		wp_register_script('espresso_reg', REG_ASSETS_URL . 'espresso_registrations_admin.js',
577
+			array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'), EVENT_ESPRESSO_VERSION, true);
578
+		wp_enqueue_script('espresso_reg');
579
+	}
580
+
581
+
582
+	public function load_scripts_styles_edit_attendee()
583
+	{
584
+		//stuff to only show up on our attendee edit details page.
585
+		$attendee_details_translations = array(
586
+			'att_publish_text' => sprintf(__('Created on: <b>%1$s</b>', 'event_espresso'),
587
+				$this->_cpt_model_obj->get_datetime('ATT_created')),
588
+		);
589
+		wp_localize_script('espresso_reg', 'ATTENDEE_DETAILS', $attendee_details_translations);
590
+		wp_enqueue_script('jquery-validate');
591
+	}
592
+
593
+
594
+	public function load_scripts_styles_view_registration()
595
+	{
596
+		//styles
597
+		wp_enqueue_style('espresso-ui-theme');
598
+		//scripts
599
+		$this->_get_reg_custom_questions_form($this->_registration->ID());
600
+		$this->_reg_custom_questions_form->wp_enqueue_scripts(true);
601
+	}
602
+
603
+
604
+	public function load_scripts_styles_contact_list()
605
+	{
606
+		wp_deregister_style('espresso_reg');
607
+		wp_register_style('espresso_att', REG_ASSETS_URL . 'espresso_attendees_admin.css', array('ee-admin-css'),
608
+			EVENT_ESPRESSO_VERSION);
609
+		wp_enqueue_style('espresso_att');
610
+	}
611
+
612
+
613
+	public function load_scripts_styles_new_registration()
614
+	{
615
+		wp_register_script('ee-spco-for-admin', REG_ASSETS_URL . 'spco_for_admin.js', array('underscore', 'jquery'),
616
+			EVENT_ESPRESSO_VERSION, true);
617
+		wp_enqueue_script('ee-spco-for-admin');
618
+		add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
619
+		EE_Form_Section_Proper::wp_enqueue_scripts();
620
+		EED_Ticket_Selector::load_tckt_slctr_assets();
621
+		EE_Datepicker_Input::enqueue_styles_and_scripts();
622
+	}
623
+
624
+
625
+	public function AHEE__EE_Admin_Page__route_admin_request_resend_registration()
626
+	{
627
+		add_filter('FHEE_load_EE_messages', '__return_true');
628
+	}
629
+
630
+
631
+	public function AHEE__EE_Admin_Page__route_admin_request_approve_registration()
632
+	{
633
+		add_filter('FHEE_load_EE_messages', '__return_true');
634
+	}
635
+
636
+
637
+	protected function _set_list_table_views_default()
638
+	{
639
+		//for notification related bulk actions we need to make sure only active messengers have an option.
640
+		EED_Messages::set_autoloaders();
641
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
642
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
643
+		$active_mts               = $message_resource_manager->list_of_active_message_types();
644
+		//key= bulk_action_slug, value= message type.
645
+		$match_array = array(
646
+			'approve_registration'    => 'registration',
647
+			'decline_registration'    => 'declined_registration',
648
+			'pending_registration'    => 'pending_approval',
649
+			'no_approve_registration' => 'not_approved_registration',
650
+			'cancel_registration'     => 'cancelled_registration',
651
+		);
652
+		/** setup reg status bulk actions **/
653
+		$def_reg_status_actions['approve_registration'] = __('Approve Registrations', 'event_espresso');
654
+		if (in_array($match_array['approve_registration'], $active_mts)
655
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
656
+		) {
657
+			$def_reg_status_actions['approve_and_notify_registration'] = __('Approve and Notify Registrations',
658
+				'event_espresso');
659
+		}
660
+		$def_reg_status_actions['decline_registration'] = __('Decline Registrations', 'event_espresso');
661
+		if (in_array($match_array['decline_registration'], $active_mts)
662
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
663
+		) {
664
+			$def_reg_status_actions['decline_and_notify_registration'] = __('Decline and Notify Registrations',
665
+				'event_espresso');
666
+		}
667
+		$def_reg_status_actions['pending_registration'] = __('Set Registrations to Pending Payment', 'event_espresso');
668
+		if (in_array($match_array['pending_registration'], $active_mts)
669
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
670
+		) {
671
+			$def_reg_status_actions['pending_and_notify_registration'] = __('Set Registrations to Pending Payment and Notify',
672
+				'event_espresso');
673
+		}
674
+		$def_reg_status_actions['no_approve_registration'] = __('Set Registrations to Not Approved', 'event_espresso');
675
+		if (in_array($match_array['no_approve_registration'], $active_mts)
676
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
677
+		) {
678
+			$def_reg_status_actions['no_approve_and_notify_registration'] = __('Set Registrations to Not Approved and Notify',
679
+				'event_espresso');
680
+		}
681
+		$def_reg_status_actions['cancel_registration'] = __('Cancel Registrations', 'event_espresso');
682
+		if (in_array($match_array['cancel_registration'], $active_mts)
683
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message', 'batch_send_messages')
684
+		) {
685
+			$def_reg_status_actions['cancel_and_notify_registration'] = __('Cancel Registrations and Notify',
686
+				'event_espresso');
687
+		}
688
+		$this->_views = array(
689
+			'all'   => array(
690
+				'slug'        => 'all',
691
+				'label'       => __('View All Registrations', 'event_espresso'),
692
+				'count'       => 0,
693
+				'bulk_action' => array_merge($def_reg_status_actions, array(
694
+					'trash_registrations' => __('Trash Registrations', 'event_espresso'),
695
+				)),
696
+			),
697
+			'month' => array(
698
+				'slug'        => 'month',
699
+				'label'       => __('This Month', 'event_espresso'),
700
+				'count'       => 0,
701
+				'bulk_action' => array_merge($def_reg_status_actions, array(
702
+					'trash_registrations' => __('Trash Registrations', 'event_espresso'),
703
+				)),
704
+			),
705
+			'today' => array(
706
+				'slug'        => 'today',
707
+				'label'       => sprintf(__('Today - %s', 'event_espresso'), date('M d, Y', current_time('timestamp'))),
708
+				'count'       => 0,
709
+				'bulk_action' => array_merge($def_reg_status_actions, array(
710
+					'trash_registrations' => __('Trash Registrations', 'event_espresso'),
711
+				)),
712
+			),
713
+		);
714
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_registrations',
715
+			'espresso_registrations_delete_registration')
716
+		) {
717
+			$this->_views['incomplete'] = array(
718
+				'slug'        => 'incomplete',
719
+				'label'       => __('Incomplete', 'event_espresso'),
720
+				'count'       => 0,
721
+				'bulk_action' => array(
722
+					'trash_registrations' => __('Trash Registrations', 'event_espresso'),
723
+				),
724
+			);
725
+			$this->_views['trash']      = array(
726
+				'slug'        => 'trash',
727
+				'label'       => __('Trash', 'event_espresso'),
728
+				'count'       => 0,
729
+				'bulk_action' => array(
730
+					'restore_registrations' => __('Restore Registrations', 'event_espresso'),
731
+					'delete_registrations'  => __('Delete Registrations Permanently', 'event_espresso'),
732
+				),
733
+			);
734
+		}
735
+	}
736
+
737
+
738
+	protected function _set_list_table_views_contact_list()
739
+	{
740
+		$this->_views = array(
741
+			'in_use' => array(
742
+				'slug'        => 'in_use',
743
+				'label'       => __('In Use', 'event_espresso'),
744
+				'count'       => 0,
745
+				'bulk_action' => array(
746
+					'trash_attendees' => __('Move to Trash', 'event_espresso'),
747
+				),
748
+			),
749
+		);
750
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_contacts',
751
+			'espresso_registrations_trash_attendees')
752
+		) {
753
+			$this->_views['trash'] = array(
754
+				'slug'        => 'trash',
755
+				'label'       => __('Trash', 'event_espresso'),
756
+				'count'       => 0,
757
+				'bulk_action' => array(
758
+					'restore_attendees' => __('Restore from Trash', 'event_espresso'),
759
+				),
760
+			);
761
+		}
762
+	}
763
+
764
+
765
+	protected function _registration_legend_items()
766
+	{
767
+		$fc_items = array(
768
+			'star-icon'        => array(
769
+				'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
770
+				'desc'  => __('This is the Primary Registrant', 'event_espresso'),
771
+			),
772
+			'view_details'     => array(
773
+				'class' => 'dashicons dashicons-clipboard',
774
+				'desc'  => __('View Registration Details', 'event_espresso'),
775
+			),
776
+			'edit_attendee'    => array(
777
+				'class' => 'ee-icon ee-icon-user-edit ee-icon-size-16',
778
+				'desc'  => __('Edit Contact Details', 'event_espresso'),
779
+			),
780
+			'view_transaction' => array(
781
+				'class' => 'dashicons dashicons-cart',
782
+				'desc'  => __('View Transaction Details', 'event_espresso'),
783
+			),
784
+			'view_invoice'     => array(
785
+				'class' => 'dashicons dashicons-media-spreadsheet',
786
+				'desc'  => __('View Transaction Invoice', 'event_espresso'),
787
+			),
788
+		);
789
+		if (EE_Registry::instance()->CAP->current_user_can('ee_send_message',
790
+			'espresso_registrations_resend_registration')
791
+		) {
792
+			$fc_items['resend_registration'] = array(
793
+				'class' => 'dashicons dashicons-email-alt',
794
+				'desc'  => __('Resend Registration Details', 'event_espresso'),
795
+			);
796
+		} else {
797
+			$fc_items['blank'] = array('class' => 'blank', 'desc' => '');
798
+		}
799
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
800
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
801
+			if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
802
+				$fc_items['view_related_messages'] = array(
803
+					'class' => $related_for_icon['css_class'],
804
+					'desc'  => $related_for_icon['label'],
805
+				);
806
+			}
807
+		}
808
+		$sc_items = array(
809
+			'approved_status'   => array(
810
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
811
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
812
+			),
813
+			'pending_status'    => array(
814
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
815
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
816
+			),
817
+			'wait_list'         => array(
818
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
819
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
820
+			),
821
+			'incomplete_status' => array(
822
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
823
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_incomplete, false, 'sentence'),
824
+			),
825
+			'not_approved'      => array(
826
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
827
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
828
+			),
829
+			'declined_status'   => array(
830
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
831
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
832
+			),
833
+			'cancelled_status'  => array(
834
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
835
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
836
+			),
837
+		);
838
+		return array_merge($fc_items, $sc_items);
839
+	}
840
+
841
+
842
+
843
+	/***************************************        REGISTRATION OVERVIEW        **************************************/
844
+	/**
845
+	 * @throws \EE_Error
846
+	 */
847
+	protected function _registrations_overview_list_table()
848
+	{
849
+		$this->_template_args['admin_page_header'] = '';
850
+		$EVT_ID                                    = ! empty($this->_req_data['event_id']) ? absint($this->_req_data['event_id']) : 0;
851
+		if ($EVT_ID) {
852
+			if (EE_Registry::instance()->CAP->current_user_can('ee_edit_registrations',
853
+				'espresso_registrations_new_registration', $EVT_ID)
854
+			) {
855
+				$this->_admin_page_title .= ' ' . $this->get_action_link_or_button('new_registration', 'add-registrant',
856
+						array('event_id' => $EVT_ID), 'add-new-h2');
857
+			}
858
+			$event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
859
+			if ($event instanceof EE_Event) {
860
+				$this->_template_args['admin_page_header'] = sprintf(__('%s Viewing registrations for the event: %s%s',
861
+					'event_espresso'), '<h3 style="line-height:1.5em;">',
862
+					'<br /><a href="' . EE_Admin_Page::add_query_args_and_nonce(array(
863
+						'action' => 'edit',
864
+						'post'   => $event->ID(),
865
+					), EVENTS_ADMIN_URL) . '">&nbsp;' . $event->get('EVT_name') . '&nbsp;</a>&nbsp;', '</h3>');
866
+			}
867
+			$DTT_ID   = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
868
+			$datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
869
+			if ($datetime instanceof EE_Datetime && $this->_template_args['admin_page_header'] !== '') {
870
+				$this->_template_args['admin_page_header'] = substr($this->_template_args['admin_page_header'], 0, -5);
871
+				$this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
872
+				$this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
873
+				$this->_template_args['admin_page_header'] .= $datetime->name();
874
+				$this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
875
+				$this->_template_args['admin_page_header'] .= '</span></h3>';
876
+			}
877
+		}
878
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_registration_legend_items());
879
+		$this->display_admin_list_table_page_with_no_sidebar();
880
+	}
881
+
882
+
883
+	/**
884
+	 * This sets the _registration property for the registration details screen
885
+	 *
886
+	 * @access private
887
+	 * @return bool
888
+	 */
889
+	private function _set_registration_object()
890
+	{
891
+		//get out if we've already set the object
892
+		if (is_object($this->_registration)) {
893
+			return true;
894
+		}
895
+		$REG    = EEM_Registration::instance();
896
+		$REG_ID = ( ! empty($this->_req_data['_REG_ID'])) ? absint($this->_req_data['_REG_ID']) : false;
897
+		if ($this->_registration = $REG->get_one_by_ID($REG_ID)) {
898
+			return true;
899
+		} else {
900
+			$error_msg = sprintf(__('An error occurred and the details for Registration ID #%s could not be retrieved.',
901
+				'event_espresso'), $REG_ID);
902
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
903
+			$this->_registration = null;
904
+			return false;
905
+		}
906
+	}
907
+
908
+
909
+	/**
910
+	 * Used to retrieve registrations for the list table.
911
+	 *
912
+	 * @param int    $per_page
913
+	 * @param bool   $count
914
+	 * @param bool   $this_month 
915
+	 * @param bool   $today
916
+	 * @return \EE_Registration[]|int
917
+	 */
918
+	public function get_registrations(
919
+		$per_page = 10,
920
+		$count = false,
921
+		$this_month = false,
922
+		$today = false
923
+	) {
924
+		if( $this_month ) {
925
+			$this->_req_data['status'] = 'month';
926
+		}
927
+		if( $today ) {
928
+			$this->_req_data['status'] = 'today';
929
+		}
930
+		$query_params = $this->_get_registration_query_parameters($this->_req_data, $per_page, $count);
931
+		return $count
932
+			? EEM_Registration::instance()->count($query_params)
933
+			/** @type EE_Registration[] */
934
+			: EEM_Registration::instance()->get_all($query_params);
935
+	}
936
+
937
+
938
+
939
+	/**
940
+	 * Retrieves the query parameters to be used by the Registration model for getting registrations.
941
+	 * Note: this listens to values on the request for some of the query parameters.
942
+	 *
943
+	 * @param array $request
944
+	 * @param int    $per_page
945
+	 * @param bool   $count
946
+	 * @return array
947
+	 */
948
+	protected function _get_registration_query_parameters(
949
+		$request = array(),
950
+		$per_page = 10,
951
+		$count = false
952
+	) {
953
+
954
+		$query_params = array(
955
+			0                          => $this->_get_where_conditions_for_registrations_query(
956
+				$request
957
+			),
958
+			'caps'                     => EEM_Registration::caps_read_admin,
959
+			'default_where_conditions' => 'this_model_only',
960
+		);
961
+		if ( ! $count) {
962
+			$query_params = array_merge(
963
+				$query_params,
964
+				$this->_get_orderby_for_registrations_query(),
965
+				$this->_get_limit($per_page)
966
+			);
967
+		}
968
+
969
+		return $query_params;
970
+	}
971
+
972
+
973
+	/**
974
+	 * This will add EVT_ID to the provided $where array for EE model query parameters.
975
+	 *
976
+	 * @param array $request usually the same as $this->_req_data but not necessarily
977
+	 * @return array
978
+	 */
979
+	protected function _add_event_id_to_where_conditions(array $request)
980
+	{
981
+		$where = array();
982
+		if ( ! empty($request['event_id'])) {
983
+			$where['EVT_ID'] = absint($request['event_id']);
984
+		}
985
+		return $where;
986
+	}
987
+
988
+
989
+	/**
990
+	 * Adds category ID if it exists in the request to the where conditions for the registrations query.
991
+	 *
992
+	 * @param array $request usually the same as $this->_req_data but not necessarily
993
+	 * @return array
994
+	 */
995
+	protected function _add_category_id_to_where_conditions(array $request)
996
+	{
997
+		$where = array();
998
+		if ( ! empty($request['EVT_CAT']) && (int)$request['EVT_CAT'] !== -1) {
999
+			$where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1000
+		}
1001
+		return $where;
1002
+	}
1003
+
1004
+
1005
+	/**
1006
+	 * Adds the datetime ID if it exists in the request to the where conditions for the registrations query.
1007
+	 *
1008
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1009
+	 * @return array
1010
+	 */
1011
+	protected function _add_datetime_id_to_where_conditions(array $request)
1012
+	{
1013
+		$where = array();
1014
+		if ( ! empty($request['datetime_id'])) {
1015
+			$where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1016
+		}
1017
+		if( ! empty($request['DTT_ID'])){
1018
+			$where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1019
+		}
1020
+		return $where;
1021
+	}
1022
+
1023
+
1024
+	/**
1025
+	 * Adds the correct registration status to the where conditions for the registrations query.
1026
+	 *
1027
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1028
+	 * @return array
1029
+	 */
1030
+	protected function _add_registration_status_to_where_conditions(array $request)
1031
+	{
1032
+		$where = array();
1033
+		$view  = EEH_Array::is_set( $request, 'status', '' );
1034
+		$registration_status = ! empty($request['_reg_status'])
1035
+			? sanitize_text_field($request['_reg_status'])
1036
+			: '';
1037
+
1038
+		/*
1039 1039
          * If filtering by registration status, then we show registrations matching that status.
1040 1040
          * If not filtering by specified status, then we show all registrations excluding incomplete registrations UNLESS
1041 1041
          * viewing trashed registrations.
1042 1042
          */
1043
-        if ( ! empty($registration_status)) {
1044
-            $where['STS_ID'] = $registration_status;
1045
-        } else {
1046
-            //make sure we exclude incomplete registrations, but only if not trashed.
1047
-            if ($view === 'trash') {
1048
-                $where['REG_deleted'] = true;
1049
-            } else if ($view === 'incomplete') {
1050
-                $where['STS_ID'] = EEM_Registration::status_id_incomplete;
1051
-            } else {
1052
-                $where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1053
-            }
1054
-        }
1055
-        return $where;
1056
-    }
1057
-
1058
-
1059
-    /**
1060
-     * Adds any provided date restraints to the where conditions for the registrations query.
1061
-     *
1062
-     * @param array $request usually the same as $this->_req_data but not necessarily
1063
-     * @return array
1064
-     */
1065
-    protected function _add_date_to_where_conditions(array $request)
1066
-    {
1067
-        $where = array();
1068
-        $view  = EEH_Array::is_set( $request, 'status', '' );
1069
-        $month_range             = ! empty($request['month_range'])
1070
-            ? sanitize_text_field($request['month_range'])
1071
-            : '';
1072
-        $retrieve_for_today      = $view === 'today';
1073
-        $retrieve_for_this_month = $view === 'month';
1074
-
1075
-        if ($retrieve_for_today) {
1076
-            $now               = date('Y-m-d', current_time('timestamp'));
1077
-            $where['REG_date'] = array(
1078
-                'BETWEEN',
1079
-                array(
1080
-                    EEM_Registration::instance()->convert_datetime_for_query(
1081
-                        'REG_date',
1082
-                        $now . ' 00:00:00',
1083
-                        'Y-m-d H:i:s'
1084
-                    ),
1085
-                    EEM_Registration::instance()->convert_datetime_for_query(
1086
-                        'REG_date',
1087
-                        $now . ' 23:59:59',
1088
-                        'Y-m-d H:i:s'
1089
-                    ),
1090
-                ),
1091
-            );
1092
-        } elseif ($retrieve_for_this_month) {
1093
-            $current_year_and_month = date('Y-m', current_time('timestamp'));
1094
-            $days_this_month        = date('t', current_time('timestamp'));
1095
-            $where['REG_date']      = array(
1096
-                'BETWEEN',
1097
-                array(
1098
-                    EEM_Registration::instance()->convert_datetime_for_query(
1099
-                        'REG_date',
1100
-                        $current_year_and_month . '-01 00:00:00',
1101
-                        'Y-m-d H:i:s'
1102
-                    ),
1103
-                    EEM_Registration::instance()->convert_datetime_for_query(
1104
-                        'REG_date',
1105
-                        $current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1106
-                        'Y-m-d H:i:s'
1107
-                    ),
1108
-                ),
1109
-            );
1110
-        } elseif ($month_range) {
1111
-            $pieces          = explode(' ', $month_range, 3);
1112
-            $month_requested = ! empty($pieces[0])
1113
-                ? date('m', strtotime($month_range))
1114
-                : '';
1115
-            $year_requested  = ! empty($pieces[1])
1116
-                ? $pieces[1]
1117
-                : '';
1118
-            //if there is not a month or year then we can't go further
1119
-            if ($month_requested && $year_requested) {
1120
-                $days_in_month     = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1121
-                $where['REG_date'] = array(
1122
-                    'BETWEEN',
1123
-                    array(
1124
-                        EEM_Registration::instance()->convert_datetime_for_query(
1125
-                            'REG_date',
1126
-                            $year_requested . '-' . $month_requested . '-01 00:00:00',
1127
-                            'Y-m-d H:i:s'
1128
-                        ),
1129
-                        EEM_Registration::instance()->convert_datetime_for_query(
1130
-                            'REG_date',
1131
-                            $year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1132
-                            'Y-m-d H:i:s'
1133
-                        ),
1134
-                    ),
1135
-                );
1136
-            }
1137
-        }
1138
-        return $where;
1139
-    }
1140
-
1141
-
1142
-    /**
1143
-     * Adds any provided search restraints to the where conditions for the registrations query
1144
-     *
1145
-     * @param array $request usually the same as $this->_req_data but not necessarily
1146
-     * @return array
1147
-     */
1148
-    protected function _add_search_to_where_conditions(array $request)
1149
-    {
1150
-        $where = array();
1151
-        if ( ! empty($request['s'])) {
1152
-            $search_string = '%' . sanitize_text_field($request['s']) . '%';
1153
-            $where['OR'] = array(
1154
-                'Event.EVT_name'                          => array('LIKE', $search_string),
1155
-                'Event.EVT_desc'                          => array('LIKE', $search_string),
1156
-                'Event.EVT_short_desc'                    => array('LIKE', $search_string),
1157
-                'Attendee.ATT_full_name'                  => array('LIKE', $search_string),
1158
-                'Attendee.ATT_fname'                      => array('LIKE', $search_string),
1159
-                'Attendee.ATT_lname'                      => array('LIKE', $search_string),
1160
-                'Attendee.ATT_short_bio'                  => array('LIKE', $search_string),
1161
-                'Attendee.ATT_email'                      => array('LIKE', $search_string),
1162
-                'Attendee.ATT_address'                    => array('LIKE', $search_string),
1163
-                'Attendee.ATT_address2'                   => array('LIKE', $search_string),
1164
-                'Attendee.ATT_city'                       => array('LIKE', $search_string),
1165
-                'REG_final_price'                         => array('LIKE', $search_string),
1166
-                'REG_code'                                => array('LIKE', $search_string),
1167
-                'REG_count'                               => array('LIKE', $search_string),
1168
-                'REG_group_size'                          => array('LIKE', $search_string),
1169
-                'Ticket.TKT_name'                         => array('LIKE', $search_string),
1170
-                'Ticket.TKT_description'                  => array('LIKE', $search_string),
1171
-                'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $search_string),
1172
-            );
1173
-        }
1174
-        return $where;
1175
-    }
1176
-
1177
-
1178
-    /**
1179
-     * Sets up the where conditions for the registrations query.
1180
-     *
1181
-     * @param array $request
1182
-     * @return array
1183
-     */
1184
-    protected function _get_where_conditions_for_registrations_query($request)
1185
-    {
1186
-        return array_merge(
1187
-            $this->_add_event_id_to_where_conditions($request),
1188
-            $this->_add_category_id_to_where_conditions($request),
1189
-            $this->_add_datetime_id_to_where_conditions($request),
1190
-            $this->_add_registration_status_to_where_conditions($request),
1191
-            $this->_add_date_to_where_conditions($request),
1192
-            $this->_add_search_to_where_conditions($request)
1193
-        );
1194
-    }
1195
-
1196
-
1197
-    /**
1198
-     * Sets up the orderby for the registrations query.
1199
-     *
1200
-     * @return array
1201
-     */
1202
-    protected function _get_orderby_for_registrations_query()
1203
-    {
1204
-        $orderby_field = ! empty($this->_req_data['orderby'])
1205
-            ? sanitize_text_field($this->_req_data['orderby'])
1206
-            : '';
1207
-        switch ($orderby_field) {
1208
-            case '_REG_ID':
1209
-                $orderby_field = 'REG_ID';
1210
-                break;
1211
-            case '_Reg_status':
1212
-                $orderby_field = 'STS_ID';
1213
-                break;
1214
-            case 'ATT_fname':
1215
-                //just for spite, we're going to order it by their LAST name, NOT their first name. Now who's the boss?
1216
-                //jk, we don't want to break existing links, and customers preferred ordering by last name
1217
-                //besides, from the UI, its ambiguous as to whether we will order by first or last name
1218
-                $orderby_field = 'Attendee.ATT_lname';
1219
-                break;
1220
-            case 'event_name':
1221
-                $orderby_field = 'Event.EVT_name';
1222
-                break;
1223
-            case 'DTT_EVT_start':
1224
-                $orderby_field = 'Event.Datetime.DTT_EVT_start';
1225
-                break;
1226
-            default: //'REG_date'
1227
-                $orderby_field = 'REG_date';
1228
-        }
1229
-
1230
-        //order
1231
-        $order = ! empty($this->_req_data['order'])
1232
-            ? sanitize_text_field($this->_req_data['order'])
1233
-            : 'DESC';
1234
-        return array('order_by' => array($orderby_field => $order));
1235
-    }
1236
-
1237
-
1238
-    /**
1239
-     * Sets up the limit for the registrations query.
1240
-     *
1241
-     * @param $per_page
1242
-     * @return array
1243
-     */
1244
-    protected function _get_limit($per_page)
1245
-    {
1246
-        $current_page = ! empty($this->_req_data['paged'])
1247
-            ? absint($this->_req_data['paged'])
1248
-            : 1;
1249
-        $per_page     = ! empty($this->_req_data['perpage'])
1250
-            ? $this->_req_data['perpage']
1251
-            : $per_page;
1252
-
1253
-        //-1 means return all results so get out if that's set.
1254
-        if ((int)$per_page === -1) {
1255
-            return array();
1256
-        }
1257
-        $per_page = absint($per_page);
1258
-        $offset   = ($current_page - 1) * $per_page;
1259
-        return array('limit' => array($offset, $per_page));
1260
-    }
1261
-
1262
-
1263
-    public function get_registration_status_array()
1264
-    {
1265
-        return self::$_reg_status;
1266
-    }
1267
-
1268
-
1269
-
1270
-
1271
-    /***************************************        REGISTRATION DETAILS        ***************************************/
1272
-    /**
1273
-     *        generates HTML for the View Registration Details Admin page
1274
-     *
1275
-     * @access protected
1276
-     * @return void
1277
-     */
1278
-    protected function _registration_details()
1279
-    {
1280
-        $this->_template_args = array();
1281
-        $this->_set_registration_object();
1282
-        if (is_object($this->_registration)) {
1283
-            $transaction                                   = $this->_registration->transaction() ? $this->_registration->transaction()
1284
-                : EE_Transaction::new_instance();
1285
-            $this->_session                                = $transaction->session_data();
1286
-            $event_id                                      = $this->_registration->event_ID();
1287
-            $this->_template_args['reg_nmbr']['value']     = $this->_registration->ID();
1288
-            $this->_template_args['reg_nmbr']['label']     = __('Registration Number', 'event_espresso');
1289
-            $this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1290
-            $this->_template_args['reg_datetime']['label'] = __('Date', 'event_espresso');
1291
-            $this->_template_args['grand_total']           = $transaction->total();
1292
-            $this->_template_args['currency_sign']         = EE_Registry::instance()->CFG->currency->sign;
1293
-            // link back to overview
1294
-            $this->_template_args['reg_overview_url']            = REG_ADMIN_URL;
1295
-            $this->_template_args['registration']                = $this->_registration;
1296
-            $this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
1297
-                'action'   => 'default',
1298
-                'event_id' => $event_id,
1299
-            ), REG_ADMIN_URL);
1300
-            $this->_template_args['filtered_transactions_link']  = EE_Admin_Page::add_query_args_and_nonce(array(
1301
-                'action' => 'default',
1302
-                'EVT_ID' => $event_id,
1303
-                'page'   => 'espresso_transactions',
1304
-            ), admin_url('admin.php'));
1305
-            $this->_template_args['event_link']                  = EE_Admin_Page::add_query_args_and_nonce(array(
1306
-                'page'   => 'espresso_events',
1307
-                'action' => 'edit',
1308
-                'post'   => $event_id,
1309
-            ), admin_url('admin.php'));
1310
-            //next and previous links
1311
-            $next_reg                                      = $this->_registration->next(null, array(), 'REG_ID');
1312
-            $this->_template_args['next_registration']     = $next_reg
1313
-                ? $this->_next_link(EE_Admin_Page::add_query_args_and_nonce(array(
1314
-                    'action'  => 'view_registration',
1315
-                    '_REG_ID' => $next_reg['REG_ID'],
1316
-                ), REG_ADMIN_URL), 'dashicons dashicons-arrow-right ee-icon-size-22') : '';
1317
-            $previous_reg                                  = $this->_registration->previous(null, array(), 'REG_ID');
1318
-            $this->_template_args['previous_registration'] = $previous_reg
1319
-                ? $this->_previous_link(EE_Admin_Page::add_query_args_and_nonce(array(
1320
-                    'action'  => 'view_registration',
1321
-                    '_REG_ID' => $previous_reg['REG_ID'],
1322
-                ), REG_ADMIN_URL), 'dashicons dashicons-arrow-left ee-icon-size-22') : '';
1323
-            // grab header
1324
-            $template_path                             = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1325
-            $this->_template_args['REG_ID']            = $this->_registration->ID();
1326
-            $this->_template_args['admin_page_header'] = EEH_Template::display_template($template_path,
1327
-                $this->_template_args, true);
1328
-        } else {
1329
-            $this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1330
-        }
1331
-        // the details template wrapper
1332
-        $this->display_admin_page_with_sidebar();
1333
-    }
1334
-
1335
-
1336
-    protected function _registration_details_metaboxes()
1337
-    {
1338
-        do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1339
-        $this->_set_registration_object();
1340
-        $attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1341
-        add_meta_box('edit-reg-status-mbox', __('Registration Status', 'event_espresso'),
1342
-            array($this, 'set_reg_status_buttons_metabox'), $this->wp_page_slug, 'normal', 'high');
1343
-        add_meta_box('edit-reg-details-mbox', __('Registration Details', 'event_espresso'),
1344
-            array($this, '_reg_details_meta_box'), $this->wp_page_slug, 'normal', 'high');
1345
-        if ($attendee instanceof EE_Attendee
1346
-            && EE_Registry::instance()->CAP->current_user_can('ee_edit_registration', 'edit-reg-questions-mbox')
1347
-        ) {
1348
-            add_meta_box('edit-reg-questions-mbox', __('Registration Form Answers', 'event_espresso'),
1349
-                array($this, '_reg_questions_meta_box'), $this->wp_page_slug, 'normal', 'high');
1350
-        }
1351
-        add_meta_box('edit-reg-registrant-mbox', __('Contact Details', 'event_espresso'),
1352
-            array($this, '_reg_registrant_side_meta_box'), $this->wp_page_slug, 'side', 'high');
1353
-        if ($this->_registration->group_size() > 1) {
1354
-            add_meta_box('edit-reg-attendees-mbox', __('Other Registrations in this Transaction', 'event_espresso'),
1355
-                array($this, '_reg_attendees_meta_box'), $this->wp_page_slug, 'normal', 'high');
1356
-        }
1357
-    }
1358
-
1359
-
1360
-    /**
1361
-     * set_reg_status_buttons_metabox
1362
-     *
1363
-     * @access protected
1364
-     * @return string
1365
-     * @throws \EE_Error
1366
-     */
1367
-    public function set_reg_status_buttons_metabox()
1368
-    {
1369
-        $this->_set_registration_object();
1370
-        $change_reg_status_form = $this->_generate_reg_status_change_form();
1371
-        echo $change_reg_status_form->form_open(self::add_query_args_and_nonce(array(
1372
-            'action' => 'change_reg_status',
1373
-        ), REG_ADMIN_URL));
1374
-        echo $change_reg_status_form->get_html();
1375
-        echo $change_reg_status_form->form_close();
1376
-    }
1377
-
1378
-
1379
-    /**
1380
-     * @return EE_Form_Section_Proper
1381
-     */
1382
-    protected function _generate_reg_status_change_form()
1383
-    {
1384
-        return new EE_Form_Section_Proper(array(
1385
-            'name'            => 'reg_status_change_form',
1386
-            'html_id'         => 'reg-status-change-form',
1387
-            'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1388
-            'subsections'     => array(
1389
-                'return'             => new EE_Hidden_Input(array(
1390
-                    'name'    => 'return',
1391
-                    'default' => 'view_registration',
1392
-                )),
1393
-                'REG_ID'             => new EE_Hidden_Input(array(
1394
-                    'name'    => 'REG_ID',
1395
-                    'default' => $this->_registration->ID(),
1396
-                )),
1397
-                'current_status'     => new EE_Form_Section_HTML(EEH_HTML::tr(EEH_HTML::th(EEH_HTML::label(EEH_HTML::strong(__('Current Registration Status',
1398
-                        'event_espresso')))) . EEH_HTML::td(EEH_HTML::strong($this->_registration->pretty_status(),
1399
-                        '', 'status-' . $this->_registration->status_ID(),
1400
-                        'line-height: 1em; font-size: 1.5em; font-weight: bold;')))),
1401
-                'reg_status'         => new EE_Select_Input($this->_get_reg_statuses(), array(
1402
-                    'html_label_text' => __('Change Registration Status to', 'event_espresso'),
1403
-                    'default'         => $this->_registration->status_ID(),
1404
-                )),
1405
-                'send_notifications' => new EE_Yes_No_Input(array(
1406
-                    'html_label_text' => __('Send Related Messages', 'event_espresso'),
1407
-                    'default'         => false,
1408
-                    'html_help_text'  => __('If set to "Yes", then the related messages will be sent to the registrant.',
1409
-                        'event_espresso'),
1410
-                )),
1411
-                'submit'             => new EE_Submit_Input(array(
1412
-                    'html_class'      => 'button-primary',
1413
-                    'html_label_text' => '&nbsp;',
1414
-                    'default'         => __('Update Registration Status', 'event_espresso'),
1415
-                )),
1416
-            ),
1417
-        ));
1418
-    }
1419
-
1420
-
1421
-
1422
-    /**
1423
-     * Returns an array of all the buttons for the various statuses and switch status actions
1424
-     *
1425
-     * @return array
1426
-     */
1427
-    protected function _get_reg_statuses()
1428
-    {
1429
-        $reg_status_array = EEM_Registration::instance()->reg_status_array();
1430
-        unset ($reg_status_array[EEM_Registration::status_id_incomplete]);
1431
-        // get current reg status
1432
-        $current_status = $this->_registration->status_ID();
1433
-        // is registration for free event? This will determine whether to display the pending payment option
1434
-        if ($current_status != EEM_Registration::status_id_pending_payment
1435
-            && $this->_registration->transaction()
1436
-                                   ->is_free()
1437
-        ) {
1438
-            unset($reg_status_array[EEM_Registration::status_id_pending_payment]);
1439
-        }
1440
-        return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1441
-    }
1442
-
1443
-
1444
-    /**
1445
-     * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1446
-     *
1447
-     * @param bool $status REG status given for changing registrations to.
1448
-     * @param bool $notify Whether to send messages notifications or not.
1449
-     * @return array  (array with reg_id(s) updated and whether update was successful.
1450
-     */
1451
-    protected function _set_registration_status_from_request($status = false, $notify = false)
1452
-    {
1453
-        if (isset($this->_req_data['reg_status_change_form'])) {
1454
-            $REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1455
-                ? (array)$this->_req_data['reg_status_change_form']['REG_ID'] : array();
1456
-        } else {
1457
-            $REG_IDs = isset($this->_req_data['_REG_ID']) ? (array)$this->_req_data['_REG_ID'] : array();
1458
-        }
1459
-        $success = $this->_set_registration_status($REG_IDs, $status);
1460
-        //notify?
1461
-        if ($success
1462
-            && $notify
1463
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message',
1464
-                'espresso_registrations_resend_registration')
1465
-        ) {
1466
-            $this->_process_resend_registration();
1467
-        }
1468
-        return $success;
1469
-    }
1470
-
1471
-
1472
-    /**
1473
-     * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1474
-     * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1475
-     *
1476
-     * @param array $REG_IDs
1477
-     * @param bool  $status
1478
-     * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1479
-     *               the array of updated registrations).
1480
-     */
1481
-    protected function _set_registration_status($REG_IDs = array(), $status = false)
1482
-    {
1483
-        $success = false;
1484
-        // typecast $REG_IDs
1485
-        $REG_IDs = (array)$REG_IDs;
1486
-        if ( ! empty($REG_IDs)) {
1487
-            $success = true;
1488
-            // set default status if none is passed
1489
-            $status = $status ? $status : EEM_Registration::status_id_pending_payment;
1490
-            // sanitize $REG_IDs
1491
-            $REG_IDs = array_filter($REG_IDs, 'absint');
1492
-            //loop through REG_ID's and change status
1493
-            foreach ($REG_IDs as $REG_ID) {
1494
-                $registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1495
-                if ($registration instanceof EE_Registration) {
1496
-                    $registration->set_status($status);
1497
-                    $result = $registration->save();
1498
-                    // verifying explicit fails because update *may* just return 0 for 0 rows affected
1499
-                    $success = $result !== false ? $success : false;
1500
-                }
1501
-            }
1502
-        }
1503
-        //reset _req_data['_REG_ID'] for any potential future messages notifications
1504
-        $this->_req_data['_REG_ID'] = $REG_IDs;
1505
-        //return $success and processed registrations
1506
-        return array('REG_ID' => $REG_IDs, 'success' => $success);
1507
-    }
1508
-
1509
-
1510
-    /**
1511
-     * Common logic for setting up success message and redirecting to appropriate route
1512
-     *
1513
-     * @param  string $STS_ID status id for the registration changed to
1514
-     * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1515
-     * @return void
1516
-     */
1517
-    protected function _reg_status_change_return($STS_ID, $notify = false)
1518
-    {
1519
-        $result  = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1520
-            : array('success' => false);
1521
-        $success = isset($result['success']) && $result['success'];
1522
-        //setup success message
1523
-        if ($success) {
1524
-            if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1525
-                $msg = sprintf(__('Registration status has been set to %s', 'event_espresso'),
1526
-                    EEH_Template::pretty_status($STS_ID, false, 'lower'));
1527
-            } else {
1528
-                $msg = sprintf(__('Registrations have been set to %s.', 'event_espresso'),
1529
-                    EEH_Template::pretty_status($STS_ID, false, 'lower'));
1530
-            }
1531
-            EE_Error::add_success($msg);
1532
-        } else {
1533
-            EE_Error::add_error(__('Something went wrong, and the status was not changed', 'event_espresso'), __FILE__,
1534
-                __LINE__, __FUNCTION__);
1535
-        }
1536
-        if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
1537
-            $route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
1538
-        } else {
1539
-            $route = array('action' => 'default');
1540
-        }
1541
-        //unset nonces
1542
-        foreach ($this->_req_data as $ref => $value) {
1543
-            if (strpos($ref, 'nonce') !== false) {
1544
-                unset($this->_req_data[$ref]);
1545
-                continue;
1546
-            }
1547
-            $value                 = is_array($value) ? array_map('urlencode', $value) : urlencode($value);
1548
-            $this->_req_data[$ref] = $value;
1549
-        }
1550
-        //merge request vars so that the reloaded list table contains any existing filter query params
1551
-        $route = array_merge($this->_req_data, $route);
1552
-        $this->_redirect_after_action($success, '', '', $route, true);
1553
-    }
1554
-
1555
-
1556
-    /**
1557
-     * incoming reg status change from reg details page.
1558
-     *
1559
-     * @return void
1560
-     */
1561
-    protected function _change_reg_status()
1562
-    {
1563
-        $this->_req_data['return'] = 'view_registration';
1564
-        //set notify based on whether the send notifications toggle is set or not
1565
-        $notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
1566
-        //$notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
1567
-        $this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
1568
-            ? $this->_req_data['reg_status_change_form']['reg_status'] : '';
1569
-        switch ($this->_req_data['reg_status_change_form']['reg_status']) {
1570
-            case EEM_Registration::status_id_approved :
1571
-            case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence') :
1572
-                $this->approve_registration($notify);
1573
-                break;
1574
-            case EEM_Registration::status_id_pending_payment :
1575
-            case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence') :
1576
-                $this->pending_registration($notify);
1577
-                break;
1578
-            case EEM_Registration::status_id_not_approved :
1579
-            case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence') :
1580
-                $this->not_approve_registration($notify);
1581
-                break;
1582
-            case EEM_Registration::status_id_declined :
1583
-            case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence') :
1584
-                $this->decline_registration($notify);
1585
-                break;
1586
-            case EEM_Registration::status_id_cancelled :
1587
-            case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence') :
1588
-                $this->cancel_registration($notify);
1589
-                break;
1590
-            case EEM_Registration::status_id_wait_list :
1591
-            case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence') :
1592
-                $this->waitlist_registration($notify);
1593
-                break;
1594
-            case EEM_Registration::status_id_incomplete :
1595
-            default :
1596
-                $result['success'] = false;
1597
-                unset($this->_req_data['return']);
1598
-                $this->_reg_status_change_return('', false);
1599
-                break;
1600
-        }
1601
-    }
1602
-
1603
-
1604
-    /**
1605
-     * approve_registration
1606
-     *
1607
-     * @access protected
1608
-     * @param bool $notify whether or not to notify the registrant about their approval.
1609
-     * @return void
1610
-     */
1611
-    protected function approve_registration($notify = false)
1612
-    {
1613
-        $this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
1614
-    }
1615
-
1616
-
1617
-    /**
1618
-     *        decline_registration
1619
-     *
1620
-     * @access protected
1621
-     * @param bool $notify whether or not to notify the registrant about their status change.
1622
-     * @return void
1623
-     */
1624
-    protected function decline_registration($notify = false)
1625
-    {
1626
-        $this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
1627
-    }
1628
-
1629
-
1630
-    /**
1631
-     *        cancel_registration
1632
-     *
1633
-     * @access protected
1634
-     * @param bool $notify whether or not to notify the registrant about their status change.
1635
-     * @return void
1636
-     */
1637
-    protected function cancel_registration($notify = false)
1638
-    {
1639
-        $this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
1640
-    }
1641
-
1642
-
1643
-    /**
1644
-     *        not_approve_registration
1645
-     *
1646
-     * @access protected
1647
-     * @param bool $notify whether or not to notify the registrant about their status change.
1648
-     * @return void
1649
-     */
1650
-    protected function not_approve_registration($notify = false)
1651
-    {
1652
-        $this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
1653
-    }
1654
-
1655
-
1656
-    /**
1657
-     *        decline_registration
1658
-     *
1659
-     * @access protected
1660
-     * @param bool $notify whether or not to notify the registrant about their status change.
1661
-     * @return void
1662
-     */
1663
-    protected function pending_registration($notify = false)
1664
-    {
1665
-        $this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
1666
-    }
1667
-
1668
-
1669
-    /**
1670
-     * waitlist_registration
1671
-     *
1672
-     * @access protected
1673
-     * @param bool $notify whether or not to notify the registrant about their status change.
1674
-     * @return void
1675
-     */
1676
-    protected function waitlist_registration($notify = false)
1677
-    {
1678
-        $this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
1679
-    }
1680
-
1681
-
1682
-    /**
1683
-     *        generates HTML for the Registration main meta box
1684
-     *
1685
-     * @access public
1686
-     * @return void
1687
-     */
1688
-    public function _reg_details_meta_box()
1689
-    {
1690
-        EEH_Autoloader::register_line_item_display_autoloaders();
1691
-        EEH_Autoloader::register_line_item_filter_autoloaders();
1692
-        EE_Registry::instance()->load_helper('Line_Item');
1693
-        $transaction    = $this->_registration->transaction() ? $this->_registration->transaction()
1694
-            : EE_Transaction::new_instance();
1695
-        $this->_session = $transaction->session_data();
1696
-        $filters        = new EE_Line_Item_Filter_Collection();
1697
-        //$filters->add( new EE_Non_Zero_Line_Item_Filter() );
1698
-        $filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
1699
-        $line_item_filter_processor              = new EE_Line_Item_Filter_Processor($filters,
1700
-            $transaction->total_line_item());
1701
-        $filtered_line_item_tree                 = $line_item_filter_processor->process();
1702
-        $line_item_display                       = new EE_Line_Item_Display('reg_admin_table',
1703
-            'EE_Admin_Table_Registration_Line_Item_Display_Strategy');
1704
-        $this->_template_args['line_item_table'] = $line_item_display->display_line_item($filtered_line_item_tree,
1705
-            array('EE_Registration' => $this->_registration));
1706
-        $attendee                                = $this->_registration->attendee();
1707
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
1708
-            'espresso_transactions_view_transaction')
1709
-        ) {
1710
-            $this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(EE_Admin_Page::add_query_args_and_nonce(array(
1711
-                'action' => 'view_transaction',
1712
-                'TXN_ID' => $transaction->ID(),
1713
-            ), TXN_ADMIN_URL), esc_html__(' View Transaction'), 'button secondary-button right',
1714
-                'dashicons dashicons-cart');
1715
-        } else {
1716
-            $this->_template_args['view_transaction_button'] = '';
1717
-        }
1718
-        if ($attendee instanceof EE_Attendee
1719
-            && EE_Registry::instance()->CAP->current_user_can('ee_send_message',
1720
-                'espresso_registrations_resend_registration')
1721
-        ) {
1722
-            $this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(EE_Admin_Page::add_query_args_and_nonce(array(
1723
-                'action'      => 'resend_registration',
1724
-                '_REG_ID'     => $this->_registration->ID(),
1725
-                'redirect_to' => 'view_registration',
1726
-            ), REG_ADMIN_URL), esc_html__(' Resend Registration'), 'button secondary-button right',
1727
-                'dashicons dashicons-email-alt');
1728
-        } else {
1729
-            $this->_template_args['resend_registration_button'] = '';
1730
-        }
1731
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1732
-        $payment                               = $transaction->get_first_related('Payment');
1733
-        $payment                               = ! $payment instanceof EE_Payment ? EE_Payment::new_instance() : $payment;
1734
-        $payment_method                        = $payment->get_first_related('Payment_Method');
1735
-        $payment_method                        = ! $payment_method instanceof EE_Payment_Method ? EE_Payment_Method::new_instance()
1736
-            : $payment_method;
1737
-        $reg_details                           = array(
1738
-            'payment_method'       => $payment_method->name(),
1739
-            'response_msg'         => $payment->gateway_response(),
1740
-            'registration_id'      => $this->_registration->get('REG_code'),
1741
-            'registration_session' => $this->_registration->session_ID(),
1742
-            'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
1743
-            'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
1744
-        );
1745
-        if (isset($reg_details['registration_id'])) {
1746
-            $this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
1747
-            $this->_template_args['reg_details']['registration_id']['label'] = __('Registration ID', 'event_espresso');
1748
-            $this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
1749
-        }
1750
-        if (isset($reg_details['payment_method'])) {
1751
-            $this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
1752
-            $this->_template_args['reg_details']['payment_method']['label'] = __('Most Recent Payment Method',
1753
-                'event_espresso');
1754
-            $this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
1755
-            $this->_template_args['reg_details']['response_msg']['value']   = $reg_details['response_msg'];
1756
-            $this->_template_args['reg_details']['response_msg']['label']   = __('Payment method response',
1757
-                'event_espresso');
1758
-            $this->_template_args['reg_details']['response_msg']['class']   = 'regular-text';
1759
-        }
1760
-        $this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
1761
-        $this->_template_args['reg_details']['registration_session']['label'] = __('Registration Session',
1762
-            'event_espresso');
1763
-        $this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
1764
-        $this->_template_args['reg_details']['ip_address']['value']           = $reg_details['ip_address'];
1765
-        $this->_template_args['reg_details']['ip_address']['label']           = __('Registration placed from IP',
1766
-            'event_espresso');
1767
-        $this->_template_args['reg_details']['ip_address']['class']           = 'regular-text';
1768
-        $this->_template_args['reg_details']['user_agent']['value']           = $reg_details['user_agent'];
1769
-        $this->_template_args['reg_details']['user_agent']['label']           = __('Registrant User Agent',
1770
-            'event_espresso');
1771
-        $this->_template_args['reg_details']['user_agent']['class']           = 'large-text';
1772
-        $this->_template_args['event_link']                                   = EE_Admin_Page::add_query_args_and_nonce(array(
1773
-            'action'   => 'default',
1774
-            'event_id' => $this->_registration->event_ID(),
1775
-        ), REG_ADMIN_URL);
1776
-        $this->_template_args['REG_ID']                                       = $this->_registration->ID();
1777
-        $this->_template_args['event_id']                                     = $this->_registration->event_ID();
1778
-        $template_path                                                        = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
1779
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1780
-    }
1781
-
1782
-
1783
-    /**
1784
-     * generates HTML for the Registration Questions meta box.
1785
-     * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
1786
-     * otherwise uses new forms system
1787
-     *
1788
-     * @access public
1789
-     * @return void
1790
-     */
1791
-    public function _reg_questions_meta_box()
1792
-    {
1793
-        //allow someone to override this method entirely
1794
-        if (apply_filters('FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default', true, $this,
1795
-            $this->_registration)) {
1796
-            $form                                              = $this->_get_reg_custom_questions_form($this->_registration->ID());
1797
-            $this->_template_args['att_questions']             = count($form->subforms()) > 0 ? $form->get_html_and_js() : '';
1798
-            $this->_template_args['reg_questions_form_action'] = 'edit_registration';
1799
-            $this->_template_args['REG_ID']                    = $this->_registration->ID();
1800
-            $template_path                                     = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
1801
-            echo EEH_Template::display_template($template_path, $this->_template_args, true);
1802
-        }
1803
-    }
1804
-
1805
-
1806
-    /**
1807
-     * form_before_question_group
1808
-     *
1809
-     * @deprecated    as of 4.8.32.rc.000
1810
-     * @access        public
1811
-     * @param        string $output
1812
-     * @return        string
1813
-     */
1814
-    public function form_before_question_group($output)
1815
-    {
1816
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1817
-            __('This method would have been protected but was used on a filter callback'
1818
-               . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1819
-            '4.8.32.rc.000');
1820
-        return '
1043
+		if ( ! empty($registration_status)) {
1044
+			$where['STS_ID'] = $registration_status;
1045
+		} else {
1046
+			//make sure we exclude incomplete registrations, but only if not trashed.
1047
+			if ($view === 'trash') {
1048
+				$where['REG_deleted'] = true;
1049
+			} else if ($view === 'incomplete') {
1050
+				$where['STS_ID'] = EEM_Registration::status_id_incomplete;
1051
+			} else {
1052
+				$where['STS_ID'] = array('!=', EEM_Registration::status_id_incomplete);
1053
+			}
1054
+		}
1055
+		return $where;
1056
+	}
1057
+
1058
+
1059
+	/**
1060
+	 * Adds any provided date restraints to the where conditions for the registrations query.
1061
+	 *
1062
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1063
+	 * @return array
1064
+	 */
1065
+	protected function _add_date_to_where_conditions(array $request)
1066
+	{
1067
+		$where = array();
1068
+		$view  = EEH_Array::is_set( $request, 'status', '' );
1069
+		$month_range             = ! empty($request['month_range'])
1070
+			? sanitize_text_field($request['month_range'])
1071
+			: '';
1072
+		$retrieve_for_today      = $view === 'today';
1073
+		$retrieve_for_this_month = $view === 'month';
1074
+
1075
+		if ($retrieve_for_today) {
1076
+			$now               = date('Y-m-d', current_time('timestamp'));
1077
+			$where['REG_date'] = array(
1078
+				'BETWEEN',
1079
+				array(
1080
+					EEM_Registration::instance()->convert_datetime_for_query(
1081
+						'REG_date',
1082
+						$now . ' 00:00:00',
1083
+						'Y-m-d H:i:s'
1084
+					),
1085
+					EEM_Registration::instance()->convert_datetime_for_query(
1086
+						'REG_date',
1087
+						$now . ' 23:59:59',
1088
+						'Y-m-d H:i:s'
1089
+					),
1090
+				),
1091
+			);
1092
+		} elseif ($retrieve_for_this_month) {
1093
+			$current_year_and_month = date('Y-m', current_time('timestamp'));
1094
+			$days_this_month        = date('t', current_time('timestamp'));
1095
+			$where['REG_date']      = array(
1096
+				'BETWEEN',
1097
+				array(
1098
+					EEM_Registration::instance()->convert_datetime_for_query(
1099
+						'REG_date',
1100
+						$current_year_and_month . '-01 00:00:00',
1101
+						'Y-m-d H:i:s'
1102
+					),
1103
+					EEM_Registration::instance()->convert_datetime_for_query(
1104
+						'REG_date',
1105
+						$current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1106
+						'Y-m-d H:i:s'
1107
+					),
1108
+				),
1109
+			);
1110
+		} elseif ($month_range) {
1111
+			$pieces          = explode(' ', $month_range, 3);
1112
+			$month_requested = ! empty($pieces[0])
1113
+				? date('m', strtotime($month_range))
1114
+				: '';
1115
+			$year_requested  = ! empty($pieces[1])
1116
+				? $pieces[1]
1117
+				: '';
1118
+			//if there is not a month or year then we can't go further
1119
+			if ($month_requested && $year_requested) {
1120
+				$days_in_month     = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1121
+				$where['REG_date'] = array(
1122
+					'BETWEEN',
1123
+					array(
1124
+						EEM_Registration::instance()->convert_datetime_for_query(
1125
+							'REG_date',
1126
+							$year_requested . '-' . $month_requested . '-01 00:00:00',
1127
+							'Y-m-d H:i:s'
1128
+						),
1129
+						EEM_Registration::instance()->convert_datetime_for_query(
1130
+							'REG_date',
1131
+							$year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1132
+							'Y-m-d H:i:s'
1133
+						),
1134
+					),
1135
+				);
1136
+			}
1137
+		}
1138
+		return $where;
1139
+	}
1140
+
1141
+
1142
+	/**
1143
+	 * Adds any provided search restraints to the where conditions for the registrations query
1144
+	 *
1145
+	 * @param array $request usually the same as $this->_req_data but not necessarily
1146
+	 * @return array
1147
+	 */
1148
+	protected function _add_search_to_where_conditions(array $request)
1149
+	{
1150
+		$where = array();
1151
+		if ( ! empty($request['s'])) {
1152
+			$search_string = '%' . sanitize_text_field($request['s']) . '%';
1153
+			$where['OR'] = array(
1154
+				'Event.EVT_name'                          => array('LIKE', $search_string),
1155
+				'Event.EVT_desc'                          => array('LIKE', $search_string),
1156
+				'Event.EVT_short_desc'                    => array('LIKE', $search_string),
1157
+				'Attendee.ATT_full_name'                  => array('LIKE', $search_string),
1158
+				'Attendee.ATT_fname'                      => array('LIKE', $search_string),
1159
+				'Attendee.ATT_lname'                      => array('LIKE', $search_string),
1160
+				'Attendee.ATT_short_bio'                  => array('LIKE', $search_string),
1161
+				'Attendee.ATT_email'                      => array('LIKE', $search_string),
1162
+				'Attendee.ATT_address'                    => array('LIKE', $search_string),
1163
+				'Attendee.ATT_address2'                   => array('LIKE', $search_string),
1164
+				'Attendee.ATT_city'                       => array('LIKE', $search_string),
1165
+				'REG_final_price'                         => array('LIKE', $search_string),
1166
+				'REG_code'                                => array('LIKE', $search_string),
1167
+				'REG_count'                               => array('LIKE', $search_string),
1168
+				'REG_group_size'                          => array('LIKE', $search_string),
1169
+				'Ticket.TKT_name'                         => array('LIKE', $search_string),
1170
+				'Ticket.TKT_description'                  => array('LIKE', $search_string),
1171
+				'Transaction.Payment.PAY_txn_id_chq_nmbr' => array('LIKE', $search_string),
1172
+			);
1173
+		}
1174
+		return $where;
1175
+	}
1176
+
1177
+
1178
+	/**
1179
+	 * Sets up the where conditions for the registrations query.
1180
+	 *
1181
+	 * @param array $request
1182
+	 * @return array
1183
+	 */
1184
+	protected function _get_where_conditions_for_registrations_query($request)
1185
+	{
1186
+		return array_merge(
1187
+			$this->_add_event_id_to_where_conditions($request),
1188
+			$this->_add_category_id_to_where_conditions($request),
1189
+			$this->_add_datetime_id_to_where_conditions($request),
1190
+			$this->_add_registration_status_to_where_conditions($request),
1191
+			$this->_add_date_to_where_conditions($request),
1192
+			$this->_add_search_to_where_conditions($request)
1193
+		);
1194
+	}
1195
+
1196
+
1197
+	/**
1198
+	 * Sets up the orderby for the registrations query.
1199
+	 *
1200
+	 * @return array
1201
+	 */
1202
+	protected function _get_orderby_for_registrations_query()
1203
+	{
1204
+		$orderby_field = ! empty($this->_req_data['orderby'])
1205
+			? sanitize_text_field($this->_req_data['orderby'])
1206
+			: '';
1207
+		switch ($orderby_field) {
1208
+			case '_REG_ID':
1209
+				$orderby_field = 'REG_ID';
1210
+				break;
1211
+			case '_Reg_status':
1212
+				$orderby_field = 'STS_ID';
1213
+				break;
1214
+			case 'ATT_fname':
1215
+				//just for spite, we're going to order it by their LAST name, NOT their first name. Now who's the boss?
1216
+				//jk, we don't want to break existing links, and customers preferred ordering by last name
1217
+				//besides, from the UI, its ambiguous as to whether we will order by first or last name
1218
+				$orderby_field = 'Attendee.ATT_lname';
1219
+				break;
1220
+			case 'event_name':
1221
+				$orderby_field = 'Event.EVT_name';
1222
+				break;
1223
+			case 'DTT_EVT_start':
1224
+				$orderby_field = 'Event.Datetime.DTT_EVT_start';
1225
+				break;
1226
+			default: //'REG_date'
1227
+				$orderby_field = 'REG_date';
1228
+		}
1229
+
1230
+		//order
1231
+		$order = ! empty($this->_req_data['order'])
1232
+			? sanitize_text_field($this->_req_data['order'])
1233
+			: 'DESC';
1234
+		return array('order_by' => array($orderby_field => $order));
1235
+	}
1236
+
1237
+
1238
+	/**
1239
+	 * Sets up the limit for the registrations query.
1240
+	 *
1241
+	 * @param $per_page
1242
+	 * @return array
1243
+	 */
1244
+	protected function _get_limit($per_page)
1245
+	{
1246
+		$current_page = ! empty($this->_req_data['paged'])
1247
+			? absint($this->_req_data['paged'])
1248
+			: 1;
1249
+		$per_page     = ! empty($this->_req_data['perpage'])
1250
+			? $this->_req_data['perpage']
1251
+			: $per_page;
1252
+
1253
+		//-1 means return all results so get out if that's set.
1254
+		if ((int)$per_page === -1) {
1255
+			return array();
1256
+		}
1257
+		$per_page = absint($per_page);
1258
+		$offset   = ($current_page - 1) * $per_page;
1259
+		return array('limit' => array($offset, $per_page));
1260
+	}
1261
+
1262
+
1263
+	public function get_registration_status_array()
1264
+	{
1265
+		return self::$_reg_status;
1266
+	}
1267
+
1268
+
1269
+
1270
+
1271
+	/***************************************        REGISTRATION DETAILS        ***************************************/
1272
+	/**
1273
+	 *        generates HTML for the View Registration Details Admin page
1274
+	 *
1275
+	 * @access protected
1276
+	 * @return void
1277
+	 */
1278
+	protected function _registration_details()
1279
+	{
1280
+		$this->_template_args = array();
1281
+		$this->_set_registration_object();
1282
+		if (is_object($this->_registration)) {
1283
+			$transaction                                   = $this->_registration->transaction() ? $this->_registration->transaction()
1284
+				: EE_Transaction::new_instance();
1285
+			$this->_session                                = $transaction->session_data();
1286
+			$event_id                                      = $this->_registration->event_ID();
1287
+			$this->_template_args['reg_nmbr']['value']     = $this->_registration->ID();
1288
+			$this->_template_args['reg_nmbr']['label']     = __('Registration Number', 'event_espresso');
1289
+			$this->_template_args['reg_datetime']['value'] = $this->_registration->get_i18n_datetime('REG_date');
1290
+			$this->_template_args['reg_datetime']['label'] = __('Date', 'event_espresso');
1291
+			$this->_template_args['grand_total']           = $transaction->total();
1292
+			$this->_template_args['currency_sign']         = EE_Registry::instance()->CFG->currency->sign;
1293
+			// link back to overview
1294
+			$this->_template_args['reg_overview_url']            = REG_ADMIN_URL;
1295
+			$this->_template_args['registration']                = $this->_registration;
1296
+			$this->_template_args['filtered_registrations_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
1297
+				'action'   => 'default',
1298
+				'event_id' => $event_id,
1299
+			), REG_ADMIN_URL);
1300
+			$this->_template_args['filtered_transactions_link']  = EE_Admin_Page::add_query_args_and_nonce(array(
1301
+				'action' => 'default',
1302
+				'EVT_ID' => $event_id,
1303
+				'page'   => 'espresso_transactions',
1304
+			), admin_url('admin.php'));
1305
+			$this->_template_args['event_link']                  = EE_Admin_Page::add_query_args_and_nonce(array(
1306
+				'page'   => 'espresso_events',
1307
+				'action' => 'edit',
1308
+				'post'   => $event_id,
1309
+			), admin_url('admin.php'));
1310
+			//next and previous links
1311
+			$next_reg                                      = $this->_registration->next(null, array(), 'REG_ID');
1312
+			$this->_template_args['next_registration']     = $next_reg
1313
+				? $this->_next_link(EE_Admin_Page::add_query_args_and_nonce(array(
1314
+					'action'  => 'view_registration',
1315
+					'_REG_ID' => $next_reg['REG_ID'],
1316
+				), REG_ADMIN_URL), 'dashicons dashicons-arrow-right ee-icon-size-22') : '';
1317
+			$previous_reg                                  = $this->_registration->previous(null, array(), 'REG_ID');
1318
+			$this->_template_args['previous_registration'] = $previous_reg
1319
+				? $this->_previous_link(EE_Admin_Page::add_query_args_and_nonce(array(
1320
+					'action'  => 'view_registration',
1321
+					'_REG_ID' => $previous_reg['REG_ID'],
1322
+				), REG_ADMIN_URL), 'dashicons dashicons-arrow-left ee-icon-size-22') : '';
1323
+			// grab header
1324
+			$template_path                             = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1325
+			$this->_template_args['REG_ID']            = $this->_registration->ID();
1326
+			$this->_template_args['admin_page_header'] = EEH_Template::display_template($template_path,
1327
+				$this->_template_args, true);
1328
+		} else {
1329
+			$this->_template_args['admin_page_header'] = $this->display_espresso_notices();
1330
+		}
1331
+		// the details template wrapper
1332
+		$this->display_admin_page_with_sidebar();
1333
+	}
1334
+
1335
+
1336
+	protected function _registration_details_metaboxes()
1337
+	{
1338
+		do_action('AHEE__Registrations_Admin_Page___registration_details_metabox__start', $this);
1339
+		$this->_set_registration_object();
1340
+		$attendee = $this->_registration instanceof EE_Registration ? $this->_registration->attendee() : null;
1341
+		add_meta_box('edit-reg-status-mbox', __('Registration Status', 'event_espresso'),
1342
+			array($this, 'set_reg_status_buttons_metabox'), $this->wp_page_slug, 'normal', 'high');
1343
+		add_meta_box('edit-reg-details-mbox', __('Registration Details', 'event_espresso'),
1344
+			array($this, '_reg_details_meta_box'), $this->wp_page_slug, 'normal', 'high');
1345
+		if ($attendee instanceof EE_Attendee
1346
+			&& EE_Registry::instance()->CAP->current_user_can('ee_edit_registration', 'edit-reg-questions-mbox')
1347
+		) {
1348
+			add_meta_box('edit-reg-questions-mbox', __('Registration Form Answers', 'event_espresso'),
1349
+				array($this, '_reg_questions_meta_box'), $this->wp_page_slug, 'normal', 'high');
1350
+		}
1351
+		add_meta_box('edit-reg-registrant-mbox', __('Contact Details', 'event_espresso'),
1352
+			array($this, '_reg_registrant_side_meta_box'), $this->wp_page_slug, 'side', 'high');
1353
+		if ($this->_registration->group_size() > 1) {
1354
+			add_meta_box('edit-reg-attendees-mbox', __('Other Registrations in this Transaction', 'event_espresso'),
1355
+				array($this, '_reg_attendees_meta_box'), $this->wp_page_slug, 'normal', 'high');
1356
+		}
1357
+	}
1358
+
1359
+
1360
+	/**
1361
+	 * set_reg_status_buttons_metabox
1362
+	 *
1363
+	 * @access protected
1364
+	 * @return string
1365
+	 * @throws \EE_Error
1366
+	 */
1367
+	public function set_reg_status_buttons_metabox()
1368
+	{
1369
+		$this->_set_registration_object();
1370
+		$change_reg_status_form = $this->_generate_reg_status_change_form();
1371
+		echo $change_reg_status_form->form_open(self::add_query_args_and_nonce(array(
1372
+			'action' => 'change_reg_status',
1373
+		), REG_ADMIN_URL));
1374
+		echo $change_reg_status_form->get_html();
1375
+		echo $change_reg_status_form->form_close();
1376
+	}
1377
+
1378
+
1379
+	/**
1380
+	 * @return EE_Form_Section_Proper
1381
+	 */
1382
+	protected function _generate_reg_status_change_form()
1383
+	{
1384
+		return new EE_Form_Section_Proper(array(
1385
+			'name'            => 'reg_status_change_form',
1386
+			'html_id'         => 'reg-status-change-form',
1387
+			'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1388
+			'subsections'     => array(
1389
+				'return'             => new EE_Hidden_Input(array(
1390
+					'name'    => 'return',
1391
+					'default' => 'view_registration',
1392
+				)),
1393
+				'REG_ID'             => new EE_Hidden_Input(array(
1394
+					'name'    => 'REG_ID',
1395
+					'default' => $this->_registration->ID(),
1396
+				)),
1397
+				'current_status'     => new EE_Form_Section_HTML(EEH_HTML::tr(EEH_HTML::th(EEH_HTML::label(EEH_HTML::strong(__('Current Registration Status',
1398
+						'event_espresso')))) . EEH_HTML::td(EEH_HTML::strong($this->_registration->pretty_status(),
1399
+						'', 'status-' . $this->_registration->status_ID(),
1400
+						'line-height: 1em; font-size: 1.5em; font-weight: bold;')))),
1401
+				'reg_status'         => new EE_Select_Input($this->_get_reg_statuses(), array(
1402
+					'html_label_text' => __('Change Registration Status to', 'event_espresso'),
1403
+					'default'         => $this->_registration->status_ID(),
1404
+				)),
1405
+				'send_notifications' => new EE_Yes_No_Input(array(
1406
+					'html_label_text' => __('Send Related Messages', 'event_espresso'),
1407
+					'default'         => false,
1408
+					'html_help_text'  => __('If set to "Yes", then the related messages will be sent to the registrant.',
1409
+						'event_espresso'),
1410
+				)),
1411
+				'submit'             => new EE_Submit_Input(array(
1412
+					'html_class'      => 'button-primary',
1413
+					'html_label_text' => '&nbsp;',
1414
+					'default'         => __('Update Registration Status', 'event_espresso'),
1415
+				)),
1416
+			),
1417
+		));
1418
+	}
1419
+
1420
+
1421
+
1422
+	/**
1423
+	 * Returns an array of all the buttons for the various statuses and switch status actions
1424
+	 *
1425
+	 * @return array
1426
+	 */
1427
+	protected function _get_reg_statuses()
1428
+	{
1429
+		$reg_status_array = EEM_Registration::instance()->reg_status_array();
1430
+		unset ($reg_status_array[EEM_Registration::status_id_incomplete]);
1431
+		// get current reg status
1432
+		$current_status = $this->_registration->status_ID();
1433
+		// is registration for free event? This will determine whether to display the pending payment option
1434
+		if ($current_status != EEM_Registration::status_id_pending_payment
1435
+			&& $this->_registration->transaction()
1436
+								   ->is_free()
1437
+		) {
1438
+			unset($reg_status_array[EEM_Registration::status_id_pending_payment]);
1439
+		}
1440
+		return EEM_Status::instance()->localized_status($reg_status_array, false, 'sentence');
1441
+	}
1442
+
1443
+
1444
+	/**
1445
+	 * This method is used when using _REG_ID from request which may or may not be an array of reg_ids.
1446
+	 *
1447
+	 * @param bool $status REG status given for changing registrations to.
1448
+	 * @param bool $notify Whether to send messages notifications or not.
1449
+	 * @return array  (array with reg_id(s) updated and whether update was successful.
1450
+	 */
1451
+	protected function _set_registration_status_from_request($status = false, $notify = false)
1452
+	{
1453
+		if (isset($this->_req_data['reg_status_change_form'])) {
1454
+			$REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1455
+				? (array)$this->_req_data['reg_status_change_form']['REG_ID'] : array();
1456
+		} else {
1457
+			$REG_IDs = isset($this->_req_data['_REG_ID']) ? (array)$this->_req_data['_REG_ID'] : array();
1458
+		}
1459
+		$success = $this->_set_registration_status($REG_IDs, $status);
1460
+		//notify?
1461
+		if ($success
1462
+			&& $notify
1463
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message',
1464
+				'espresso_registrations_resend_registration')
1465
+		) {
1466
+			$this->_process_resend_registration();
1467
+		}
1468
+		return $success;
1469
+	}
1470
+
1471
+
1472
+	/**
1473
+	 * Set the registration status for the given reg_id (which may or may not be an array, it gets typecast to an
1474
+	 * array). Note, this method does NOT take care of possible notifications.  That is required by calling code.
1475
+	 *
1476
+	 * @param array $REG_IDs
1477
+	 * @param bool  $status
1478
+	 * @return array (an array with 'success' key representing whether status change was successful, and 'REG_ID' as
1479
+	 *               the array of updated registrations).
1480
+	 */
1481
+	protected function _set_registration_status($REG_IDs = array(), $status = false)
1482
+	{
1483
+		$success = false;
1484
+		// typecast $REG_IDs
1485
+		$REG_IDs = (array)$REG_IDs;
1486
+		if ( ! empty($REG_IDs)) {
1487
+			$success = true;
1488
+			// set default status if none is passed
1489
+			$status = $status ? $status : EEM_Registration::status_id_pending_payment;
1490
+			// sanitize $REG_IDs
1491
+			$REG_IDs = array_filter($REG_IDs, 'absint');
1492
+			//loop through REG_ID's and change status
1493
+			foreach ($REG_IDs as $REG_ID) {
1494
+				$registration = EEM_Registration::instance()->get_one_by_ID($REG_ID);
1495
+				if ($registration instanceof EE_Registration) {
1496
+					$registration->set_status($status);
1497
+					$result = $registration->save();
1498
+					// verifying explicit fails because update *may* just return 0 for 0 rows affected
1499
+					$success = $result !== false ? $success : false;
1500
+				}
1501
+			}
1502
+		}
1503
+		//reset _req_data['_REG_ID'] for any potential future messages notifications
1504
+		$this->_req_data['_REG_ID'] = $REG_IDs;
1505
+		//return $success and processed registrations
1506
+		return array('REG_ID' => $REG_IDs, 'success' => $success);
1507
+	}
1508
+
1509
+
1510
+	/**
1511
+	 * Common logic for setting up success message and redirecting to appropriate route
1512
+	 *
1513
+	 * @param  string $STS_ID status id for the registration changed to
1514
+	 * @param   bool  $notify indicates whether the _set_registration_status_from_request does notifications or not.
1515
+	 * @return void
1516
+	 */
1517
+	protected function _reg_status_change_return($STS_ID, $notify = false)
1518
+	{
1519
+		$result  = ! empty($STS_ID) ? $this->_set_registration_status_from_request($STS_ID, $notify)
1520
+			: array('success' => false);
1521
+		$success = isset($result['success']) && $result['success'];
1522
+		//setup success message
1523
+		if ($success) {
1524
+			if (is_array($result['REG_ID']) && count($result['REG_ID']) === 1) {
1525
+				$msg = sprintf(__('Registration status has been set to %s', 'event_espresso'),
1526
+					EEH_Template::pretty_status($STS_ID, false, 'lower'));
1527
+			} else {
1528
+				$msg = sprintf(__('Registrations have been set to %s.', 'event_espresso'),
1529
+					EEH_Template::pretty_status($STS_ID, false, 'lower'));
1530
+			}
1531
+			EE_Error::add_success($msg);
1532
+		} else {
1533
+			EE_Error::add_error(__('Something went wrong, and the status was not changed', 'event_espresso'), __FILE__,
1534
+				__LINE__, __FUNCTION__);
1535
+		}
1536
+		if (isset($this->_req_data['return']) && $this->_req_data['return'] == 'view_registration') {
1537
+			$route = array('action' => 'view_registration', '_REG_ID' => reset($result['REG_ID']));
1538
+		} else {
1539
+			$route = array('action' => 'default');
1540
+		}
1541
+		//unset nonces
1542
+		foreach ($this->_req_data as $ref => $value) {
1543
+			if (strpos($ref, 'nonce') !== false) {
1544
+				unset($this->_req_data[$ref]);
1545
+				continue;
1546
+			}
1547
+			$value                 = is_array($value) ? array_map('urlencode', $value) : urlencode($value);
1548
+			$this->_req_data[$ref] = $value;
1549
+		}
1550
+		//merge request vars so that the reloaded list table contains any existing filter query params
1551
+		$route = array_merge($this->_req_data, $route);
1552
+		$this->_redirect_after_action($success, '', '', $route, true);
1553
+	}
1554
+
1555
+
1556
+	/**
1557
+	 * incoming reg status change from reg details page.
1558
+	 *
1559
+	 * @return void
1560
+	 */
1561
+	protected function _change_reg_status()
1562
+	{
1563
+		$this->_req_data['return'] = 'view_registration';
1564
+		//set notify based on whether the send notifications toggle is set or not
1565
+		$notify = ! empty($this->_req_data['reg_status_change_form']['send_notifications']);
1566
+		//$notify = ! empty( $this->_req_data['txn_reg_status_change']['send_notifications'] );
1567
+		$this->_req_data['reg_status_change_form']['reg_status'] = isset($this->_req_data['reg_status_change_form']['reg_status'])
1568
+			? $this->_req_data['reg_status_change_form']['reg_status'] : '';
1569
+		switch ($this->_req_data['reg_status_change_form']['reg_status']) {
1570
+			case EEM_Registration::status_id_approved :
1571
+			case EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence') :
1572
+				$this->approve_registration($notify);
1573
+				break;
1574
+			case EEM_Registration::status_id_pending_payment :
1575
+			case EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence') :
1576
+				$this->pending_registration($notify);
1577
+				break;
1578
+			case EEM_Registration::status_id_not_approved :
1579
+			case EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence') :
1580
+				$this->not_approve_registration($notify);
1581
+				break;
1582
+			case EEM_Registration::status_id_declined :
1583
+			case EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence') :
1584
+				$this->decline_registration($notify);
1585
+				break;
1586
+			case EEM_Registration::status_id_cancelled :
1587
+			case EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence') :
1588
+				$this->cancel_registration($notify);
1589
+				break;
1590
+			case EEM_Registration::status_id_wait_list :
1591
+			case EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence') :
1592
+				$this->waitlist_registration($notify);
1593
+				break;
1594
+			case EEM_Registration::status_id_incomplete :
1595
+			default :
1596
+				$result['success'] = false;
1597
+				unset($this->_req_data['return']);
1598
+				$this->_reg_status_change_return('', false);
1599
+				break;
1600
+		}
1601
+	}
1602
+
1603
+
1604
+	/**
1605
+	 * approve_registration
1606
+	 *
1607
+	 * @access protected
1608
+	 * @param bool $notify whether or not to notify the registrant about their approval.
1609
+	 * @return void
1610
+	 */
1611
+	protected function approve_registration($notify = false)
1612
+	{
1613
+		$this->_reg_status_change_return(EEM_Registration::status_id_approved, $notify);
1614
+	}
1615
+
1616
+
1617
+	/**
1618
+	 *        decline_registration
1619
+	 *
1620
+	 * @access protected
1621
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1622
+	 * @return void
1623
+	 */
1624
+	protected function decline_registration($notify = false)
1625
+	{
1626
+		$this->_reg_status_change_return(EEM_Registration::status_id_declined, $notify);
1627
+	}
1628
+
1629
+
1630
+	/**
1631
+	 *        cancel_registration
1632
+	 *
1633
+	 * @access protected
1634
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1635
+	 * @return void
1636
+	 */
1637
+	protected function cancel_registration($notify = false)
1638
+	{
1639
+		$this->_reg_status_change_return(EEM_Registration::status_id_cancelled, $notify);
1640
+	}
1641
+
1642
+
1643
+	/**
1644
+	 *        not_approve_registration
1645
+	 *
1646
+	 * @access protected
1647
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1648
+	 * @return void
1649
+	 */
1650
+	protected function not_approve_registration($notify = false)
1651
+	{
1652
+		$this->_reg_status_change_return(EEM_Registration::status_id_not_approved, $notify);
1653
+	}
1654
+
1655
+
1656
+	/**
1657
+	 *        decline_registration
1658
+	 *
1659
+	 * @access protected
1660
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1661
+	 * @return void
1662
+	 */
1663
+	protected function pending_registration($notify = false)
1664
+	{
1665
+		$this->_reg_status_change_return(EEM_Registration::status_id_pending_payment, $notify);
1666
+	}
1667
+
1668
+
1669
+	/**
1670
+	 * waitlist_registration
1671
+	 *
1672
+	 * @access protected
1673
+	 * @param bool $notify whether or not to notify the registrant about their status change.
1674
+	 * @return void
1675
+	 */
1676
+	protected function waitlist_registration($notify = false)
1677
+	{
1678
+		$this->_reg_status_change_return(EEM_Registration::status_id_wait_list, $notify);
1679
+	}
1680
+
1681
+
1682
+	/**
1683
+	 *        generates HTML for the Registration main meta box
1684
+	 *
1685
+	 * @access public
1686
+	 * @return void
1687
+	 */
1688
+	public function _reg_details_meta_box()
1689
+	{
1690
+		EEH_Autoloader::register_line_item_display_autoloaders();
1691
+		EEH_Autoloader::register_line_item_filter_autoloaders();
1692
+		EE_Registry::instance()->load_helper('Line_Item');
1693
+		$transaction    = $this->_registration->transaction() ? $this->_registration->transaction()
1694
+			: EE_Transaction::new_instance();
1695
+		$this->_session = $transaction->session_data();
1696
+		$filters        = new EE_Line_Item_Filter_Collection();
1697
+		//$filters->add( new EE_Non_Zero_Line_Item_Filter() );
1698
+		$filters->add(new EE_Single_Registration_Line_Item_Filter($this->_registration));
1699
+		$line_item_filter_processor              = new EE_Line_Item_Filter_Processor($filters,
1700
+			$transaction->total_line_item());
1701
+		$filtered_line_item_tree                 = $line_item_filter_processor->process();
1702
+		$line_item_display                       = new EE_Line_Item_Display('reg_admin_table',
1703
+			'EE_Admin_Table_Registration_Line_Item_Display_Strategy');
1704
+		$this->_template_args['line_item_table'] = $line_item_display->display_line_item($filtered_line_item_tree,
1705
+			array('EE_Registration' => $this->_registration));
1706
+		$attendee                                = $this->_registration->attendee();
1707
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_transaction',
1708
+			'espresso_transactions_view_transaction')
1709
+		) {
1710
+			$this->_template_args['view_transaction_button'] = EEH_Template::get_button_or_link(EE_Admin_Page::add_query_args_and_nonce(array(
1711
+				'action' => 'view_transaction',
1712
+				'TXN_ID' => $transaction->ID(),
1713
+			), TXN_ADMIN_URL), esc_html__(' View Transaction'), 'button secondary-button right',
1714
+				'dashicons dashicons-cart');
1715
+		} else {
1716
+			$this->_template_args['view_transaction_button'] = '';
1717
+		}
1718
+		if ($attendee instanceof EE_Attendee
1719
+			&& EE_Registry::instance()->CAP->current_user_can('ee_send_message',
1720
+				'espresso_registrations_resend_registration')
1721
+		) {
1722
+			$this->_template_args['resend_registration_button'] = EEH_Template::get_button_or_link(EE_Admin_Page::add_query_args_and_nonce(array(
1723
+				'action'      => 'resend_registration',
1724
+				'_REG_ID'     => $this->_registration->ID(),
1725
+				'redirect_to' => 'view_registration',
1726
+			), REG_ADMIN_URL), esc_html__(' Resend Registration'), 'button secondary-button right',
1727
+				'dashicons dashicons-email-alt');
1728
+		} else {
1729
+			$this->_template_args['resend_registration_button'] = '';
1730
+		}
1731
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
1732
+		$payment                               = $transaction->get_first_related('Payment');
1733
+		$payment                               = ! $payment instanceof EE_Payment ? EE_Payment::new_instance() : $payment;
1734
+		$payment_method                        = $payment->get_first_related('Payment_Method');
1735
+		$payment_method                        = ! $payment_method instanceof EE_Payment_Method ? EE_Payment_Method::new_instance()
1736
+			: $payment_method;
1737
+		$reg_details                           = array(
1738
+			'payment_method'       => $payment_method->name(),
1739
+			'response_msg'         => $payment->gateway_response(),
1740
+			'registration_id'      => $this->_registration->get('REG_code'),
1741
+			'registration_session' => $this->_registration->session_ID(),
1742
+			'ip_address'           => isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '',
1743
+			'user_agent'           => isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '',
1744
+		);
1745
+		if (isset($reg_details['registration_id'])) {
1746
+			$this->_template_args['reg_details']['registration_id']['value'] = $reg_details['registration_id'];
1747
+			$this->_template_args['reg_details']['registration_id']['label'] = __('Registration ID', 'event_espresso');
1748
+			$this->_template_args['reg_details']['registration_id']['class'] = 'regular-text';
1749
+		}
1750
+		if (isset($reg_details['payment_method'])) {
1751
+			$this->_template_args['reg_details']['payment_method']['value'] = $reg_details['payment_method'];
1752
+			$this->_template_args['reg_details']['payment_method']['label'] = __('Most Recent Payment Method',
1753
+				'event_espresso');
1754
+			$this->_template_args['reg_details']['payment_method']['class'] = 'regular-text';
1755
+			$this->_template_args['reg_details']['response_msg']['value']   = $reg_details['response_msg'];
1756
+			$this->_template_args['reg_details']['response_msg']['label']   = __('Payment method response',
1757
+				'event_espresso');
1758
+			$this->_template_args['reg_details']['response_msg']['class']   = 'regular-text';
1759
+		}
1760
+		$this->_template_args['reg_details']['registration_session']['value'] = $reg_details['registration_session'];
1761
+		$this->_template_args['reg_details']['registration_session']['label'] = __('Registration Session',
1762
+			'event_espresso');
1763
+		$this->_template_args['reg_details']['registration_session']['class'] = 'regular-text';
1764
+		$this->_template_args['reg_details']['ip_address']['value']           = $reg_details['ip_address'];
1765
+		$this->_template_args['reg_details']['ip_address']['label']           = __('Registration placed from IP',
1766
+			'event_espresso');
1767
+		$this->_template_args['reg_details']['ip_address']['class']           = 'regular-text';
1768
+		$this->_template_args['reg_details']['user_agent']['value']           = $reg_details['user_agent'];
1769
+		$this->_template_args['reg_details']['user_agent']['label']           = __('Registrant User Agent',
1770
+			'event_espresso');
1771
+		$this->_template_args['reg_details']['user_agent']['class']           = 'large-text';
1772
+		$this->_template_args['event_link']                                   = EE_Admin_Page::add_query_args_and_nonce(array(
1773
+			'action'   => 'default',
1774
+			'event_id' => $this->_registration->event_ID(),
1775
+		), REG_ADMIN_URL);
1776
+		$this->_template_args['REG_ID']                                       = $this->_registration->ID();
1777
+		$this->_template_args['event_id']                                     = $this->_registration->event_ID();
1778
+		$template_path                                                        = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
1779
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1780
+	}
1781
+
1782
+
1783
+	/**
1784
+	 * generates HTML for the Registration Questions meta box.
1785
+	 * If pre-4.8.32.rc.000 hooks are used, uses old methods (with its filters),
1786
+	 * otherwise uses new forms system
1787
+	 *
1788
+	 * @access public
1789
+	 * @return void
1790
+	 */
1791
+	public function _reg_questions_meta_box()
1792
+	{
1793
+		//allow someone to override this method entirely
1794
+		if (apply_filters('FHEE__Registrations_Admin_Page___reg_questions_meta_box__do_default', true, $this,
1795
+			$this->_registration)) {
1796
+			$form                                              = $this->_get_reg_custom_questions_form($this->_registration->ID());
1797
+			$this->_template_args['att_questions']             = count($form->subforms()) > 0 ? $form->get_html_and_js() : '';
1798
+			$this->_template_args['reg_questions_form_action'] = 'edit_registration';
1799
+			$this->_template_args['REG_ID']                    = $this->_registration->ID();
1800
+			$template_path                                     = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
1801
+			echo EEH_Template::display_template($template_path, $this->_template_args, true);
1802
+		}
1803
+	}
1804
+
1805
+
1806
+	/**
1807
+	 * form_before_question_group
1808
+	 *
1809
+	 * @deprecated    as of 4.8.32.rc.000
1810
+	 * @access        public
1811
+	 * @param        string $output
1812
+	 * @return        string
1813
+	 */
1814
+	public function form_before_question_group($output)
1815
+	{
1816
+		EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1817
+			__('This method would have been protected but was used on a filter callback'
1818
+			   . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1819
+			'4.8.32.rc.000');
1820
+		return '
1821 1821
 	<table class="form-table ee-width-100">
1822 1822
 		<tbody>
1823 1823
 			';
1824
-    }
1825
-
1826
-
1827
-    /**
1828
-     * form_after_question_group
1829
-     *
1830
-     * @deprecated    as of 4.8.32.rc.000
1831
-     * @access        public
1832
-     * @param        string $output
1833
-     * @return        string
1834
-     */
1835
-    public function form_after_question_group($output)
1836
-    {
1837
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1838
-            __('This method would have been protected but was used on a filter callback'
1839
-               . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1840
-            '4.8.32.rc.000');
1841
-        return '
1824
+	}
1825
+
1826
+
1827
+	/**
1828
+	 * form_after_question_group
1829
+	 *
1830
+	 * @deprecated    as of 4.8.32.rc.000
1831
+	 * @access        public
1832
+	 * @param        string $output
1833
+	 * @return        string
1834
+	 */
1835
+	public function form_after_question_group($output)
1836
+	{
1837
+		EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1838
+			__('This method would have been protected but was used on a filter callback'
1839
+			   . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1840
+			'4.8.32.rc.000');
1841
+		return '
1842 1842
 			<tr class="hide-if-no-js">
1843 1843
 				<th> </th>
1844 1844
 				<td class="reg-admin-edit-attendee-question-td">
1845 1845
 					<a class="reg-admin-edit-attendee-question-lnk" href="#" title="'
1846
-               . esc_attr__('click to edit question', 'event_espresso')
1847
-               . '">
1846
+			   . esc_attr__('click to edit question', 'event_espresso')
1847
+			   . '">
1848 1848
 						<span class="reg-admin-edit-question-group-spn lt-grey-txt">'
1849
-               . __('edit the above question group', 'event_espresso')
1850
-               . '</span>
1849
+			   . __('edit the above question group', 'event_espresso')
1850
+			   . '</span>
1851 1851
 						<div class="dashicons dashicons-edit"></div>
1852 1852
 					</a>
1853 1853
 				</td>
@@ -1855,494 +1855,494 @@  discard block
 block discarded – undo
1855 1855
 		</tbody>
1856 1856
 	</table>
1857 1857
 ';
1858
-    }
1859
-
1860
-
1861
-    /**
1862
-     * form_form_field_label_wrap
1863
-     *
1864
-     * @deprecated    as of 4.8.32.rc.000
1865
-     * @access        public
1866
-     * @param        string $label
1867
-     * @return        string
1868
-     */
1869
-    public function form_form_field_label_wrap($label)
1870
-    {
1871
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1872
-            __('This method would have been protected but was used on a filter callback'
1873
-               . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1874
-            '4.8.32.rc.000');
1875
-        return '
1858
+	}
1859
+
1860
+
1861
+	/**
1862
+	 * form_form_field_label_wrap
1863
+	 *
1864
+	 * @deprecated    as of 4.8.32.rc.000
1865
+	 * @access        public
1866
+	 * @param        string $label
1867
+	 * @return        string
1868
+	 */
1869
+	public function form_form_field_label_wrap($label)
1870
+	{
1871
+		EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1872
+			__('This method would have been protected but was used on a filter callback'
1873
+			   . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1874
+			'4.8.32.rc.000');
1875
+		return '
1876 1876
 			<tr>
1877 1877
 				<th>
1878 1878
 					' . $label . '
1879 1879
 				</th>';
1880
-    }
1881
-
1882
-
1883
-    /**
1884
-     * form_form_field_input__wrap
1885
-     *
1886
-     * @deprecated    as of 4.8.32.rc.000
1887
-     * @access        public
1888
-     * @param        string $input
1889
-     * @return        string
1890
-     */
1891
-    public function form_form_field_input__wrap($input)
1892
-    {
1893
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1894
-            __('This method would have been protected but was used on a filter callback'
1895
-               . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1896
-            '4.8.32.rc.000');
1897
-        return '
1880
+	}
1881
+
1882
+
1883
+	/**
1884
+	 * form_form_field_input__wrap
1885
+	 *
1886
+	 * @deprecated    as of 4.8.32.rc.000
1887
+	 * @access        public
1888
+	 * @param        string $input
1889
+	 * @return        string
1890
+	 */
1891
+	public function form_form_field_input__wrap($input)
1892
+	{
1893
+		EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1894
+			__('This method would have been protected but was used on a filter callback'
1895
+			   . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1896
+			'4.8.32.rc.000');
1897
+		return '
1898 1898
 				<td class="reg-admin-attendee-questions-input-td disabled-input">
1899 1899
 					' . $input . '
1900 1900
 				</td>
1901 1901
 			</tr>';
1902
-    }
1903
-
1904
-
1905
-    /**
1906
-     * Updates the registration's custom questions according to the form info, if the form is submitted.
1907
-     * If it's not a post, the "view_registrations" route will be called next on the SAME request
1908
-     * to display the page
1909
-     *
1910
-     * @access protected
1911
-     * @return void
1912
-     */
1913
-    protected function _update_attendee_registration_form()
1914
-    {
1915
-        do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
1916
-        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
1917
-            $REG_ID  = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
1918
-            $success = $this->_save_reg_custom_questions_form($REG_ID);
1919
-            if ($success) {
1920
-                $what  = __('Registration Form', 'event_espresso');
1921
-                $route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
1922
-                    : array('action' => 'default');
1923
-                $this->_redirect_after_action($success, $what, __('updated', 'event_espresso'), $route);
1924
-            }
1925
-        }
1926
-    }
1927
-
1928
-
1929
-    /**
1930
-     * Gets the form for saving registrations custom questions (if done
1931
-     * previously retrieves the cached form object, which may have validation errors in it)
1932
-     *
1933
-     * @param int $REG_ID
1934
-     * @return EE_Registration_Custom_Questions_Form
1935
-     */
1936
-    protected function _get_reg_custom_questions_form($REG_ID)
1937
-    {
1938
-        if ( ! $this->_reg_custom_questions_form) {
1939
-            require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
1940
-            $this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(EEM_Registration::instance()
1941
-                                                                                                          ->get_one_by_ID($REG_ID));
1942
-            $this->_reg_custom_questions_form->_construct_finalize(null, null);
1943
-        }
1944
-        return $this->_reg_custom_questions_form;
1945
-    }
1946
-
1947
-
1948
-    /**
1949
-     * Saves
1950
-     *
1951
-     * @access private
1952
-     * @param bool $REG_ID
1953
-     * @return bool
1954
-     */
1955
-    private function _save_reg_custom_questions_form($REG_ID = false)
1956
-    {
1957
-        if ( ! $REG_ID) {
1958
-            EE_Error::add_error(__('An error occurred. No registration ID was received.', 'event_espresso'), __FILE__,
1959
-                __FUNCTION__, __LINE__);
1960
-        }
1961
-        $form = $this->_get_reg_custom_questions_form($REG_ID);
1962
-        $form->receive_form_submission($this->_req_data);
1963
-        $success = false;
1964
-        if ($form->is_valid()) {
1965
-            foreach ($form->subforms() as $question_group_id => $question_group_form) {
1966
-                foreach ($question_group_form->inputs() as $question_id => $input) {
1967
-                    $where_conditions    = array(
1968
-                        'QST_ID' => $question_id,
1969
-                        'REG_ID' => $REG_ID,
1970
-                    );
1971
-                    $possibly_new_values = array(
1972
-                        'ANS_value' => $input->normalized_value(),
1973
-                    );
1974
-                    $answer              = EEM_Answer::instance()->get_one(array($where_conditions));
1975
-                    if ($answer instanceof EE_Answer) {
1976
-                        $success = $answer->save($possibly_new_values);
1977
-                    } else {
1978
-                        //insert it then
1979
-                        $cols_n_vals = array_merge($where_conditions, $possibly_new_values);
1980
-                        $answer      = EE_Answer::new_instance($cols_n_vals);
1981
-                        $success     = $answer->save();
1982
-                    }
1983
-                }
1984
-            }
1985
-        } else {
1986
-            EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
1987
-        }
1988
-        return $success;
1989
-    }
1990
-
1991
-
1992
-    /**
1993
-     *        generates HTML for the Registration main meta box
1994
-     *
1995
-     * @access public
1996
-     * @return void
1997
-     */
1998
-    public function _reg_attendees_meta_box()
1999
-    {
2000
-        $REG = EEM_Registration::instance();
2001
-        //get all other registrations on this transaction, and cache
2002
-        //the attendees for them so we don't have to run another query using force_join
2003
-        $registrations                           = $REG->get_all(array(
2004
-            array(
2005
-                'TXN_ID' => $this->_registration->transaction_ID(),
2006
-                'REG_ID' => array('!=', $this->_registration->ID()),
2007
-            ),
2008
-            'force_join' => array('Attendee'),
2009
-        ));
2010
-        $this->_template_args['attendees']       = array();
2011
-        $this->_template_args['attendee_notice'] = '';
2012
-        if (empty($registrations)
2013
-            || (is_array($registrations)
2014
-                && ! EEH_Array::get_one_item_from_array($registrations))
2015
-        ) {
2016
-            EE_Error::add_error(__('There are no records attached to this registration. Something may have gone wrong with the registration',
2017
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
2018
-            $this->_template_args['attendee_notice'] = EE_Error::get_notices();
2019
-        } else {
2020
-            $att_nmbr = 1;
2021
-            foreach ($registrations as $registration) {
2022
-                /* @var $registration EE_Registration */
2023
-                $attendee                                                    = $registration->attendee()
2024
-                    ? $registration->attendee()
2025
-                    : EEM_Attendee::instance()
2026
-                                  ->create_default_object();
2027
-                $this->_template_args['attendees'][$att_nmbr]['STS_ID']      = $registration->status_ID();
2028
-                $this->_template_args['attendees'][$att_nmbr]['fname']       = $attendee->fname();//( isset( $registration->ATT_fname ) & ! empty( $registration->ATT_fname ) ) ? $registration->ATT_fname : '';
2029
-                $this->_template_args['attendees'][$att_nmbr]['lname']       = $attendee->lname();//( isset( $registration->ATT_lname ) & ! empty( $registration->ATT_lname ) ) ? $registration->ATT_lname : '';
2030
-                $this->_template_args['attendees'][$att_nmbr]['email']       = $attendee->email();//( isset( $registration->ATT_email ) & ! empty( $registration->ATT_email ) ) ? $registration->ATT_email : '';
2031
-                $this->_template_args['attendees'][$att_nmbr]['final_price'] = $registration->final_price();//( isset( $registration->REG_final_price ) & ! empty( $registration->REG_final_price ) ) ? $registration->REG_final_price : '';
2032
-                $this->_template_args['attendees'][$att_nmbr]['address']     = implode(', ',
2033
-                    $attendee->full_address_as_array());
2034
-                $this->_template_args['attendees'][$att_nmbr]['att_link']    = self::add_query_args_and_nonce(array(
2035
-                    'action' => 'edit_attendee',
2036
-                    'post'   => $attendee->ID(),
2037
-                ), REG_ADMIN_URL);
2038
-                $this->_template_args['attendees'][$att_nmbr]['event_name']  = $registration->event_obj()->name();
2039
-                $att_nmbr++;
2040
-            }
2041
-            //EEH_Debug_Tools::printr( $attendees, '$attendees  <br /><span style="font-size:10px;font-weight:normal;">( file: '. __FILE__ . ' - line no: ' . __LINE__ . ' )</span>', 'auto' );
2042
-            $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2043
-            //			$this->_template_args['registration_form_url'] = add_query_arg( array( 'action' => 'edit_registration', 'process' => 'attendees'  ), REG_ADMIN_URL );
2044
-        }
2045
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2046
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2047
-    }
2048
-
2049
-
2050
-    /**
2051
-     *        generates HTML for the Edit Registration side meta box
2052
-     *
2053
-     * @access public
2054
-     * @return void
2055
-     */
2056
-    public function _reg_registrant_side_meta_box()
2057
-    {
2058
-        /*@var $attendee EE_Attendee */
2059
-        $att_check = $this->_registration->attendee();
2060
-        $attendee  = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2061
-        //now let's determine if this is not the primary registration.  If it isn't then we set the primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the primary registration object (that way we know if we need to show create button or not)
2062
-        if ( ! $this->_registration->is_primary_registrant()) {
2063
-            $primary_registration = $this->_registration->get_primary_registration();
2064
-            $primary_attendee     = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2065
-                : null;
2066
-            if ( ! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2067
-                //in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own custom attendee object so let's not worry about the primary reg.
2068
-                $primary_registration = null;
2069
-            }
2070
-        } else {
2071
-            $primary_registration = null;
2072
-        }
2073
-        $this->_template_args['ATT_ID']            = $attendee->ID();
2074
-        $this->_template_args['fname']             = $attendee->fname();//$this->_registration->ATT_fname;
2075
-        $this->_template_args['lname']             = $attendee->lname();//$this->_registration->ATT_lname;
2076
-        $this->_template_args['email']             = $attendee->email();//$this->_registration->ATT_email;
2077
-        $this->_template_args['phone']             = $attendee->phone();
2078
-        $this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2079
-        //edit link
2080
-        $this->_template_args['att_edit_link']  = EE_Admin_Page::add_query_args_and_nonce(array(
2081
-            'action' => 'edit_attendee',
2082
-            'post'   => $attendee->ID(),
2083
-        ), REG_ADMIN_URL);
2084
-        $this->_template_args['att_edit_label'] = __('View/Edit Contact', 'event_espresso');
2085
-        //create link
2086
-        $this->_template_args['create_link']  = $primary_registration instanceof EE_Registration
2087
-            ? EE_Admin_Page::add_query_args_and_nonce(array(
2088
-                'action'  => 'duplicate_attendee',
2089
-                '_REG_ID' => $this->_registration->ID(),
2090
-            ), REG_ADMIN_URL) : '';
2091
-        $this->_template_args['create_label'] = __('Create Contact', 'event_espresso');
2092
-        $this->_template_args['att_check']    = $att_check;
2093
-        $template_path                        = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2094
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
2095
-    }
2096
-
2097
-
2098
-    /**
2099
-     * trash or restore registrations
2100
-     *
2101
-     * @param  boolean $trash whether to archive or restore
2102
-     * @access protected
2103
-     * @return void
2104
-     */
2105
-    protected function _trash_or_restore_registrations($trash = true)
2106
-    {
2107
-        $REGM    = EEM_Registration::instance();
2108
-        $success = 1;
2109
-        $error   = 0;
2110
-        $tickets = array();
2111
-        $dtts    = array();
2112
-        //if empty _REG_ID then get out because there's nothing to do
2113
-        if (empty($this->_req_data['_REG_ID'])) {
2114
-            $msg = $trash
2115
-                ? __('In order to trash registrations you must select which ones you wish to trash by clicking the checkboxes.',
2116
-                    'event_espresso')
2117
-                : __('In order to restore registrations you must select which ones you wish to restore by clicking the checkboxes.',
2118
-                    'event_espresso');
2119
-            EE_Error::add_error($msg, __FILE__, __LINE__, __FUNCTION__);
2120
-            $this->_redirect_after_action(false, '', '', array(), true);
2121
-        }
2122
-        //Checkboxes
2123
-        if ( ! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2124
-            // if array has more than one element than success message should be plural
2125
-            $success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2126
-            // cycle thru checkboxes
2127
-            while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2128
-                /** @var EE_Registration $REG */
2129
-                $REG           = $REGM->get_one_by_ID($REG_ID);
2130
-                $payment_count = $REG->get_first_related('Transaction')->count_related('Payment');
2131
-                if ($payment_count > 0) {
2132
-                    $name    = $REG->attendee() instanceof EE_Attendee ? $REG->attendee()->full_name()
2133
-                        : __('Unknown Attendee', 'event_espresso');
2134
-                    $error   = 1;
2135
-                    $success = 0;
2136
-                    EE_Error::add_error(sprintf(__('The registration for %s could not be trashed because it has payments attached to the related transaction.  If you wish to trash this registration you must first delete the payments on the related transaction.',
2137
-                        'event_espresso'), $name), __FILE__, __FUNCTION__, __LINE__);
2138
-                    continue; //can't trash this registration because it has payments.
2139
-                }
2140
-                $ticket                 = $REG->get_first_related('Ticket');
2141
-                $tickets[$ticket->ID()] = $ticket;
2142
-                $dtt                    = $ticket->get_many_related('Datetime');
2143
-                $dtts                   = array_merge($dtts, $dtt);
2144
-                $updated                = $trash ? $REG->delete() : $REG->restore();
2145
-                if ( ! $updated) {
2146
-                    $success = 0;
2147
-                } else {
2148
-                    $success = 2;
2149
-                }/**/
2150
-            }
2151
-        } else {
2152
-            // grab single id and delete
2153
-            $REG_ID                 = absint($this->_req_data['_REG_ID']);
2154
-            $REG                    = $REGM->get_one_by_ID($REG_ID);
2155
-            $ticket                 = $REG->get_first_related('Ticket');
2156
-            $tickets[$ticket->ID()] = $ticket;
2157
-            $dtts                   = $ticket->get_many_related('Datetime');
2158
-            $updated                = $trash ? $REG->delete() : $REG->restore();
2159
-            if ( ! $updated) {
2160
-                $success = 0;
2161
-            }
2162
-        }
2163
-        //now let's update counts
2164
-        EEM_Ticket::instance()->update_tickets_sold($tickets);
2165
-        EEM_Datetime::instance()->update_sold($dtts);
2166
-        $what           = $success > 1 ? __('Registrations', 'event_espresso') : __('Registration', 'event_espresso');
2167
-        $action_desc    = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2168
-        $overwrite_msgs = $error ? true : false;
2169
-        $this->_redirect_after_action($success, $what, $action_desc, array('action' => 'default'), $overwrite_msgs);
2170
-    }
2171
-
2172
-
2173
-    /**
2174
-     * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2175
-     * registration but also.
2176
-     * 1. Removing relations to EE_Attendee
2177
-     * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2178
-     * ALSO trashed.
2179
-     * 3. Deleting permanently any related Line items but only if the above conditions are met.
2180
-     * 4. Removing relationships between all tickets and the related registrations
2181
-     * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2182
-     * 6. Deleting permanently any related Checkins.
2183
-     *
2184
-     * @return void
2185
-     */
2186
-    protected function _delete_registrations()
2187
-    {
2188
-        $REG_MDL = EEM_Registration::instance();
2189
-        $success = 1;
2190
-        //Checkboxes
2191
-        if ( ! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2192
-            // if array has more than one element than success message should be plural
2193
-            $success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2194
-            // cycle thru checkboxes
2195
-            while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2196
-                $REG = $REG_MDL->get_one_by_ID($REG_ID);
2197
-                if ( ! $REG instanceof EE_Registration) {
2198
-                    continue;
2199
-                }
2200
-                $deleted = $this->_delete_registration($REG);
2201
-                if ( ! $deleted) {
2202
-                    $success = 0;
2203
-                }
2204
-            }
2205
-        } else {
2206
-            // grab single id and delete
2207
-            $REG_ID  = $this->_req_data['_REG_ID'];
2208
-            $REG     = $REG_MDL->get_one_by_ID($REG_ID);
2209
-            $deleted = $this->_delete_registration($REG);
2210
-            if ( ! $deleted) {
2211
-                $success = 0;
2212
-            }
2213
-        }
2214
-        $what        = $success > 1 ? __('Registrations', 'event_espresso') : __('Registration', 'event_espresso');
2215
-        $action_desc = __('permanently deleted.', 'event_espresso');
2216
-        $this->_redirect_after_action($success, $what, $action_desc, array('action' => 'default'), true);
2217
-    }
2218
-
2219
-
2220
-    /**
2221
-     * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2222
-     * models get affected.
2223
-     *
2224
-     * @param  EE_Registration $REG registration to be deleted permenantly
2225
-     * @return boolean              true = successful deletion, false = fail.
2226
-     */
2227
-    protected function _delete_registration(EE_Registration $REG)
2228
-    {
2229
-        //first we start with the transaction... ultimately, we WILL not delete permanently if there are any related registrations on the transaction that are NOT trashed.
2230
-        $TXN         = $REG->get_first_related('Transaction');
2231
-        $REGS        = $TXN->get_many_related('Registration');
2232
-        $all_trashed = true;
2233
-        foreach ($REGS as $registration) {
2234
-            if ( ! $registration->get('REG_deleted')) {
2235
-                $all_trashed = false;
2236
-            }
2237
-        }
2238
-        if ( ! $all_trashed) {
2239
-            EE_Error::add_error(__('Unable to permanently delete this registration. Before this registration can be permanently deleted, all registrations made in the same transaction must be trashed as well.  These registrations will be permanently deleted in the same action.',
2240
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
2241
-            return false;
2242
-        }
2243
-        //k made it here so that means we can delete all the related transactions and their answers (but let's do them separately from THIS one).
2244
-        foreach ($REGS as $registration) {
2245
-            //delete related answers
2246
-            $registration->delete_related_permanently('Answer');
2247
-            //remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2248
-            $attendee = $registration->get_first_related('Attendee');
2249
-            if ($attendee instanceof EE_Attendee) {
2250
-                $registration->_remove_relation_to($attendee, 'Attendee');
2251
-            }
2252
-            //now remove relationships to tickets on this registration.
2253
-            $registration->_remove_relations('Ticket');
2254
-            //now delete permanently the checkins related to this registration.
2255
-            $registration->delete_related_permanently('Checkin');
2256
-            if ($registration->ID() === $REG->ID()) {
2257
-                continue;
2258
-            } //we don't want to delete permanently the existing registration just yet.
2259
-            //remove relation to transaction for these registrations if NOT the existing registrations
2260
-            $registration->_remove_relations('Transaction');
2261
-            //delete permanently any related messages.
2262
-            $registration->delete_related_permanently('Message');
2263
-            //now delete this registration permanently
2264
-            $registration->delete_permanently();
2265
-        }
2266
-        //now all related registrations on the transaction are handled.  So let's just handle this registration itself (the transaction and line items should be all that's left).
2267
-        //delete the line items related to the transaction for this registration.
2268
-        $TXN->delete_related_permanently('Line_Item');
2269
-        //we need to remove all the relationships on the transaction
2270
-        $TXN->delete_related_permanently('Payment');
2271
-        $TXN->delete_related_permanently('Extra_Meta');
2272
-        $TXN->delete_related_permanently('Message');
2273
-        //now we can delete this REG permanently (and the transaction of course)
2274
-        $REG->delete_related_permanently('Transaction');
2275
-        return $REG->delete_permanently();
2276
-    }
2277
-
2278
-
2279
-    /**
2280
-     *    generates HTML for the Register New Attendee Admin page
2281
-     *
2282
-     * @access private
2283
-     * @throws \EE_Error
2284
-     * @return void
2285
-     */
2286
-    public function new_registration()
2287
-    {
2288
-        if ( ! $this->_set_reg_event()) {
2289
-            throw new EE_Error(__('Unable to continue with registering because there is no Event ID in the request',
2290
-                'event_espresso'));
2291
-        }
2292
-        EE_Registry::instance()->REQ->set_espresso_page(true);
2293
-        // gotta start with a clean slate if we're not coming here via ajax
2294
-        if ( ! defined('DOING_AJAX')
2295
-             && ( ! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2296
-        ) {
2297
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2298
-        }
2299
-        $this->_template_args['event_name'] = '';
2300
-        // event name
2301
-        if ($this->_reg_event) {
2302
-            $this->_template_args['event_name'] = $this->_reg_event->name();
2303
-            $edit_event_url                     = self::add_query_args_and_nonce(array(
2304
-                'action' => 'edit',
2305
-                'post'   => $this->_reg_event->ID(),
2306
-            ), EVENTS_ADMIN_URL);
2307
-            $edit_event_lnk                     = '<a href="'
2308
-                                                  . $edit_event_url
2309
-                                                  . '" title="'
2310
-                                                  . esc_attr__('Edit ', 'event_espresso')
2311
-                                                  . $this->_reg_event->name()
2312
-                                                  . '">'
2313
-                                                  . __('Edit Event', 'event_espresso')
2314
-                                                  . '</a>';
2315
-            $this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2316
-                                                   . $edit_event_lnk
2317
-                                                   . '</span>';
2318
-        }
2319
-        $this->_template_args['step_content'] = $this->_get_registration_step_content();
2320
-        if (defined('DOING_AJAX')) {
2321
-            $this->_return_json();
2322
-        }
2323
-        // grab header
2324
-        $template_path                              = REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2325
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path,
2326
-            $this->_template_args, true);
2327
-        //$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2328
-        // the details template wrapper
2329
-        $this->display_admin_page_with_sidebar();
2330
-    }
2331
-
2332
-
2333
-    /**
2334
-     * This returns the content for a registration step
2335
-     *
2336
-     * @access protected
2337
-     * @return string html
2338
-     */
2339
-    protected function _get_registration_step_content()
2340
-    {
2341
-        if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
2342
-            $warning_msg = sprintf(__('%2$sWARNING!!!%3$s%1$sPlease do not use the back button to return to this page for the purpose of adding another registration.%1$sThis can result in lost and/or corrupted data.%1$sIf you wish to add another registration, then please click the%1$s%7$s"Add Another New Registration to Event"%8$s button%1$son the Transaction details page, after you are redirected.%1$s%1$s%4$s redirecting in %5$s seconds %6$s',
2343
-                'event_espresso'), '<br />', '<h3 class="important-notice">', '</h3>', '<div class="float-right">',
2344
-                '<span id="redirect_timer" class="important-notice">30</span>', '</div>', '<b>', '</b>');
2345
-            return '
1902
+	}
1903
+
1904
+
1905
+	/**
1906
+	 * Updates the registration's custom questions according to the form info, if the form is submitted.
1907
+	 * If it's not a post, the "view_registrations" route will be called next on the SAME request
1908
+	 * to display the page
1909
+	 *
1910
+	 * @access protected
1911
+	 * @return void
1912
+	 */
1913
+	protected function _update_attendee_registration_form()
1914
+	{
1915
+		do_action('AHEE__Registrations_Admin_Page___update_attendee_registration_form__start', $this);
1916
+		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
1917
+			$REG_ID  = isset($this->_req_data['_REG_ID']) ? absint($this->_req_data['_REG_ID']) : false;
1918
+			$success = $this->_save_reg_custom_questions_form($REG_ID);
1919
+			if ($success) {
1920
+				$what  = __('Registration Form', 'event_espresso');
1921
+				$route = $REG_ID ? array('action' => 'view_registration', '_REG_ID' => $REG_ID)
1922
+					: array('action' => 'default');
1923
+				$this->_redirect_after_action($success, $what, __('updated', 'event_espresso'), $route);
1924
+			}
1925
+		}
1926
+	}
1927
+
1928
+
1929
+	/**
1930
+	 * Gets the form for saving registrations custom questions (if done
1931
+	 * previously retrieves the cached form object, which may have validation errors in it)
1932
+	 *
1933
+	 * @param int $REG_ID
1934
+	 * @return EE_Registration_Custom_Questions_Form
1935
+	 */
1936
+	protected function _get_reg_custom_questions_form($REG_ID)
1937
+	{
1938
+		if ( ! $this->_reg_custom_questions_form) {
1939
+			require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
1940
+			$this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(EEM_Registration::instance()
1941
+																										  ->get_one_by_ID($REG_ID));
1942
+			$this->_reg_custom_questions_form->_construct_finalize(null, null);
1943
+		}
1944
+		return $this->_reg_custom_questions_form;
1945
+	}
1946
+
1947
+
1948
+	/**
1949
+	 * Saves
1950
+	 *
1951
+	 * @access private
1952
+	 * @param bool $REG_ID
1953
+	 * @return bool
1954
+	 */
1955
+	private function _save_reg_custom_questions_form($REG_ID = false)
1956
+	{
1957
+		if ( ! $REG_ID) {
1958
+			EE_Error::add_error(__('An error occurred. No registration ID was received.', 'event_espresso'), __FILE__,
1959
+				__FUNCTION__, __LINE__);
1960
+		}
1961
+		$form = $this->_get_reg_custom_questions_form($REG_ID);
1962
+		$form->receive_form_submission($this->_req_data);
1963
+		$success = false;
1964
+		if ($form->is_valid()) {
1965
+			foreach ($form->subforms() as $question_group_id => $question_group_form) {
1966
+				foreach ($question_group_form->inputs() as $question_id => $input) {
1967
+					$where_conditions    = array(
1968
+						'QST_ID' => $question_id,
1969
+						'REG_ID' => $REG_ID,
1970
+					);
1971
+					$possibly_new_values = array(
1972
+						'ANS_value' => $input->normalized_value(),
1973
+					);
1974
+					$answer              = EEM_Answer::instance()->get_one(array($where_conditions));
1975
+					if ($answer instanceof EE_Answer) {
1976
+						$success = $answer->save($possibly_new_values);
1977
+					} else {
1978
+						//insert it then
1979
+						$cols_n_vals = array_merge($where_conditions, $possibly_new_values);
1980
+						$answer      = EE_Answer::new_instance($cols_n_vals);
1981
+						$success     = $answer->save();
1982
+					}
1983
+				}
1984
+			}
1985
+		} else {
1986
+			EE_Error::add_error($form->get_validation_error_string(), __FILE__, __FUNCTION__, __LINE__);
1987
+		}
1988
+		return $success;
1989
+	}
1990
+
1991
+
1992
+	/**
1993
+	 *        generates HTML for the Registration main meta box
1994
+	 *
1995
+	 * @access public
1996
+	 * @return void
1997
+	 */
1998
+	public function _reg_attendees_meta_box()
1999
+	{
2000
+		$REG = EEM_Registration::instance();
2001
+		//get all other registrations on this transaction, and cache
2002
+		//the attendees for them so we don't have to run another query using force_join
2003
+		$registrations                           = $REG->get_all(array(
2004
+			array(
2005
+				'TXN_ID' => $this->_registration->transaction_ID(),
2006
+				'REG_ID' => array('!=', $this->_registration->ID()),
2007
+			),
2008
+			'force_join' => array('Attendee'),
2009
+		));
2010
+		$this->_template_args['attendees']       = array();
2011
+		$this->_template_args['attendee_notice'] = '';
2012
+		if (empty($registrations)
2013
+			|| (is_array($registrations)
2014
+				&& ! EEH_Array::get_one_item_from_array($registrations))
2015
+		) {
2016
+			EE_Error::add_error(__('There are no records attached to this registration. Something may have gone wrong with the registration',
2017
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
2018
+			$this->_template_args['attendee_notice'] = EE_Error::get_notices();
2019
+		} else {
2020
+			$att_nmbr = 1;
2021
+			foreach ($registrations as $registration) {
2022
+				/* @var $registration EE_Registration */
2023
+				$attendee                                                    = $registration->attendee()
2024
+					? $registration->attendee()
2025
+					: EEM_Attendee::instance()
2026
+								  ->create_default_object();
2027
+				$this->_template_args['attendees'][$att_nmbr]['STS_ID']      = $registration->status_ID();
2028
+				$this->_template_args['attendees'][$att_nmbr]['fname']       = $attendee->fname();//( isset( $registration->ATT_fname ) & ! empty( $registration->ATT_fname ) ) ? $registration->ATT_fname : '';
2029
+				$this->_template_args['attendees'][$att_nmbr]['lname']       = $attendee->lname();//( isset( $registration->ATT_lname ) & ! empty( $registration->ATT_lname ) ) ? $registration->ATT_lname : '';
2030
+				$this->_template_args['attendees'][$att_nmbr]['email']       = $attendee->email();//( isset( $registration->ATT_email ) & ! empty( $registration->ATT_email ) ) ? $registration->ATT_email : '';
2031
+				$this->_template_args['attendees'][$att_nmbr]['final_price'] = $registration->final_price();//( isset( $registration->REG_final_price ) & ! empty( $registration->REG_final_price ) ) ? $registration->REG_final_price : '';
2032
+				$this->_template_args['attendees'][$att_nmbr]['address']     = implode(', ',
2033
+					$attendee->full_address_as_array());
2034
+				$this->_template_args['attendees'][$att_nmbr]['att_link']    = self::add_query_args_and_nonce(array(
2035
+					'action' => 'edit_attendee',
2036
+					'post'   => $attendee->ID(),
2037
+				), REG_ADMIN_URL);
2038
+				$this->_template_args['attendees'][$att_nmbr]['event_name']  = $registration->event_obj()->name();
2039
+				$att_nmbr++;
2040
+			}
2041
+			//EEH_Debug_Tools::printr( $attendees, '$attendees  <br /><span style="font-size:10px;font-weight:normal;">( file: '. __FILE__ . ' - line no: ' . __LINE__ . ' )</span>', 'auto' );
2042
+			$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2043
+			//			$this->_template_args['registration_form_url'] = add_query_arg( array( 'action' => 'edit_registration', 'process' => 'attendees'  ), REG_ADMIN_URL );
2044
+		}
2045
+		$template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2046
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2047
+	}
2048
+
2049
+
2050
+	/**
2051
+	 *        generates HTML for the Edit Registration side meta box
2052
+	 *
2053
+	 * @access public
2054
+	 * @return void
2055
+	 */
2056
+	public function _reg_registrant_side_meta_box()
2057
+	{
2058
+		/*@var $attendee EE_Attendee */
2059
+		$att_check = $this->_registration->attendee();
2060
+		$attendee  = $att_check instanceof EE_Attendee ? $att_check : EEM_Attendee::instance()->create_default_object();
2061
+		//now let's determine if this is not the primary registration.  If it isn't then we set the primary_registration object for reference BUT ONLY if the Attendee object loaded is not the same as the primary registration object (that way we know if we need to show create button or not)
2062
+		if ( ! $this->_registration->is_primary_registrant()) {
2063
+			$primary_registration = $this->_registration->get_primary_registration();
2064
+			$primary_attendee     = $primary_registration instanceof EE_Registration ? $primary_registration->attendee()
2065
+				: null;
2066
+			if ( ! $primary_attendee instanceof EE_Attendee || $attendee->ID() !== $primary_attendee->ID()) {
2067
+				//in here?  This means the displayed registration is not the primary registrant but ALREADY HAS its own custom attendee object so let's not worry about the primary reg.
2068
+				$primary_registration = null;
2069
+			}
2070
+		} else {
2071
+			$primary_registration = null;
2072
+		}
2073
+		$this->_template_args['ATT_ID']            = $attendee->ID();
2074
+		$this->_template_args['fname']             = $attendee->fname();//$this->_registration->ATT_fname;
2075
+		$this->_template_args['lname']             = $attendee->lname();//$this->_registration->ATT_lname;
2076
+		$this->_template_args['email']             = $attendee->email();//$this->_registration->ATT_email;
2077
+		$this->_template_args['phone']             = $attendee->phone();
2078
+		$this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2079
+		//edit link
2080
+		$this->_template_args['att_edit_link']  = EE_Admin_Page::add_query_args_and_nonce(array(
2081
+			'action' => 'edit_attendee',
2082
+			'post'   => $attendee->ID(),
2083
+		), REG_ADMIN_URL);
2084
+		$this->_template_args['att_edit_label'] = __('View/Edit Contact', 'event_espresso');
2085
+		//create link
2086
+		$this->_template_args['create_link']  = $primary_registration instanceof EE_Registration
2087
+			? EE_Admin_Page::add_query_args_and_nonce(array(
2088
+				'action'  => 'duplicate_attendee',
2089
+				'_REG_ID' => $this->_registration->ID(),
2090
+			), REG_ADMIN_URL) : '';
2091
+		$this->_template_args['create_label'] = __('Create Contact', 'event_espresso');
2092
+		$this->_template_args['att_check']    = $att_check;
2093
+		$template_path                        = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2094
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
2095
+	}
2096
+
2097
+
2098
+	/**
2099
+	 * trash or restore registrations
2100
+	 *
2101
+	 * @param  boolean $trash whether to archive or restore
2102
+	 * @access protected
2103
+	 * @return void
2104
+	 */
2105
+	protected function _trash_or_restore_registrations($trash = true)
2106
+	{
2107
+		$REGM    = EEM_Registration::instance();
2108
+		$success = 1;
2109
+		$error   = 0;
2110
+		$tickets = array();
2111
+		$dtts    = array();
2112
+		//if empty _REG_ID then get out because there's nothing to do
2113
+		if (empty($this->_req_data['_REG_ID'])) {
2114
+			$msg = $trash
2115
+				? __('In order to trash registrations you must select which ones you wish to trash by clicking the checkboxes.',
2116
+					'event_espresso')
2117
+				: __('In order to restore registrations you must select which ones you wish to restore by clicking the checkboxes.',
2118
+					'event_espresso');
2119
+			EE_Error::add_error($msg, __FILE__, __LINE__, __FUNCTION__);
2120
+			$this->_redirect_after_action(false, '', '', array(), true);
2121
+		}
2122
+		//Checkboxes
2123
+		if ( ! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2124
+			// if array has more than one element than success message should be plural
2125
+			$success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2126
+			// cycle thru checkboxes
2127
+			while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2128
+				/** @var EE_Registration $REG */
2129
+				$REG           = $REGM->get_one_by_ID($REG_ID);
2130
+				$payment_count = $REG->get_first_related('Transaction')->count_related('Payment');
2131
+				if ($payment_count > 0) {
2132
+					$name    = $REG->attendee() instanceof EE_Attendee ? $REG->attendee()->full_name()
2133
+						: __('Unknown Attendee', 'event_espresso');
2134
+					$error   = 1;
2135
+					$success = 0;
2136
+					EE_Error::add_error(sprintf(__('The registration for %s could not be trashed because it has payments attached to the related transaction.  If you wish to trash this registration you must first delete the payments on the related transaction.',
2137
+						'event_espresso'), $name), __FILE__, __FUNCTION__, __LINE__);
2138
+					continue; //can't trash this registration because it has payments.
2139
+				}
2140
+				$ticket                 = $REG->get_first_related('Ticket');
2141
+				$tickets[$ticket->ID()] = $ticket;
2142
+				$dtt                    = $ticket->get_many_related('Datetime');
2143
+				$dtts                   = array_merge($dtts, $dtt);
2144
+				$updated                = $trash ? $REG->delete() : $REG->restore();
2145
+				if ( ! $updated) {
2146
+					$success = 0;
2147
+				} else {
2148
+					$success = 2;
2149
+				}/**/
2150
+			}
2151
+		} else {
2152
+			// grab single id and delete
2153
+			$REG_ID                 = absint($this->_req_data['_REG_ID']);
2154
+			$REG                    = $REGM->get_one_by_ID($REG_ID);
2155
+			$ticket                 = $REG->get_first_related('Ticket');
2156
+			$tickets[$ticket->ID()] = $ticket;
2157
+			$dtts                   = $ticket->get_many_related('Datetime');
2158
+			$updated                = $trash ? $REG->delete() : $REG->restore();
2159
+			if ( ! $updated) {
2160
+				$success = 0;
2161
+			}
2162
+		}
2163
+		//now let's update counts
2164
+		EEM_Ticket::instance()->update_tickets_sold($tickets);
2165
+		EEM_Datetime::instance()->update_sold($dtts);
2166
+		$what           = $success > 1 ? __('Registrations', 'event_espresso') : __('Registration', 'event_espresso');
2167
+		$action_desc    = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
2168
+		$overwrite_msgs = $error ? true : false;
2169
+		$this->_redirect_after_action($success, $what, $action_desc, array('action' => 'default'), $overwrite_msgs);
2170
+	}
2171
+
2172
+
2173
+	/**
2174
+	 * This is used to permanently delete registrations.  Note, this will handle not only deleting permanently the
2175
+	 * registration but also.
2176
+	 * 1. Removing relations to EE_Attendee
2177
+	 * 2. Deleting permanently the related transaction, but ONLY if all related registrations to the transaction are
2178
+	 * ALSO trashed.
2179
+	 * 3. Deleting permanently any related Line items but only if the above conditions are met.
2180
+	 * 4. Removing relationships between all tickets and the related registrations
2181
+	 * 5. Deleting permanently any related Answers (and the answers for other related registrations that were deleted.)
2182
+	 * 6. Deleting permanently any related Checkins.
2183
+	 *
2184
+	 * @return void
2185
+	 */
2186
+	protected function _delete_registrations()
2187
+	{
2188
+		$REG_MDL = EEM_Registration::instance();
2189
+		$success = 1;
2190
+		//Checkboxes
2191
+		if ( ! empty($this->_req_data['_REG_ID']) && is_array($this->_req_data['_REG_ID'])) {
2192
+			// if array has more than one element than success message should be plural
2193
+			$success = count($this->_req_data['_REG_ID']) > 1 ? 2 : 1;
2194
+			// cycle thru checkboxes
2195
+			while (list($ind, $REG_ID) = each($this->_req_data['_REG_ID'])) {
2196
+				$REG = $REG_MDL->get_one_by_ID($REG_ID);
2197
+				if ( ! $REG instanceof EE_Registration) {
2198
+					continue;
2199
+				}
2200
+				$deleted = $this->_delete_registration($REG);
2201
+				if ( ! $deleted) {
2202
+					$success = 0;
2203
+				}
2204
+			}
2205
+		} else {
2206
+			// grab single id and delete
2207
+			$REG_ID  = $this->_req_data['_REG_ID'];
2208
+			$REG     = $REG_MDL->get_one_by_ID($REG_ID);
2209
+			$deleted = $this->_delete_registration($REG);
2210
+			if ( ! $deleted) {
2211
+				$success = 0;
2212
+			}
2213
+		}
2214
+		$what        = $success > 1 ? __('Registrations', 'event_espresso') : __('Registration', 'event_espresso');
2215
+		$action_desc = __('permanently deleted.', 'event_espresso');
2216
+		$this->_redirect_after_action($success, $what, $action_desc, array('action' => 'default'), true);
2217
+	}
2218
+
2219
+
2220
+	/**
2221
+	 * handles the permanent deletion of a registration.  See comments with _delete_registrations() for details on what
2222
+	 * models get affected.
2223
+	 *
2224
+	 * @param  EE_Registration $REG registration to be deleted permenantly
2225
+	 * @return boolean              true = successful deletion, false = fail.
2226
+	 */
2227
+	protected function _delete_registration(EE_Registration $REG)
2228
+	{
2229
+		//first we start with the transaction... ultimately, we WILL not delete permanently if there are any related registrations on the transaction that are NOT trashed.
2230
+		$TXN         = $REG->get_first_related('Transaction');
2231
+		$REGS        = $TXN->get_many_related('Registration');
2232
+		$all_trashed = true;
2233
+		foreach ($REGS as $registration) {
2234
+			if ( ! $registration->get('REG_deleted')) {
2235
+				$all_trashed = false;
2236
+			}
2237
+		}
2238
+		if ( ! $all_trashed) {
2239
+			EE_Error::add_error(__('Unable to permanently delete this registration. Before this registration can be permanently deleted, all registrations made in the same transaction must be trashed as well.  These registrations will be permanently deleted in the same action.',
2240
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
2241
+			return false;
2242
+		}
2243
+		//k made it here so that means we can delete all the related transactions and their answers (but let's do them separately from THIS one).
2244
+		foreach ($REGS as $registration) {
2245
+			//delete related answers
2246
+			$registration->delete_related_permanently('Answer');
2247
+			//remove relationship to EE_Attendee (but we ALWAYS leave the contact record intact)
2248
+			$attendee = $registration->get_first_related('Attendee');
2249
+			if ($attendee instanceof EE_Attendee) {
2250
+				$registration->_remove_relation_to($attendee, 'Attendee');
2251
+			}
2252
+			//now remove relationships to tickets on this registration.
2253
+			$registration->_remove_relations('Ticket');
2254
+			//now delete permanently the checkins related to this registration.
2255
+			$registration->delete_related_permanently('Checkin');
2256
+			if ($registration->ID() === $REG->ID()) {
2257
+				continue;
2258
+			} //we don't want to delete permanently the existing registration just yet.
2259
+			//remove relation to transaction for these registrations if NOT the existing registrations
2260
+			$registration->_remove_relations('Transaction');
2261
+			//delete permanently any related messages.
2262
+			$registration->delete_related_permanently('Message');
2263
+			//now delete this registration permanently
2264
+			$registration->delete_permanently();
2265
+		}
2266
+		//now all related registrations on the transaction are handled.  So let's just handle this registration itself (the transaction and line items should be all that's left).
2267
+		//delete the line items related to the transaction for this registration.
2268
+		$TXN->delete_related_permanently('Line_Item');
2269
+		//we need to remove all the relationships on the transaction
2270
+		$TXN->delete_related_permanently('Payment');
2271
+		$TXN->delete_related_permanently('Extra_Meta');
2272
+		$TXN->delete_related_permanently('Message');
2273
+		//now we can delete this REG permanently (and the transaction of course)
2274
+		$REG->delete_related_permanently('Transaction');
2275
+		return $REG->delete_permanently();
2276
+	}
2277
+
2278
+
2279
+	/**
2280
+	 *    generates HTML for the Register New Attendee Admin page
2281
+	 *
2282
+	 * @access private
2283
+	 * @throws \EE_Error
2284
+	 * @return void
2285
+	 */
2286
+	public function new_registration()
2287
+	{
2288
+		if ( ! $this->_set_reg_event()) {
2289
+			throw new EE_Error(__('Unable to continue with registering because there is no Event ID in the request',
2290
+				'event_espresso'));
2291
+		}
2292
+		EE_Registry::instance()->REQ->set_espresso_page(true);
2293
+		// gotta start with a clean slate if we're not coming here via ajax
2294
+		if ( ! defined('DOING_AJAX')
2295
+			 && ( ! isset($this->_req_data['processing_registration']) || isset($this->_req_data['step_error']))
2296
+		) {
2297
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2298
+		}
2299
+		$this->_template_args['event_name'] = '';
2300
+		// event name
2301
+		if ($this->_reg_event) {
2302
+			$this->_template_args['event_name'] = $this->_reg_event->name();
2303
+			$edit_event_url                     = self::add_query_args_and_nonce(array(
2304
+				'action' => 'edit',
2305
+				'post'   => $this->_reg_event->ID(),
2306
+			), EVENTS_ADMIN_URL);
2307
+			$edit_event_lnk                     = '<a href="'
2308
+												  . $edit_event_url
2309
+												  . '" title="'
2310
+												  . esc_attr__('Edit ', 'event_espresso')
2311
+												  . $this->_reg_event->name()
2312
+												  . '">'
2313
+												  . __('Edit Event', 'event_espresso')
2314
+												  . '</a>';
2315
+			$this->_template_args['event_name'] .= ' <span class="admin-page-header-edit-lnk not-bold">'
2316
+												   . $edit_event_lnk
2317
+												   . '</span>';
2318
+		}
2319
+		$this->_template_args['step_content'] = $this->_get_registration_step_content();
2320
+		if (defined('DOING_AJAX')) {
2321
+			$this->_return_json();
2322
+		}
2323
+		// grab header
2324
+		$template_path                              = REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2325
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path,
2326
+			$this->_template_args, true);
2327
+		//$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
2328
+		// the details template wrapper
2329
+		$this->display_admin_page_with_sidebar();
2330
+	}
2331
+
2332
+
2333
+	/**
2334
+	 * This returns the content for a registration step
2335
+	 *
2336
+	 * @access protected
2337
+	 * @return string html
2338
+	 */
2339
+	protected function _get_registration_step_content()
2340
+	{
2341
+		if (isset($_COOKIE['ee_registration_added']) && $_COOKIE['ee_registration_added']) {
2342
+			$warning_msg = sprintf(__('%2$sWARNING!!!%3$s%1$sPlease do not use the back button to return to this page for the purpose of adding another registration.%1$sThis can result in lost and/or corrupted data.%1$sIf you wish to add another registration, then please click the%1$s%7$s"Add Another New Registration to Event"%8$s button%1$son the Transaction details page, after you are redirected.%1$s%1$s%4$s redirecting in %5$s seconds %6$s',
2343
+				'event_espresso'), '<br />', '<h3 class="important-notice">', '</h3>', '<div class="float-right">',
2344
+				'<span id="redirect_timer" class="important-notice">30</span>', '</div>', '<b>', '</b>');
2345
+			return '
2346 2346
 	<div id="ee-add-reg-back-button-dv"><p>' . $warning_msg . '</p></div>
2347 2347
 	<script >
2348 2348
 		// WHOAH !!! it appears that someone is using the back button from the Transaction admin page
@@ -2355,658 +2355,658 @@  discard block
 block discarded – undo
2355 2355
 	        }
2356 2356
 	    }, 800 );
2357 2357
 	</script >';
2358
-        }
2359
-        $template_args = array(
2360
-            'title'                    => '',
2361
-            'content'                  => '',
2362
-            'step_button_text'         => '',
2363
-            'show_notification_toggle' => false,
2364
-        );
2365
-        //to indicate we're processing a new registration
2366
-        $hidden_fields = array(
2367
-            'processing_registration' => array(
2368
-                'type'  => 'hidden',
2369
-                'value' => 0,
2370
-            ),
2371
-            'event_id'                => array(
2372
-                'type'  => 'hidden',
2373
-                'value' => $this->_reg_event->ID(),
2374
-            ),
2375
-        );
2376
-        //if the cart is empty then we know we're at step one so we'll display ticket selector
2377
-        $cart = EE_Registry::instance()->SSN->cart();
2378
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2379
-        switch ($step) {
2380
-            case 'ticket' :
2381
-                $hidden_fields['processing_registration']['value'] = 1;
2382
-                $template_args['title']                            = __('Step One: Select the Ticket for this registration',
2383
-                    'event_espresso');
2384
-                $template_args['content']                          = EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
2385
-                $template_args['step_button_text']                 = __('Add Tickets and Continue to Registrant Details',
2386
-                    'event_espresso');
2387
-                $template_args['show_notification_toggle']         = false;
2388
-                break;
2389
-            case 'questions' :
2390
-                $hidden_fields['processing_registration']['value'] = 2;
2391
-                $template_args['title']                            = __('Step Two: Add Registrant Details for this Registration',
2392
-                    'event_espresso');
2393
-                //in theory we should be able to run EED_SPCO at this point because the cart should have been setup properly by the first process_reg_step run.
2394
-                $template_args['content']                  = EED_Single_Page_Checkout::registration_checkout_for_admin();
2395
-                $template_args['step_button_text']         = __('Save Registration and Continue to Details',
2396
-                    'event_espresso');
2397
-                $template_args['show_notification_toggle'] = true;
2398
-                break;
2399
-        }
2400
-        $this->_set_add_edit_form_tags('process_reg_step',
2401
-            $hidden_fields); //we come back to the process_registration_step route.
2402
-        return EEH_Template::display_template(REG_TEMPLATE_PATH
2403
-                                              . 'reg_admin_register_new_attendee_step_content.template.php',
2404
-            $template_args, true);
2405
-    }
2406
-
2407
-
2408
-    /**
2409
-     *        set_reg_event
2410
-     *
2411
-     * @access private
2412
-     * @return boolean
2413
-     */
2414
-    private function _set_reg_event()
2415
-    {
2416
-        if (is_object($this->_reg_event)) {
2417
-            return true;
2418
-        }
2419
-        $EVT_ID = ( ! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
2420
-        if ( ! $EVT_ID) {
2421
-            return false;
2422
-        }
2423
-        $this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2424
-        return true;
2425
-    }
2426
-
2427
-
2428
-    /**
2429
-     * process_reg_step
2430
-     *
2431
-     * @access        public
2432
-     * @return        string
2433
-     * @throws \RuntimeException
2434
-     * @throws \EE_Error
2435
-     */
2436
-    public function process_reg_step()
2437
-    {
2438
-        EE_System::do_not_cache();
2439
-        $this->_set_reg_event();
2440
-        EE_Registry::instance()->REQ->set_espresso_page(true);
2441
-        EE_Registry::instance()->REQ->set('uts', time());
2442
-        //what step are we on?
2443
-        $cart = EE_Registry::instance()->SSN->cart();
2444
-        $step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2445
-        //if doing ajax then we need to verify the nonce
2446
-        if (defined('DOING_AJAX')) {
2447
-            $nonce = isset($this->_req_data[$this->_req_nonce])
2448
-                ? sanitize_text_field($this->_req_data[$this->_req_nonce]) : '';
2449
-            $this->_verify_nonce($nonce, $this->_req_nonce);
2450
-        }
2451
-        switch ($step) {
2452
-            case 'ticket' :
2453
-                //process ticket selection
2454
-                $success = EED_Ticket_Selector::instance()->process_ticket_selections();
2455
-                if ($success) {
2456
-                    EE_Error::add_success(esc_html__('Tickets Selected. Now complete the registration.',
2457
-                        'event_espresso'));
2458
-                } else {
2459
-                    $query_args['step_error'] = $this->_req_data['step_error'] = true;
2460
-                }
2461
-                if (defined('DOING_AJAX')) {
2462
-                    $this->new_registration(); //display next step
2463
-                } else {
2464
-                    $query_args = array(
2465
-                        'action'                  => 'new_registration',
2466
-                        'processing_registration' => 1,
2467
-                        'event_id'                => $this->_reg_event->ID(),
2468
-                        'uts'                     => time(),
2469
-                    );
2470
-                    $this->_redirect_after_action(false, '', '', $query_args, true);
2471
-                }
2472
-                break;
2473
-            case 'questions' :
2474
-                if ( ! isset($this->_req_data['txn_reg_status_change'], $this->_req_data['txn_reg_status_change']['send_notifications'])) {
2475
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
2476
-                }
2477
-                //process registration
2478
-                $transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
2479
-                if ($cart instanceof EE_Cart) {
2480
-                    $grand_total = $cart->get_cart_grand_total();
2481
-                    if ($grand_total instanceof EE_Line_Item) {
2482
-                        $grand_total->save_this_and_descendants_to_txn();
2483
-                    }
2484
-                }
2485
-                if ( ! $transaction instanceof EE_Transaction) {
2486
-                    $query_args = array(
2487
-                        'action'                  => 'new_registration',
2488
-                        'processing_registration' => 2,
2489
-                        'event_id'                => $this->_reg_event->ID(),
2490
-                        'uts'                     => time(),
2491
-                    );
2492
-                    if (defined('DOING_AJAX')) {
2493
-                        //display registration form again because there are errors (maybe validation?)
2494
-                        $this->new_registration();
2495
-                        return;
2496
-                    } else {
2497
-                        $this->_redirect_after_action(false, '', '', $query_args, true);
2498
-                        return;
2499
-                    }
2500
-                }
2501
-                // maybe update status, and make sure to save transaction if not done already
2502
-                if ( ! $transaction->update_status_based_on_total_paid()) {
2503
-                    $transaction->save();
2504
-                }
2505
-                EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2506
-                $this->_req_data = array();
2507
-                $query_args      = array(
2508
-                    'action'        => 'redirect_to_txn',
2509
-                    'TXN_ID'        => $transaction->ID(),
2510
-                    'EVT_ID'        => $this->_reg_event->ID(),
2511
-                    'event_name'    => urlencode($this->_reg_event->name()),
2512
-                    'redirect_from' => 'new_registration',
2513
-                );
2514
-                $this->_redirect_after_action(false, '', '', $query_args, true);
2515
-                break;
2516
-        }
2517
-        //what are you looking here for?  Should be nothing to do at this point.
2518
-    }
2519
-
2520
-
2521
-    /**
2522
-     * redirect_to_txn
2523
-     *
2524
-     * @access public
2525
-     * @return void
2526
-     */
2527
-    public function redirect_to_txn()
2528
-    {
2529
-        EE_System::do_not_cache();
2530
-        EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2531
-        $query_args = array(
2532
-            'action' => 'view_transaction',
2533
-            'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
2534
-            'page'   => 'espresso_transactions',
2535
-        );
2536
-        if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
2537
-            $query_args['EVT_ID']        = $this->_req_data['EVT_ID'];
2538
-            $query_args['event_name']    = urlencode($this->_req_data['event_name']);
2539
-            $query_args['redirect_from'] = $this->_req_data['redirect_from'];
2540
-        }
2541
-        EE_Error::add_success(__('Registration Created.  Please review the transaction and add any payments as necessary',
2542
-            'event_espresso'));
2543
-        $this->_redirect_after_action(false, '', '', $query_args, true);
2544
-    }
2545
-
2546
-
2547
-    /**
2548
-     *        generates HTML for the Attendee Contact List
2549
-     *
2550
-     * @access protected
2551
-     * @return void
2552
-     */
2553
-    protected function _attendee_contact_list_table()
2554
-    {
2555
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2556
-        $this->_search_btn_label = __('Contacts', 'event_espresso');
2557
-        $this->display_admin_list_table_page_with_no_sidebar();
2558
-    }
2559
-
2560
-
2561
-    /**
2562
-     *        get_attendees
2563
-     *
2564
-     * @param bool $count whether to return count or data.
2565
-     * @access public
2566
-     * @return array
2567
-     */
2568
-    public function get_attendees($per_page, $count = false, $trash = false)
2569
-    {
2570
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2571
-        require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
2572
-        $ATT_MDL                    = EEM_Attendee::instance();
2573
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2574
-        switch ($this->_req_data['orderby']) {
2575
-            case 'ATT_ID':
2576
-                $orderby = 'ATT_ID';
2577
-                break;
2578
-            case 'ATT_fname':
2579
-                $orderby = 'ATT_fname';
2580
-                break;
2581
-            case 'ATT_email':
2582
-                $orderby = 'ATT_email';
2583
-                break;
2584
-            case 'ATT_city':
2585
-                $orderby = 'ATT_city';
2586
-                break;
2587
-            case 'STA_ID':
2588
-                $orderby = 'STA_ID';
2589
-                break;
2590
-            case 'CNT_ID':
2591
-                $orderby = 'CNT_ID';
2592
-                break;
2593
-            default:
2594
-                $orderby = 'ATT_lname';
2595
-        }
2596
-        $sort         = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
2597
-            : 'ASC';
2598
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
2599
-            ? $this->_req_data['paged'] : 1;
2600
-        $per_page     = isset($per_page) && ! empty($per_page) ? $per_page : 10;
2601
-        $per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
2602
-            ? $this->_req_data['perpage'] : $per_page;
2603
-        $_where       = array();
2604
-        if ( ! empty($this->_req_data['s'])) {
2605
-            $sstr         = '%' . $this->_req_data['s'] . '%';
2606
-            $_where['OR'] = array(
2607
-                'Registration.Event.EVT_name'       => array('LIKE', $sstr),
2608
-                'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
2609
-                'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
2610
-                'ATT_fname'                         => array('LIKE', $sstr),
2611
-                'ATT_lname'                         => array('LIKE', $sstr),
2612
-                'ATT_short_bio'                     => array('LIKE', $sstr),
2613
-                'ATT_email'                         => array('LIKE', $sstr),
2614
-                'ATT_address'                       => array('LIKE', $sstr),
2615
-                'ATT_address2'                      => array('LIKE', $sstr),
2616
-                'ATT_city'                          => array('LIKE', $sstr),
2617
-                'Country.CNT_name'                  => array('LIKE', $sstr),
2618
-                'State.STA_name'                    => array('LIKE', $sstr),
2619
-                'ATT_phone'                         => array('LIKE', $sstr),
2620
-                'Registration.REG_final_price'      => array('LIKE', $sstr),
2621
-                'Registration.REG_code'             => array('LIKE', $sstr),
2622
-                'Registration.REG_count'            => array('LIKE', $sstr),
2623
-                'Registration.REG_group_size'       => array('LIKE', $sstr),
2624
-            );
2625
-        }
2626
-        $offset = ($current_page - 1) * $per_page;
2627
-        $limit  = $count ? null : array($offset, $per_page);
2628
-        if ($trash) {
2629
-            $_where['status'] = array('!=', 'publish');
2630
-            $all_attendees    = $count
2631
-                ? $ATT_MDL->count(array(
2632
-                    $_where,
2633
-                    'order_by' => array($orderby => $sort),
2634
-                    'limit'    => $limit,
2635
-                ), 'ATT_ID', true)
2636
-                : $ATT_MDL->get_all(array(
2637
-                    $_where,
2638
-                    'order_by' => array($orderby => $sort),
2639
-                    'limit'    => $limit,
2640
-                ));
2641
-        } else {
2642
-            $_where['status'] = array('IN', array('publish'));
2643
-            $all_attendees    = $count
2644
-                ? $ATT_MDL->count(array(
2645
-                    $_where,
2646
-                    'order_by' => array($orderby => $sort),
2647
-                    'limit'    => $limit,
2648
-                ), 'ATT_ID', true)
2649
-                : $ATT_MDL->get_all(array(
2650
-                    $_where,
2651
-                    'order_by' => array($orderby => $sort),
2652
-                    'limit'    => $limit,
2653
-                ));
2654
-        }
2655
-        return $all_attendees;
2656
-    }
2657
-
2658
-
2659
-    /**
2660
-     * This is just taking care of resending the registration confirmation
2661
-     *
2662
-     * @access protected
2663
-     * @return void
2664
-     */
2665
-    protected function _resend_registration()
2666
-    {
2667
-        $this->_process_resend_registration();
2668
-        $query_args = isset($this->_req_data['redirect_to'])
2669
-            ? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
2670
-            : array(
2671
-                'action' => 'default',
2672
-            );
2673
-        $this->_redirect_after_action(false, '', '', $query_args, true);
2674
-    }
2675
-
2676
-    /**
2677
-     * Creates a registration report, but accepts the name of a method to use for preparing the query parameters
2678
-     * to use when selecting registrations
2679
-     * @param string $method_name_for_getting_query_params the name of the method (on this class) to use for preparing
2680
-     *                                                     the query parameters from the request
2681
-     * @return void ends the request with a redirect or download
2682
-     */
2683
-    public function _registrations_report_base( $method_name_for_getting_query_params )
2684
-    {
2685
-        if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
2686
-            wp_redirect(EE_Admin_Page::add_query_args_and_nonce(array(
2687
-                'page'        => 'espresso_batch',
2688
-                'batch'       => 'file',
2689
-                'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
2690
-                'filters'     => urlencode(
2691
-                    serialize(
2692
-                        call_user_func(
2693
-                            array( $this, $method_name_for_getting_query_params ),
2694
-                            EEH_Array::is_set(
2695
-                                $this->_req_data,
2696
-                                'filters',
2697
-                                array()
2698
-                            )
2699
-                        )
2700
-                    )
2701
-                ),
2702
-                'use_filters' => EEH_Array::is_set($this->_req_data, 'use_filters', false),
2703
-                'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
2704
-                'return_url'  => urlencode($this->_req_data['return_url']),
2705
-            )));
2706
-        } else {
2707
-            $new_request_args = array(
2708
-                'export' => 'report',
2709
-                'action' => 'registrations_report_for_event',
2710
-                'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
2711
-            );
2712
-            $this->_req_data = array_merge($this->_req_data, $new_request_args);
2713
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2714
-                require_once(EE_CLASSES . 'EE_Export.class.php');
2715
-                $EE_Export = EE_Export::instance($this->_req_data);
2716
-                $EE_Export->export();
2717
-            }
2718
-        }
2719
-    }
2720
-
2721
-
2722
-
2723
-    /**
2724
-     * Creates a registration report using only query parameters in the request
2725
-     * @return void
2726
-     */
2727
-    public function _registrations_report()
2728
-    {
2729
-        $this->_registrations_report_base( '_get_registration_query_parameters' );
2730
-    }
2731
-
2732
-
2733
-    public function _contact_list_export()
2734
-    {
2735
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2736
-            require_once(EE_CLASSES . 'EE_Export.class.php');
2737
-            $EE_Export = EE_Export::instance($this->_req_data);
2738
-            $EE_Export->export_attendees();
2739
-        }
2740
-    }
2741
-
2742
-
2743
-    public function _contact_list_report()
2744
-    {
2745
-        if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
2746
-            wp_redirect(EE_Admin_Page::add_query_args_and_nonce(array(
2747
-                'page'        => 'espresso_batch',
2748
-                'batch'       => 'file',
2749
-                'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
2750
-                'return_url'  => urlencode($this->_req_data['return_url']),
2751
-            )));
2752
-        } else {
2753
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2754
-                require_once(EE_CLASSES . 'EE_Export.class.php');
2755
-                $EE_Export = EE_Export::instance($this->_req_data);
2756
-                $EE_Export->report_attendees();
2757
-            }
2758
-        }
2759
-    }
2760
-
2761
-
2762
-
2763
-
2764
-
2765
-    /***************************************        ATTENDEE DETAILS        ***************************************/
2766
-    /**
2767
-     * This duplicates the attendee object for the given incoming registration id and attendee_id.
2768
-     *
2769
-     * @return void
2770
-     */
2771
-    protected function _duplicate_attendee()
2772
-    {
2773
-        $action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
2774
-        //verify we have necessary info
2775
-        if (empty($this->_req_data['_REG_ID'])) {
2776
-            EE_Error::add_error(__('Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
2777
-                'event_espresso'), __FILE__, __LINE__, __FUNCTION__);
2778
-            $query_args = array('action' => $action);
2779
-            $this->_redirect_after_action('', '', '', $query_args, true);
2780
-        }
2781
-        //okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
2782
-        $registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
2783
-        $attendee     = $registration->attendee();
2784
-        //remove relation of existing attendee on registration
2785
-        $registration->_remove_relation_to($attendee, 'Attendee');
2786
-        //new attendee
2787
-        $new_attendee = clone $attendee;
2788
-        $new_attendee->set('ATT_ID', 0);
2789
-        $new_attendee->save();
2790
-        //add new attendee to reg
2791
-        $registration->_add_relation_to($new_attendee, 'Attendee');
2792
-        EE_Error::add_success(__('New Contact record created.  Now make any edits you wish to make for this contact.',
2793
-            'event_espresso'));
2794
-        //redirect to edit page for attendee
2795
-        $query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
2796
-        $this->_redirect_after_action('', '', '', $query_args, true);
2797
-    }
2798
-
2799
-
2800
-    //related to cpt routes
2801
-    protected function _insert_update_cpt_item($post_id, $post)
2802
-    {
2803
-        $success  = true;
2804
-        $attendee = EEM_Attendee::instance()->get_one_by_ID($post_id);
2805
-        //for attendee updates
2806
-        if ($post->post_type = 'espresso_attendees' && ! empty($attendee)) {
2807
-            //note we should only be UPDATING attendees at this point.
2808
-            $updated_fields = array(
2809
-                'ATT_fname'     => $this->_req_data['ATT_fname'],
2810
-                'ATT_lname'     => $this->_req_data['ATT_lname'],
2811
-                'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
2812
-                'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
2813
-                'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
2814
-                'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
2815
-                'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
2816
-                'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
2817
-                'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
2818
-                'ATT_email'     => isset($this->_req_data['ATT_email']) ? $this->_req_data['ATT_email'] : '',
2819
-                'ATT_phone'     => isset($this->_req_data['ATT_phone']) ? $this->_req_data['ATT_phone'] : '',
2820
-            );
2821
-            foreach ($updated_fields as $field => $value) {
2822
-                $attendee->set($field, $value);
2823
-            }
2824
-            $success                   = $attendee->save();
2825
-            $attendee_update_callbacks = apply_filters('FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
2826
-                array());
2827
-            foreach ($attendee_update_callbacks as $a_callback) {
2828
-                if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
2829
-                    throw new EE_Error(sprintf(__('The %s callback given for the "FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update" filter is not a valid callback.  Please check the spelling.',
2830
-                        'event_espresso'), $a_callback));
2831
-                }
2832
-            }
2833
-        }
2834
-        if ($success === false) {
2835
-            EE_Error::add_error(__('Something went wrong with updating the meta table data for the registration.',
2836
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
2837
-        }
2838
-    }
2839
-
2840
-
2841
-    public function trash_cpt_item($post_id)
2842
-    {
2843
-    }
2844
-
2845
-
2846
-    public function delete_cpt_item($post_id)
2847
-    {
2848
-    }
2849
-
2850
-
2851
-    public function restore_cpt_item($post_id)
2852
-    {
2853
-    }
2854
-
2855
-
2856
-    protected function _restore_cpt_item($post_id, $revision_id)
2857
-    {
2858
-    }
2859
-
2860
-
2861
-    public function attendee_editor_metaboxes()
2862
-    {
2863
-        $this->verify_cpt_object();
2864
-        remove_meta_box('postexcerpt', __('Excerpt'), 'post_excerpt_meta_box', $this->_cpt_routes[$this->_req_action],
2865
-            'normal', 'core');
2866
-        remove_meta_box('commentstatusdiv', $this->_cpt_routes[$this->_req_action], 'normal', 'core');
2867
-        if (post_type_supports('espresso_attendees', 'excerpt')) {
2868
-            add_meta_box('postexcerpt', __('Short Biography', 'event_espresso'), 'post_excerpt_meta_box',
2869
-                $this->_cpt_routes[$this->_req_action], 'normal');
2870
-        }
2871
-        if (post_type_supports('espresso_attendees', 'comments')) {
2872
-            add_meta_box('commentsdiv', __('Notes on the Contact', 'event_espresso'), 'post_comment_meta_box',
2873
-                $this->_cpt_routes[$this->_req_action], 'normal', 'core');
2874
-        }
2875
-        add_meta_box('attendee_contact_info', __('Contact Info', 'event_espresso'),
2876
-            array($this, 'attendee_contact_info'), $this->_cpt_routes[$this->_req_action], 'side', 'core');
2877
-        add_meta_box('attendee_details_address', __('Address Details', 'event_espresso'),
2878
-            array($this, 'attendee_address_details'), $this->_cpt_routes[$this->_req_action], 'normal', 'core');
2879
-        add_meta_box('attendee_registrations', __('Registrations for this Contact', 'event_espresso'),
2880
-            array($this, 'attendee_registrations_meta_box'), $this->_cpt_routes[$this->_req_action], 'normal', 'high');
2881
-    }
2882
-
2883
-
2884
-    /**
2885
-     * Metabox for attendee contact info
2886
-     *
2887
-     * @param  WP_Post $post wp post object
2888
-     * @return string        attendee contact info ( and form )
2889
-     */
2890
-    public function attendee_contact_info($post)
2891
-    {
2892
-        //get attendee object ( should already have it )
2893
-        $this->_template_args['attendee'] = $this->_cpt_model_obj;
2894
-        $template                         = REG_TEMPLATE_PATH . 'attendee_contact_info_metabox_content.template.php';
2895
-        EEH_Template::display_template($template, $this->_template_args);
2896
-    }
2897
-
2898
-
2899
-    /**
2900
-     * Metabox for attendee details
2901
-     *
2902
-     * @param  WP_Post $post wp post object
2903
-     * @return string        attendee address details (and form)
2904
-     */
2905
-    public function attendee_address_details($post)
2906
-    {
2907
-        //get attendee object (should already have it)
2908
-        $this->_template_args['attendee']     = $this->_cpt_model_obj;
2909
-        $this->_template_args['state_html']   = EEH_Form_Fields::generate_form_input(new EE_Question_Form_Input(EE_Question::new_instance(array(
2910
-            'QST_ID'           => 0,
2911
-            'QST_display_text' => __('State/Province', 'event_espresso'),
2912
-            'QST_system'       => 'admin-state',
2913
-        )), EE_Answer::new_instance(array(
2914
-            'ANS_ID'    => 0,
2915
-            'ANS_value' => $this->_cpt_model_obj->state_ID(),
2916
-        )), array(
2917
-            'input_id'       => 'STA_ID',
2918
-            'input_name'     => 'STA_ID',
2919
-            'input_prefix'   => '',
2920
-            'append_qstn_id' => false,
2921
-        )));
2922
-        $this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(new EE_Question_Form_Input(EE_Question::new_instance(array(
2923
-            'QST_ID'           => 0,
2924
-            'QST_display_text' => __('Country', 'event_espresso'),
2925
-            'QST_system'       => 'admin-country',
2926
-        )), EE_Answer::new_instance(array(
2927
-            'ANS_ID'    => 0,
2928
-            'ANS_value' => $this->_cpt_model_obj->country_ID(),
2929
-        )), array(
2930
-            'input_id'       => 'CNT_ISO',
2931
-            'input_name'     => 'CNT_ISO',
2932
-            'input_prefix'   => '',
2933
-            'append_qstn_id' => false,
2934
-        )));
2935
-        $template                             = REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
2936
-        EEH_Template::display_template($template, $this->_template_args);
2937
-    }
2938
-
2939
-
2940
-    /**
2941
-     *        _attendee_details
2942
-     *
2943
-     * @access protected
2944
-     * @return void
2945
-     */
2946
-    public function attendee_registrations_meta_box($post)
2947
-    {
2948
-        $this->_template_args['attendee']      = $this->_cpt_model_obj;
2949
-        $this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
2950
-        $template                              = REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
2951
-        EEH_Template::display_template($template, $this->_template_args);
2952
-    }
2953
-
2954
-
2955
-    /**
2956
-     * add in the form fields for the attendee edit
2957
-     *
2958
-     * @param  WP_Post $post wp post object
2959
-     * @return string        html for new form.
2960
-     */
2961
-    public function after_title_form_fields($post)
2962
-    {
2963
-        if ($post->post_type == 'espresso_attendees') {
2964
-            $template                  = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
2965
-            $template_args['attendee'] = $this->_cpt_model_obj;
2966
-            EEH_Template::display_template($template, $template_args);
2967
-        }
2968
-    }
2969
-
2970
-
2971
-    /**
2972
-     *        _trash_or_restore_attendee
2973
-     *
2974
-     * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
2975
-     * @access protected
2976
-     * @return void
2977
-     */
2978
-    protected function _trash_or_restore_attendees($trash = true)
2979
-    {
2980
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2981
-        $ATT_MDL = EEM_Attendee::instance();
2982
-        $success = 1;
2983
-        //Checkboxes
2984
-        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2985
-            // if array has more than one element than success message should be plural
2986
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2987
-            // cycle thru checkboxes
2988
-            while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
2989
-                $updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
2990
-                    : $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
2991
-                if ( ! $updated) {
2992
-                    $success = 0;
2993
-                }
2994
-            }
2995
-        } else {
2996
-            // grab single id and delete
2997
-            $ATT_ID = absint($this->_req_data['ATT_ID']);
2998
-            //get attendee
2999
-            $att     = $ATT_MDL->get_one_by_ID($ATT_ID);
3000
-            $updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
3001
-            $updated = $att->save();
3002
-            if ( ! $updated) {
3003
-                $success = 0;
3004
-            }
3005
-        }
3006
-        $what        = $success > 1 ? __('Contacts', 'event_espresso') : __('Contact', 'event_espresso');
3007
-        $action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
3008
-        $this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
3009
-    }
2358
+		}
2359
+		$template_args = array(
2360
+			'title'                    => '',
2361
+			'content'                  => '',
2362
+			'step_button_text'         => '',
2363
+			'show_notification_toggle' => false,
2364
+		);
2365
+		//to indicate we're processing a new registration
2366
+		$hidden_fields = array(
2367
+			'processing_registration' => array(
2368
+				'type'  => 'hidden',
2369
+				'value' => 0,
2370
+			),
2371
+			'event_id'                => array(
2372
+				'type'  => 'hidden',
2373
+				'value' => $this->_reg_event->ID(),
2374
+			),
2375
+		);
2376
+		//if the cart is empty then we know we're at step one so we'll display ticket selector
2377
+		$cart = EE_Registry::instance()->SSN->cart();
2378
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2379
+		switch ($step) {
2380
+			case 'ticket' :
2381
+				$hidden_fields['processing_registration']['value'] = 1;
2382
+				$template_args['title']                            = __('Step One: Select the Ticket for this registration',
2383
+					'event_espresso');
2384
+				$template_args['content']                          = EED_Ticket_Selector::instance()->display_ticket_selector($this->_reg_event);
2385
+				$template_args['step_button_text']                 = __('Add Tickets and Continue to Registrant Details',
2386
+					'event_espresso');
2387
+				$template_args['show_notification_toggle']         = false;
2388
+				break;
2389
+			case 'questions' :
2390
+				$hidden_fields['processing_registration']['value'] = 2;
2391
+				$template_args['title']                            = __('Step Two: Add Registrant Details for this Registration',
2392
+					'event_espresso');
2393
+				//in theory we should be able to run EED_SPCO at this point because the cart should have been setup properly by the first process_reg_step run.
2394
+				$template_args['content']                  = EED_Single_Page_Checkout::registration_checkout_for_admin();
2395
+				$template_args['step_button_text']         = __('Save Registration and Continue to Details',
2396
+					'event_espresso');
2397
+				$template_args['show_notification_toggle'] = true;
2398
+				break;
2399
+		}
2400
+		$this->_set_add_edit_form_tags('process_reg_step',
2401
+			$hidden_fields); //we come back to the process_registration_step route.
2402
+		return EEH_Template::display_template(REG_TEMPLATE_PATH
2403
+											  . 'reg_admin_register_new_attendee_step_content.template.php',
2404
+			$template_args, true);
2405
+	}
2406
+
2407
+
2408
+	/**
2409
+	 *        set_reg_event
2410
+	 *
2411
+	 * @access private
2412
+	 * @return boolean
2413
+	 */
2414
+	private function _set_reg_event()
2415
+	{
2416
+		if (is_object($this->_reg_event)) {
2417
+			return true;
2418
+		}
2419
+		$EVT_ID = ( ! empty($this->_req_data['event_id'])) ? absint($this->_req_data['event_id']) : false;
2420
+		if ( ! $EVT_ID) {
2421
+			return false;
2422
+		}
2423
+		$this->_reg_event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
2424
+		return true;
2425
+	}
2426
+
2427
+
2428
+	/**
2429
+	 * process_reg_step
2430
+	 *
2431
+	 * @access        public
2432
+	 * @return        string
2433
+	 * @throws \RuntimeException
2434
+	 * @throws \EE_Error
2435
+	 */
2436
+	public function process_reg_step()
2437
+	{
2438
+		EE_System::do_not_cache();
2439
+		$this->_set_reg_event();
2440
+		EE_Registry::instance()->REQ->set_espresso_page(true);
2441
+		EE_Registry::instance()->REQ->set('uts', time());
2442
+		//what step are we on?
2443
+		$cart = EE_Registry::instance()->SSN->cart();
2444
+		$step = ! $cart instanceof EE_Cart ? 'ticket' : 'questions';
2445
+		//if doing ajax then we need to verify the nonce
2446
+		if (defined('DOING_AJAX')) {
2447
+			$nonce = isset($this->_req_data[$this->_req_nonce])
2448
+				? sanitize_text_field($this->_req_data[$this->_req_nonce]) : '';
2449
+			$this->_verify_nonce($nonce, $this->_req_nonce);
2450
+		}
2451
+		switch ($step) {
2452
+			case 'ticket' :
2453
+				//process ticket selection
2454
+				$success = EED_Ticket_Selector::instance()->process_ticket_selections();
2455
+				if ($success) {
2456
+					EE_Error::add_success(esc_html__('Tickets Selected. Now complete the registration.',
2457
+						'event_espresso'));
2458
+				} else {
2459
+					$query_args['step_error'] = $this->_req_data['step_error'] = true;
2460
+				}
2461
+				if (defined('DOING_AJAX')) {
2462
+					$this->new_registration(); //display next step
2463
+				} else {
2464
+					$query_args = array(
2465
+						'action'                  => 'new_registration',
2466
+						'processing_registration' => 1,
2467
+						'event_id'                => $this->_reg_event->ID(),
2468
+						'uts'                     => time(),
2469
+					);
2470
+					$this->_redirect_after_action(false, '', '', $query_args, true);
2471
+				}
2472
+				break;
2473
+			case 'questions' :
2474
+				if ( ! isset($this->_req_data['txn_reg_status_change'], $this->_req_data['txn_reg_status_change']['send_notifications'])) {
2475
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_false', 15);
2476
+				}
2477
+				//process registration
2478
+				$transaction = EED_Single_Page_Checkout::instance()->process_registration_from_admin();
2479
+				if ($cart instanceof EE_Cart) {
2480
+					$grand_total = $cart->get_cart_grand_total();
2481
+					if ($grand_total instanceof EE_Line_Item) {
2482
+						$grand_total->save_this_and_descendants_to_txn();
2483
+					}
2484
+				}
2485
+				if ( ! $transaction instanceof EE_Transaction) {
2486
+					$query_args = array(
2487
+						'action'                  => 'new_registration',
2488
+						'processing_registration' => 2,
2489
+						'event_id'                => $this->_reg_event->ID(),
2490
+						'uts'                     => time(),
2491
+					);
2492
+					if (defined('DOING_AJAX')) {
2493
+						//display registration form again because there are errors (maybe validation?)
2494
+						$this->new_registration();
2495
+						return;
2496
+					} else {
2497
+						$this->_redirect_after_action(false, '', '', $query_args, true);
2498
+						return;
2499
+					}
2500
+				}
2501
+				// maybe update status, and make sure to save transaction if not done already
2502
+				if ( ! $transaction->update_status_based_on_total_paid()) {
2503
+					$transaction->save();
2504
+				}
2505
+				EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2506
+				$this->_req_data = array();
2507
+				$query_args      = array(
2508
+					'action'        => 'redirect_to_txn',
2509
+					'TXN_ID'        => $transaction->ID(),
2510
+					'EVT_ID'        => $this->_reg_event->ID(),
2511
+					'event_name'    => urlencode($this->_reg_event->name()),
2512
+					'redirect_from' => 'new_registration',
2513
+				);
2514
+				$this->_redirect_after_action(false, '', '', $query_args, true);
2515
+				break;
2516
+		}
2517
+		//what are you looking here for?  Should be nothing to do at this point.
2518
+	}
2519
+
2520
+
2521
+	/**
2522
+	 * redirect_to_txn
2523
+	 *
2524
+	 * @access public
2525
+	 * @return void
2526
+	 */
2527
+	public function redirect_to_txn()
2528
+	{
2529
+		EE_System::do_not_cache();
2530
+		EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
2531
+		$query_args = array(
2532
+			'action' => 'view_transaction',
2533
+			'TXN_ID' => isset($this->_req_data['TXN_ID']) ? absint($this->_req_data['TXN_ID']) : 0,
2534
+			'page'   => 'espresso_transactions',
2535
+		);
2536
+		if (isset($this->_req_data['EVT_ID'], $this->_req_data['redirect_from'])) {
2537
+			$query_args['EVT_ID']        = $this->_req_data['EVT_ID'];
2538
+			$query_args['event_name']    = urlencode($this->_req_data['event_name']);
2539
+			$query_args['redirect_from'] = $this->_req_data['redirect_from'];
2540
+		}
2541
+		EE_Error::add_success(__('Registration Created.  Please review the transaction and add any payments as necessary',
2542
+			'event_espresso'));
2543
+		$this->_redirect_after_action(false, '', '', $query_args, true);
2544
+	}
2545
+
2546
+
2547
+	/**
2548
+	 *        generates HTML for the Attendee Contact List
2549
+	 *
2550
+	 * @access protected
2551
+	 * @return void
2552
+	 */
2553
+	protected function _attendee_contact_list_table()
2554
+	{
2555
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2556
+		$this->_search_btn_label = __('Contacts', 'event_espresso');
2557
+		$this->display_admin_list_table_page_with_no_sidebar();
2558
+	}
2559
+
2560
+
2561
+	/**
2562
+	 *        get_attendees
2563
+	 *
2564
+	 * @param bool $count whether to return count or data.
2565
+	 * @access public
2566
+	 * @return array
2567
+	 */
2568
+	public function get_attendees($per_page, $count = false, $trash = false)
2569
+	{
2570
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2571
+		require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
2572
+		$ATT_MDL                    = EEM_Attendee::instance();
2573
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2574
+		switch ($this->_req_data['orderby']) {
2575
+			case 'ATT_ID':
2576
+				$orderby = 'ATT_ID';
2577
+				break;
2578
+			case 'ATT_fname':
2579
+				$orderby = 'ATT_fname';
2580
+				break;
2581
+			case 'ATT_email':
2582
+				$orderby = 'ATT_email';
2583
+				break;
2584
+			case 'ATT_city':
2585
+				$orderby = 'ATT_city';
2586
+				break;
2587
+			case 'STA_ID':
2588
+				$orderby = 'STA_ID';
2589
+				break;
2590
+			case 'CNT_ID':
2591
+				$orderby = 'CNT_ID';
2592
+				break;
2593
+			default:
2594
+				$orderby = 'ATT_lname';
2595
+		}
2596
+		$sort         = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
2597
+			: 'ASC';
2598
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
2599
+			? $this->_req_data['paged'] : 1;
2600
+		$per_page     = isset($per_page) && ! empty($per_page) ? $per_page : 10;
2601
+		$per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
2602
+			? $this->_req_data['perpage'] : $per_page;
2603
+		$_where       = array();
2604
+		if ( ! empty($this->_req_data['s'])) {
2605
+			$sstr         = '%' . $this->_req_data['s'] . '%';
2606
+			$_where['OR'] = array(
2607
+				'Registration.Event.EVT_name'       => array('LIKE', $sstr),
2608
+				'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
2609
+				'Registration.Event.EVT_short_desc' => array('LIKE', $sstr),
2610
+				'ATT_fname'                         => array('LIKE', $sstr),
2611
+				'ATT_lname'                         => array('LIKE', $sstr),
2612
+				'ATT_short_bio'                     => array('LIKE', $sstr),
2613
+				'ATT_email'                         => array('LIKE', $sstr),
2614
+				'ATT_address'                       => array('LIKE', $sstr),
2615
+				'ATT_address2'                      => array('LIKE', $sstr),
2616
+				'ATT_city'                          => array('LIKE', $sstr),
2617
+				'Country.CNT_name'                  => array('LIKE', $sstr),
2618
+				'State.STA_name'                    => array('LIKE', $sstr),
2619
+				'ATT_phone'                         => array('LIKE', $sstr),
2620
+				'Registration.REG_final_price'      => array('LIKE', $sstr),
2621
+				'Registration.REG_code'             => array('LIKE', $sstr),
2622
+				'Registration.REG_count'            => array('LIKE', $sstr),
2623
+				'Registration.REG_group_size'       => array('LIKE', $sstr),
2624
+			);
2625
+		}
2626
+		$offset = ($current_page - 1) * $per_page;
2627
+		$limit  = $count ? null : array($offset, $per_page);
2628
+		if ($trash) {
2629
+			$_where['status'] = array('!=', 'publish');
2630
+			$all_attendees    = $count
2631
+				? $ATT_MDL->count(array(
2632
+					$_where,
2633
+					'order_by' => array($orderby => $sort),
2634
+					'limit'    => $limit,
2635
+				), 'ATT_ID', true)
2636
+				: $ATT_MDL->get_all(array(
2637
+					$_where,
2638
+					'order_by' => array($orderby => $sort),
2639
+					'limit'    => $limit,
2640
+				));
2641
+		} else {
2642
+			$_where['status'] = array('IN', array('publish'));
2643
+			$all_attendees    = $count
2644
+				? $ATT_MDL->count(array(
2645
+					$_where,
2646
+					'order_by' => array($orderby => $sort),
2647
+					'limit'    => $limit,
2648
+				), 'ATT_ID', true)
2649
+				: $ATT_MDL->get_all(array(
2650
+					$_where,
2651
+					'order_by' => array($orderby => $sort),
2652
+					'limit'    => $limit,
2653
+				));
2654
+		}
2655
+		return $all_attendees;
2656
+	}
2657
+
2658
+
2659
+	/**
2660
+	 * This is just taking care of resending the registration confirmation
2661
+	 *
2662
+	 * @access protected
2663
+	 * @return void
2664
+	 */
2665
+	protected function _resend_registration()
2666
+	{
2667
+		$this->_process_resend_registration();
2668
+		$query_args = isset($this->_req_data['redirect_to'])
2669
+			? array('action' => $this->_req_data['redirect_to'], '_REG_ID' => $this->_req_data['_REG_ID'])
2670
+			: array(
2671
+				'action' => 'default',
2672
+			);
2673
+		$this->_redirect_after_action(false, '', '', $query_args, true);
2674
+	}
2675
+
2676
+	/**
2677
+	 * Creates a registration report, but accepts the name of a method to use for preparing the query parameters
2678
+	 * to use when selecting registrations
2679
+	 * @param string $method_name_for_getting_query_params the name of the method (on this class) to use for preparing
2680
+	 *                                                     the query parameters from the request
2681
+	 * @return void ends the request with a redirect or download
2682
+	 */
2683
+	public function _registrations_report_base( $method_name_for_getting_query_params )
2684
+	{
2685
+		if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
2686
+			wp_redirect(EE_Admin_Page::add_query_args_and_nonce(array(
2687
+				'page'        => 'espresso_batch',
2688
+				'batch'       => 'file',
2689
+				'EVT_ID'      => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
2690
+				'filters'     => urlencode(
2691
+					serialize(
2692
+						call_user_func(
2693
+							array( $this, $method_name_for_getting_query_params ),
2694
+							EEH_Array::is_set(
2695
+								$this->_req_data,
2696
+								'filters',
2697
+								array()
2698
+							)
2699
+						)
2700
+					)
2701
+				),
2702
+				'use_filters' => EEH_Array::is_set($this->_req_data, 'use_filters', false),
2703
+				'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\RegistrationsReport'),
2704
+				'return_url'  => urlencode($this->_req_data['return_url']),
2705
+			)));
2706
+		} else {
2707
+			$new_request_args = array(
2708
+				'export' => 'report',
2709
+				'action' => 'registrations_report_for_event',
2710
+				'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
2711
+			);
2712
+			$this->_req_data = array_merge($this->_req_data, $new_request_args);
2713
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2714
+				require_once(EE_CLASSES . 'EE_Export.class.php');
2715
+				$EE_Export = EE_Export::instance($this->_req_data);
2716
+				$EE_Export->export();
2717
+			}
2718
+		}
2719
+	}
2720
+
2721
+
2722
+
2723
+	/**
2724
+	 * Creates a registration report using only query parameters in the request
2725
+	 * @return void
2726
+	 */
2727
+	public function _registrations_report()
2728
+	{
2729
+		$this->_registrations_report_base( '_get_registration_query_parameters' );
2730
+	}
2731
+
2732
+
2733
+	public function _contact_list_export()
2734
+	{
2735
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2736
+			require_once(EE_CLASSES . 'EE_Export.class.php');
2737
+			$EE_Export = EE_Export::instance($this->_req_data);
2738
+			$EE_Export->export_attendees();
2739
+		}
2740
+	}
2741
+
2742
+
2743
+	public function _contact_list_report()
2744
+	{
2745
+		if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
2746
+			wp_redirect(EE_Admin_Page::add_query_args_and_nonce(array(
2747
+				'page'        => 'espresso_batch',
2748
+				'batch'       => 'file',
2749
+				'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\AttendeesReport'),
2750
+				'return_url'  => urlencode($this->_req_data['return_url']),
2751
+			)));
2752
+		} else {
2753
+			if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2754
+				require_once(EE_CLASSES . 'EE_Export.class.php');
2755
+				$EE_Export = EE_Export::instance($this->_req_data);
2756
+				$EE_Export->report_attendees();
2757
+			}
2758
+		}
2759
+	}
2760
+
2761
+
2762
+
2763
+
2764
+
2765
+	/***************************************        ATTENDEE DETAILS        ***************************************/
2766
+	/**
2767
+	 * This duplicates the attendee object for the given incoming registration id and attendee_id.
2768
+	 *
2769
+	 * @return void
2770
+	 */
2771
+	protected function _duplicate_attendee()
2772
+	{
2773
+		$action = ! empty($this->_req_data['return']) ? $this->_req_data['return'] : 'default';
2774
+		//verify we have necessary info
2775
+		if (empty($this->_req_data['_REG_ID'])) {
2776
+			EE_Error::add_error(__('Unable to create the contact for the registration because the required parameters are not present (_REG_ID )',
2777
+				'event_espresso'), __FILE__, __LINE__, __FUNCTION__);
2778
+			$query_args = array('action' => $action);
2779
+			$this->_redirect_after_action('', '', '', $query_args, true);
2780
+		}
2781
+		//okay necessary deets present... let's dupe the incoming attendee and attach to incoming registration.
2782
+		$registration = EEM_Registration::instance()->get_one_by_ID($this->_req_data['_REG_ID']);
2783
+		$attendee     = $registration->attendee();
2784
+		//remove relation of existing attendee on registration
2785
+		$registration->_remove_relation_to($attendee, 'Attendee');
2786
+		//new attendee
2787
+		$new_attendee = clone $attendee;
2788
+		$new_attendee->set('ATT_ID', 0);
2789
+		$new_attendee->save();
2790
+		//add new attendee to reg
2791
+		$registration->_add_relation_to($new_attendee, 'Attendee');
2792
+		EE_Error::add_success(__('New Contact record created.  Now make any edits you wish to make for this contact.',
2793
+			'event_espresso'));
2794
+		//redirect to edit page for attendee
2795
+		$query_args = array('post' => $new_attendee->ID(), 'action' => 'edit_attendee');
2796
+		$this->_redirect_after_action('', '', '', $query_args, true);
2797
+	}
2798
+
2799
+
2800
+	//related to cpt routes
2801
+	protected function _insert_update_cpt_item($post_id, $post)
2802
+	{
2803
+		$success  = true;
2804
+		$attendee = EEM_Attendee::instance()->get_one_by_ID($post_id);
2805
+		//for attendee updates
2806
+		if ($post->post_type = 'espresso_attendees' && ! empty($attendee)) {
2807
+			//note we should only be UPDATING attendees at this point.
2808
+			$updated_fields = array(
2809
+				'ATT_fname'     => $this->_req_data['ATT_fname'],
2810
+				'ATT_lname'     => $this->_req_data['ATT_lname'],
2811
+				'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
2812
+				'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
2813
+				'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
2814
+				'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
2815
+				'STA_ID'        => isset($this->_req_data['STA_ID']) ? $this->_req_data['STA_ID'] : '',
2816
+				'CNT_ISO'       => isset($this->_req_data['CNT_ISO']) ? $this->_req_data['CNT_ISO'] : '',
2817
+				'ATT_zip'       => isset($this->_req_data['ATT_zip']) ? $this->_req_data['ATT_zip'] : '',
2818
+				'ATT_email'     => isset($this->_req_data['ATT_email']) ? $this->_req_data['ATT_email'] : '',
2819
+				'ATT_phone'     => isset($this->_req_data['ATT_phone']) ? $this->_req_data['ATT_phone'] : '',
2820
+			);
2821
+			foreach ($updated_fields as $field => $value) {
2822
+				$attendee->set($field, $value);
2823
+			}
2824
+			$success                   = $attendee->save();
2825
+			$attendee_update_callbacks = apply_filters('FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update',
2826
+				array());
2827
+			foreach ($attendee_update_callbacks as $a_callback) {
2828
+				if (false === call_user_func_array($a_callback, array($attendee, $this->_req_data))) {
2829
+					throw new EE_Error(sprintf(__('The %s callback given for the "FHEE__Registrations_Admin_Page__insert_update_cpt_item__attendee_update" filter is not a valid callback.  Please check the spelling.',
2830
+						'event_espresso'), $a_callback));
2831
+				}
2832
+			}
2833
+		}
2834
+		if ($success === false) {
2835
+			EE_Error::add_error(__('Something went wrong with updating the meta table data for the registration.',
2836
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
2837
+		}
2838
+	}
2839
+
2840
+
2841
+	public function trash_cpt_item($post_id)
2842
+	{
2843
+	}
2844
+
2845
+
2846
+	public function delete_cpt_item($post_id)
2847
+	{
2848
+	}
2849
+
2850
+
2851
+	public function restore_cpt_item($post_id)
2852
+	{
2853
+	}
2854
+
2855
+
2856
+	protected function _restore_cpt_item($post_id, $revision_id)
2857
+	{
2858
+	}
2859
+
2860
+
2861
+	public function attendee_editor_metaboxes()
2862
+	{
2863
+		$this->verify_cpt_object();
2864
+		remove_meta_box('postexcerpt', __('Excerpt'), 'post_excerpt_meta_box', $this->_cpt_routes[$this->_req_action],
2865
+			'normal', 'core');
2866
+		remove_meta_box('commentstatusdiv', $this->_cpt_routes[$this->_req_action], 'normal', 'core');
2867
+		if (post_type_supports('espresso_attendees', 'excerpt')) {
2868
+			add_meta_box('postexcerpt', __('Short Biography', 'event_espresso'), 'post_excerpt_meta_box',
2869
+				$this->_cpt_routes[$this->_req_action], 'normal');
2870
+		}
2871
+		if (post_type_supports('espresso_attendees', 'comments')) {
2872
+			add_meta_box('commentsdiv', __('Notes on the Contact', 'event_espresso'), 'post_comment_meta_box',
2873
+				$this->_cpt_routes[$this->_req_action], 'normal', 'core');
2874
+		}
2875
+		add_meta_box('attendee_contact_info', __('Contact Info', 'event_espresso'),
2876
+			array($this, 'attendee_contact_info'), $this->_cpt_routes[$this->_req_action], 'side', 'core');
2877
+		add_meta_box('attendee_details_address', __('Address Details', 'event_espresso'),
2878
+			array($this, 'attendee_address_details'), $this->_cpt_routes[$this->_req_action], 'normal', 'core');
2879
+		add_meta_box('attendee_registrations', __('Registrations for this Contact', 'event_espresso'),
2880
+			array($this, 'attendee_registrations_meta_box'), $this->_cpt_routes[$this->_req_action], 'normal', 'high');
2881
+	}
2882
+
2883
+
2884
+	/**
2885
+	 * Metabox for attendee contact info
2886
+	 *
2887
+	 * @param  WP_Post $post wp post object
2888
+	 * @return string        attendee contact info ( and form )
2889
+	 */
2890
+	public function attendee_contact_info($post)
2891
+	{
2892
+		//get attendee object ( should already have it )
2893
+		$this->_template_args['attendee'] = $this->_cpt_model_obj;
2894
+		$template                         = REG_TEMPLATE_PATH . 'attendee_contact_info_metabox_content.template.php';
2895
+		EEH_Template::display_template($template, $this->_template_args);
2896
+	}
2897
+
2898
+
2899
+	/**
2900
+	 * Metabox for attendee details
2901
+	 *
2902
+	 * @param  WP_Post $post wp post object
2903
+	 * @return string        attendee address details (and form)
2904
+	 */
2905
+	public function attendee_address_details($post)
2906
+	{
2907
+		//get attendee object (should already have it)
2908
+		$this->_template_args['attendee']     = $this->_cpt_model_obj;
2909
+		$this->_template_args['state_html']   = EEH_Form_Fields::generate_form_input(new EE_Question_Form_Input(EE_Question::new_instance(array(
2910
+			'QST_ID'           => 0,
2911
+			'QST_display_text' => __('State/Province', 'event_espresso'),
2912
+			'QST_system'       => 'admin-state',
2913
+		)), EE_Answer::new_instance(array(
2914
+			'ANS_ID'    => 0,
2915
+			'ANS_value' => $this->_cpt_model_obj->state_ID(),
2916
+		)), array(
2917
+			'input_id'       => 'STA_ID',
2918
+			'input_name'     => 'STA_ID',
2919
+			'input_prefix'   => '',
2920
+			'append_qstn_id' => false,
2921
+		)));
2922
+		$this->_template_args['country_html'] = EEH_Form_Fields::generate_form_input(new EE_Question_Form_Input(EE_Question::new_instance(array(
2923
+			'QST_ID'           => 0,
2924
+			'QST_display_text' => __('Country', 'event_espresso'),
2925
+			'QST_system'       => 'admin-country',
2926
+		)), EE_Answer::new_instance(array(
2927
+			'ANS_ID'    => 0,
2928
+			'ANS_value' => $this->_cpt_model_obj->country_ID(),
2929
+		)), array(
2930
+			'input_id'       => 'CNT_ISO',
2931
+			'input_name'     => 'CNT_ISO',
2932
+			'input_prefix'   => '',
2933
+			'append_qstn_id' => false,
2934
+		)));
2935
+		$template                             = REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
2936
+		EEH_Template::display_template($template, $this->_template_args);
2937
+	}
2938
+
2939
+
2940
+	/**
2941
+	 *        _attendee_details
2942
+	 *
2943
+	 * @access protected
2944
+	 * @return void
2945
+	 */
2946
+	public function attendee_registrations_meta_box($post)
2947
+	{
2948
+		$this->_template_args['attendee']      = $this->_cpt_model_obj;
2949
+		$this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
2950
+		$template                              = REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
2951
+		EEH_Template::display_template($template, $this->_template_args);
2952
+	}
2953
+
2954
+
2955
+	/**
2956
+	 * add in the form fields for the attendee edit
2957
+	 *
2958
+	 * @param  WP_Post $post wp post object
2959
+	 * @return string        html for new form.
2960
+	 */
2961
+	public function after_title_form_fields($post)
2962
+	{
2963
+		if ($post->post_type == 'espresso_attendees') {
2964
+			$template                  = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
2965
+			$template_args['attendee'] = $this->_cpt_model_obj;
2966
+			EEH_Template::display_template($template, $template_args);
2967
+		}
2968
+	}
2969
+
2970
+
2971
+	/**
2972
+	 *        _trash_or_restore_attendee
2973
+	 *
2974
+	 * @param boolean $trash - whether to move item to trash (TRUE) or restore it (FALSE)
2975
+	 * @access protected
2976
+	 * @return void
2977
+	 */
2978
+	protected function _trash_or_restore_attendees($trash = true)
2979
+	{
2980
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2981
+		$ATT_MDL = EEM_Attendee::instance();
2982
+		$success = 1;
2983
+		//Checkboxes
2984
+		if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
2985
+			// if array has more than one element than success message should be plural
2986
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
2987
+			// cycle thru checkboxes
2988
+			while (list($ATT_ID, $value) = each($this->_req_data['checkbox'])) {
2989
+				$updated = $trash ? $ATT_MDL->update_by_ID(array('status' => 'trash'), $ATT_ID)
2990
+					: $ATT_MDL->update_by_ID(array('status' => 'publish'), $ATT_ID);
2991
+				if ( ! $updated) {
2992
+					$success = 0;
2993
+				}
2994
+			}
2995
+		} else {
2996
+			// grab single id and delete
2997
+			$ATT_ID = absint($this->_req_data['ATT_ID']);
2998
+			//get attendee
2999
+			$att     = $ATT_MDL->get_one_by_ID($ATT_ID);
3000
+			$updated = $trash ? $att->set_status('trash') : $att->set_status('publish');
3001
+			$updated = $att->save();
3002
+			if ( ! $updated) {
3003
+				$success = 0;
3004
+			}
3005
+		}
3006
+		$what        = $success > 1 ? __('Contacts', 'event_espresso') : __('Contact', 'event_espresso');
3007
+		$action_desc = $trash ? __('moved to the trash', 'event_espresso') : __('restored', 'event_espresso');
3008
+		$this->_redirect_after_action($success, $what, $action_desc, array('action' => 'contact_list'));
3009
+	}
3010 3010
 
3011 3011
 }
3012 3012
 
Please login to merge, or discard this patch.
Spacing   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -569,11 +569,11 @@  discard block
 block discarded – undo
569 569
     {
570 570
         //style
571 571
         //wp_register_style('espresso_attendees', ATT_ASSETS_URL . 'espresso_attendees_admin.css', array(), EVENT_ESPRESSO_VERSION );
572
-        wp_register_style('espresso_reg', REG_ASSETS_URL . 'espresso_registrations_admin.css', array('ee-admin-css'),
572
+        wp_register_style('espresso_reg', REG_ASSETS_URL.'espresso_registrations_admin.css', array('ee-admin-css'),
573 573
             EVENT_ESPRESSO_VERSION);
574 574
         wp_enqueue_style('espresso_reg');
575 575
         //script
576
-        wp_register_script('espresso_reg', REG_ASSETS_URL . 'espresso_registrations_admin.js',
576
+        wp_register_script('espresso_reg', REG_ASSETS_URL.'espresso_registrations_admin.js',
577 577
             array('jquery-ui-datepicker', 'jquery-ui-draggable', 'ee_admin_js'), EVENT_ESPRESSO_VERSION, true);
578 578
         wp_enqueue_script('espresso_reg');
579 579
     }
@@ -604,7 +604,7 @@  discard block
 block discarded – undo
604 604
     public function load_scripts_styles_contact_list()
605 605
     {
606 606
         wp_deregister_style('espresso_reg');
607
-        wp_register_style('espresso_att', REG_ASSETS_URL . 'espresso_attendees_admin.css', array('ee-admin-css'),
607
+        wp_register_style('espresso_att', REG_ASSETS_URL.'espresso_attendees_admin.css', array('ee-admin-css'),
608 608
             EVENT_ESPRESSO_VERSION);
609 609
         wp_enqueue_style('espresso_att');
610 610
     }
@@ -612,7 +612,7 @@  discard block
 block discarded – undo
612 612
 
613 613
     public function load_scripts_styles_new_registration()
614 614
     {
615
-        wp_register_script('ee-spco-for-admin', REG_ASSETS_URL . 'spco_for_admin.js', array('underscore', 'jquery'),
615
+        wp_register_script('ee-spco-for-admin', REG_ASSETS_URL.'spco_for_admin.js', array('underscore', 'jquery'),
616 616
             EVENT_ESPRESSO_VERSION, true);
617 617
         wp_enqueue_script('ee-spco-for-admin');
618 618
         add_filter('FHEE__EED_Ticket_Selector__load_tckt_slctr_assets', '__return_true');
@@ -722,7 +722,7 @@  discard block
 block discarded – undo
722 722
                     'trash_registrations' => __('Trash Registrations', 'event_espresso'),
723 723
                 ),
724 724
             );
725
-            $this->_views['trash']      = array(
725
+            $this->_views['trash'] = array(
726 726
                 'slug'        => 'trash',
727 727
                 'label'       => __('Trash', 'event_espresso'),
728 728
                 'count'       => 0,
@@ -807,31 +807,31 @@  discard block
 block discarded – undo
807 807
         }
808 808
         $sc_items = array(
809 809
             'approved_status'   => array(
810
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
810
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_approved,
811 811
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
812 812
             ),
813 813
             'pending_status'    => array(
814
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
814
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_pending_payment,
815 815
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
816 816
             ),
817 817
             'wait_list'         => array(
818
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
818
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_wait_list,
819 819
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
820 820
             ),
821 821
             'incomplete_status' => array(
822
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_incomplete,
822
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_incomplete,
823 823
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_incomplete, false, 'sentence'),
824 824
             ),
825 825
             'not_approved'      => array(
826
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
826
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_not_approved,
827 827
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
828 828
             ),
829 829
             'declined_status'   => array(
830
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
830
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_declined,
831 831
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
832 832
             ),
833 833
             'cancelled_status'  => array(
834
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
834
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_cancelled,
835 835
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
836 836
             ),
837 837
         );
@@ -852,17 +852,17 @@  discard block
 block discarded – undo
852 852
             if (EE_Registry::instance()->CAP->current_user_can('ee_edit_registrations',
853 853
                 'espresso_registrations_new_registration', $EVT_ID)
854 854
             ) {
855
-                $this->_admin_page_title .= ' ' . $this->get_action_link_or_button('new_registration', 'add-registrant',
855
+                $this->_admin_page_title .= ' '.$this->get_action_link_or_button('new_registration', 'add-registrant',
856 856
                         array('event_id' => $EVT_ID), 'add-new-h2');
857 857
             }
858 858
             $event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
859 859
             if ($event instanceof EE_Event) {
860 860
                 $this->_template_args['admin_page_header'] = sprintf(__('%s Viewing registrations for the event: %s%s',
861 861
                     'event_espresso'), '<h3 style="line-height:1.5em;">',
862
-                    '<br /><a href="' . EE_Admin_Page::add_query_args_and_nonce(array(
862
+                    '<br /><a href="'.EE_Admin_Page::add_query_args_and_nonce(array(
863 863
                         'action' => 'edit',
864 864
                         'post'   => $event->ID(),
865
-                    ), EVENTS_ADMIN_URL) . '">&nbsp;' . $event->get('EVT_name') . '&nbsp;</a>&nbsp;', '</h3>');
865
+                    ), EVENTS_ADMIN_URL).'">&nbsp;'.$event->get('EVT_name').'&nbsp;</a>&nbsp;', '</h3>');
866 866
             }
867 867
             $DTT_ID   = ! empty($this->_req_data['datetime_id']) ? absint($this->_req_data['datetime_id']) : 0;
868 868
             $datetime = EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
@@ -871,7 +871,7 @@  discard block
 block discarded – undo
871 871
                 $this->_template_args['admin_page_header'] .= ' &nbsp;<span class="drk-grey-text">';
872 872
                 $this->_template_args['admin_page_header'] .= '<span class="dashicons dashicons-calendar"></span>';
873 873
                 $this->_template_args['admin_page_header'] .= $datetime->name();
874
-                $this->_template_args['admin_page_header'] .= ' ( ' . $datetime->start_date() . ' )';
874
+                $this->_template_args['admin_page_header'] .= ' ( '.$datetime->start_date().' )';
875 875
                 $this->_template_args['admin_page_header'] .= '</span></h3>';
876 876
             }
877 877
         }
@@ -921,10 +921,10 @@  discard block
 block discarded – undo
921 921
         $this_month = false,
922 922
         $today = false
923 923
     ) {
924
-        if( $this_month ) {
924
+        if ($this_month) {
925 925
             $this->_req_data['status'] = 'month';
926 926
         }
927
-        if( $today ) {
927
+        if ($today) {
928 928
             $this->_req_data['status'] = 'today';
929 929
         }
930 930
         $query_params = $this->_get_registration_query_parameters($this->_req_data, $per_page, $count);
@@ -995,7 +995,7 @@  discard block
 block discarded – undo
995 995
     protected function _add_category_id_to_where_conditions(array $request)
996 996
     {
997 997
         $where = array();
998
-        if ( ! empty($request['EVT_CAT']) && (int)$request['EVT_CAT'] !== -1) {
998
+        if ( ! empty($request['EVT_CAT']) && (int) $request['EVT_CAT'] !== -1) {
999 999
             $where['Event.Term_Taxonomy.term_id'] = absint($request['EVT_CAT']);
1000 1000
         }
1001 1001
         return $where;
@@ -1014,7 +1014,7 @@  discard block
 block discarded – undo
1014 1014
         if ( ! empty($request['datetime_id'])) {
1015 1015
             $where['Ticket.Datetime.DTT_ID'] = absint($request['datetime_id']);
1016 1016
         }
1017
-        if( ! empty($request['DTT_ID'])){
1017
+        if ( ! empty($request['DTT_ID'])) {
1018 1018
             $where['Ticket.Datetime.DTT_ID'] = absint($request['DTT_ID']);
1019 1019
         }
1020 1020
         return $where;
@@ -1030,7 +1030,7 @@  discard block
 block discarded – undo
1030 1030
     protected function _add_registration_status_to_where_conditions(array $request)
1031 1031
     {
1032 1032
         $where = array();
1033
-        $view  = EEH_Array::is_set( $request, 'status', '' );
1033
+        $view  = EEH_Array::is_set($request, 'status', '');
1034 1034
         $registration_status = ! empty($request['_reg_status'])
1035 1035
             ? sanitize_text_field($request['_reg_status'])
1036 1036
             : '';
@@ -1065,7 +1065,7 @@  discard block
 block discarded – undo
1065 1065
     protected function _add_date_to_where_conditions(array $request)
1066 1066
     {
1067 1067
         $where = array();
1068
-        $view  = EEH_Array::is_set( $request, 'status', '' );
1068
+        $view  = EEH_Array::is_set($request, 'status', '');
1069 1069
         $month_range             = ! empty($request['month_range'])
1070 1070
             ? sanitize_text_field($request['month_range'])
1071 1071
             : '';
@@ -1079,12 +1079,12 @@  discard block
 block discarded – undo
1079 1079
                 array(
1080 1080
                     EEM_Registration::instance()->convert_datetime_for_query(
1081 1081
                         'REG_date',
1082
-                        $now . ' 00:00:00',
1082
+                        $now.' 00:00:00',
1083 1083
                         'Y-m-d H:i:s'
1084 1084
                     ),
1085 1085
                     EEM_Registration::instance()->convert_datetime_for_query(
1086 1086
                         'REG_date',
1087
-                        $now . ' 23:59:59',
1087
+                        $now.' 23:59:59',
1088 1088
                         'Y-m-d H:i:s'
1089 1089
                     ),
1090 1090
                 ),
@@ -1097,12 +1097,12 @@  discard block
 block discarded – undo
1097 1097
                 array(
1098 1098
                     EEM_Registration::instance()->convert_datetime_for_query(
1099 1099
                         'REG_date',
1100
-                        $current_year_and_month . '-01 00:00:00',
1100
+                        $current_year_and_month.'-01 00:00:00',
1101 1101
                         'Y-m-d H:i:s'
1102 1102
                     ),
1103 1103
                     EEM_Registration::instance()->convert_datetime_for_query(
1104 1104
                         'REG_date',
1105
-                        $current_year_and_month . '-' . $days_this_month . ' 23:59:59',
1105
+                        $current_year_and_month.'-'.$days_this_month.' 23:59:59',
1106 1106
                         'Y-m-d H:i:s'
1107 1107
                     ),
1108 1108
                 ),
@@ -1117,18 +1117,18 @@  discard block
 block discarded – undo
1117 1117
                 : '';
1118 1118
             //if there is not a month or year then we can't go further
1119 1119
             if ($month_requested && $year_requested) {
1120
-                $days_in_month     = date('t', strtotime($year_requested . '-' . $month_requested . '-' . '01'));
1120
+                $days_in_month     = date('t', strtotime($year_requested.'-'.$month_requested.'-'.'01'));
1121 1121
                 $where['REG_date'] = array(
1122 1122
                     'BETWEEN',
1123 1123
                     array(
1124 1124
                         EEM_Registration::instance()->convert_datetime_for_query(
1125 1125
                             'REG_date',
1126
-                            $year_requested . '-' . $month_requested . '-01 00:00:00',
1126
+                            $year_requested.'-'.$month_requested.'-01 00:00:00',
1127 1127
                             'Y-m-d H:i:s'
1128 1128
                         ),
1129 1129
                         EEM_Registration::instance()->convert_datetime_for_query(
1130 1130
                             'REG_date',
1131
-                            $year_requested . '-' . $month_requested . '-' . $days_in_month . ' 23:59:59',
1131
+                            $year_requested.'-'.$month_requested.'-'.$days_in_month.' 23:59:59',
1132 1132
                             'Y-m-d H:i:s'
1133 1133
                         ),
1134 1134
                     ),
@@ -1149,7 +1149,7 @@  discard block
 block discarded – undo
1149 1149
     {
1150 1150
         $where = array();
1151 1151
         if ( ! empty($request['s'])) {
1152
-            $search_string = '%' . sanitize_text_field($request['s']) . '%';
1152
+            $search_string = '%'.sanitize_text_field($request['s']).'%';
1153 1153
             $where['OR'] = array(
1154 1154
                 'Event.EVT_name'                          => array('LIKE', $search_string),
1155 1155
                 'Event.EVT_desc'                          => array('LIKE', $search_string),
@@ -1251,7 +1251,7 @@  discard block
 block discarded – undo
1251 1251
             : $per_page;
1252 1252
 
1253 1253
         //-1 means return all results so get out if that's set.
1254
-        if ((int)$per_page === -1) {
1254
+        if ((int) $per_page === -1) {
1255 1255
             return array();
1256 1256
         }
1257 1257
         $per_page = absint($per_page);
@@ -1297,12 +1297,12 @@  discard block
 block discarded – undo
1297 1297
                 'action'   => 'default',
1298 1298
                 'event_id' => $event_id,
1299 1299
             ), REG_ADMIN_URL);
1300
-            $this->_template_args['filtered_transactions_link']  = EE_Admin_Page::add_query_args_and_nonce(array(
1300
+            $this->_template_args['filtered_transactions_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
1301 1301
                 'action' => 'default',
1302 1302
                 'EVT_ID' => $event_id,
1303 1303
                 'page'   => 'espresso_transactions',
1304 1304
             ), admin_url('admin.php'));
1305
-            $this->_template_args['event_link']                  = EE_Admin_Page::add_query_args_and_nonce(array(
1305
+            $this->_template_args['event_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
1306 1306
                 'page'   => 'espresso_events',
1307 1307
                 'action' => 'edit',
1308 1308
                 'post'   => $event_id,
@@ -1321,7 +1321,7 @@  discard block
 block discarded – undo
1321 1321
                     '_REG_ID' => $previous_reg['REG_ID'],
1322 1322
                 ), REG_ADMIN_URL), 'dashicons dashicons-arrow-left ee-icon-size-22') : '';
1323 1323
             // grab header
1324
-            $template_path                             = REG_TEMPLATE_PATH . 'reg_admin_details_header.template.php';
1324
+            $template_path                             = REG_TEMPLATE_PATH.'reg_admin_details_header.template.php';
1325 1325
             $this->_template_args['REG_ID']            = $this->_registration->ID();
1326 1326
             $this->_template_args['admin_page_header'] = EEH_Template::display_template($template_path,
1327 1327
                 $this->_template_args, true);
@@ -1395,8 +1395,8 @@  discard block
 block discarded – undo
1395 1395
                     'default' => $this->_registration->ID(),
1396 1396
                 )),
1397 1397
                 'current_status'     => new EE_Form_Section_HTML(EEH_HTML::tr(EEH_HTML::th(EEH_HTML::label(EEH_HTML::strong(__('Current Registration Status',
1398
-                        'event_espresso')))) . EEH_HTML::td(EEH_HTML::strong($this->_registration->pretty_status(),
1399
-                        '', 'status-' . $this->_registration->status_ID(),
1398
+                        'event_espresso')))).EEH_HTML::td(EEH_HTML::strong($this->_registration->pretty_status(),
1399
+                        '', 'status-'.$this->_registration->status_ID(),
1400 1400
                         'line-height: 1em; font-size: 1.5em; font-weight: bold;')))),
1401 1401
                 'reg_status'         => new EE_Select_Input($this->_get_reg_statuses(), array(
1402 1402
                     'html_label_text' => __('Change Registration Status to', 'event_espresso'),
@@ -1452,9 +1452,9 @@  discard block
 block discarded – undo
1452 1452
     {
1453 1453
         if (isset($this->_req_data['reg_status_change_form'])) {
1454 1454
             $REG_IDs = isset($this->_req_data['reg_status_change_form']['REG_ID'])
1455
-                ? (array)$this->_req_data['reg_status_change_form']['REG_ID'] : array();
1455
+                ? (array) $this->_req_data['reg_status_change_form']['REG_ID'] : array();
1456 1456
         } else {
1457
-            $REG_IDs = isset($this->_req_data['_REG_ID']) ? (array)$this->_req_data['_REG_ID'] : array();
1457
+            $REG_IDs = isset($this->_req_data['_REG_ID']) ? (array) $this->_req_data['_REG_ID'] : array();
1458 1458
         }
1459 1459
         $success = $this->_set_registration_status($REG_IDs, $status);
1460 1460
         //notify?
@@ -1482,7 +1482,7 @@  discard block
 block discarded – undo
1482 1482
     {
1483 1483
         $success = false;
1484 1484
         // typecast $REG_IDs
1485
-        $REG_IDs = (array)$REG_IDs;
1485
+        $REG_IDs = (array) $REG_IDs;
1486 1486
         if ( ! empty($REG_IDs)) {
1487 1487
             $success = true;
1488 1488
             // set default status if none is passed
@@ -1775,7 +1775,7 @@  discard block
 block discarded – undo
1775 1775
         ), REG_ADMIN_URL);
1776 1776
         $this->_template_args['REG_ID']                                       = $this->_registration->ID();
1777 1777
         $this->_template_args['event_id']                                     = $this->_registration->event_ID();
1778
-        $template_path                                                        = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_details.template.php';
1778
+        $template_path                                                        = REG_TEMPLATE_PATH.'reg_admin_details_main_meta_box_reg_details.template.php';
1779 1779
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
1780 1780
     }
1781 1781
 
@@ -1797,7 +1797,7 @@  discard block
 block discarded – undo
1797 1797
             $this->_template_args['att_questions']             = count($form->subforms()) > 0 ? $form->get_html_and_js() : '';
1798 1798
             $this->_template_args['reg_questions_form_action'] = 'edit_registration';
1799 1799
             $this->_template_args['REG_ID']                    = $this->_registration->ID();
1800
-            $template_path                                     = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_reg_questions.template.php';
1800
+            $template_path                                     = REG_TEMPLATE_PATH.'reg_admin_details_main_meta_box_reg_questions.template.php';
1801 1801
             echo EEH_Template::display_template($template_path, $this->_template_args, true);
1802 1802
         }
1803 1803
     }
@@ -1813,7 +1813,7 @@  discard block
 block discarded – undo
1813 1813
      */
1814 1814
     public function form_before_question_group($output)
1815 1815
     {
1816
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1816
+        EE_Error::doing_it_wrong(__CLASS__.'::'.__FUNCTION__,
1817 1817
             __('This method would have been protected but was used on a filter callback'
1818 1818
                . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1819 1819
             '4.8.32.rc.000');
@@ -1834,7 +1834,7 @@  discard block
 block discarded – undo
1834 1834
      */
1835 1835
     public function form_after_question_group($output)
1836 1836
     {
1837
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1837
+        EE_Error::doing_it_wrong(__CLASS__.'::'.__FUNCTION__,
1838 1838
             __('This method would have been protected but was used on a filter callback'
1839 1839
                . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1840 1840
             '4.8.32.rc.000');
@@ -1868,14 +1868,14 @@  discard block
 block discarded – undo
1868 1868
      */
1869 1869
     public function form_form_field_label_wrap($label)
1870 1870
     {
1871
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1871
+        EE_Error::doing_it_wrong(__CLASS__.'::'.__FUNCTION__,
1872 1872
             __('This method would have been protected but was used on a filter callback'
1873 1873
                . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1874 1874
             '4.8.32.rc.000');
1875 1875
         return '
1876 1876
 			<tr>
1877 1877
 				<th>
1878
-					' . $label . '
1878
+					' . $label.'
1879 1879
 				</th>';
1880 1880
     }
1881 1881
 
@@ -1890,13 +1890,13 @@  discard block
 block discarded – undo
1890 1890
      */
1891 1891
     public function form_form_field_input__wrap($input)
1892 1892
     {
1893
-        EE_Error::doing_it_wrong(__CLASS__ . '::' . __FUNCTION__,
1893
+        EE_Error::doing_it_wrong(__CLASS__.'::'.__FUNCTION__,
1894 1894
             __('This method would have been protected but was used on a filter callback'
1895 1895
                . 'so needed to be public. Please discontinue usage as it will be removed soon.', 'event_espresso'),
1896 1896
             '4.8.32.rc.000');
1897 1897
         return '
1898 1898
 				<td class="reg-admin-attendee-questions-input-td disabled-input">
1899
-					' . $input . '
1899
+					' . $input.'
1900 1900
 				</td>
1901 1901
 			</tr>';
1902 1902
     }
@@ -1936,7 +1936,7 @@  discard block
 block discarded – undo
1936 1936
     protected function _get_reg_custom_questions_form($REG_ID)
1937 1937
     {
1938 1938
         if ( ! $this->_reg_custom_questions_form) {
1939
-            require_once(REG_ADMIN . 'form_sections' . DS . 'EE_Registration_Custom_Questions_Form.form.php');
1939
+            require_once(REG_ADMIN.'form_sections'.DS.'EE_Registration_Custom_Questions_Form.form.php');
1940 1940
             $this->_reg_custom_questions_form = new EE_Registration_Custom_Questions_Form(EEM_Registration::instance()
1941 1941
                                                                                                           ->get_one_by_ID($REG_ID));
1942 1942
             $this->_reg_custom_questions_form->_construct_finalize(null, null);
@@ -1964,7 +1964,7 @@  discard block
 block discarded – undo
1964 1964
         if ($form->is_valid()) {
1965 1965
             foreach ($form->subforms() as $question_group_id => $question_group_form) {
1966 1966
                 foreach ($question_group_form->inputs() as $question_id => $input) {
1967
-                    $where_conditions    = array(
1967
+                    $where_conditions = array(
1968 1968
                         'QST_ID' => $question_id,
1969 1969
                         'REG_ID' => $REG_ID,
1970 1970
                     );
@@ -2000,7 +2000,7 @@  discard block
 block discarded – undo
2000 2000
         $REG = EEM_Registration::instance();
2001 2001
         //get all other registrations on this transaction, and cache
2002 2002
         //the attendees for them so we don't have to run another query using force_join
2003
-        $registrations                           = $REG->get_all(array(
2003
+        $registrations = $REG->get_all(array(
2004 2004
             array(
2005 2005
                 'TXN_ID' => $this->_registration->transaction_ID(),
2006 2006
                 'REG_ID' => array('!=', $this->_registration->ID()),
@@ -2020,29 +2020,29 @@  discard block
 block discarded – undo
2020 2020
             $att_nmbr = 1;
2021 2021
             foreach ($registrations as $registration) {
2022 2022
                 /* @var $registration EE_Registration */
2023
-                $attendee                                                    = $registration->attendee()
2023
+                $attendee = $registration->attendee()
2024 2024
                     ? $registration->attendee()
2025 2025
                     : EEM_Attendee::instance()
2026 2026
                                   ->create_default_object();
2027 2027
                 $this->_template_args['attendees'][$att_nmbr]['STS_ID']      = $registration->status_ID();
2028
-                $this->_template_args['attendees'][$att_nmbr]['fname']       = $attendee->fname();//( isset( $registration->ATT_fname ) & ! empty( $registration->ATT_fname ) ) ? $registration->ATT_fname : '';
2029
-                $this->_template_args['attendees'][$att_nmbr]['lname']       = $attendee->lname();//( isset( $registration->ATT_lname ) & ! empty( $registration->ATT_lname ) ) ? $registration->ATT_lname : '';
2030
-                $this->_template_args['attendees'][$att_nmbr]['email']       = $attendee->email();//( isset( $registration->ATT_email ) & ! empty( $registration->ATT_email ) ) ? $registration->ATT_email : '';
2031
-                $this->_template_args['attendees'][$att_nmbr]['final_price'] = $registration->final_price();//( isset( $registration->REG_final_price ) & ! empty( $registration->REG_final_price ) ) ? $registration->REG_final_price : '';
2028
+                $this->_template_args['attendees'][$att_nmbr]['fname']       = $attendee->fname(); //( isset( $registration->ATT_fname ) & ! empty( $registration->ATT_fname ) ) ? $registration->ATT_fname : '';
2029
+                $this->_template_args['attendees'][$att_nmbr]['lname']       = $attendee->lname(); //( isset( $registration->ATT_lname ) & ! empty( $registration->ATT_lname ) ) ? $registration->ATT_lname : '';
2030
+                $this->_template_args['attendees'][$att_nmbr]['email']       = $attendee->email(); //( isset( $registration->ATT_email ) & ! empty( $registration->ATT_email ) ) ? $registration->ATT_email : '';
2031
+                $this->_template_args['attendees'][$att_nmbr]['final_price'] = $registration->final_price(); //( isset( $registration->REG_final_price ) & ! empty( $registration->REG_final_price ) ) ? $registration->REG_final_price : '';
2032 2032
                 $this->_template_args['attendees'][$att_nmbr]['address']     = implode(', ',
2033 2033
                     $attendee->full_address_as_array());
2034 2034
                 $this->_template_args['attendees'][$att_nmbr]['att_link']    = self::add_query_args_and_nonce(array(
2035 2035
                     'action' => 'edit_attendee',
2036 2036
                     'post'   => $attendee->ID(),
2037 2037
                 ), REG_ADMIN_URL);
2038
-                $this->_template_args['attendees'][$att_nmbr]['event_name']  = $registration->event_obj()->name();
2038
+                $this->_template_args['attendees'][$att_nmbr]['event_name'] = $registration->event_obj()->name();
2039 2039
                 $att_nmbr++;
2040 2040
             }
2041 2041
             //EEH_Debug_Tools::printr( $attendees, '$attendees  <br /><span style="font-size:10px;font-weight:normal;">( file: '. __FILE__ . ' - line no: ' . __LINE__ . ' )</span>', 'auto' );
2042 2042
             $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
2043 2043
             //			$this->_template_args['registration_form_url'] = add_query_arg( array( 'action' => 'edit_registration', 'process' => 'attendees'  ), REG_ADMIN_URL );
2044 2044
         }
2045
-        $template_path = REG_TEMPLATE_PATH . 'reg_admin_details_main_meta_box_attendees.template.php';
2045
+        $template_path = REG_TEMPLATE_PATH.'reg_admin_details_main_meta_box_attendees.template.php';
2046 2046
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
2047 2047
     }
2048 2048
 
@@ -2071,26 +2071,26 @@  discard block
 block discarded – undo
2071 2071
             $primary_registration = null;
2072 2072
         }
2073 2073
         $this->_template_args['ATT_ID']            = $attendee->ID();
2074
-        $this->_template_args['fname']             = $attendee->fname();//$this->_registration->ATT_fname;
2075
-        $this->_template_args['lname']             = $attendee->lname();//$this->_registration->ATT_lname;
2076
-        $this->_template_args['email']             = $attendee->email();//$this->_registration->ATT_email;
2074
+        $this->_template_args['fname']             = $attendee->fname(); //$this->_registration->ATT_fname;
2075
+        $this->_template_args['lname']             = $attendee->lname(); //$this->_registration->ATT_lname;
2076
+        $this->_template_args['email']             = $attendee->email(); //$this->_registration->ATT_email;
2077 2077
         $this->_template_args['phone']             = $attendee->phone();
2078 2078
         $this->_template_args['formatted_address'] = EEH_Address::format($attendee);
2079 2079
         //edit link
2080
-        $this->_template_args['att_edit_link']  = EE_Admin_Page::add_query_args_and_nonce(array(
2080
+        $this->_template_args['att_edit_link'] = EE_Admin_Page::add_query_args_and_nonce(array(
2081 2081
             'action' => 'edit_attendee',
2082 2082
             'post'   => $attendee->ID(),
2083 2083
         ), REG_ADMIN_URL);
2084 2084
         $this->_template_args['att_edit_label'] = __('View/Edit Contact', 'event_espresso');
2085 2085
         //create link
2086
-        $this->_template_args['create_link']  = $primary_registration instanceof EE_Registration
2086
+        $this->_template_args['create_link'] = $primary_registration instanceof EE_Registration
2087 2087
             ? EE_Admin_Page::add_query_args_and_nonce(array(
2088 2088
                 'action'  => 'duplicate_attendee',
2089 2089
                 '_REG_ID' => $this->_registration->ID(),
2090 2090
             ), REG_ADMIN_URL) : '';
2091 2091
         $this->_template_args['create_label'] = __('Create Contact', 'event_espresso');
2092 2092
         $this->_template_args['att_check']    = $att_check;
2093
-        $template_path                        = REG_TEMPLATE_PATH . 'reg_admin_details_side_meta_box_registrant.template.php';
2093
+        $template_path                        = REG_TEMPLATE_PATH.'reg_admin_details_side_meta_box_registrant.template.php';
2094 2094
         echo EEH_Template::display_template($template_path, $this->_template_args, true);
2095 2095
     }
2096 2096
 
@@ -2304,7 +2304,7 @@  discard block
 block discarded – undo
2304 2304
                 'action' => 'edit',
2305 2305
                 'post'   => $this->_reg_event->ID(),
2306 2306
             ), EVENTS_ADMIN_URL);
2307
-            $edit_event_lnk                     = '<a href="'
2307
+            $edit_event_lnk = '<a href="'
2308 2308
                                                   . $edit_event_url
2309 2309
                                                   . '" title="'
2310 2310
                                                   . esc_attr__('Edit ', 'event_espresso')
@@ -2321,7 +2321,7 @@  discard block
 block discarded – undo
2321 2321
             $this->_return_json();
2322 2322
         }
2323 2323
         // grab header
2324
-        $template_path                              = REG_TEMPLATE_PATH . 'reg_admin_register_new_attendee.template.php';
2324
+        $template_path                              = REG_TEMPLATE_PATH.'reg_admin_register_new_attendee.template.php';
2325 2325
         $this->_template_args['admin_page_content'] = EEH_Template::display_template($template_path,
2326 2326
             $this->_template_args, true);
2327 2327
         //$this->_set_publish_post_box_vars( NULL, FALSE, FALSE, NULL, FALSE );
@@ -2343,7 +2343,7 @@  discard block
 block discarded – undo
2343 2343
                 'event_espresso'), '<br />', '<h3 class="important-notice">', '</h3>', '<div class="float-right">',
2344 2344
                 '<span id="redirect_timer" class="important-notice">30</span>', '</div>', '<b>', '</b>');
2345 2345
             return '
2346
-	<div id="ee-add-reg-back-button-dv"><p>' . $warning_msg . '</p></div>
2346
+	<div id="ee-add-reg-back-button-dv"><p>' . $warning_msg.'</p></div>
2347 2347
 	<script >
2348 2348
 		// WHOAH !!! it appears that someone is using the back button from the Transaction admin page
2349 2349
 		// after just adding a new registration... we gotta try to put a stop to that !!!
@@ -2568,7 +2568,7 @@  discard block
 block discarded – undo
2568 2568
     public function get_attendees($per_page, $count = false, $trash = false)
2569 2569
     {
2570 2570
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2571
-        require_once(REG_ADMIN . 'EE_Attendee_Contact_List_Table.class.php');
2571
+        require_once(REG_ADMIN.'EE_Attendee_Contact_List_Table.class.php');
2572 2572
         $ATT_MDL                    = EEM_Attendee::instance();
2573 2573
         $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
2574 2574
         switch ($this->_req_data['orderby']) {
@@ -2602,7 +2602,7 @@  discard block
 block discarded – undo
2602 2602
             ? $this->_req_data['perpage'] : $per_page;
2603 2603
         $_where       = array();
2604 2604
         if ( ! empty($this->_req_data['s'])) {
2605
-            $sstr         = '%' . $this->_req_data['s'] . '%';
2605
+            $sstr         = '%'.$this->_req_data['s'].'%';
2606 2606
             $_where['OR'] = array(
2607 2607
                 'Registration.Event.EVT_name'       => array('LIKE', $sstr),
2608 2608
                 'Registration.Event.EVT_desc'       => array('LIKE', $sstr),
@@ -2680,7 +2680,7 @@  discard block
 block discarded – undo
2680 2680
      *                                                     the query parameters from the request
2681 2681
      * @return void ends the request with a redirect or download
2682 2682
      */
2683
-    public function _registrations_report_base( $method_name_for_getting_query_params )
2683
+    public function _registrations_report_base($method_name_for_getting_query_params)
2684 2684
     {
2685 2685
         if ( ! defined('EE_USE_OLD_CSV_REPORT_CLASS')) {
2686 2686
             wp_redirect(EE_Admin_Page::add_query_args_and_nonce(array(
@@ -2690,7 +2690,7 @@  discard block
 block discarded – undo
2690 2690
                 'filters'     => urlencode(
2691 2691
                     serialize(
2692 2692
                         call_user_func(
2693
-                            array( $this, $method_name_for_getting_query_params ),
2693
+                            array($this, $method_name_for_getting_query_params),
2694 2694
                             EEH_Array::is_set(
2695 2695
                                 $this->_req_data,
2696 2696
                                 'filters',
@@ -2710,8 +2710,8 @@  discard block
 block discarded – undo
2710 2710
                 'EVT_ID' => isset($this->_req_data['EVT_ID']) ? $this->_req_data['EVT_ID'] : null,
2711 2711
             );
2712 2712
             $this->_req_data = array_merge($this->_req_data, $new_request_args);
2713
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2714
-                require_once(EE_CLASSES . 'EE_Export.class.php');
2713
+            if (is_readable(EE_CLASSES.'EE_Export.class.php')) {
2714
+                require_once(EE_CLASSES.'EE_Export.class.php');
2715 2715
                 $EE_Export = EE_Export::instance($this->_req_data);
2716 2716
                 $EE_Export->export();
2717 2717
             }
@@ -2726,14 +2726,14 @@  discard block
 block discarded – undo
2726 2726
      */
2727 2727
     public function _registrations_report()
2728 2728
     {
2729
-        $this->_registrations_report_base( '_get_registration_query_parameters' );
2729
+        $this->_registrations_report_base('_get_registration_query_parameters');
2730 2730
     }
2731 2731
 
2732 2732
 
2733 2733
     public function _contact_list_export()
2734 2734
     {
2735
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2736
-            require_once(EE_CLASSES . 'EE_Export.class.php');
2735
+        if (is_readable(EE_CLASSES.'EE_Export.class.php')) {
2736
+            require_once(EE_CLASSES.'EE_Export.class.php');
2737 2737
             $EE_Export = EE_Export::instance($this->_req_data);
2738 2738
             $EE_Export->export_attendees();
2739 2739
         }
@@ -2750,8 +2750,8 @@  discard block
 block discarded – undo
2750 2750
                 'return_url'  => urlencode($this->_req_data['return_url']),
2751 2751
             )));
2752 2752
         } else {
2753
-            if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
2754
-                require_once(EE_CLASSES . 'EE_Export.class.php');
2753
+            if (is_readable(EE_CLASSES.'EE_Export.class.php')) {
2754
+                require_once(EE_CLASSES.'EE_Export.class.php');
2755 2755
                 $EE_Export = EE_Export::instance($this->_req_data);
2756 2756
                 $EE_Export->report_attendees();
2757 2757
             }
@@ -2808,7 +2808,7 @@  discard block
 block discarded – undo
2808 2808
             $updated_fields = array(
2809 2809
                 'ATT_fname'     => $this->_req_data['ATT_fname'],
2810 2810
                 'ATT_lname'     => $this->_req_data['ATT_lname'],
2811
-                'ATT_full_name' => $this->_req_data['ATT_fname'] . ' ' . $this->_req_data['ATT_lname'],
2811
+                'ATT_full_name' => $this->_req_data['ATT_fname'].' '.$this->_req_data['ATT_lname'],
2812 2812
                 'ATT_address'   => isset($this->_req_data['ATT_address']) ? $this->_req_data['ATT_address'] : '',
2813 2813
                 'ATT_address2'  => isset($this->_req_data['ATT_address2']) ? $this->_req_data['ATT_address2'] : '',
2814 2814
                 'ATT_city'      => isset($this->_req_data['ATT_city']) ? $this->_req_data['ATT_city'] : '',
@@ -2891,7 +2891,7 @@  discard block
 block discarded – undo
2891 2891
     {
2892 2892
         //get attendee object ( should already have it )
2893 2893
         $this->_template_args['attendee'] = $this->_cpt_model_obj;
2894
-        $template                         = REG_TEMPLATE_PATH . 'attendee_contact_info_metabox_content.template.php';
2894
+        $template                         = REG_TEMPLATE_PATH.'attendee_contact_info_metabox_content.template.php';
2895 2895
         EEH_Template::display_template($template, $this->_template_args);
2896 2896
     }
2897 2897
 
@@ -2932,7 +2932,7 @@  discard block
 block discarded – undo
2932 2932
             'input_prefix'   => '',
2933 2933
             'append_qstn_id' => false,
2934 2934
         )));
2935
-        $template                             = REG_TEMPLATE_PATH . 'attendee_address_details_metabox_content.template.php';
2935
+        $template = REG_TEMPLATE_PATH.'attendee_address_details_metabox_content.template.php';
2936 2936
         EEH_Template::display_template($template, $this->_template_args);
2937 2937
     }
2938 2938
 
@@ -2947,7 +2947,7 @@  discard block
 block discarded – undo
2947 2947
     {
2948 2948
         $this->_template_args['attendee']      = $this->_cpt_model_obj;
2949 2949
         $this->_template_args['registrations'] = $this->_cpt_model_obj->get_many_related('Registration');
2950
-        $template                              = REG_TEMPLATE_PATH . 'attendee_registrations_main_meta_box.template.php';
2950
+        $template                              = REG_TEMPLATE_PATH.'attendee_registrations_main_meta_box.template.php';
2951 2951
         EEH_Template::display_template($template, $this->_template_args);
2952 2952
     }
2953 2953
 
@@ -2961,7 +2961,7 @@  discard block
 block discarded – undo
2961 2961
     public function after_title_form_fields($post)
2962 2962
     {
2963 2963
         if ($post->post_type == 'espresso_attendees') {
2964
-            $template                  = REG_TEMPLATE_PATH . 'attendee_details_after_title_form_fields.template.php';
2964
+            $template                  = REG_TEMPLATE_PATH.'attendee_details_after_title_form_fields.template.php';
2965 2965
             $template_args['attendee'] = $this->_cpt_model_obj;
2966 2966
             EEH_Template::display_template($template, $template_args);
2967 2967
         }
Please login to merge, or discard this patch.
admin/extend/registrations/Extend_Registrations_Admin_Page.core.php 2 patches
Spacing   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -35,9 +35,9 @@  discard block
 block discarded – undo
35 35
     {
36 36
         parent::__construct($routing);
37 37
         if ( ! defined('REG_CAF_TEMPLATE_PATH')) {
38
-            define('REG_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/templates/');
39
-            define('REG_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/assets/');
40
-            define('REG_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registrations/assets/');
38
+            define('REG_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND.'registrations/templates/');
39
+            define('REG_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND.'registrations/assets/');
40
+            define('REG_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL.'registrations/assets/');
41 41
         }
42 42
     }
43 43
 
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
 
46 46
     protected function _extend_page_config()
47 47
     {
48
-        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'registrations';
48
+        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND.'registrations';
49 49
         $reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
50 50
             ? $this->_req_data['_REG_ID']
51 51
             : 0;
@@ -178,14 +178,14 @@  discard block
 block discarded – undo
178 178
             //enqueue newsletter js
179 179
             wp_enqueue_script(
180 180
                 'ee-newsletter-trigger',
181
-                REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.js',
181
+                REG_CAF_ASSETS_URL.'ee-newsletter-trigger.js',
182 182
                 array('ee-dialog'),
183 183
                 EVENT_ESPRESSO_VERSION,
184 184
                 true
185 185
             );
186 186
             wp_enqueue_style(
187 187
                 'ee-newsletter-trigger-css',
188
-                REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.css',
188
+                REG_CAF_ASSETS_URL.'ee-newsletter-trigger.css',
189 189
                 array(),
190 190
                 EVENT_ESPRESSO_VERSION
191 191
             );
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
     {
205 205
         wp_register_script(
206 206
             'ee-reg-reports-js',
207
-            REG_CAF_ASSETS_URL . 'ee-registration-admin-reports.js',
207
+            REG_CAF_ASSETS_URL.'ee-registration-admin-reports.js',
208 208
             array('google-charts'),
209 209
             EVENT_ESPRESSO_VERSION,
210 210
             true
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
             $codes[$field] = implode(', ', array_keys($shortcode_array));
410 410
         }
411 411
         $shortcodes = $codes;
412
-        $form_template = REG_CAF_TEMPLATE_PATH . 'newsletter-send-form.template.php';
412
+        $form_template = REG_CAF_TEMPLATE_PATH.'newsletter-send-form.template.php';
413 413
         $form_template_args = array(
414 414
             'form_action'       => admin_url('admin.php?page=espresso_registrations'),
415 415
             'form_route'        => 'newsletter_selected_send',
@@ -570,7 +570,7 @@  discard block
 block discarded – undo
570 570
      */
571 571
     protected function _registration_reports()
572 572
     {
573
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_reports.template.php';
573
+        $template_path = EE_ADMIN_TEMPLATE.'admin_reports.template.php';
574 574
         $this->_template_args['admin_page_content'] = EEH_Template::display_template(
575 575
             $template_path,
576 576
             $this->_reports_template_data,
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
     {
593 593
         $report_ID = 'reg-admin-registrations-per-day-report-dv';
594 594
         $results = EEM_Registration::instance()->get_registrations_per_day_and_per_status_report($period);
595
-        $results = (array)$results;
595
+        $results = (array) $results;
596 596
         $regs = array();
597 597
         $subtitle = '';
598 598
         if ($results) {
@@ -602,7 +602,7 @@  discard block
 block discarded – undo
602 602
                 $report_column_values = array();
603 603
                 foreach ($result as $property_name => $property_value) {
604 604
                     $property_value = $property_name === 'Registration_REG_date' ? $property_value
605
-                        : (int)$property_value;
605
+                        : (int) $property_value;
606 606
                     $report_column_values[] = $property_value;
607 607
                     if ($tracker === 0) {
608 608
                         if ($property_name === 'Registration_REG_date') {
@@ -619,7 +619,7 @@  discard block
 block discarded – undo
619 619
             array_unshift($regs, $column_titles);
620 620
             //setup the date range.
621 621
             $DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
622
-            $beginning_date = new DateTime("now " . $period, $DateTimeZone);
622
+            $beginning_date = new DateTime("now ".$period, $DateTimeZone);
623 623
             $ending_date = new DateTime("now", $DateTimeZone);
624 624
             $subtitle = sprintf(
625 625
                 _x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
@@ -639,7 +639,7 @@  discard block
 block discarded – undo
639 639
                     '%sThere are currently no registration records in the last month for this report.%s',
640 640
                     'event_espresso'
641 641
                 ),
642
-                '<h2>' . $report_title . '</h2><p>',
642
+                '<h2>'.$report_title.'</h2><p>',
643 643
                 '</p>'
644 644
             ),
645 645
         );
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
     {
660 660
         $report_ID = 'reg-admin-registrations-per-event-report-dv';
661 661
         $results = EEM_Registration::instance()->get_registrations_per_event_and_per_status_report($period);
662
-        $results = (array)$results;
662
+        $results = (array) $results;
663 663
         $regs = array();
664 664
         $subtitle = '';
665 665
         if ($results) {
@@ -672,7 +672,7 @@  discard block
 block discarded – undo
672 672
                         $property_value,
673 673
                         4,
674 674
                         '...'
675
-                    ) : (int)$property_value;
675
+                    ) : (int) $property_value;
676 676
                     $report_column_values[] = $property_value;
677 677
                     if ($tracker === 0) {
678 678
                         if ($property_name === 'Registration_Event') {
@@ -689,7 +689,7 @@  discard block
 block discarded – undo
689 689
             array_unshift($regs, $column_titles);
690 690
             //setup the date range.
691 691
             $DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
692
-            $beginning_date = new DateTime("now " . $period, $DateTimeZone);
692
+            $beginning_date = new DateTime("now ".$period, $DateTimeZone);
693 693
             $ending_date = new DateTime("now", $DateTimeZone);
694 694
             $subtitle = sprintf(
695 695
                 _x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
@@ -709,7 +709,7 @@  discard block
 block discarded – undo
709 709
                     '%sThere are currently no registration records in the last month for this report.%s',
710 710
                     'event_espresso'
711 711
                 ),
712
-                '<h2>' . $report_title . '</h2><p>',
712
+                '<h2>'.$report_title.'</h2><p>',
713 713
                 '</p>'
714 714
             ),
715 715
         );
@@ -759,31 +759,31 @@  discard block
 block discarded – undo
759 759
             $this->_admin_base_url
760 760
         ) : '';
761 761
         $this->_template_args['before_list_table'] = ! empty($reg_id) && ! empty($dtt_id)
762
-            ? '<h2>' . sprintf(
762
+            ? '<h2>'.sprintf(
763 763
                 __("%s's check in records for %s at the event, %s", 'event_espresso'),
764 764
                 '<span id="checkin-attendee-name">'
765 765
                 . EEM_Registration::instance()
766 766
                                   ->get_one_by_ID($reg_id)
767 767
                                   ->get_first_related('Attendee')
768
-                                  ->full_name() . '</span>',
769
-                '<span id="checkin-dtt"><a href="' . $go_back_url . '">'
768
+                                  ->full_name().'</span>',
769
+                '<span id="checkin-dtt"><a href="'.$go_back_url.'">'
770 770
                 . EEM_Datetime::instance()
771 771
                               ->get_one_by_ID($dtt_id)
772
-                              ->start_date_and_time() . ' - '
772
+                              ->start_date_and_time().' - '
773 773
                 . EEM_Datetime::instance()
774 774
                               ->get_one_by_ID($dtt_id)
775
-                              ->end_date_and_time() . '</a></span>',
775
+                              ->end_date_and_time().'</a></span>',
776 776
                 '<span id="checkin-event-name">'
777 777
                 . EEM_Datetime::instance()
778 778
                               ->get_one_by_ID($dtt_id)
779 779
                               ->get_first_related('Event')
780
-                              ->get('EVT_name') . '</span>'
781
-            ) . '</h2>'
780
+                              ->get('EVT_name').'</span>'
781
+            ).'</h2>'
782 782
             : '';
783 783
         $this->_template_args['list_table_hidden_fields'] = ! empty($reg_id)
784
-            ? '<input type="hidden" name="_REGID" value="' . $reg_id . '">' : '';
784
+            ? '<input type="hidden" name="_REGID" value="'.$reg_id.'">' : '';
785 785
         $this->_template_args['list_table_hidden_fields'] .= ! empty($dtt_id)
786
-            ? '<input type="hidden" name="DTT_ID" value="' . $dtt_id . '">' : '';
786
+            ? '<input type="hidden" name="DTT_ID" value="'.$dtt_id.'">' : '';
787 787
         $this->display_admin_list_table_page_with_no_sidebar();
788 788
     }
789 789
 
@@ -1024,37 +1024,37 @@  discard block
 block discarded – undo
1024 1024
                 'desc'  => __('View All Check-in Records for this Registrant', 'event_espresso'),
1025 1025
             ),
1026 1026
             'approved_status'  => array(
1027
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
1027
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_approved,
1028 1028
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
1029 1029
             ),
1030 1030
             'cancelled_status' => array(
1031
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1031
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_cancelled,
1032 1032
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
1033 1033
             ),
1034 1034
             'declined_status'  => array(
1035
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
1035
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_declined,
1036 1036
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
1037 1037
             ),
1038 1038
             'not_approved'     => array(
1039
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
1039
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_not_approved,
1040 1040
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
1041 1041
             ),
1042 1042
             'pending_status'   => array(
1043
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
1043
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_pending_payment,
1044 1044
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
1045 1045
             ),
1046 1046
             'wait_list'        => array(
1047
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
1047
+                'class' => 'ee-status-legend ee-status-legend-'.EEM_Registration::status_id_wait_list,
1048 1048
                 'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
1049 1049
             ),
1050 1050
         );
1051 1051
         $this->_template_args['after_list_table'] = $this->_display_legend($legend_items);
1052 1052
         $event_id = isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null;
1053 1053
         $this->_template_args['before_list_table'] = ! empty($event_id)
1054
-            ? '<h2>' . sprintf(
1054
+            ? '<h2>'.sprintf(
1055 1055
                 __('Viewing Registrations for Event: %s', 'event_espresso'),
1056 1056
                 EEM_Event::instance()->get_one_by_ID($event_id)->get('EVT_name')
1057
-            ) . '</h2>'
1057
+            ).'</h2>'
1058 1058
             : '';
1059 1059
         //need to get the number of datetimes on the event and set default datetime_id if there is only one datetime on the event.
1060 1060
         /** @var EE_Event $event */
@@ -1073,7 +1073,7 @@  discard block
 block discarded – undo
1073 1073
             $this->_template_args['before_list_table'] .= ' &nbsp;<span class="drk-grey-text">';
1074 1074
             $this->_template_args['before_list_table'] .= '<span class="dashicons dashicons-calendar"></span>';
1075 1075
             $this->_template_args['before_list_table'] .= $datetime->name();
1076
-            $this->_template_args['before_list_table'] .= ' ( ' . $datetime->date_and_time_range() . ' )';
1076
+            $this->_template_args['before_list_table'] .= ' ( '.$datetime->date_and_time_range().' )';
1077 1077
             $this->_template_args['before_list_table'] .= '</span></h2>';
1078 1078
         }
1079 1079
         //if no datetime, then we're on the initial view, so let's give some helpful instructions on what the status column
@@ -1141,11 +1141,11 @@  discard block
 block discarded – undo
1141 1141
         //normalize some request params that get setup by the parent `get_registrations` method.
1142 1142
         $request = $this->_req_data;
1143 1143
         $request['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : $orderby;
1144
-        $request['order'] =  ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'ASC';
1145
-        if($trash){
1144
+        $request['order'] = ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'ASC';
1145
+        if ($trash) {
1146 1146
             $request['status'] = 'trash';
1147 1147
         }
1148
-        $query_params = $this->_get_checkin_query_params_from_request( $request, $per_page, $count );
1148
+        $query_params = $this->_get_checkin_query_params_from_request($request, $per_page, $count);
1149 1149
 
1150 1150
         return $count
1151 1151
             ? EEM_Registration::instance()->count($query_params)
Please login to merge, or discard this patch.
Indentation   +1135 added lines, -1135 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
 
@@ -17,1139 +17,1139 @@  discard block
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * This is used to hold the reports template data which is setup early in the request.
22
-     *
23
-     * @type array
24
-     */
25
-    protected $_reports_template_data = array();
26
-
27
-
28
-
29
-    /**
30
-     * Extend_Registrations_Admin_Page constructor.
31
-     *
32
-     * @param bool $routing
33
-     */
34
-    public function __construct($routing = true)
35
-    {
36
-        parent::__construct($routing);
37
-        if ( ! defined('REG_CAF_TEMPLATE_PATH')) {
38
-            define('REG_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/templates/');
39
-            define('REG_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/assets/');
40
-            define('REG_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registrations/assets/');
41
-        }
42
-    }
43
-
44
-
45
-
46
-    protected function _extend_page_config()
47
-    {
48
-        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'registrations';
49
-        $reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
50
-            ? $this->_req_data['_REG_ID']
51
-            : 0;
52
-        // $att_id = ! empty( $this->_req_data['ATT_ID'] ) ? ! is_array( $this->_req_data['ATT_ID'] ) : 0;
53
-        // $att_id = ! empty( $this->_req_data['post'] ) && ! is_array( $this->_req_data['post'] )
54
-        // 	? $this->_req_data['post'] : $att_id;
55
-        $new_page_routes = array(
56
-            'reports'                  => array(
57
-                'func'       => '_registration_reports',
58
-                'capability' => 'ee_read_registrations',
59
-            ),
60
-            'registration_checkins'    => array(
61
-                'func'       => '_registration_checkin_list_table',
62
-                'capability' => 'ee_read_checkins',
63
-            ),
64
-            'newsletter_selected_send' => array(
65
-                'func'       => '_newsletter_selected_send',
66
-                'noheader'   => true,
67
-                'capability' => 'ee_send_message',
68
-            ),
69
-            'delete_checkin_rows'      => array(
70
-                'func'       => '_delete_checkin_rows',
71
-                'noheader'   => true,
72
-                'capability' => 'ee_delete_checkins',
73
-            ),
74
-            'delete_checkin_row'       => array(
75
-                'func'       => '_delete_checkin_row',
76
-                'noheader'   => true,
77
-                'capability' => 'ee_delete_checkin',
78
-                'obj_id'     => $reg_id,
79
-            ),
80
-            'toggle_checkin_status'    => array(
81
-                'func'       => '_toggle_checkin_status',
82
-                'noheader'   => true,
83
-                'capability' => 'ee_edit_checkin',
84
-                'obj_id'     => $reg_id,
85
-            ),
86
-            'event_registrations'      => array(
87
-                'func'       => '_event_registrations_list_table',
88
-                'capability' => 'ee_read_checkins',
89
-            ),
90
-            'registrations_checkin_report' => array(
91
-                'func'       => '_registrations_checkin_report',
92
-                'noheader'   => true,
93
-                'capability' => 'ee_read_registrations',
94
-            ),
95
-        );
96
-        $this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
97
-        $new_page_config = array(
98
-            'reports'               => array(
99
-                'nav'           => array(
100
-                    'label' => __('Reports', 'event_espresso'),
101
-                    'order' => 30,
102
-                ),
103
-                'help_tabs'     => array(
104
-                    'registrations_reports_help_tab' => array(
105
-                        'title'    => __('Registration Reports', 'event_espresso'),
106
-                        'filename' => 'registrations_reports',
107
-                    ),
108
-                ),
109
-                /*'help_tour' => array( 'Registration_Reports_Help_Tour' ),*/
110
-                'require_nonce' => false,
111
-            ),
112
-            'event_registrations'   => array(
113
-                'nav'           => array(
114
-                    'label'      => __('Event Check-In', 'event_espresso'),
115
-                    'order'      => 10,
116
-                    'persistent' => true,
117
-                ),
118
-                'help_tabs'     => array(
119
-                    'registrations_event_checkin_help_tab'                       => array(
120
-                        'title'    => __('Registrations Event Check-In', 'event_espresso'),
121
-                        'filename' => 'registrations_event_checkin',
122
-                    ),
123
-                    'registrations_event_checkin_table_column_headings_help_tab' => array(
124
-                        'title'    => __('Event Check-In Table Column Headings', 'event_espresso'),
125
-                        'filename' => 'registrations_event_checkin_table_column_headings',
126
-                    ),
127
-                    'registrations_event_checkin_filters_help_tab'               => array(
128
-                        'title'    => __('Event Check-In Filters', 'event_espresso'),
129
-                        'filename' => 'registrations_event_checkin_filters',
130
-                    ),
131
-                    'registrations_event_checkin_views_help_tab'                 => array(
132
-                        'title'    => __('Event Check-In Views', 'event_espresso'),
133
-                        'filename' => 'registrations_event_checkin_views',
134
-                    ),
135
-                    'registrations_event_checkin_other_help_tab'                 => array(
136
-                        'title'    => __('Event Check-In Other', 'event_espresso'),
137
-                        'filename' => 'registrations_event_checkin_other',
138
-                    ),
139
-                ),
140
-                'help_tour'     => array('Event_Checkin_Help_Tour'),
141
-                'qtips'         => array('Registration_List_Table_Tips'),
142
-                'list_table'    => 'EE_Event_Registrations_List_Table',
143
-                'metaboxes'     => array(),
144
-                'require_nonce' => false,
145
-            ),
146
-            'registration_checkins' => array(
147
-                'nav'           => array(
148
-                    'label'      => __('Check-In Records', 'event_espresso'),
149
-                    'order'      => 15,
150
-                    'persistent' => false,
151
-                ),
152
-                'list_table'    => 'EE_Registration_CheckIn_List_Table',
153
-                //'help_tour' => array( 'Checkin_Toggle_View_Help_Tour' ),
154
-                'metaboxes'     => array(),
155
-                'require_nonce' => false,
156
-            ),
157
-        );
158
-        $this->_page_config = array_merge($this->_page_config, $new_page_config);
159
-        $this->_page_config['contact_list']['list_table'] = 'Extend_EE_Attendee_Contact_List_Table';
160
-        $this->_page_config['default']['list_table'] = 'Extend_EE_Registrations_List_Table';
161
-    }
162
-
163
-
164
-
165
-    protected function _ajax_hooks()
166
-    {
167
-        parent::_ajax_hooks();
168
-        add_action('wp_ajax_get_newsletter_form_content', array($this, 'get_newsletter_form_content'));
169
-    }
170
-
171
-
172
-
173
-    public function load_scripts_styles()
174
-    {
175
-        parent::load_scripts_styles();
176
-        //if newsletter message type is active then let's add filter and load js for it.
177
-        if (EEH_MSG_Template::is_mt_active('newsletter')) {
178
-            //enqueue newsletter js
179
-            wp_enqueue_script(
180
-                'ee-newsletter-trigger',
181
-                REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.js',
182
-                array('ee-dialog'),
183
-                EVENT_ESPRESSO_VERSION,
184
-                true
185
-            );
186
-            wp_enqueue_style(
187
-                'ee-newsletter-trigger-css',
188
-                REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.css',
189
-                array(),
190
-                EVENT_ESPRESSO_VERSION
191
-            );
192
-            //hook in buttons for newsletter message type trigger.
193
-            add_action(
194
-                'AHEE__EE_Admin_List_Table__extra_tablenav__after_bottom_buttons',
195
-                array($this, 'add_newsletter_action_buttons'),
196
-                10
197
-            );
198
-        }
199
-    }
200
-
201
-
202
-
203
-    public function load_scripts_styles_reports()
204
-    {
205
-        wp_register_script(
206
-            'ee-reg-reports-js',
207
-            REG_CAF_ASSETS_URL . 'ee-registration-admin-reports.js',
208
-            array('google-charts'),
209
-            EVENT_ESPRESSO_VERSION,
210
-            true
211
-        );
212
-        wp_enqueue_script('ee-reg-reports-js');
213
-        $this->_registration_reports_js_setup();
214
-    }
215
-
216
-
217
-
218
-    protected function _add_screen_options_event_registrations()
219
-    {
220
-        $this->_per_page_screen_option();
221
-    }
222
-
223
-
224
-
225
-    protected function _add_screen_options_registration_checkins()
226
-    {
227
-        $page_title = $this->_admin_page_title;
228
-        $this->_admin_page_title = __('Check-In Records', 'event_espresso');
229
-        $this->_per_page_screen_option();
230
-        $this->_admin_page_title = $page_title;
231
-    }
232
-
233
-
234
-
235
-    protected function _set_list_table_views_event_registrations()
236
-    {
237
-        $this->_views = array(
238
-            'all' => array(
239
-                'slug'        => 'all',
240
-                'label'       => __('All', 'event_espresso'),
241
-                'count'       => 0,
242
-                'bulk_action' => ! isset($this->_req_data['event_id'])
243
-                    ? array()
244
-                    : array(
245
-                        'toggle_checkin_status' => __('Toggle Check-In', 'event_espresso'),
246
-                        //'trash_registrations' => __('Trash Registrations', 'event_espresso')
247
-                    ),
248
-            ),
249
-        );
250
-    }
251
-
252
-
253
-
254
-    protected function _set_list_table_views_registration_checkins()
255
-    {
256
-        $this->_views = array(
257
-            'all' => array(
258
-                'slug'        => 'all',
259
-                'label'       => __('All', 'event_espresso'),
260
-                'count'       => 0,
261
-                'bulk_action' => array('delete_checkin_rows' => __('Delete Check-In Rows', 'event_espresso')),
262
-            ),
263
-        );
264
-    }
265
-
266
-
267
-
268
-    /**
269
-     * callback for ajax action.
270
-     *
271
-     * @since 4.3.0
272
-     * @return void (JSON)
273
-     * @throws \EE_Error
274
-     */
275
-    public function get_newsletter_form_content()
276
-    {
277
-        //do a nonce check cause we're not coming in from an normal route here.
278
-        $nonce = isset($this->_req_data['get_newsletter_form_content_nonce']) ? sanitize_text_field(
279
-            $this->_req_data['get_newsletter_form_content_nonce']
280
-        ) : '';
281
-        $nonce_ref = 'get_newsletter_form_content_nonce';
282
-        $this->_verify_nonce($nonce, $nonce_ref);
283
-        //let's get the mtp for the incoming MTP_ ID
284
-        if ( ! isset($this->_req_data['GRP_ID'])) {
285
-            EE_Error::add_error(
286
-                __(
287
-                    'There must be something broken with the js or html structure because the required data for getting a message template group is not present (need an GRP_ID).',
288
-                    'event_espresso'
289
-                ),
290
-                __FILE__,
291
-                __FUNCTION__,
292
-                __LINE__
293
-            );
294
-            $this->_template_args['success'] = false;
295
-            $this->_template_args['error'] = true;
296
-            $this->_return_json();
297
-        }
298
-        $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID($this->_req_data['GRP_ID']);
299
-        if ( ! $MTPG instanceof EE_Message_Template_Group) {
300
-            EE_Error::add_error(
301
-                sprintf(
302
-                    __(
303
-                        'The GRP_ID given (%d) does not appear to have a corresponding row in the database.',
304
-                        'event_espresso'
305
-                    ),
306
-                    $this->_req_data['GRP_ID']
307
-                ),
308
-                __FILE__,
309
-                __FUNCTION__,
310
-                __LINE__
311
-            );
312
-            $this->_template_args['success'] = false;
313
-            $this->_template_args['error'] = true;
314
-            $this->_return_json();
315
-        }
316
-        $MTPs = $MTPG->context_templates();
317
-        $MTPs = $MTPs['attendee'];
318
-        $template_fields = array();
319
-        /** @var EE_Message_Template $MTP */
320
-        foreach ($MTPs as $MTP) {
321
-            $field = $MTP->get('MTP_template_field');
322
-            if ($field === 'content') {
323
-                $content = $MTP->get('MTP_content');
324
-                if ( ! empty($content['newsletter_content'])) {
325
-                    $template_fields['newsletter_content'] = $content['newsletter_content'];
326
-                }
327
-                continue;
328
-            }
329
-            $template_fields[$MTP->get('MTP_template_field')] = $MTP->get('MTP_content');
330
-        }
331
-        $this->_template_args['success'] = true;
332
-        $this->_template_args['error'] = false;
333
-        $this->_template_args['data'] = array(
334
-            'batch_message_from'    => isset($template_fields['from'])
335
-                ? $template_fields['from']
336
-                : '',
337
-            'batch_message_subject' => isset($template_fields['subject'])
338
-                ? $template_fields['subject']
339
-                : '',
340
-            'batch_message_content' => isset($template_fields['newsletter_content'])
341
-                ? $template_fields['newsletter_content']
342
-                : '',
343
-        );
344
-        $this->_return_json();
345
-    }
346
-
347
-
348
-
349
-    /**
350
-     * callback for AHEE__EE_Admin_List_Table__extra_tablenav__after_bottom_buttons action
351
-     *
352
-     * @since 4.3.0
353
-     * @param EE_Admin_List_Table $list_table
354
-     * @return void
355
-     */
356
-    public function add_newsletter_action_buttons(EE_Admin_List_Table $list_table)
357
-    {
358
-        if ( ! EE_Registry::instance()->CAP->current_user_can(
359
-            'ee_send_message',
360
-            'espresso_registrations_newsletter_selected_send'
361
-        )
362
-        ) {
363
-            return;
364
-        }
365
-        $routes_to_add_to = array(
366
-            'contact_list',
367
-            'event_registrations',
368
-            'default',
369
-        );
370
-        if ($this->_current_page === 'espresso_registrations' && in_array($this->_req_action, $routes_to_add_to)) {
371
-            if (($this->_req_action === 'event_registrations' && empty($this->_req_data['event_id']))
372
-                || (isset($this->_req_data['status']) && $this->_req_data['status'] === 'trash')
373
-            ) {
374
-                echo '';
375
-            } else {
376
-                $button_text = sprintf(
377
-                    __('Send Batch Message (%s selected)', 'event_espresso'),
378
-                    '<span class="send-selected-newsletter-count">0</span>'
379
-                );
380
-                echo '<button id="selected-batch-send-trigger" class="button secondary-button"><span class="dashicons dashicons-email "></span>'
381
-                     . $button_text
382
-                     . '</button>';
383
-                add_action('admin_footer', array($this, 'newsletter_send_form_skeleton'));
384
-            }
385
-        }
386
-    }
387
-
388
-
389
-
390
-    public function newsletter_send_form_skeleton()
391
-    {
392
-        $list_table = $this->_list_table_object;
393
-        $codes = array();
394
-        //need to templates for the newsletter message type for the template selector.
395
-        $values[] = array('text' => __('Select Template to Use', 'event_espresso'), 'id' => 0);
396
-        $mtps = EEM_Message_Template_Group::instance()->get_all(
397
-            array(array('MTP_message_type' => 'newsletter', 'MTP_messenger' => 'email'))
398
-        );
399
-        foreach ($mtps as $mtp) {
400
-            $name = $mtp->name();
401
-            $values[] = array(
402
-                'text' => empty($name) ? __('Global', 'event_espresso') : $name,
403
-                'id'   => $mtp->ID(),
404
-            );
405
-        }
406
-        //need to get a list of shortcodes that are available for the newsletter message type.
407
-        $shortcodes = EEH_MSG_Template::get_shortcodes('newsletter', 'email', array(), 'attendee', false);
408
-        foreach ($shortcodes as $field => $shortcode_array) {
409
-            $codes[$field] = implode(', ', array_keys($shortcode_array));
410
-        }
411
-        $shortcodes = $codes;
412
-        $form_template = REG_CAF_TEMPLATE_PATH . 'newsletter-send-form.template.php';
413
-        $form_template_args = array(
414
-            'form_action'       => admin_url('admin.php?page=espresso_registrations'),
415
-            'form_route'        => 'newsletter_selected_send',
416
-            'form_nonce_name'   => 'newsletter_selected_send_nonce',
417
-            'form_nonce'        => wp_create_nonce('newsletter_selected_send_nonce'),
418
-            'redirect_back_to'  => $this->_req_action,
419
-            'ajax_nonce'        => wp_create_nonce('get_newsletter_form_content_nonce'),
420
-            'template_selector' => EEH_Form_Fields::select_input('newsletter_mtp_selected', $values),
421
-            'shortcodes'        => $shortcodes,
422
-            'id_type'           => $list_table instanceof EE_Attendee_Contact_List_Table ? 'contact' : 'registration',
423
-        );
424
-        EEH_Template::display_template($form_template, $form_template_args);
425
-    }
426
-
427
-
428
-
429
-    /**
430
-     * Handles sending selected registrations/contacts a newsletter.
431
-     *
432
-     * @since  4.3.0
433
-     * @return void
434
-     * @throws \EE_Error
435
-     */
436
-    protected function _newsletter_selected_send()
437
-    {
438
-        $success = true;
439
-        //first we need to make sure we have a GRP_ID so we know what template we're sending and updating!
440
-        if (empty($this->_req_data['newsletter_mtp_selected'])) {
441
-            EE_Error::add_error(
442
-                __(
443
-                    'In order to send a message, a Message Template GRP_ID is needed. It was not provided so messages were not sent.',
444
-                    'event_espresso'
445
-                ),
446
-                __FILE__,
447
-                __FUNCTION__,
448
-                __LINE__
449
-            );
450
-            $success = false;
451
-        }
452
-        if ($success) {
453
-            //update Message template in case there are any changes
454
-            $Message_Template_Group = EEM_Message_Template_Group::instance()->get_one_by_ID(
455
-                $this->_req_data['newsletter_mtp_selected']
456
-            );
457
-            $Message_Templates = $Message_Template_Group instanceof EE_Message_Template_Group
458
-                ? $Message_Template_Group->context_templates()
459
-                : array();
460
-            if (empty($Message_Templates)) {
461
-                EE_Error::add_error(
462
-                    __(
463
-                        'Unable to retrieve message template fields from the db. Messages not sent.',
464
-                        'event_espresso'
465
-                    ),
466
-                    __FILE__,
467
-                    __FUNCTION__,
468
-                    __LINE__
469
-                );
470
-            }
471
-            //let's just update the specific fields
472
-            foreach ($Message_Templates['attendee'] as $Message_Template) {
473
-                if ($Message_Template instanceof EE_Message_Template) {
474
-                    $field = $Message_Template->get('MTP_template_field');
475
-                    $content = $Message_Template->get('MTP_content');
476
-                    $new_content = $content;
477
-                    switch ($field) {
478
-                        case 'from' :
479
-                            $new_content = ! empty($this->_req_data['batch_message']['from'])
480
-                                ? $this->_req_data['batch_message']['from']
481
-                                : $content;
482
-                            break;
483
-                        case 'subject' :
484
-                            $new_content = ! empty($this->_req_data['batch_message']['subject'])
485
-                                ? $this->_req_data['batch_message']['subject']
486
-                                : $content;
487
-                            break;
488
-                        case 'content' :
489
-                            $new_content = $content;
490
-                            $new_content['newsletter_content'] = ! empty($this->_req_data['batch_message']['content'])
491
-                                ? $this->_req_data['batch_message']['content']
492
-                                : $content['newsletter_content'];
493
-                            break;
494
-                        default :
495
-                            //continue the foreach loop, we don't want to set $new_content nor save.
496
-                            continue 2;
497
-                    }
498
-                    $Message_Template->set('MTP_content', $new_content);
499
-                    $Message_Template->save();
500
-                }
501
-            }
502
-            //great fields are updated!  now let's make sure we just have contact objects (EE_Attendee).
503
-            $id_type = ! empty($this->_req_data['batch_message']['id_type'])
504
-                ? $this->_req_data['batch_message']['id_type']
505
-                : 'registration';
506
-            //id_type will affect how we assemble the ids.
507
-            $ids = ! empty($this->_req_data['batch_message']['ids'])
508
-                ? json_decode(stripslashes($this->_req_data['batch_message']['ids']))
509
-                : array();
510
-            $registrations_used_for_contact_data = array();
511
-            //using switch because eventually we'll have other contexts that will be used for generating messages.
512
-            switch ($id_type) {
513
-                case 'registration' :
514
-                    $registrations_used_for_contact_data = EEM_Registration::instance()->get_all(
515
-                        array(
516
-                            array(
517
-                                'REG_ID' => array('IN', $ids),
518
-                            ),
519
-                        )
520
-                    );
521
-                    break;
522
-                case 'contact' :
523
-                    $registrations_used_for_contact_data = EEM_Registration::instance()
524
-                                                                           ->get_latest_registration_for_each_of_given_contacts($ids);
525
-                    break;
526
-            }
527
-            do_action(
528
-                'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
529
-                $registrations_used_for_contact_data,
530
-                $Message_Template_Group->ID()
531
-            );
532
-            //kept for backward compat, internally we no longer use this action.
533
-            //@deprecated 4.8.36.rc.002
534
-            $contacts = $id_type === 'registration'
535
-                ? EEM_Attendee::instance()->get_array_of_contacts_from_reg_ids($ids)
536
-                : EEM_Attendee::instance()->get_all(array(array('ATT_ID' => array('in', $ids))));
537
-            do_action(
538
-                'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send',
539
-                $contacts,
540
-                $Message_Template_Group->ID()
541
-            );
542
-        }
543
-        $query_args = array(
544
-            'action' => ! empty($this->_req_data['redirect_back_to'])
545
-                ? $this->_req_data['redirect_back_to']
546
-                : 'default',
547
-        );
548
-        $this->_redirect_after_action(false, '', '', $query_args, true);
549
-    }
550
-
551
-
552
-
553
-    /**
554
-     * This is called when javascript is being enqueued to setup the various data needed for the reports js.
555
-     * Also $this->{$_reports_template_data} property is set for later usage by the _registration_reports method.
556
-     */
557
-    protected function _registration_reports_js_setup()
558
-    {
559
-        $this->_reports_template_data['admin_reports'][] = $this->_registrations_per_day_report();
560
-        $this->_reports_template_data['admin_reports'][] = $this->_registrations_per_event_report();
561
-    }
562
-
563
-
564
-
565
-    /**
566
-     *        generates Business Reports regarding Registrations
567
-     *
568
-     * @access protected
569
-     * @return void
570
-     */
571
-    protected function _registration_reports()
572
-    {
573
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_reports.template.php';
574
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
575
-            $template_path,
576
-            $this->_reports_template_data,
577
-            true
578
-        );
579
-        // the final template wrapper
580
-        $this->display_admin_page_with_no_sidebar();
581
-    }
582
-
583
-
584
-
585
-    /**
586
-     * Generates Business Report showing total registrations per day.
587
-     *
588
-     * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
589
-     * @return string
590
-     */
591
-    private function _registrations_per_day_report($period = '-1 month')
592
-    {
593
-        $report_ID = 'reg-admin-registrations-per-day-report-dv';
594
-        $results = EEM_Registration::instance()->get_registrations_per_day_and_per_status_report($period);
595
-        $results = (array)$results;
596
-        $regs = array();
597
-        $subtitle = '';
598
-        if ($results) {
599
-            $column_titles = array();
600
-            $tracker = 0;
601
-            foreach ($results as $result) {
602
-                $report_column_values = array();
603
-                foreach ($result as $property_name => $property_value) {
604
-                    $property_value = $property_name === 'Registration_REG_date' ? $property_value
605
-                        : (int)$property_value;
606
-                    $report_column_values[] = $property_value;
607
-                    if ($tracker === 0) {
608
-                        if ($property_name === 'Registration_REG_date') {
609
-                            $column_titles[] = __('Date (only days with registrations are shown)', 'event_espresso');
610
-                        } else {
611
-                            $column_titles[] = EEH_Template::pretty_status($property_name, false, 'sentence');
612
-                        }
613
-                    }
614
-                }
615
-                $tracker++;
616
-                $regs[] = $report_column_values;
617
-            }
618
-            //make sure the column_titles is pushed to the beginning of the array
619
-            array_unshift($regs, $column_titles);
620
-            //setup the date range.
621
-            $DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
622
-            $beginning_date = new DateTime("now " . $period, $DateTimeZone);
623
-            $ending_date = new DateTime("now", $DateTimeZone);
624
-            $subtitle = sprintf(
625
-                _x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
626
-                $beginning_date->format('Y-m-d'),
627
-                $ending_date->format('Y-m-d')
628
-            );
629
-        }
630
-        $report_title = __('Total Registrations per Day', 'event_espresso');
631
-        $report_params = array(
632
-            'title'     => $report_title,
633
-            'subtitle'  => $subtitle,
634
-            'id'        => $report_ID,
635
-            'regs'      => $regs,
636
-            'noResults' => empty($regs),
637
-            'noRegsMsg' => sprintf(
638
-                __(
639
-                    '%sThere are currently no registration records in the last month for this report.%s',
640
-                    'event_espresso'
641
-                ),
642
-                '<h2>' . $report_title . '</h2><p>',
643
-                '</p>'
644
-            ),
645
-        );
646
-        wp_localize_script('ee-reg-reports-js', 'regPerDay', $report_params);
647
-        return $report_ID;
648
-    }
649
-
650
-
651
-
652
-    /**
653
-     * Generates Business Report showing total registrations per event.
654
-     *
655
-     * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
656
-     * @return string
657
-     */
658
-    private function _registrations_per_event_report($period = '-1 month')
659
-    {
660
-        $report_ID = 'reg-admin-registrations-per-event-report-dv';
661
-        $results = EEM_Registration::instance()->get_registrations_per_event_and_per_status_report($period);
662
-        $results = (array)$results;
663
-        $regs = array();
664
-        $subtitle = '';
665
-        if ($results) {
666
-            $column_titles = array();
667
-            $tracker = 0;
668
-            foreach ($results as $result) {
669
-                $report_column_values = array();
670
-                foreach ($result as $property_name => $property_value) {
671
-                    $property_value = $property_name === 'Registration_Event' ? wp_trim_words(
672
-                        $property_value,
673
-                        4,
674
-                        '...'
675
-                    ) : (int)$property_value;
676
-                    $report_column_values[] = $property_value;
677
-                    if ($tracker === 0) {
678
-                        if ($property_name === 'Registration_Event') {
679
-                            $column_titles[] = __('Event', 'event_espresso');
680
-                        } else {
681
-                            $column_titles[] = EEH_Template::pretty_status($property_name, false, 'sentence');
682
-                        }
683
-                    }
684
-                }
685
-                $tracker++;
686
-                $regs[] = $report_column_values;
687
-            }
688
-            //make sure the column_titles is pushed to the beginning of the array
689
-            array_unshift($regs, $column_titles);
690
-            //setup the date range.
691
-            $DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
692
-            $beginning_date = new DateTime("now " . $period, $DateTimeZone);
693
-            $ending_date = new DateTime("now", $DateTimeZone);
694
-            $subtitle = sprintf(
695
-                _x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
696
-                $beginning_date->format('Y-m-d'),
697
-                $ending_date->format('Y-m-d')
698
-            );
699
-        }
700
-        $report_title = __('Total Registrations per Event', 'event_espresso');
701
-        $report_params = array(
702
-            'title'     => $report_title,
703
-            'subtitle'  => $subtitle,
704
-            'id'        => $report_ID,
705
-            'regs'      => $regs,
706
-            'noResults' => empty($regs),
707
-            'noRegsMsg' => sprintf(
708
-                __(
709
-                    '%sThere are currently no registration records in the last month for this report.%s',
710
-                    'event_espresso'
711
-                ),
712
-                '<h2>' . $report_title . '</h2><p>',
713
-                '</p>'
714
-            ),
715
-        );
716
-        wp_localize_script('ee-reg-reports-js', 'regPerEvent', $report_params);
717
-        return $report_ID;
718
-    }
719
-
720
-
721
-
722
-    /**
723
-     * generates HTML for the Registration Check-in list table (showing all Check-ins for a specific registration)
724
-     *
725
-     * @access protected
726
-     * @return void
727
-     * @throws \EE_Error
728
-     */
729
-    protected function _registration_checkin_list_table()
730
-    {
731
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
732
-        $reg_id = isset($this->_req_data['_REGID']) ? $this->_req_data['_REGID'] : null;
733
-        /** @var EE_Registration $reg */
734
-        $reg = EEM_Registration::instance()->get_one_by_ID($reg_id);
735
-        $this->_admin_page_title .= $this->get_action_link_or_button(
736
-            'new_registration',
737
-            'add-registrant',
738
-            array('event_id' => $reg->event_ID()),
739
-            'add-new-h2'
740
-        );
741
-        $legend_items = array(
742
-            'checkin'  => array(
743
-                'class' => 'ee-icon ee-icon-check-in',
744
-                'desc'  => __('This indicates the attendee has been checked in', 'event_espresso'),
745
-            ),
746
-            'checkout' => array(
747
-                'class' => 'ee-icon ee-icon-check-out',
748
-                'desc'  => __('This indicates the attendee has been checked out', 'event_espresso'),
749
-            ),
750
-        );
751
-        $this->_template_args['after_list_table'] = $this->_display_legend($legend_items);
752
-        $dtt_id = isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null;
753
-        $go_back_url = ! empty($reg_id) ? EE_Admin_Page::add_query_args_and_nonce(
754
-            array(
755
-                'action'   => 'event_registrations',
756
-                'event_id' => EEM_Registration::instance()->get_one_by_ID($reg_id)->get_first_related('Event')->ID(),
757
-                'DTT_ID'   => $dtt_id,
758
-            ),
759
-            $this->_admin_base_url
760
-        ) : '';
761
-        $this->_template_args['before_list_table'] = ! empty($reg_id) && ! empty($dtt_id)
762
-            ? '<h2>' . sprintf(
763
-                __("%s's check in records for %s at the event, %s", 'event_espresso'),
764
-                '<span id="checkin-attendee-name">'
765
-                . EEM_Registration::instance()
766
-                                  ->get_one_by_ID($reg_id)
767
-                                  ->get_first_related('Attendee')
768
-                                  ->full_name() . '</span>',
769
-                '<span id="checkin-dtt"><a href="' . $go_back_url . '">'
770
-                . EEM_Datetime::instance()
771
-                              ->get_one_by_ID($dtt_id)
772
-                              ->start_date_and_time() . ' - '
773
-                . EEM_Datetime::instance()
774
-                              ->get_one_by_ID($dtt_id)
775
-                              ->end_date_and_time() . '</a></span>',
776
-                '<span id="checkin-event-name">'
777
-                . EEM_Datetime::instance()
778
-                              ->get_one_by_ID($dtt_id)
779
-                              ->get_first_related('Event')
780
-                              ->get('EVT_name') . '</span>'
781
-            ) . '</h2>'
782
-            : '';
783
-        $this->_template_args['list_table_hidden_fields'] = ! empty($reg_id)
784
-            ? '<input type="hidden" name="_REGID" value="' . $reg_id . '">' : '';
785
-        $this->_template_args['list_table_hidden_fields'] .= ! empty($dtt_id)
786
-            ? '<input type="hidden" name="DTT_ID" value="' . $dtt_id . '">' : '';
787
-        $this->display_admin_list_table_page_with_no_sidebar();
788
-    }
789
-
790
-
791
-
792
-    /**
793
-     * toggle the Check-in status for the given registration (coming from ajax)
794
-     *
795
-     * @return void (JSON)
796
-     */
797
-    public function toggle_checkin_status()
798
-    {
799
-        //first make sure we have the necessary data
800
-        if ( ! isset($this->_req_data['_regid'])) {
801
-            EE_Error::add_error(
802
-                __(
803
-                    'There must be something broken with the html structure because the required data for toggling the Check-in status is not being sent via ajax',
804
-                    'event_espresso'
805
-                ),
806
-                __FILE__,
807
-                __FUNCTION__,
808
-                __LINE__
809
-            );
810
-            $this->_template_args['success'] = false;
811
-            $this->_template_args['error'] = true;
812
-            $this->_return_json();
813
-        };
814
-        //do a nonce check cause we're not coming in from an normal route here.
815
-        $nonce = isset($this->_req_data['checkinnonce']) ? sanitize_text_field($this->_req_data['checkinnonce'])
816
-            : '';
817
-        $nonce_ref = 'checkin_nonce';
818
-        $this->_verify_nonce($nonce, $nonce_ref);
819
-        //beautiful! Made it this far so let's get the status.
820
-        $new_status = $this->_toggle_checkin_status();
821
-        //setup new class to return via ajax
822
-        $this->_template_args['admin_page_content'] = 'clickable trigger-checkin checkin-icons checkedin-status-'
823
-                                                      . $new_status;
824
-        $this->_template_args['success'] = true;
825
-        $this->_return_json();
826
-    }
827
-
828
-
829
-
830
-    /**
831
-     * handles toggling the checkin status for the registration,
832
-     *
833
-     * @access protected
834
-     * @return int|void
835
-     */
836
-    protected function _toggle_checkin_status()
837
-    {
838
-        //first let's get the query args out of the way for the redirect
839
-        $query_args = array(
840
-            'action'   => 'event_registrations',
841
-            'event_id' => isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null,
842
-            'DTT_ID'   => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null,
843
-        );
844
-        $new_status = false;
845
-        // bulk action check in toggle
846
-        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
847
-            // cycle thru checkboxes
848
-            while (list($REG_ID, $value) = each($this->_req_data['checkbox'])) {
849
-                $DTT_ID = isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null;
850
-                $new_status = $this->_toggle_checkin($REG_ID, $DTT_ID);
851
-            }
852
-        } elseif (isset($this->_req_data['_regid'])) {
853
-            //coming from ajax request
854
-            $DTT_ID = isset($this->_req_data['dttid']) ? $this->_req_data['dttid'] : null;
855
-            $query_args['DTT_ID'] = $DTT_ID;
856
-            $new_status = $this->_toggle_checkin($this->_req_data['_regid'], $DTT_ID);
857
-        } else {
858
-            EE_Error::add_error(
859
-                __('Missing some required data to toggle the Check-in', 'event_espresso'),
860
-                __FILE__,
861
-                __FUNCTION__,
862
-                __LINE__
863
-            );
864
-        }
865
-        if (defined('DOING_AJAX')) {
866
-            return $new_status;
867
-        }
868
-        $this->_redirect_after_action(false, '', '', $query_args, true);
869
-    }
870
-
871
-
872
-
873
-    /**
874
-     * This is toggles a single Check-in for the given registration and datetime.
875
-     *
876
-     * @param  int $REG_ID The registration we're toggling
877
-     * @param  int $DTT_ID The datetime we're toggling
878
-     * @return int            The new status toggled to.
879
-     * @throws \EE_Error
880
-     */
881
-    private function _toggle_checkin($REG_ID, $DTT_ID)
882
-    {
883
-        /** @var EE_Registration $REG */
884
-        $REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
885
-        $new_status = $REG->toggle_checkin_status($DTT_ID);
886
-        if ($new_status !== false) {
887
-            EE_Error::add_success($REG->get_checkin_msg($DTT_ID));
888
-        } else {
889
-            EE_Error::add_error($REG->get_checkin_msg($DTT_ID, true), __FILE__, __FUNCTION__, __LINE__);
890
-            $new_status = false;
891
-        }
892
-        return $new_status;
893
-    }
894
-
895
-
896
-
897
-    /**
898
-     * Takes care of deleting multiple EE_Checkin table rows
899
-     *
900
-     * @access protected
901
-     * @return void
902
-     * @throws \EE_Error
903
-     */
904
-    protected function _delete_checkin_rows()
905
-    {
906
-        $query_args = array(
907
-            'action' => 'registration_checkins',
908
-            'DTT_ID' => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : 0,
909
-            '_REGID' => isset($this->_req_data['_REGID']) ? $this->_req_data['_REGID'] : 0,
910
-        );
911
-        $errors = 0;
912
-        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
913
-            while (list($CHK_ID, $value) = each($this->_req_data['checkbox'])) {
914
-                if ( ! EEM_Checkin::instance()->delete_by_ID($CHK_ID)) {
915
-                    $errors++;
916
-                }
917
-            }
918
-        } else {
919
-            EE_Error::add_error(
920
-                __(
921
-                    'So, something went wrong with the bulk delete because there was no data received for instructions on WHAT to delete!',
922
-                    'event_espresso'
923
-                ),
924
-                __FILE__,
925
-                __FUNCTION__,
926
-                __LINE__
927
-            );
928
-            $this->_redirect_after_action(false, '', '', $query_args, true);
929
-        }
930
-        if ($errors > 0) {
931
-            EE_Error::add_error(
932
-                sprintf(__('There were %d records that did not delete successfully', 'event_espresso'), $errors),
933
-                __FILE__,
934
-                __FUNCTION__,
935
-                __LINE__
936
-            );
937
-        } else {
938
-            EE_Error::add_success(__('Records were successfully deleted', 'event_espresso'));
939
-        }
940
-        $this->_redirect_after_action(false, '', '', $query_args, true);
941
-    }
942
-
943
-
944
-
945
-    /**
946
-     * Deletes a single EE_Checkin row
947
-     *
948
-     * @return void
949
-     * @throws \EE_Error
950
-     */
951
-    protected function _delete_checkin_row()
952
-    {
953
-        $query_args = array(
954
-            'action' => 'registration_checkins',
955
-            'DTT_ID' => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : 0,
956
-            '_REGID' => isset($this->_req_data['_REGID']) ? $this->_req_data['_REGID'] : 0,
957
-        );
958
-        if ( ! empty($this->_req_data['CHK_ID'])) {
959
-            if ( ! EEM_Checkin::instance()->delete_by_ID($this->_req_data['CHK_ID'])) {
960
-                EE_Error::add_error(
961
-                    __('Something went wrong and this check-in record was not deleted', 'event_espresso'),
962
-                    __FILE__,
963
-                    __FUNCTION__,
964
-                    __LINE__
965
-                );
966
-            } else {
967
-                EE_Error::add_success(__('Check-In record successfully deleted', 'event_espresso'));
968
-            }
969
-        } else {
970
-            EE_Error::add_error(
971
-                __(
972
-                    'In order to delete a Check-in record, there must be a Check-In ID available. There is not. It is not your fault, there is just a gremlin living in the code',
973
-                    'event_espresso'
974
-                ),
975
-                __FILE__,
976
-                __FUNCTION__,
977
-                __LINE__
978
-            );
979
-        }
980
-        $this->_redirect_after_action(false, '', '', $query_args, true);
981
-    }
982
-
983
-
984
-
985
-    /**
986
-     *        generates HTML for the Event Registrations List Table
987
-     *
988
-     * @access protected
989
-     * @return void
990
-     * @throws \EE_Error
991
-     */
992
-    protected function _event_registrations_list_table()
993
-    {
994
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
995
-        $this->_admin_page_title .= isset($this->_req_data['event_id'])
996
-            ? $this->get_action_link_or_button(
997
-                'new_registration',
998
-                'add-registrant',
999
-                array('event_id' => $this->_req_data['event_id']),
1000
-                'add-new-h2',
1001
-                '',
1002
-                false
1003
-            )
1004
-            : '';
1005
-        $legend_items = array(
1006
-            'star-icon'        => array(
1007
-                'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
1008
-                'desc'  => __('This Registrant is the Primary Registrant', 'event_espresso'),
1009
-            ),
1010
-            'checkin'          => array(
1011
-                'class' => 'ee-icon ee-icon-check-in',
1012
-                'desc'  => __('This Registrant has been Checked In', 'event_espresso'),
1013
-            ),
1014
-            'checkout'         => array(
1015
-                'class' => 'ee-icon ee-icon-check-out',
1016
-                'desc'  => __('This Registrant has been Checked Out', 'event_espresso'),
1017
-            ),
1018
-            'nocheckinrecord'  => array(
1019
-                'class' => 'dashicons dashicons-no',
1020
-                'desc'  => __('No Check-in Record has been Created for this Registrant', 'event_espresso'),
1021
-            ),
1022
-            'view_details'     => array(
1023
-                'class' => 'dashicons dashicons-search',
1024
-                'desc'  => __('View All Check-in Records for this Registrant', 'event_espresso'),
1025
-            ),
1026
-            'approved_status'  => array(
1027
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
1028
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
1029
-            ),
1030
-            'cancelled_status' => array(
1031
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1032
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
1033
-            ),
1034
-            'declined_status'  => array(
1035
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
1036
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
1037
-            ),
1038
-            'not_approved'     => array(
1039
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
1040
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
1041
-            ),
1042
-            'pending_status'   => array(
1043
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
1044
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
1045
-            ),
1046
-            'wait_list'        => array(
1047
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
1048
-                'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
1049
-            ),
1050
-        );
1051
-        $this->_template_args['after_list_table'] = $this->_display_legend($legend_items);
1052
-        $event_id = isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null;
1053
-        $this->_template_args['before_list_table'] = ! empty($event_id)
1054
-            ? '<h2>' . sprintf(
1055
-                __('Viewing Registrations for Event: %s', 'event_espresso'),
1056
-                EEM_Event::instance()->get_one_by_ID($event_id)->get('EVT_name')
1057
-            ) . '</h2>'
1058
-            : '';
1059
-        //need to get the number of datetimes on the event and set default datetime_id if there is only one datetime on the event.
1060
-        /** @var EE_Event $event */
1061
-        $event = EEM_Event::instance()->get_one_by_ID($event_id);
1062
-        $DTT_ID = ! empty($this->_req_data['DTT_ID']) ? absint($this->_req_data['DTT_ID']) : 0;
1063
-        $datetime = null;
1064
-        if ($event instanceof EE_Event) {
1065
-            $datetimes_on_event = $event->datetimes();
1066
-            if (count($datetimes_on_event) === 1) {
1067
-                $datetime = reset($datetimes_on_event);
1068
-            }
1069
-        }
1070
-        $datetime = $datetime instanceof EE_Datetime ? $datetime : EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1071
-        if ($datetime instanceof EE_Datetime && $this->_template_args['before_list_table'] !== '') {
1072
-            $this->_template_args['before_list_table'] = substr($this->_template_args['before_list_table'], 0, -5);
1073
-            $this->_template_args['before_list_table'] .= ' &nbsp;<span class="drk-grey-text">';
1074
-            $this->_template_args['before_list_table'] .= '<span class="dashicons dashicons-calendar"></span>';
1075
-            $this->_template_args['before_list_table'] .= $datetime->name();
1076
-            $this->_template_args['before_list_table'] .= ' ( ' . $datetime->date_and_time_range() . ' )';
1077
-            $this->_template_args['before_list_table'] .= '</span></h2>';
1078
-        }
1079
-        //if no datetime, then we're on the initial view, so let's give some helpful instructions on what the status column
1080
-        //represents
1081
-        if ( ! $datetime instanceof EE_Datetime) {
1082
-            $this->_template_args['before_list_table'] .= '<br><p class="description">'
1083
-                                                          . __('In this view, the check-in status represents the latest check-in record for the registration in that row.',
1084
-                    'event_espresso')
1085
-                                                          . '</p>';
1086
-        }
1087
-        $this->display_admin_list_table_page_with_no_sidebar();
1088
-    }
1089
-
1090
-    /**
1091
-     * Download the registrations check-in report (same as the normal registration report, but with different where
1092
-     * conditions)
1093
-     *
1094
-     * @return void ends the request by a redirect or download
1095
-     */
1096
-    public function _registrations_checkin_report()
1097
-    {
1098
-        $this->_registrations_report_base('_get_checkin_query_params_from_request');
1099
-    }
1100
-
1101
-    /**
1102
-     * Gets the query params from the request, plus adds a where condition for the registration status,
1103
-     * because on the checkin page we only ever want to see approved and pending-approval registrations
1104
-     *
1105
-     * @param array     $request
1106
-     * @param int  $per_page
1107
-     * @param bool $count
1108
-     * @return array
1109
-     */
1110
-    protected function _get_checkin_query_params_from_request(
1111
-        $request,
1112
-        $per_page = 10,
1113
-        $count = false
1114
-    ) {
1115
-        $query_params = $this->_get_registration_query_parameters($request, $per_page, $count);
1116
-        //unlike the regular registrations list table,
1117
-        $status_ids_array = apply_filters(
1118
-            'FHEE__Extend_Registrations_Admin_Page__get_event_attendees__status_ids_array',
1119
-            array(EEM_Registration::status_id_pending_payment, EEM_Registration::status_id_approved)
1120
-        );
1121
-        $query_params[0]['STS_ID'] = array('IN', $status_ids_array);
1122
-        return $query_params;
1123
-    }
1124
-
1125
-
1126
-
1127
-
1128
-    /**
1129
-     * Gets registrations for an event
1130
-     *
1131
-     * @param int    $per_page
1132
-     * @param bool   $count whether to return count or data.
1133
-     * @param bool   $trash
1134
-     * @param string $orderby
1135
-     * @return EE_Registration[]|int
1136
-     * @throws \EE_Error
1137
-     */
1138
-    public function get_event_attendees($per_page = 10, $count = false, $trash = false, $orderby = 'ATT_fname')
1139
-    {
1140
-        //normalize some request params that get setup by the parent `get_registrations` method.
1141
-        $request = $this->_req_data;
1142
-        $request['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : $orderby;
1143
-        $request['order'] =  ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'ASC';
1144
-        if($trash){
1145
-            $request['status'] = 'trash';
1146
-        }
1147
-        $query_params = $this->_get_checkin_query_params_from_request( $request, $per_page, $count );
1148
-
1149
-        return $count
1150
-            ? EEM_Registration::instance()->count($query_params)
1151
-            /** @type EE_Registration[] */
1152
-            : EEM_Registration::instance()->get_all($query_params);
1153
-    }
20
+	/**
21
+	 * This is used to hold the reports template data which is setup early in the request.
22
+	 *
23
+	 * @type array
24
+	 */
25
+	protected $_reports_template_data = array();
26
+
27
+
28
+
29
+	/**
30
+	 * Extend_Registrations_Admin_Page constructor.
31
+	 *
32
+	 * @param bool $routing
33
+	 */
34
+	public function __construct($routing = true)
35
+	{
36
+		parent::__construct($routing);
37
+		if ( ! defined('REG_CAF_TEMPLATE_PATH')) {
38
+			define('REG_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/templates/');
39
+			define('REG_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'registrations/assets/');
40
+			define('REG_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'registrations/assets/');
41
+		}
42
+	}
43
+
44
+
45
+
46
+	protected function _extend_page_config()
47
+	{
48
+		$this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'registrations';
49
+		$reg_id = ! empty($this->_req_data['_REG_ID']) && ! is_array($this->_req_data['_REG_ID'])
50
+			? $this->_req_data['_REG_ID']
51
+			: 0;
52
+		// $att_id = ! empty( $this->_req_data['ATT_ID'] ) ? ! is_array( $this->_req_data['ATT_ID'] ) : 0;
53
+		// $att_id = ! empty( $this->_req_data['post'] ) && ! is_array( $this->_req_data['post'] )
54
+		// 	? $this->_req_data['post'] : $att_id;
55
+		$new_page_routes = array(
56
+			'reports'                  => array(
57
+				'func'       => '_registration_reports',
58
+				'capability' => 'ee_read_registrations',
59
+			),
60
+			'registration_checkins'    => array(
61
+				'func'       => '_registration_checkin_list_table',
62
+				'capability' => 'ee_read_checkins',
63
+			),
64
+			'newsletter_selected_send' => array(
65
+				'func'       => '_newsletter_selected_send',
66
+				'noheader'   => true,
67
+				'capability' => 'ee_send_message',
68
+			),
69
+			'delete_checkin_rows'      => array(
70
+				'func'       => '_delete_checkin_rows',
71
+				'noheader'   => true,
72
+				'capability' => 'ee_delete_checkins',
73
+			),
74
+			'delete_checkin_row'       => array(
75
+				'func'       => '_delete_checkin_row',
76
+				'noheader'   => true,
77
+				'capability' => 'ee_delete_checkin',
78
+				'obj_id'     => $reg_id,
79
+			),
80
+			'toggle_checkin_status'    => array(
81
+				'func'       => '_toggle_checkin_status',
82
+				'noheader'   => true,
83
+				'capability' => 'ee_edit_checkin',
84
+				'obj_id'     => $reg_id,
85
+			),
86
+			'event_registrations'      => array(
87
+				'func'       => '_event_registrations_list_table',
88
+				'capability' => 'ee_read_checkins',
89
+			),
90
+			'registrations_checkin_report' => array(
91
+				'func'       => '_registrations_checkin_report',
92
+				'noheader'   => true,
93
+				'capability' => 'ee_read_registrations',
94
+			),
95
+		);
96
+		$this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
97
+		$new_page_config = array(
98
+			'reports'               => array(
99
+				'nav'           => array(
100
+					'label' => __('Reports', 'event_espresso'),
101
+					'order' => 30,
102
+				),
103
+				'help_tabs'     => array(
104
+					'registrations_reports_help_tab' => array(
105
+						'title'    => __('Registration Reports', 'event_espresso'),
106
+						'filename' => 'registrations_reports',
107
+					),
108
+				),
109
+				/*'help_tour' => array( 'Registration_Reports_Help_Tour' ),*/
110
+				'require_nonce' => false,
111
+			),
112
+			'event_registrations'   => array(
113
+				'nav'           => array(
114
+					'label'      => __('Event Check-In', 'event_espresso'),
115
+					'order'      => 10,
116
+					'persistent' => true,
117
+				),
118
+				'help_tabs'     => array(
119
+					'registrations_event_checkin_help_tab'                       => array(
120
+						'title'    => __('Registrations Event Check-In', 'event_espresso'),
121
+						'filename' => 'registrations_event_checkin',
122
+					),
123
+					'registrations_event_checkin_table_column_headings_help_tab' => array(
124
+						'title'    => __('Event Check-In Table Column Headings', 'event_espresso'),
125
+						'filename' => 'registrations_event_checkin_table_column_headings',
126
+					),
127
+					'registrations_event_checkin_filters_help_tab'               => array(
128
+						'title'    => __('Event Check-In Filters', 'event_espresso'),
129
+						'filename' => 'registrations_event_checkin_filters',
130
+					),
131
+					'registrations_event_checkin_views_help_tab'                 => array(
132
+						'title'    => __('Event Check-In Views', 'event_espresso'),
133
+						'filename' => 'registrations_event_checkin_views',
134
+					),
135
+					'registrations_event_checkin_other_help_tab'                 => array(
136
+						'title'    => __('Event Check-In Other', 'event_espresso'),
137
+						'filename' => 'registrations_event_checkin_other',
138
+					),
139
+				),
140
+				'help_tour'     => array('Event_Checkin_Help_Tour'),
141
+				'qtips'         => array('Registration_List_Table_Tips'),
142
+				'list_table'    => 'EE_Event_Registrations_List_Table',
143
+				'metaboxes'     => array(),
144
+				'require_nonce' => false,
145
+			),
146
+			'registration_checkins' => array(
147
+				'nav'           => array(
148
+					'label'      => __('Check-In Records', 'event_espresso'),
149
+					'order'      => 15,
150
+					'persistent' => false,
151
+				),
152
+				'list_table'    => 'EE_Registration_CheckIn_List_Table',
153
+				//'help_tour' => array( 'Checkin_Toggle_View_Help_Tour' ),
154
+				'metaboxes'     => array(),
155
+				'require_nonce' => false,
156
+			),
157
+		);
158
+		$this->_page_config = array_merge($this->_page_config, $new_page_config);
159
+		$this->_page_config['contact_list']['list_table'] = 'Extend_EE_Attendee_Contact_List_Table';
160
+		$this->_page_config['default']['list_table'] = 'Extend_EE_Registrations_List_Table';
161
+	}
162
+
163
+
164
+
165
+	protected function _ajax_hooks()
166
+	{
167
+		parent::_ajax_hooks();
168
+		add_action('wp_ajax_get_newsletter_form_content', array($this, 'get_newsletter_form_content'));
169
+	}
170
+
171
+
172
+
173
+	public function load_scripts_styles()
174
+	{
175
+		parent::load_scripts_styles();
176
+		//if newsletter message type is active then let's add filter and load js for it.
177
+		if (EEH_MSG_Template::is_mt_active('newsletter')) {
178
+			//enqueue newsletter js
179
+			wp_enqueue_script(
180
+				'ee-newsletter-trigger',
181
+				REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.js',
182
+				array('ee-dialog'),
183
+				EVENT_ESPRESSO_VERSION,
184
+				true
185
+			);
186
+			wp_enqueue_style(
187
+				'ee-newsletter-trigger-css',
188
+				REG_CAF_ASSETS_URL . 'ee-newsletter-trigger.css',
189
+				array(),
190
+				EVENT_ESPRESSO_VERSION
191
+			);
192
+			//hook in buttons for newsletter message type trigger.
193
+			add_action(
194
+				'AHEE__EE_Admin_List_Table__extra_tablenav__after_bottom_buttons',
195
+				array($this, 'add_newsletter_action_buttons'),
196
+				10
197
+			);
198
+		}
199
+	}
200
+
201
+
202
+
203
+	public function load_scripts_styles_reports()
204
+	{
205
+		wp_register_script(
206
+			'ee-reg-reports-js',
207
+			REG_CAF_ASSETS_URL . 'ee-registration-admin-reports.js',
208
+			array('google-charts'),
209
+			EVENT_ESPRESSO_VERSION,
210
+			true
211
+		);
212
+		wp_enqueue_script('ee-reg-reports-js');
213
+		$this->_registration_reports_js_setup();
214
+	}
215
+
216
+
217
+
218
+	protected function _add_screen_options_event_registrations()
219
+	{
220
+		$this->_per_page_screen_option();
221
+	}
222
+
223
+
224
+
225
+	protected function _add_screen_options_registration_checkins()
226
+	{
227
+		$page_title = $this->_admin_page_title;
228
+		$this->_admin_page_title = __('Check-In Records', 'event_espresso');
229
+		$this->_per_page_screen_option();
230
+		$this->_admin_page_title = $page_title;
231
+	}
232
+
233
+
234
+
235
+	protected function _set_list_table_views_event_registrations()
236
+	{
237
+		$this->_views = array(
238
+			'all' => array(
239
+				'slug'        => 'all',
240
+				'label'       => __('All', 'event_espresso'),
241
+				'count'       => 0,
242
+				'bulk_action' => ! isset($this->_req_data['event_id'])
243
+					? array()
244
+					: array(
245
+						'toggle_checkin_status' => __('Toggle Check-In', 'event_espresso'),
246
+						//'trash_registrations' => __('Trash Registrations', 'event_espresso')
247
+					),
248
+			),
249
+		);
250
+	}
251
+
252
+
253
+
254
+	protected function _set_list_table_views_registration_checkins()
255
+	{
256
+		$this->_views = array(
257
+			'all' => array(
258
+				'slug'        => 'all',
259
+				'label'       => __('All', 'event_espresso'),
260
+				'count'       => 0,
261
+				'bulk_action' => array('delete_checkin_rows' => __('Delete Check-In Rows', 'event_espresso')),
262
+			),
263
+		);
264
+	}
265
+
266
+
267
+
268
+	/**
269
+	 * callback for ajax action.
270
+	 *
271
+	 * @since 4.3.0
272
+	 * @return void (JSON)
273
+	 * @throws \EE_Error
274
+	 */
275
+	public function get_newsletter_form_content()
276
+	{
277
+		//do a nonce check cause we're not coming in from an normal route here.
278
+		$nonce = isset($this->_req_data['get_newsletter_form_content_nonce']) ? sanitize_text_field(
279
+			$this->_req_data['get_newsletter_form_content_nonce']
280
+		) : '';
281
+		$nonce_ref = 'get_newsletter_form_content_nonce';
282
+		$this->_verify_nonce($nonce, $nonce_ref);
283
+		//let's get the mtp for the incoming MTP_ ID
284
+		if ( ! isset($this->_req_data['GRP_ID'])) {
285
+			EE_Error::add_error(
286
+				__(
287
+					'There must be something broken with the js or html structure because the required data for getting a message template group is not present (need an GRP_ID).',
288
+					'event_espresso'
289
+				),
290
+				__FILE__,
291
+				__FUNCTION__,
292
+				__LINE__
293
+			);
294
+			$this->_template_args['success'] = false;
295
+			$this->_template_args['error'] = true;
296
+			$this->_return_json();
297
+		}
298
+		$MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID($this->_req_data['GRP_ID']);
299
+		if ( ! $MTPG instanceof EE_Message_Template_Group) {
300
+			EE_Error::add_error(
301
+				sprintf(
302
+					__(
303
+						'The GRP_ID given (%d) does not appear to have a corresponding row in the database.',
304
+						'event_espresso'
305
+					),
306
+					$this->_req_data['GRP_ID']
307
+				),
308
+				__FILE__,
309
+				__FUNCTION__,
310
+				__LINE__
311
+			);
312
+			$this->_template_args['success'] = false;
313
+			$this->_template_args['error'] = true;
314
+			$this->_return_json();
315
+		}
316
+		$MTPs = $MTPG->context_templates();
317
+		$MTPs = $MTPs['attendee'];
318
+		$template_fields = array();
319
+		/** @var EE_Message_Template $MTP */
320
+		foreach ($MTPs as $MTP) {
321
+			$field = $MTP->get('MTP_template_field');
322
+			if ($field === 'content') {
323
+				$content = $MTP->get('MTP_content');
324
+				if ( ! empty($content['newsletter_content'])) {
325
+					$template_fields['newsletter_content'] = $content['newsletter_content'];
326
+				}
327
+				continue;
328
+			}
329
+			$template_fields[$MTP->get('MTP_template_field')] = $MTP->get('MTP_content');
330
+		}
331
+		$this->_template_args['success'] = true;
332
+		$this->_template_args['error'] = false;
333
+		$this->_template_args['data'] = array(
334
+			'batch_message_from'    => isset($template_fields['from'])
335
+				? $template_fields['from']
336
+				: '',
337
+			'batch_message_subject' => isset($template_fields['subject'])
338
+				? $template_fields['subject']
339
+				: '',
340
+			'batch_message_content' => isset($template_fields['newsletter_content'])
341
+				? $template_fields['newsletter_content']
342
+				: '',
343
+		);
344
+		$this->_return_json();
345
+	}
346
+
347
+
348
+
349
+	/**
350
+	 * callback for AHEE__EE_Admin_List_Table__extra_tablenav__after_bottom_buttons action
351
+	 *
352
+	 * @since 4.3.0
353
+	 * @param EE_Admin_List_Table $list_table
354
+	 * @return void
355
+	 */
356
+	public function add_newsletter_action_buttons(EE_Admin_List_Table $list_table)
357
+	{
358
+		if ( ! EE_Registry::instance()->CAP->current_user_can(
359
+			'ee_send_message',
360
+			'espresso_registrations_newsletter_selected_send'
361
+		)
362
+		) {
363
+			return;
364
+		}
365
+		$routes_to_add_to = array(
366
+			'contact_list',
367
+			'event_registrations',
368
+			'default',
369
+		);
370
+		if ($this->_current_page === 'espresso_registrations' && in_array($this->_req_action, $routes_to_add_to)) {
371
+			if (($this->_req_action === 'event_registrations' && empty($this->_req_data['event_id']))
372
+				|| (isset($this->_req_data['status']) && $this->_req_data['status'] === 'trash')
373
+			) {
374
+				echo '';
375
+			} else {
376
+				$button_text = sprintf(
377
+					__('Send Batch Message (%s selected)', 'event_espresso'),
378
+					'<span class="send-selected-newsletter-count">0</span>'
379
+				);
380
+				echo '<button id="selected-batch-send-trigger" class="button secondary-button"><span class="dashicons dashicons-email "></span>'
381
+					 . $button_text
382
+					 . '</button>';
383
+				add_action('admin_footer', array($this, 'newsletter_send_form_skeleton'));
384
+			}
385
+		}
386
+	}
387
+
388
+
389
+
390
+	public function newsletter_send_form_skeleton()
391
+	{
392
+		$list_table = $this->_list_table_object;
393
+		$codes = array();
394
+		//need to templates for the newsletter message type for the template selector.
395
+		$values[] = array('text' => __('Select Template to Use', 'event_espresso'), 'id' => 0);
396
+		$mtps = EEM_Message_Template_Group::instance()->get_all(
397
+			array(array('MTP_message_type' => 'newsletter', 'MTP_messenger' => 'email'))
398
+		);
399
+		foreach ($mtps as $mtp) {
400
+			$name = $mtp->name();
401
+			$values[] = array(
402
+				'text' => empty($name) ? __('Global', 'event_espresso') : $name,
403
+				'id'   => $mtp->ID(),
404
+			);
405
+		}
406
+		//need to get a list of shortcodes that are available for the newsletter message type.
407
+		$shortcodes = EEH_MSG_Template::get_shortcodes('newsletter', 'email', array(), 'attendee', false);
408
+		foreach ($shortcodes as $field => $shortcode_array) {
409
+			$codes[$field] = implode(', ', array_keys($shortcode_array));
410
+		}
411
+		$shortcodes = $codes;
412
+		$form_template = REG_CAF_TEMPLATE_PATH . 'newsletter-send-form.template.php';
413
+		$form_template_args = array(
414
+			'form_action'       => admin_url('admin.php?page=espresso_registrations'),
415
+			'form_route'        => 'newsletter_selected_send',
416
+			'form_nonce_name'   => 'newsletter_selected_send_nonce',
417
+			'form_nonce'        => wp_create_nonce('newsletter_selected_send_nonce'),
418
+			'redirect_back_to'  => $this->_req_action,
419
+			'ajax_nonce'        => wp_create_nonce('get_newsletter_form_content_nonce'),
420
+			'template_selector' => EEH_Form_Fields::select_input('newsletter_mtp_selected', $values),
421
+			'shortcodes'        => $shortcodes,
422
+			'id_type'           => $list_table instanceof EE_Attendee_Contact_List_Table ? 'contact' : 'registration',
423
+		);
424
+		EEH_Template::display_template($form_template, $form_template_args);
425
+	}
426
+
427
+
428
+
429
+	/**
430
+	 * Handles sending selected registrations/contacts a newsletter.
431
+	 *
432
+	 * @since  4.3.0
433
+	 * @return void
434
+	 * @throws \EE_Error
435
+	 */
436
+	protected function _newsletter_selected_send()
437
+	{
438
+		$success = true;
439
+		//first we need to make sure we have a GRP_ID so we know what template we're sending and updating!
440
+		if (empty($this->_req_data['newsletter_mtp_selected'])) {
441
+			EE_Error::add_error(
442
+				__(
443
+					'In order to send a message, a Message Template GRP_ID is needed. It was not provided so messages were not sent.',
444
+					'event_espresso'
445
+				),
446
+				__FILE__,
447
+				__FUNCTION__,
448
+				__LINE__
449
+			);
450
+			$success = false;
451
+		}
452
+		if ($success) {
453
+			//update Message template in case there are any changes
454
+			$Message_Template_Group = EEM_Message_Template_Group::instance()->get_one_by_ID(
455
+				$this->_req_data['newsletter_mtp_selected']
456
+			);
457
+			$Message_Templates = $Message_Template_Group instanceof EE_Message_Template_Group
458
+				? $Message_Template_Group->context_templates()
459
+				: array();
460
+			if (empty($Message_Templates)) {
461
+				EE_Error::add_error(
462
+					__(
463
+						'Unable to retrieve message template fields from the db. Messages not sent.',
464
+						'event_espresso'
465
+					),
466
+					__FILE__,
467
+					__FUNCTION__,
468
+					__LINE__
469
+				);
470
+			}
471
+			//let's just update the specific fields
472
+			foreach ($Message_Templates['attendee'] as $Message_Template) {
473
+				if ($Message_Template instanceof EE_Message_Template) {
474
+					$field = $Message_Template->get('MTP_template_field');
475
+					$content = $Message_Template->get('MTP_content');
476
+					$new_content = $content;
477
+					switch ($field) {
478
+						case 'from' :
479
+							$new_content = ! empty($this->_req_data['batch_message']['from'])
480
+								? $this->_req_data['batch_message']['from']
481
+								: $content;
482
+							break;
483
+						case 'subject' :
484
+							$new_content = ! empty($this->_req_data['batch_message']['subject'])
485
+								? $this->_req_data['batch_message']['subject']
486
+								: $content;
487
+							break;
488
+						case 'content' :
489
+							$new_content = $content;
490
+							$new_content['newsletter_content'] = ! empty($this->_req_data['batch_message']['content'])
491
+								? $this->_req_data['batch_message']['content']
492
+								: $content['newsletter_content'];
493
+							break;
494
+						default :
495
+							//continue the foreach loop, we don't want to set $new_content nor save.
496
+							continue 2;
497
+					}
498
+					$Message_Template->set('MTP_content', $new_content);
499
+					$Message_Template->save();
500
+				}
501
+			}
502
+			//great fields are updated!  now let's make sure we just have contact objects (EE_Attendee).
503
+			$id_type = ! empty($this->_req_data['batch_message']['id_type'])
504
+				? $this->_req_data['batch_message']['id_type']
505
+				: 'registration';
506
+			//id_type will affect how we assemble the ids.
507
+			$ids = ! empty($this->_req_data['batch_message']['ids'])
508
+				? json_decode(stripslashes($this->_req_data['batch_message']['ids']))
509
+				: array();
510
+			$registrations_used_for_contact_data = array();
511
+			//using switch because eventually we'll have other contexts that will be used for generating messages.
512
+			switch ($id_type) {
513
+				case 'registration' :
514
+					$registrations_used_for_contact_data = EEM_Registration::instance()->get_all(
515
+						array(
516
+							array(
517
+								'REG_ID' => array('IN', $ids),
518
+							),
519
+						)
520
+					);
521
+					break;
522
+				case 'contact' :
523
+					$registrations_used_for_contact_data = EEM_Registration::instance()
524
+																		   ->get_latest_registration_for_each_of_given_contacts($ids);
525
+					break;
526
+			}
527
+			do_action(
528
+				'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
529
+				$registrations_used_for_contact_data,
530
+				$Message_Template_Group->ID()
531
+			);
532
+			//kept for backward compat, internally we no longer use this action.
533
+			//@deprecated 4.8.36.rc.002
534
+			$contacts = $id_type === 'registration'
535
+				? EEM_Attendee::instance()->get_array_of_contacts_from_reg_ids($ids)
536
+				: EEM_Attendee::instance()->get_all(array(array('ATT_ID' => array('in', $ids))));
537
+			do_action(
538
+				'AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send',
539
+				$contacts,
540
+				$Message_Template_Group->ID()
541
+			);
542
+		}
543
+		$query_args = array(
544
+			'action' => ! empty($this->_req_data['redirect_back_to'])
545
+				? $this->_req_data['redirect_back_to']
546
+				: 'default',
547
+		);
548
+		$this->_redirect_after_action(false, '', '', $query_args, true);
549
+	}
550
+
551
+
552
+
553
+	/**
554
+	 * This is called when javascript is being enqueued to setup the various data needed for the reports js.
555
+	 * Also $this->{$_reports_template_data} property is set for later usage by the _registration_reports method.
556
+	 */
557
+	protected function _registration_reports_js_setup()
558
+	{
559
+		$this->_reports_template_data['admin_reports'][] = $this->_registrations_per_day_report();
560
+		$this->_reports_template_data['admin_reports'][] = $this->_registrations_per_event_report();
561
+	}
562
+
563
+
564
+
565
+	/**
566
+	 *        generates Business Reports regarding Registrations
567
+	 *
568
+	 * @access protected
569
+	 * @return void
570
+	 */
571
+	protected function _registration_reports()
572
+	{
573
+		$template_path = EE_ADMIN_TEMPLATE . 'admin_reports.template.php';
574
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
575
+			$template_path,
576
+			$this->_reports_template_data,
577
+			true
578
+		);
579
+		// the final template wrapper
580
+		$this->display_admin_page_with_no_sidebar();
581
+	}
582
+
583
+
584
+
585
+	/**
586
+	 * Generates Business Report showing total registrations per day.
587
+	 *
588
+	 * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
589
+	 * @return string
590
+	 */
591
+	private function _registrations_per_day_report($period = '-1 month')
592
+	{
593
+		$report_ID = 'reg-admin-registrations-per-day-report-dv';
594
+		$results = EEM_Registration::instance()->get_registrations_per_day_and_per_status_report($period);
595
+		$results = (array)$results;
596
+		$regs = array();
597
+		$subtitle = '';
598
+		if ($results) {
599
+			$column_titles = array();
600
+			$tracker = 0;
601
+			foreach ($results as $result) {
602
+				$report_column_values = array();
603
+				foreach ($result as $property_name => $property_value) {
604
+					$property_value = $property_name === 'Registration_REG_date' ? $property_value
605
+						: (int)$property_value;
606
+					$report_column_values[] = $property_value;
607
+					if ($tracker === 0) {
608
+						if ($property_name === 'Registration_REG_date') {
609
+							$column_titles[] = __('Date (only days with registrations are shown)', 'event_espresso');
610
+						} else {
611
+							$column_titles[] = EEH_Template::pretty_status($property_name, false, 'sentence');
612
+						}
613
+					}
614
+				}
615
+				$tracker++;
616
+				$regs[] = $report_column_values;
617
+			}
618
+			//make sure the column_titles is pushed to the beginning of the array
619
+			array_unshift($regs, $column_titles);
620
+			//setup the date range.
621
+			$DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
622
+			$beginning_date = new DateTime("now " . $period, $DateTimeZone);
623
+			$ending_date = new DateTime("now", $DateTimeZone);
624
+			$subtitle = sprintf(
625
+				_x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
626
+				$beginning_date->format('Y-m-d'),
627
+				$ending_date->format('Y-m-d')
628
+			);
629
+		}
630
+		$report_title = __('Total Registrations per Day', 'event_espresso');
631
+		$report_params = array(
632
+			'title'     => $report_title,
633
+			'subtitle'  => $subtitle,
634
+			'id'        => $report_ID,
635
+			'regs'      => $regs,
636
+			'noResults' => empty($regs),
637
+			'noRegsMsg' => sprintf(
638
+				__(
639
+					'%sThere are currently no registration records in the last month for this report.%s',
640
+					'event_espresso'
641
+				),
642
+				'<h2>' . $report_title . '</h2><p>',
643
+				'</p>'
644
+			),
645
+		);
646
+		wp_localize_script('ee-reg-reports-js', 'regPerDay', $report_params);
647
+		return $report_ID;
648
+	}
649
+
650
+
651
+
652
+	/**
653
+	 * Generates Business Report showing total registrations per event.
654
+	 *
655
+	 * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
656
+	 * @return string
657
+	 */
658
+	private function _registrations_per_event_report($period = '-1 month')
659
+	{
660
+		$report_ID = 'reg-admin-registrations-per-event-report-dv';
661
+		$results = EEM_Registration::instance()->get_registrations_per_event_and_per_status_report($period);
662
+		$results = (array)$results;
663
+		$regs = array();
664
+		$subtitle = '';
665
+		if ($results) {
666
+			$column_titles = array();
667
+			$tracker = 0;
668
+			foreach ($results as $result) {
669
+				$report_column_values = array();
670
+				foreach ($result as $property_name => $property_value) {
671
+					$property_value = $property_name === 'Registration_Event' ? wp_trim_words(
672
+						$property_value,
673
+						4,
674
+						'...'
675
+					) : (int)$property_value;
676
+					$report_column_values[] = $property_value;
677
+					if ($tracker === 0) {
678
+						if ($property_name === 'Registration_Event') {
679
+							$column_titles[] = __('Event', 'event_espresso');
680
+						} else {
681
+							$column_titles[] = EEH_Template::pretty_status($property_name, false, 'sentence');
682
+						}
683
+					}
684
+				}
685
+				$tracker++;
686
+				$regs[] = $report_column_values;
687
+			}
688
+			//make sure the column_titles is pushed to the beginning of the array
689
+			array_unshift($regs, $column_titles);
690
+			//setup the date range.
691
+			$DateTimeZone = new DateTimeZone(EEH_DTT_Helper::get_timezone());
692
+			$beginning_date = new DateTime("now " . $period, $DateTimeZone);
693
+			$ending_date = new DateTime("now", $DateTimeZone);
694
+			$subtitle = sprintf(
695
+				_x('For the period: %1$s to %2$s', 'Used to give date range', 'event_espresso'),
696
+				$beginning_date->format('Y-m-d'),
697
+				$ending_date->format('Y-m-d')
698
+			);
699
+		}
700
+		$report_title = __('Total Registrations per Event', 'event_espresso');
701
+		$report_params = array(
702
+			'title'     => $report_title,
703
+			'subtitle'  => $subtitle,
704
+			'id'        => $report_ID,
705
+			'regs'      => $regs,
706
+			'noResults' => empty($regs),
707
+			'noRegsMsg' => sprintf(
708
+				__(
709
+					'%sThere are currently no registration records in the last month for this report.%s',
710
+					'event_espresso'
711
+				),
712
+				'<h2>' . $report_title . '</h2><p>',
713
+				'</p>'
714
+			),
715
+		);
716
+		wp_localize_script('ee-reg-reports-js', 'regPerEvent', $report_params);
717
+		return $report_ID;
718
+	}
719
+
720
+
721
+
722
+	/**
723
+	 * generates HTML for the Registration Check-in list table (showing all Check-ins for a specific registration)
724
+	 *
725
+	 * @access protected
726
+	 * @return void
727
+	 * @throws \EE_Error
728
+	 */
729
+	protected function _registration_checkin_list_table()
730
+	{
731
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
732
+		$reg_id = isset($this->_req_data['_REGID']) ? $this->_req_data['_REGID'] : null;
733
+		/** @var EE_Registration $reg */
734
+		$reg = EEM_Registration::instance()->get_one_by_ID($reg_id);
735
+		$this->_admin_page_title .= $this->get_action_link_or_button(
736
+			'new_registration',
737
+			'add-registrant',
738
+			array('event_id' => $reg->event_ID()),
739
+			'add-new-h2'
740
+		);
741
+		$legend_items = array(
742
+			'checkin'  => array(
743
+				'class' => 'ee-icon ee-icon-check-in',
744
+				'desc'  => __('This indicates the attendee has been checked in', 'event_espresso'),
745
+			),
746
+			'checkout' => array(
747
+				'class' => 'ee-icon ee-icon-check-out',
748
+				'desc'  => __('This indicates the attendee has been checked out', 'event_espresso'),
749
+			),
750
+		);
751
+		$this->_template_args['after_list_table'] = $this->_display_legend($legend_items);
752
+		$dtt_id = isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null;
753
+		$go_back_url = ! empty($reg_id) ? EE_Admin_Page::add_query_args_and_nonce(
754
+			array(
755
+				'action'   => 'event_registrations',
756
+				'event_id' => EEM_Registration::instance()->get_one_by_ID($reg_id)->get_first_related('Event')->ID(),
757
+				'DTT_ID'   => $dtt_id,
758
+			),
759
+			$this->_admin_base_url
760
+		) : '';
761
+		$this->_template_args['before_list_table'] = ! empty($reg_id) && ! empty($dtt_id)
762
+			? '<h2>' . sprintf(
763
+				__("%s's check in records for %s at the event, %s", 'event_espresso'),
764
+				'<span id="checkin-attendee-name">'
765
+				. EEM_Registration::instance()
766
+								  ->get_one_by_ID($reg_id)
767
+								  ->get_first_related('Attendee')
768
+								  ->full_name() . '</span>',
769
+				'<span id="checkin-dtt"><a href="' . $go_back_url . '">'
770
+				. EEM_Datetime::instance()
771
+							  ->get_one_by_ID($dtt_id)
772
+							  ->start_date_and_time() . ' - '
773
+				. EEM_Datetime::instance()
774
+							  ->get_one_by_ID($dtt_id)
775
+							  ->end_date_and_time() . '</a></span>',
776
+				'<span id="checkin-event-name">'
777
+				. EEM_Datetime::instance()
778
+							  ->get_one_by_ID($dtt_id)
779
+							  ->get_first_related('Event')
780
+							  ->get('EVT_name') . '</span>'
781
+			) . '</h2>'
782
+			: '';
783
+		$this->_template_args['list_table_hidden_fields'] = ! empty($reg_id)
784
+			? '<input type="hidden" name="_REGID" value="' . $reg_id . '">' : '';
785
+		$this->_template_args['list_table_hidden_fields'] .= ! empty($dtt_id)
786
+			? '<input type="hidden" name="DTT_ID" value="' . $dtt_id . '">' : '';
787
+		$this->display_admin_list_table_page_with_no_sidebar();
788
+	}
789
+
790
+
791
+
792
+	/**
793
+	 * toggle the Check-in status for the given registration (coming from ajax)
794
+	 *
795
+	 * @return void (JSON)
796
+	 */
797
+	public function toggle_checkin_status()
798
+	{
799
+		//first make sure we have the necessary data
800
+		if ( ! isset($this->_req_data['_regid'])) {
801
+			EE_Error::add_error(
802
+				__(
803
+					'There must be something broken with the html structure because the required data for toggling the Check-in status is not being sent via ajax',
804
+					'event_espresso'
805
+				),
806
+				__FILE__,
807
+				__FUNCTION__,
808
+				__LINE__
809
+			);
810
+			$this->_template_args['success'] = false;
811
+			$this->_template_args['error'] = true;
812
+			$this->_return_json();
813
+		};
814
+		//do a nonce check cause we're not coming in from an normal route here.
815
+		$nonce = isset($this->_req_data['checkinnonce']) ? sanitize_text_field($this->_req_data['checkinnonce'])
816
+			: '';
817
+		$nonce_ref = 'checkin_nonce';
818
+		$this->_verify_nonce($nonce, $nonce_ref);
819
+		//beautiful! Made it this far so let's get the status.
820
+		$new_status = $this->_toggle_checkin_status();
821
+		//setup new class to return via ajax
822
+		$this->_template_args['admin_page_content'] = 'clickable trigger-checkin checkin-icons checkedin-status-'
823
+													  . $new_status;
824
+		$this->_template_args['success'] = true;
825
+		$this->_return_json();
826
+	}
827
+
828
+
829
+
830
+	/**
831
+	 * handles toggling the checkin status for the registration,
832
+	 *
833
+	 * @access protected
834
+	 * @return int|void
835
+	 */
836
+	protected function _toggle_checkin_status()
837
+	{
838
+		//first let's get the query args out of the way for the redirect
839
+		$query_args = array(
840
+			'action'   => 'event_registrations',
841
+			'event_id' => isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null,
842
+			'DTT_ID'   => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null,
843
+		);
844
+		$new_status = false;
845
+		// bulk action check in toggle
846
+		if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
847
+			// cycle thru checkboxes
848
+			while (list($REG_ID, $value) = each($this->_req_data['checkbox'])) {
849
+				$DTT_ID = isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : null;
850
+				$new_status = $this->_toggle_checkin($REG_ID, $DTT_ID);
851
+			}
852
+		} elseif (isset($this->_req_data['_regid'])) {
853
+			//coming from ajax request
854
+			$DTT_ID = isset($this->_req_data['dttid']) ? $this->_req_data['dttid'] : null;
855
+			$query_args['DTT_ID'] = $DTT_ID;
856
+			$new_status = $this->_toggle_checkin($this->_req_data['_regid'], $DTT_ID);
857
+		} else {
858
+			EE_Error::add_error(
859
+				__('Missing some required data to toggle the Check-in', 'event_espresso'),
860
+				__FILE__,
861
+				__FUNCTION__,
862
+				__LINE__
863
+			);
864
+		}
865
+		if (defined('DOING_AJAX')) {
866
+			return $new_status;
867
+		}
868
+		$this->_redirect_after_action(false, '', '', $query_args, true);
869
+	}
870
+
871
+
872
+
873
+	/**
874
+	 * This is toggles a single Check-in for the given registration and datetime.
875
+	 *
876
+	 * @param  int $REG_ID The registration we're toggling
877
+	 * @param  int $DTT_ID The datetime we're toggling
878
+	 * @return int            The new status toggled to.
879
+	 * @throws \EE_Error
880
+	 */
881
+	private function _toggle_checkin($REG_ID, $DTT_ID)
882
+	{
883
+		/** @var EE_Registration $REG */
884
+		$REG = EEM_Registration::instance()->get_one_by_ID($REG_ID);
885
+		$new_status = $REG->toggle_checkin_status($DTT_ID);
886
+		if ($new_status !== false) {
887
+			EE_Error::add_success($REG->get_checkin_msg($DTT_ID));
888
+		} else {
889
+			EE_Error::add_error($REG->get_checkin_msg($DTT_ID, true), __FILE__, __FUNCTION__, __LINE__);
890
+			$new_status = false;
891
+		}
892
+		return $new_status;
893
+	}
894
+
895
+
896
+
897
+	/**
898
+	 * Takes care of deleting multiple EE_Checkin table rows
899
+	 *
900
+	 * @access protected
901
+	 * @return void
902
+	 * @throws \EE_Error
903
+	 */
904
+	protected function _delete_checkin_rows()
905
+	{
906
+		$query_args = array(
907
+			'action' => 'registration_checkins',
908
+			'DTT_ID' => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : 0,
909
+			'_REGID' => isset($this->_req_data['_REGID']) ? $this->_req_data['_REGID'] : 0,
910
+		);
911
+		$errors = 0;
912
+		if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
913
+			while (list($CHK_ID, $value) = each($this->_req_data['checkbox'])) {
914
+				if ( ! EEM_Checkin::instance()->delete_by_ID($CHK_ID)) {
915
+					$errors++;
916
+				}
917
+			}
918
+		} else {
919
+			EE_Error::add_error(
920
+				__(
921
+					'So, something went wrong with the bulk delete because there was no data received for instructions on WHAT to delete!',
922
+					'event_espresso'
923
+				),
924
+				__FILE__,
925
+				__FUNCTION__,
926
+				__LINE__
927
+			);
928
+			$this->_redirect_after_action(false, '', '', $query_args, true);
929
+		}
930
+		if ($errors > 0) {
931
+			EE_Error::add_error(
932
+				sprintf(__('There were %d records that did not delete successfully', 'event_espresso'), $errors),
933
+				__FILE__,
934
+				__FUNCTION__,
935
+				__LINE__
936
+			);
937
+		} else {
938
+			EE_Error::add_success(__('Records were successfully deleted', 'event_espresso'));
939
+		}
940
+		$this->_redirect_after_action(false, '', '', $query_args, true);
941
+	}
942
+
943
+
944
+
945
+	/**
946
+	 * Deletes a single EE_Checkin row
947
+	 *
948
+	 * @return void
949
+	 * @throws \EE_Error
950
+	 */
951
+	protected function _delete_checkin_row()
952
+	{
953
+		$query_args = array(
954
+			'action' => 'registration_checkins',
955
+			'DTT_ID' => isset($this->_req_data['DTT_ID']) ? $this->_req_data['DTT_ID'] : 0,
956
+			'_REGID' => isset($this->_req_data['_REGID']) ? $this->_req_data['_REGID'] : 0,
957
+		);
958
+		if ( ! empty($this->_req_data['CHK_ID'])) {
959
+			if ( ! EEM_Checkin::instance()->delete_by_ID($this->_req_data['CHK_ID'])) {
960
+				EE_Error::add_error(
961
+					__('Something went wrong and this check-in record was not deleted', 'event_espresso'),
962
+					__FILE__,
963
+					__FUNCTION__,
964
+					__LINE__
965
+				);
966
+			} else {
967
+				EE_Error::add_success(__('Check-In record successfully deleted', 'event_espresso'));
968
+			}
969
+		} else {
970
+			EE_Error::add_error(
971
+				__(
972
+					'In order to delete a Check-in record, there must be a Check-In ID available. There is not. It is not your fault, there is just a gremlin living in the code',
973
+					'event_espresso'
974
+				),
975
+				__FILE__,
976
+				__FUNCTION__,
977
+				__LINE__
978
+			);
979
+		}
980
+		$this->_redirect_after_action(false, '', '', $query_args, true);
981
+	}
982
+
983
+
984
+
985
+	/**
986
+	 *        generates HTML for the Event Registrations List Table
987
+	 *
988
+	 * @access protected
989
+	 * @return void
990
+	 * @throws \EE_Error
991
+	 */
992
+	protected function _event_registrations_list_table()
993
+	{
994
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
995
+		$this->_admin_page_title .= isset($this->_req_data['event_id'])
996
+			? $this->get_action_link_or_button(
997
+				'new_registration',
998
+				'add-registrant',
999
+				array('event_id' => $this->_req_data['event_id']),
1000
+				'add-new-h2',
1001
+				'',
1002
+				false
1003
+			)
1004
+			: '';
1005
+		$legend_items = array(
1006
+			'star-icon'        => array(
1007
+				'class' => 'dashicons dashicons-star-filled lt-blue-icon ee-icon-size-8',
1008
+				'desc'  => __('This Registrant is the Primary Registrant', 'event_espresso'),
1009
+			),
1010
+			'checkin'          => array(
1011
+				'class' => 'ee-icon ee-icon-check-in',
1012
+				'desc'  => __('This Registrant has been Checked In', 'event_espresso'),
1013
+			),
1014
+			'checkout'         => array(
1015
+				'class' => 'ee-icon ee-icon-check-out',
1016
+				'desc'  => __('This Registrant has been Checked Out', 'event_espresso'),
1017
+			),
1018
+			'nocheckinrecord'  => array(
1019
+				'class' => 'dashicons dashicons-no',
1020
+				'desc'  => __('No Check-in Record has been Created for this Registrant', 'event_espresso'),
1021
+			),
1022
+			'view_details'     => array(
1023
+				'class' => 'dashicons dashicons-search',
1024
+				'desc'  => __('View All Check-in Records for this Registrant', 'event_espresso'),
1025
+			),
1026
+			'approved_status'  => array(
1027
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_approved,
1028
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_approved, false, 'sentence'),
1029
+			),
1030
+			'cancelled_status' => array(
1031
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_cancelled,
1032
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_cancelled, false, 'sentence'),
1033
+			),
1034
+			'declined_status'  => array(
1035
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_declined,
1036
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_declined, false, 'sentence'),
1037
+			),
1038
+			'not_approved'     => array(
1039
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_not_approved,
1040
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_not_approved, false, 'sentence'),
1041
+			),
1042
+			'pending_status'   => array(
1043
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_pending_payment,
1044
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_pending_payment, false, 'sentence'),
1045
+			),
1046
+			'wait_list'        => array(
1047
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Registration::status_id_wait_list,
1048
+				'desc'  => EEH_Template::pretty_status(EEM_Registration::status_id_wait_list, false, 'sentence'),
1049
+			),
1050
+		);
1051
+		$this->_template_args['after_list_table'] = $this->_display_legend($legend_items);
1052
+		$event_id = isset($this->_req_data['event_id']) ? $this->_req_data['event_id'] : null;
1053
+		$this->_template_args['before_list_table'] = ! empty($event_id)
1054
+			? '<h2>' . sprintf(
1055
+				__('Viewing Registrations for Event: %s', 'event_espresso'),
1056
+				EEM_Event::instance()->get_one_by_ID($event_id)->get('EVT_name')
1057
+			) . '</h2>'
1058
+			: '';
1059
+		//need to get the number of datetimes on the event and set default datetime_id if there is only one datetime on the event.
1060
+		/** @var EE_Event $event */
1061
+		$event = EEM_Event::instance()->get_one_by_ID($event_id);
1062
+		$DTT_ID = ! empty($this->_req_data['DTT_ID']) ? absint($this->_req_data['DTT_ID']) : 0;
1063
+		$datetime = null;
1064
+		if ($event instanceof EE_Event) {
1065
+			$datetimes_on_event = $event->datetimes();
1066
+			if (count($datetimes_on_event) === 1) {
1067
+				$datetime = reset($datetimes_on_event);
1068
+			}
1069
+		}
1070
+		$datetime = $datetime instanceof EE_Datetime ? $datetime : EEM_Datetime::instance()->get_one_by_ID($DTT_ID);
1071
+		if ($datetime instanceof EE_Datetime && $this->_template_args['before_list_table'] !== '') {
1072
+			$this->_template_args['before_list_table'] = substr($this->_template_args['before_list_table'], 0, -5);
1073
+			$this->_template_args['before_list_table'] .= ' &nbsp;<span class="drk-grey-text">';
1074
+			$this->_template_args['before_list_table'] .= '<span class="dashicons dashicons-calendar"></span>';
1075
+			$this->_template_args['before_list_table'] .= $datetime->name();
1076
+			$this->_template_args['before_list_table'] .= ' ( ' . $datetime->date_and_time_range() . ' )';
1077
+			$this->_template_args['before_list_table'] .= '</span></h2>';
1078
+		}
1079
+		//if no datetime, then we're on the initial view, so let's give some helpful instructions on what the status column
1080
+		//represents
1081
+		if ( ! $datetime instanceof EE_Datetime) {
1082
+			$this->_template_args['before_list_table'] .= '<br><p class="description">'
1083
+														  . __('In this view, the check-in status represents the latest check-in record for the registration in that row.',
1084
+					'event_espresso')
1085
+														  . '</p>';
1086
+		}
1087
+		$this->display_admin_list_table_page_with_no_sidebar();
1088
+	}
1089
+
1090
+	/**
1091
+	 * Download the registrations check-in report (same as the normal registration report, but with different where
1092
+	 * conditions)
1093
+	 *
1094
+	 * @return void ends the request by a redirect or download
1095
+	 */
1096
+	public function _registrations_checkin_report()
1097
+	{
1098
+		$this->_registrations_report_base('_get_checkin_query_params_from_request');
1099
+	}
1100
+
1101
+	/**
1102
+	 * Gets the query params from the request, plus adds a where condition for the registration status,
1103
+	 * because on the checkin page we only ever want to see approved and pending-approval registrations
1104
+	 *
1105
+	 * @param array     $request
1106
+	 * @param int  $per_page
1107
+	 * @param bool $count
1108
+	 * @return array
1109
+	 */
1110
+	protected function _get_checkin_query_params_from_request(
1111
+		$request,
1112
+		$per_page = 10,
1113
+		$count = false
1114
+	) {
1115
+		$query_params = $this->_get_registration_query_parameters($request, $per_page, $count);
1116
+		//unlike the regular registrations list table,
1117
+		$status_ids_array = apply_filters(
1118
+			'FHEE__Extend_Registrations_Admin_Page__get_event_attendees__status_ids_array',
1119
+			array(EEM_Registration::status_id_pending_payment, EEM_Registration::status_id_approved)
1120
+		);
1121
+		$query_params[0]['STS_ID'] = array('IN', $status_ids_array);
1122
+		return $query_params;
1123
+	}
1124
+
1125
+
1126
+
1127
+
1128
+	/**
1129
+	 * Gets registrations for an event
1130
+	 *
1131
+	 * @param int    $per_page
1132
+	 * @param bool   $count whether to return count or data.
1133
+	 * @param bool   $trash
1134
+	 * @param string $orderby
1135
+	 * @return EE_Registration[]|int
1136
+	 * @throws \EE_Error
1137
+	 */
1138
+	public function get_event_attendees($per_page = 10, $count = false, $trash = false, $orderby = 'ATT_fname')
1139
+	{
1140
+		//normalize some request params that get setup by the parent `get_registrations` method.
1141
+		$request = $this->_req_data;
1142
+		$request['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : $orderby;
1143
+		$request['order'] =  ! empty($this->_req_data['order']) ? $this->_req_data['order'] : 'ASC';
1144
+		if($trash){
1145
+			$request['status'] = 'trash';
1146
+		}
1147
+		$query_params = $this->_get_checkin_query_params_from_request( $request, $per_page, $count );
1148
+
1149
+		return $count
1150
+			? EEM_Registration::instance()->count($query_params)
1151
+			/** @type EE_Registration[] */
1152
+			: EEM_Registration::instance()->get_all($query_params);
1153
+	}
1154 1154
 
1155 1155
 } //end class Registrations Admin Page
Please login to merge, or discard this patch.
core/libraries/batch/Helpers/JobParameters.php 1 patch
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -96,12 +96,12 @@  discard block
 block discarded – undo
96 96
 	 * @param array $request_data
97 97
 	 * @param array $extra_data
98 98
 	 */
99
-	function __construct( $job_id, $classname, $request_data, $extra_data = array() ) {
100
-		$this->set_job_id( $job_id );
101
-		$this->set_classname( $classname );
102
-		$this->set_request_data( $request_data );
103
-		$this->set_extra_data( $extra_data );
104
-		$this->set_status( JobParameters::status_continue );
99
+	function __construct($job_id, $classname, $request_data, $extra_data = array()) {
100
+		$this->set_job_id($job_id);
101
+		$this->set_classname($classname);
102
+		$this->set_request_data($request_data);
103
+		$this->set_extra_data($extra_data);
104
+		$this->set_status(JobParameters::status_continue);
105 105
 	}
106 106
 
107 107
 
@@ -126,12 +126,12 @@  discard block
 block discarded – undo
126 126
 	 * @param boolean $first
127 127
 	 * @return boolean success
128 128
 	 */
129
-	function save( $first = false ) {
130
-		$object_vars = get_object_vars( $this );
131
-		if( $first ) {
132
-			return add_option( $this->option_name(), $object_vars, null, 'no' );
133
-		} else{
134
-			return update_option( $this->option_name(), $object_vars );
129
+	function save($first = false) {
130
+		$object_vars = get_object_vars($this);
131
+		if ($first) {
132
+			return add_option($this->option_name(), $object_vars, null, 'no');
133
+		} else {
134
+			return update_option($this->option_name(), $object_vars);
135 135
 		}
136 136
 	}
137 137
 
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 	 * @return boolean
144 144
 	 */
145 145
 	function delete() {
146
-		return delete_option( $this->option_name() );
146
+		return delete_option($this->option_name());
147 147
 	}
148 148
 
149 149
 
@@ -154,26 +154,26 @@  discard block
 block discarded – undo
154 154
 	 * @return JobParameters
155 155
 	 * @throws BatchRequestException
156 156
 	 */
157
-	static function load( $job_id ) {
158
-		$job_parameter_vars = get_option( JobParameters::wp_option_prefix . $job_id );
159
-		if(
160
-			! is_array( $job_parameter_vars ) ||
161
-			! isset( $job_parameter_vars[ '_classname' ] ) ||
162
-			! isset( $job_parameter_vars[ '_request_data' ] )
157
+	static function load($job_id) {
158
+		$job_parameter_vars = get_option(JobParameters::wp_option_prefix.$job_id);
159
+		if (
160
+			! is_array($job_parameter_vars) ||
161
+			! isset($job_parameter_vars['_classname']) ||
162
+			! isset($job_parameter_vars['_request_data'])
163 163
 		) {
164 164
 			throw new BatchRequestException(
165 165
 				sprintf(
166 166
 					__('Could not retrieve job %1$s from the Wordpress options table, and so the job could not continue. The wordpress option was %2$s', 'event_espresso'),
167 167
 					$job_id,
168
-					get_option( JobParameters::wp_option_prefix . $job_id )
168
+					get_option(JobParameters::wp_option_prefix.$job_id)
169 169
 				)
170 170
 			);
171 171
 		}
172 172
 		$job_parameters = new JobParameters(
173 173
 				$job_id,
174
-				$job_parameter_vars[ '_classname' ],
175
-				$job_parameter_vars[ '_request_data'] );
176
-		foreach( $job_parameter_vars as $key => $value ) {
174
+				$job_parameter_vars['_classname'],
175
+				$job_parameter_vars['_request_data'] );
176
+		foreach ($job_parameter_vars as $key => $value) {
177 177
 			$job_parameters->{$key} = $value;
178 178
 		}
179 179
 		return $job_parameters;
@@ -217,9 +217,9 @@  discard block
 block discarded – undo
217 217
 	 * @param string|array $default
218 218
 	 * @return string|array
219 219
 	 */
220
-	function request_datum( $key, $default = '' ) {
221
-		if( isset( $this->_request_data[ $key ] ) ) {
222
-			return $this->_request_data[ $key ];
220
+	function request_datum($key, $default = '') {
221
+		if (isset($this->_request_data[$key])) {
222
+			return $this->_request_data[$key];
223 223
 		} else {
224 224
 			return $default;
225 225
 		}
@@ -233,9 +233,9 @@  discard block
 block discarded – undo
233 233
 	 * @param string|array $default
234 234
 	 * @return string|array
235 235
 	 */
236
-	function extra_datum( $key, $default = '' ) {
237
-		if( isset( $this->_extra_data[ $key ] ) ) {
238
-			return $this->_extra_data[ $key ];
236
+	function extra_datum($key, $default = '') {
237
+		if (isset($this->_extra_data[$key])) {
238
+			return $this->_extra_data[$key];
239 239
 		} else {
240 240
 			return $default;
241 241
 		}
@@ -248,8 +248,8 @@  discard block
 block discarded – undo
248 248
 	 * @param string $key
249 249
 	 * @param string|int|array|null $value almost any extra data you want to store
250 250
 	 */
251
-	function add_extra_data( $key, $value ) {
252
-		$this->_extra_data[ $key ] = $value;
251
+	function add_extra_data($key, $value) {
252
+		$this->_extra_data[$key] = $value;
253 253
 	}
254 254
 
255 255
 
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 	 * Sets the job size. You decide what units to use
279 279
 	 * @param int $size
280 280
 	 */
281
-	function set_job_size( $size ) {
281
+	function set_job_size($size) {
282 282
 		$this->_job_size = $size;
283 283
 	}
284 284
 
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
 	 * @param int $newly_processed
300 300
 	 * @return int updated units processed
301 301
 	 */
302
-	function mark_processed( $newly_processed ) {
302
+	function mark_processed($newly_processed) {
303 303
 		$this->_units_processed += $newly_processed;
304 304
 		return $this->_units_processed;
305 305
 	}
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 	 * Sets the total count of units processed. You might prefer to use mark_processed
311 311
 	 * @param int $total_units_processed
312 312
 	 */
313
-	function set_units_processed( $total_units_processed ) {
313
+	function set_units_processed($total_units_processed) {
314 314
 		$this->_units_processed = $total_units_processed;
315 315
 	}
316 316
 
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
 	 * Sets the job's ID
321 321
 	 * @param string $job_id
322 322
 	 */
323
-	function set_job_id( $job_id ) {
323
+	function set_job_id($job_id) {
324 324
 		$this->_job_id = $job_id;
325 325
 	}
326 326
 
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 	 * sets the classname
331 331
 	 * @param string $classname
332 332
 	 */
333
-	function set_classname( $classname ) {
333
+	function set_classname($classname) {
334 334
 		$this->_classname = $classname;
335 335
 	}
336 336
 
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 	 * Sets the request data
341 341
 	 * @param array $request_data
342 342
 	 */
343
-	function set_request_data( $request_data ) {
343
+	function set_request_data($request_data) {
344 344
 		$this->_request_data = $request_data;
345 345
 	}
346 346
 
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
 	 * Sets the array of extra data we want to store on this request
351 351
 	 * @param array $extra_data
352 352
 	 */
353
-	function set_extra_data( $extra_data ) {
353
+	function set_extra_data($extra_data) {
354 354
 		$this->_extra_data = $extra_data;
355 355
 	}
356 356
 
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
 	 * @return string
362 362
 	 */
363 363
 	function option_name() {
364
-		return JobParameters::wp_option_prefix . $this->job_id();
364
+		return JobParameters::wp_option_prefix.$this->job_id();
365 365
 	}
366 366
 
367 367
 
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 	 *
381 381
 	 * @param string $status on eof JobParameters::valid_stati()
382 382
 	 */
383
-	public function set_status( $status ) {
383
+	public function set_status($status) {
384 384
 		$this->_status = $status;
385 385
 	}
386 386
 
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +19 added lines, -17 removed lines patch added patch discarded remove patch
@@ -961,7 +961,7 @@  discard block
 block discarded – undo
961 961
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
962 962
      * foreign key to the WP_User table)
963 963
      *
964
-     * @return string|boolean string on success, boolean false when there is no
964
+     * @return string|false string on success, boolean false when there is no
965 965
      * foreign key to the WP_User table
966 966
      */
967 967
     public function wp_user_field_name()
@@ -1067,7 +1067,7 @@  discard block
 block discarded – undo
1067 1067
      *
1068 1068
      * @param array  $query_params      like EEM_Base::get_all's $query_params
1069 1069
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1070
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1071 1071
      *                                  fields on the model, and the models we joined to in the query. However, you can
1072 1072
      *                                  override this and set the select to "*", or a specific column name, like
1073 1073
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1459,7 +1459,7 @@  discard block
 block discarded – undo
1459 1459
      * @param string $field_name The name of the field the formats are being retrieved for.
1460 1460
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1461 1461
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1462
-     * @return array formats in an array with the date format first, and the time format last.
1462
+     * @return string[] formats in an array with the date format first, and the time format last.
1463 1463
      */
1464 1464
     public function get_formats_for($field_name, $pretty = false)
1465 1465
     {
@@ -1492,7 +1492,7 @@  discard block
 block discarded – undo
1492 1492
      *                                 be returned.
1493 1493
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1494 1494
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1495
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1495
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1496 1496
      *                                 exception is triggered.
1497 1497
      */
1498 1498
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1532,7 +1532,7 @@  discard block
 block discarded – undo
1532 1532
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1533 1533
      *                                format is
1534 1534
      *                                'U', this is ignored.
1535
-     * @return DateTime
1535
+     * @return string
1536 1536
      * @throws \EE_Error
1537 1537
      */
1538 1538
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -1830,7 +1830,7 @@  discard block
 block discarded – undo
1830 1830
      * Wrapper for EEM_Base::delete_permanently()
1831 1831
      *
1832 1832
      * @param mixed $id
1833
-     * @return boolean whether the row got deleted or not
1833
+     * @return integer whether the row got deleted or not
1834 1834
      * @throws \EE_Error
1835 1835
      */
1836 1836
     public function delete_permanently_by_ID($id)
@@ -1850,7 +1850,7 @@  discard block
 block discarded – undo
1850 1850
      * Wrapper for EEM_Base::delete()
1851 1851
      *
1852 1852
      * @param mixed $id
1853
-     * @return boolean whether the row got deleted or not
1853
+     * @return integer whether the row got deleted or not
1854 1854
      * @throws \EE_Error
1855 1855
      */
1856 1856
     public function delete_by_ID($id)
@@ -2300,7 +2300,7 @@  discard block
 block discarded – undo
2300 2300
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2301 2301
      * EEM_Base::$_db_verification_level
2302 2302
      *
2303
-     * @param $wpdb_method
2303
+     * @param string $wpdb_method
2304 2304
      * @param $arguments_to_provide
2305 2305
      * @return string
2306 2306
      */
@@ -2424,6 +2424,7 @@  discard block
 block discarded – undo
2424 2424
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2425 2425
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2426 2426
      *                             because these will be inserted in any new rows created as well.
2427
+     * @param EE_Base_Class $id_or_obj
2427 2428
      */
2428 2429
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2429 2430
     {
@@ -2434,7 +2435,7 @@  discard block
 block discarded – undo
2434 2435
 
2435 2436
 
2436 2437
     /**
2437
-     * @param mixed           $id_or_obj
2438
+     * @param EE_Base_Class           $id_or_obj
2438 2439
      * @param string          $relationName
2439 2440
      * @param array           $where_query_params
2440 2441
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2475,7 +2476,7 @@  discard block
 block discarded – undo
2475 2476
      * However, if the model objects can't be deleted because of blocking related model objects, then
2476 2477
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2477 2478
      *
2478
-     * @param EE_Base_Class|int|string $id_or_obj
2479
+     * @param EE_Base_Class $id_or_obj
2479 2480
      * @param string                   $model_name
2480 2481
      * @param array                    $query_params
2481 2482
      * @return int how many deleted
@@ -2496,7 +2497,7 @@  discard block
 block discarded – undo
2496 2497
      * the model objects can't be hard deleted because of blocking related model objects,
2497 2498
      * just does a soft-delete on them instead.
2498 2499
      *
2499
-     * @param EE_Base_Class|int|string $id_or_obj
2500
+     * @param EE_Base_Class $id_or_obj
2500 2501
      * @param string                   $model_name
2501 2502
      * @param array                    $query_params
2502 2503
      * @return int how many deleted
@@ -2553,6 +2554,7 @@  discard block
 block discarded – undo
2553 2554
      * @param string $model_name   like 'Event', or 'Registration'
2554 2555
      * @param array  $query_params like EEM_Base::get_all's
2555 2556
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2557
+     * @param EE_Base_Class $id_or_obj
2556 2558
      * @return float
2557 2559
      * @throws \EE_Error
2558 2560
      */
@@ -3023,7 +3025,7 @@  discard block
 block discarded – undo
3023 3025
      * Finds all the fields that correspond to the given table
3024 3026
      *
3025 3027
      * @param string $table_alias , array key in EEM_Base::_tables
3026
-     * @return EE_Model_Field_Base[]
3028
+     * @return EE_Model_Field_Base
3027 3029
      */
3028 3030
     public function _get_fields_for_table($table_alias)
3029 3031
     {
@@ -3508,7 +3510,7 @@  discard block
 block discarded – undo
3508 3510
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3509 3511
      * We should use default where conditions on related models when they requested to use default where conditions
3510 3512
      * on all models, or specifically just on other related models
3511
-     * @param      $default_where_conditions_value
3513
+     * @param      string $default_where_conditions_value
3512 3514
      * @param bool $for_this_model false means this is for OTHER related models
3513 3515
      * @return bool
3514 3516
      */
@@ -3546,7 +3548,7 @@  discard block
 block discarded – undo
3546 3548
      * where conditions.
3547 3549
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3548 3550
      * on this model or others
3549
-     * @param      $default_where_conditions_value
3551
+     * @param      string $default_where_conditions_value
3550 3552
      * @param bool $for_this_model false means this is for OTHER related models
3551 3553
      * @return bool
3552 3554
      */
@@ -4536,7 +4538,7 @@  discard block
 block discarded – undo
4536 4538
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4537 4539
      * Eg, on EE_Answer that would be ANS_ID field object
4538 4540
      *
4539
-     * @param $field_obj
4541
+     * @param EE_Model_Field_Base $field_obj
4540 4542
      * @return boolean
4541 4543
      */
4542 4544
     public function is_primary_key_field($field_obj)
@@ -4647,7 +4649,7 @@  discard block
 block discarded – undo
4647 4649
      * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4648 4650
      *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4649 4651
      *                            Either one works
4650
-     * @return EE_Table_Base
4652
+     * @return string
4651 4653
      */
4652 4654
     public function get_table_for_alias($table_alias)
4653 4655
     {
@@ -5258,7 +5260,7 @@  discard block
 block discarded – undo
5258 5260
     /**
5259 5261
      * Read comments for assume_values_already_prepared_by_model_object()
5260 5262
      *
5261
-     * @return int
5263
+     * @return boolean
5262 5264
      */
5263 5265
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5264 5266
     {
Please login to merge, or discard this patch.
Indentation   +5754 added lines, -5754 removed lines patch added patch discarded remove patch
@@ -29,5762 +29,5762 @@
 block discarded – undo
29 29
 abstract class EEM_Base extends EE_Base
30 30
 {
31 31
 
32
-    //admin posty
33
-    //basic -> grants access to mine -> if they don't have it, select none
34
-    //*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
-    //*_published -> grants access to published -> if they dont have it, select non-published
37
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
39
-    //frontend posty
40
-    //by default has access to published
41
-    //basic -> grants access to mine that arent published, and all published
42
-    //*_others ->grants access to others that arent private, all mine
43
-    //*_private -> grants full access
44
-    //frontend non-posty
45
-    //like admin posty
46
-    //category-y
47
-    //assign -> grants access to join-table
48
-    //(delete, edit)
49
-    //payment-method-y
50
-    //for each registered payment method,
51
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
-    /**
53
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
-     * They almost always WILL NOT, but it's not necessarily a requirement.
56
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
-     *
58
-     * @var boolean
59
-     */
60
-    private $_values_already_prepared_by_model_object = 0;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the data is just like form input that needs to have the model fields'
65
-     * prepare_for_set and prepare_for_use_in_db called on it
66
-     */
67
-    const not_prepared_by_model_object = 0;
68
-
69
-    /**
70
-     * when $_values_already_prepared_by_model_object equals this, we
71
-     * assume this value is coming from a model object and doesn't need to have
72
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
73
-     */
74
-    const prepared_by_model_object = 1;
75
-
76
-    /**
77
-     * when $_values_already_prepared_by_model_object equals this, we assume
78
-     * the values are already to be used in the database (ie no processing is done
79
-     * on them by the model's fields)
80
-     */
81
-    const prepared_for_use_in_db = 2;
82
-
83
-
84
-    protected $singular_item = 'Item';
85
-
86
-    protected $plural_item   = 'Items';
87
-
88
-    /**
89
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
-     */
91
-    protected $_tables;
92
-
93
-    /**
94
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
-     *
98
-     * @var \EE_Model_Field_Base[] $_fields
99
-     */
100
-    protected $_fields;
101
-
102
-    /**
103
-     * array of different kinds of relations
104
-     *
105
-     * @var \EE_Model_Relation_Base[] $_model_relations
106
-     */
107
-    protected $_model_relations;
108
-
109
-    /**
110
-     * @var \EE_Index[] $_indexes
111
-     */
112
-    protected $_indexes = array();
113
-
114
-    /**
115
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
116
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
-     * by setting the same columns as used in these queries in the query yourself.
118
-     *
119
-     * @var EE_Default_Where_Conditions
120
-     */
121
-    protected $_default_where_conditions_strategy;
122
-
123
-    /**
124
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
-     * This is particularly useful when you want something between 'none' and 'default'
126
-     *
127
-     * @var EE_Default_Where_Conditions
128
-     */
129
-    protected $_minimum_where_conditions_strategy;
130
-
131
-    /**
132
-     * String describing how to find the "owner" of this model's objects.
133
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
-     * But when there isn't, this indicates which related model, or transiently-related model,
135
-     * has the foreign key to the wp_users table.
136
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
-     * related to events, and events have a foreign key to wp_users.
138
-     * On EEM_Transaction, this would be 'Transaction.Event'
139
-     *
140
-     * @var string
141
-     */
142
-    protected $_model_chain_to_wp_user = '';
143
-
144
-    /**
145
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
-     * don't need it (particularly CPT models)
147
-     *
148
-     * @var bool
149
-     */
150
-    protected $_ignore_where_strategy = false;
151
-
152
-    /**
153
-     * String used in caps relating to this model. Eg, if the caps relating to this
154
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
-     *
156
-     * @var string. If null it hasn't been initialized yet. If false then we
157
-     * have indicated capabilities don't apply to this
158
-     */
159
-    protected $_caps_slug = null;
160
-
161
-    /**
162
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
-     * and next-level keys are capability names, and each's value is a
164
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
-     * they specify which context to use (ie, frontend, backend, edit or delete)
166
-     * and then each capability in the corresponding sub-array that they're missing
167
-     * adds the where conditions onto the query.
168
-     *
169
-     * @var array
170
-     */
171
-    protected $_cap_restrictions = array(
172
-        self::caps_read       => array(),
173
-        self::caps_read_admin => array(),
174
-        self::caps_edit       => array(),
175
-        self::caps_delete     => array(),
176
-    );
177
-
178
-    /**
179
-     * Array defining which cap restriction generators to use to create default
180
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
181
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
-     * automatically set this to false (not just null).
184
-     *
185
-     * @var EE_Restriction_Generator_Base[]
186
-     */
187
-    protected $_cap_restriction_generators = array();
188
-
189
-    /**
190
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
-     */
192
-    const caps_read       = 'read';
193
-
194
-    const caps_read_admin = 'read_admin';
195
-
196
-    const caps_edit       = 'edit';
197
-
198
-    const caps_delete     = 'delete';
199
-
200
-    /**
201
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
-     * maps to 'read' because when looking for relevant permissions we're going to use
204
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
205
-     *
206
-     * @var array
207
-     */
208
-    protected $_cap_contexts_to_cap_action_map = array(
209
-        self::caps_read       => 'read',
210
-        self::caps_read_admin => 'read',
211
-        self::caps_edit       => 'edit',
212
-        self::caps_delete     => 'delete',
213
-    );
214
-
215
-    /**
216
-     * Timezone
217
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
-     * EE_Datetime_Field data type will have access to it.
221
-     *
222
-     * @var string
223
-     */
224
-    protected $_timezone;
225
-
226
-
227
-    /**
228
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
-     * multisite.
230
-     *
231
-     * @var int
232
-     */
233
-    protected static $_model_query_blog_id;
234
-
235
-    /**
236
-     * A copy of _fields, except the array keys are the model names pointed to by
237
-     * the field
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cache_foreign_key_to_fields = array();
242
-
243
-    /**
244
-     * Cached list of all the fields on the model, indexed by their name
245
-     *
246
-     * @var EE_Model_Field_Base[]
247
-     */
248
-    private $_cached_fields = null;
249
-
250
-    /**
251
-     * Cached list of all the fields on the model, except those that are
252
-     * marked as only pertinent to the database
253
-     *
254
-     * @var EE_Model_Field_Base[]
255
-     */
256
-    private $_cached_fields_non_db_only = null;
257
-
258
-    /**
259
-     * A cached reference to the primary key for quick lookup
260
-     *
261
-     * @var EE_Model_Field_Base
262
-     */
263
-    private $_primary_key_field = null;
264
-
265
-    /**
266
-     * Flag indicating whether this model has a primary key or not
267
-     *
268
-     * @var boolean
269
-     */
270
-    protected $_has_primary_key_field = null;
271
-
272
-    /**
273
-     * Whether or not this model is based off a table in WP core only (CPTs should set
274
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
-     *
276
-     * @var boolean
277
-     */
278
-    protected $_wp_core_model = false;
279
-
280
-    /**
281
-     *    List of valid operators that can be used for querying.
282
-     * The keys are all operators we'll accept, the values are the real SQL
283
-     * operators used
284
-     *
285
-     * @var array
286
-     */
287
-    protected $_valid_operators = array(
288
-        '='           => '=',
289
-        '<='          => '<=',
290
-        '<'           => '<',
291
-        '>='          => '>=',
292
-        '>'           => '>',
293
-        '!='          => '!=',
294
-        'LIKE'        => 'LIKE',
295
-        'like'        => 'LIKE',
296
-        'NOT_LIKE'    => 'NOT LIKE',
297
-        'not_like'    => 'NOT LIKE',
298
-        'NOT LIKE'    => 'NOT LIKE',
299
-        'not like'    => 'NOT LIKE',
300
-        'IN'          => 'IN',
301
-        'in'          => 'IN',
302
-        'NOT_IN'      => 'NOT IN',
303
-        'not_in'      => 'NOT IN',
304
-        'NOT IN'      => 'NOT IN',
305
-        'not in'      => 'NOT IN',
306
-        'between'     => 'BETWEEN',
307
-        'BETWEEN'     => 'BETWEEN',
308
-        'IS_NOT_NULL' => 'IS NOT NULL',
309
-        'is_not_null' => 'IS NOT NULL',
310
-        'IS NOT NULL' => 'IS NOT NULL',
311
-        'is not null' => 'IS NOT NULL',
312
-        'IS_NULL'     => 'IS NULL',
313
-        'is_null'     => 'IS NULL',
314
-        'IS NULL'     => 'IS NULL',
315
-        'is null'     => 'IS NULL',
316
-        'REGEXP'      => 'REGEXP',
317
-        'regexp'      => 'REGEXP',
318
-        'NOT_REGEXP'  => 'NOT REGEXP',
319
-        'not_regexp'  => 'NOT REGEXP',
320
-        'NOT REGEXP'  => 'NOT REGEXP',
321
-        'not regexp'  => 'NOT REGEXP',
322
-    );
323
-
324
-    /**
325
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
-     *
327
-     * @var array
328
-     */
329
-    protected $_in_style_operators = array('IN', 'NOT IN');
330
-
331
-    /**
332
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
-     * '12-31-2012'"
334
-     *
335
-     * @var array
336
-     */
337
-    protected $_between_style_operators = array('BETWEEN');
338
-
339
-    /**
340
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
-     * on a join table.
342
-     *
343
-     * @var array
344
-     */
345
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
-
347
-    /**
348
-     * Allowed values for $query_params['order'] for ordering in queries
349
-     *
350
-     * @var array
351
-     */
352
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
-
354
-    /**
355
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
357
-     *
358
-     * @var array
359
-     */
360
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
-
362
-    /**
363
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
365
-     *
366
-     * @var array
367
-     */
368
-    private $_allowed_query_params = array(
369
-        0,
370
-        'limit',
371
-        'order_by',
372
-        'group_by',
373
-        'having',
374
-        'force_join',
375
-        'order',
376
-        'on_join_limit',
377
-        'default_where_conditions',
378
-        'caps',
379
-    );
380
-
381
-    /**
382
-     * All the data types that can be used in $wpdb->prepare statements.
383
-     *
384
-     * @var array
385
-     */
386
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
-
388
-    /**
389
-     *    EE_Registry Object
390
-     *
391
-     * @var    object
392
-     * @access    protected
393
-     */
394
-    protected $EE = null;
395
-
396
-
397
-    /**
398
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
-     *
400
-     * @var int
401
-     */
402
-    protected $_show_next_x_db_queries = 0;
403
-
404
-    /**
405
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
-     *
408
-     * @var array
409
-     */
410
-    protected $_custom_selections = array();
411
-
412
-    /**
413
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
-     * caches every model object we've fetched from the DB on this request
415
-     *
416
-     * @var array
417
-     */
418
-    protected $_entity_map;
419
-
420
-    /**
421
-     * constant used to show EEM_Base has not yet verified the db on this http request
422
-     */
423
-    const db_verified_none = 0;
424
-
425
-    /**
426
-     * constant used to show EEM_Base has verified the EE core db on this http request,
427
-     * but not the addons' dbs
428
-     */
429
-    const db_verified_core = 1;
430
-
431
-    /**
432
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
-     * the EE core db too)
434
-     */
435
-    const db_verified_addons = 2;
436
-
437
-    /**
438
-     * indicates whether an EEM_Base child has already re-verified the DB
439
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
440
-     * looking like EEM_Base::db_verified_*
441
-     *
442
-     * @var int - 0 = none, 1 = core, 2 = addons
443
-     */
444
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
445
-
446
-    /**
447
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
448
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
449
-     *        registrations for non-trashed tickets for non-trashed datetimes)
450
-     */
451
-    const default_where_conditions_all = 'all';
452
-
453
-    /**
454
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
455
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
456
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
457
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
458
-     *        models which share tables with other models, this can return data for the wrong model.
459
-     */
460
-    const default_where_conditions_this_only = 'this_model_only';
461
-
462
-    /**
463
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
464
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
465
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
466
-     */
467
-    const default_where_conditions_others_only = 'other_models_only';
468
-
469
-    /**
470
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
471
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
472
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
473
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
474
-     *        (regardless of whether those events and venues are trashed)
475
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
476
-     *        events.
477
-     */
478
-    const default_where_conditions_minimum_all = 'minimum';
479
-
480
-    /**
481
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
482
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
483
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
484
-     *        not)
485
-     */
486
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
487
-
488
-    /**
489
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
490
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
491
-     *        it's possible it will return table entries for other models. You should use
492
-     *        EEM_Base::default_where_conditions_minimum_all instead.
493
-     */
494
-    const default_where_conditions_none = 'none';
495
-
496
-
497
-
498
-    /**
499
-     * About all child constructors:
500
-     * they should define the _tables, _fields and _model_relations arrays.
501
-     * Should ALWAYS be called after child constructor.
502
-     * In order to make the child constructors to be as simple as possible, this parent constructor
503
-     * finalizes constructing all the object's attributes.
504
-     * Generally, rather than requiring a child to code
505
-     * $this->_tables = array(
506
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
507
-     *        ...);
508
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
509
-     * each EE_Table has a function to set the table's alias after the constructor, using
510
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
511
-     * do something similar.
512
-     *
513
-     * @param null $timezone
514
-     * @throws \EE_Error
515
-     */
516
-    protected function __construct($timezone = null)
517
-    {
518
-        // check that the model has not been loaded too soon
519
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
520
-            throw new EE_Error (
521
-                sprintf(
522
-                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
523
-                        'event_espresso'),
524
-                    get_class($this)
525
-                )
526
-            );
527
-        }
528
-        /**
529
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
530
-         */
531
-        if (empty(EEM_Base::$_model_query_blog_id)) {
532
-            EEM_Base::set_model_query_blog_id();
533
-        }
534
-        /**
535
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
536
-         * just use EE_Register_Model_Extension
537
-         *
538
-         * @var EE_Table_Base[] $_tables
539
-         */
540
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
541
-        foreach ($this->_tables as $table_alias => $table_obj) {
542
-            /** @var $table_obj EE_Table_Base */
543
-            $table_obj->_construct_finalize_with_alias($table_alias);
544
-            if ($table_obj instanceof EE_Secondary_Table) {
545
-                /** @var $table_obj EE_Secondary_Table */
546
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
547
-            }
548
-        }
549
-        /**
550
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
551
-         * EE_Register_Model_Extension
552
-         *
553
-         * @param EE_Model_Field_Base[] $_fields
554
-         */
555
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
556
-        $this->_invalidate_field_caches();
557
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
558
-            if (! array_key_exists($table_alias, $this->_tables)) {
559
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
560
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
561
-            }
562
-            foreach ($fields_for_table as $field_name => $field_obj) {
563
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
564
-                //primary key field base has a slightly different _construct_finalize
565
-                /** @var $field_obj EE_Model_Field_Base */
566
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
567
-            }
568
-        }
569
-        // everything is related to Extra_Meta
570
-        if (get_class($this) !== 'EEM_Extra_Meta') {
571
-            //make extra meta related to everything, but don't block deleting things just
572
-            //because they have related extra meta info. For now just orphan those extra meta
573
-            //in the future we should automatically delete them
574
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
575
-        }
576
-        //and change logs
577
-        if (get_class($this) !== 'EEM_Change_Log') {
578
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
579
-        }
580
-        /**
581
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
582
-         * EE_Register_Model_Extension
583
-         *
584
-         * @param EE_Model_Relation_Base[] $_model_relations
585
-         */
586
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
587
-            $this->_model_relations);
588
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
589
-            /** @var $relation_obj EE_Model_Relation_Base */
590
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
591
-        }
592
-        foreach ($this->_indexes as $index_name => $index_obj) {
593
-            /** @var $index_obj EE_Index */
594
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
595
-        }
596
-        $this->set_timezone($timezone);
597
-        //finalize default where condition strategy, or set default
598
-        if (! $this->_default_where_conditions_strategy) {
599
-            //nothing was set during child constructor, so set default
600
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
601
-        }
602
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
603
-        if (! $this->_minimum_where_conditions_strategy) {
604
-            //nothing was set during child constructor, so set default
605
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
606
-        }
607
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
608
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
609
-        //to indicate to NOT set it, set it to the logical default
610
-        if ($this->_caps_slug === null) {
611
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
612
-        }
613
-        //initialize the standard cap restriction generators if none were specified by the child constructor
614
-        if ($this->_cap_restriction_generators !== false) {
615
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
616
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
617
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
618
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
619
-                        new EE_Restriction_Generator_Protected(),
620
-                        $cap_context,
621
-                        $this
622
-                    );
623
-                }
624
-            }
625
-        }
626
-        //if there are cap restriction generators, use them to make the default cap restrictions
627
-        if ($this->_cap_restriction_generators !== false) {
628
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
629
-                if (! $generator_object) {
630
-                    continue;
631
-                }
632
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
633
-                    throw new EE_Error(
634
-                        sprintf(
635
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
636
-                                'event_espresso'),
637
-                            $context,
638
-                            $this->get_this_model_name()
639
-                        )
640
-                    );
641
-                }
642
-                $action = $this->cap_action_for_context($context);
643
-                if (! $generator_object->construction_finalized()) {
644
-                    $generator_object->_construct_finalize($this, $action);
645
-                }
646
-            }
647
-        }
648
-        do_action('AHEE__' . get_class($this) . '__construct__end');
649
-    }
650
-
651
-
652
-
653
-    /**
654
-     * Generates the cap restrictions for the given context, or if they were
655
-     * already generated just gets what's cached
656
-     *
657
-     * @param string $context one of EEM_Base::valid_cap_contexts()
658
-     * @return EE_Default_Where_Conditions[]
659
-     */
660
-    protected function _generate_cap_restrictions($context)
661
-    {
662
-        if (isset($this->_cap_restriction_generators[$context])
663
-            && $this->_cap_restriction_generators[$context]
664
-               instanceof
665
-               EE_Restriction_Generator_Base
666
-        ) {
667
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
668
-        } else {
669
-            return array();
670
-        }
671
-    }
672
-
673
-
674
-
675
-    /**
676
-     * Used to set the $_model_query_blog_id static property.
677
-     *
678
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
679
-     *                      value for get_current_blog_id() will be used.
680
-     */
681
-    public static function set_model_query_blog_id($blog_id = 0)
682
-    {
683
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
684
-    }
685
-
686
-
687
-
688
-    /**
689
-     * Returns whatever is set as the internal $model_query_blog_id.
690
-     *
691
-     * @return int
692
-     */
693
-    public static function get_model_query_blog_id()
694
-    {
695
-        return EEM_Base::$_model_query_blog_id;
696
-    }
697
-
698
-
699
-
700
-    /**
701
-     *        This function is a singleton method used to instantiate the Espresso_model object
702
-     *
703
-     * @access public
704
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
705
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
706
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
707
-     *                         timezone in the 'timezone_string' wp option)
708
-     * @return static (as in the concrete child class)
709
-     */
710
-    public static function instance($timezone = null)
711
-    {
712
-        // check if instance of Espresso_model already exists
713
-        if (! static::$_instance instanceof static) {
714
-            // instantiate Espresso_model
715
-            static::$_instance = new static($timezone);
716
-        }
717
-        //we might have a timezone set, let set_timezone decide what to do with it
718
-        static::$_instance->set_timezone($timezone);
719
-        // Espresso_model object
720
-        return static::$_instance;
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * resets the model and returns it
727
-     *
728
-     * @param null | string $timezone
729
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
730
-     * all its properties reset; if it wasn't instantiated, returns null)
731
-     */
732
-    public static function reset($timezone = null)
733
-    {
734
-        if (static::$_instance instanceof EEM_Base) {
735
-            //let's try to NOT swap out the current instance for a new one
736
-            //because if someone has a reference to it, we can't remove their reference
737
-            //so it's best to keep using the same reference, but change the original object
738
-            //reset all its properties to their original values as defined in the class
739
-            $r = new ReflectionClass(get_class(static::$_instance));
740
-            $static_properties = $r->getStaticProperties();
741
-            foreach ($r->getDefaultProperties() as $property => $value) {
742
-                //don't set instance to null like it was originally,
743
-                //but it's static anyways, and we're ignoring static properties (for now at least)
744
-                if (! isset($static_properties[$property])) {
745
-                    static::$_instance->{$property} = $value;
746
-                }
747
-            }
748
-            //and then directly call its constructor again, like we would if we
749
-            //were creating a new one
750
-            static::$_instance->__construct($timezone);
751
-            return self::instance();
752
-        }
753
-        return null;
754
-    }
755
-
756
-
757
-
758
-    /**
759
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
760
-     *
761
-     * @param  boolean $translated return localized strings or JUST the array.
762
-     * @return array
763
-     * @throws \EE_Error
764
-     */
765
-    public function status_array($translated = false)
766
-    {
767
-        if (! array_key_exists('Status', $this->_model_relations)) {
768
-            return array();
769
-        }
770
-        $model_name = $this->get_this_model_name();
771
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
772
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
773
-        $status_array = array();
774
-        foreach ($stati as $status) {
775
-            $status_array[$status->ID()] = $status->get('STS_code');
776
-        }
777
-        return $translated
778
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
779
-            : $status_array;
780
-    }
781
-
782
-
783
-
784
-    /**
785
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
786
-     *
787
-     * @param array $query_params             {
788
-     * @var array $0 (where) array {
789
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
790
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
791
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
792
-     *                                        conditions based on related models (and even
793
-     *                                        models-related-to-related-models) prepend the model's name onto the field
794
-     *                                        name. Eg,
795
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
796
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
797
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
798
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
799
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
800
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
801
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
802
-     *                                        to Venues (even when each of those models actually consisted of two
803
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
804
-     *                                        just having
805
-     *                                        "Venue.VNU_ID", you could have
806
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
807
-     *                                        events are related to Registrations, which are related to Attendees). You
808
-     *                                        can take it even further with
809
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
810
-     *                                        (from the default of '='), change the value to an numerically-indexed
811
-     *                                        array, where the first item in the list is the operator. eg: array(
812
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
813
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
814
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
815
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
816
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
817
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
818
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
819
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
820
-     *                                        the value is a field, simply provide a third array item (true) to the
821
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
822
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
823
-     *                                        Note: you can also use related model field names like you would any other
824
-     *                                        field name. eg:
825
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
826
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
827
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
828
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
829
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
830
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
831
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
832
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
833
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
834
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
835
-     *                                        "stick" until you specify an AND. eg
836
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
837
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
838
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
839
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
840
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
841
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
842
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
843
-     *                                        too, eg:
844
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
845
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
846
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
847
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
848
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
849
-     *                                        the OFFSET, the 2nd is the LIMIT
850
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
851
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
852
-     *                                        following format array('on_join_limit'
853
-     *                                        => array( 'table_alias', array(1,2) ) ).
854
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
855
-     *                                        values are either 'ASC' or 'DESC'.
856
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
857
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
858
-     *                                        DESC..." respectively. Like the
859
-     *                                        'where' conditions, these fields can be on related models. Eg
860
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
861
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
862
-     *                                        Attendee, Price, Datetime, etc.)
863
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
864
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
865
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
866
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
867
-     *                                        order by the primary key. Eg,
868
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
869
-     *                                        //(will join with the Datetime model's table(s) and order by its field
870
-     *                                        DTT_EVT_start) or
871
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
872
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
873
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
874
-     *                                        'group_by'=>'VNU_ID', or
875
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
876
-     *                                        if no
877
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
878
-     *                                        model's primary key (or combined primary keys). This avoids some
879
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
880
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
881
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
882
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
883
-     *                                        results)
884
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
885
-     *                                        array where values are models to be joined in the query.Eg
886
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
887
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
888
-     *                                        probably only want to do this in hopes of increasing efficiency, as
889
-     *                                        related models which belongs to the current model
890
-     *                                        (ie, the current model has a foreign key to them, like how Registration
891
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
892
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
893
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
894
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
895
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
896
-     *                                        default where conditions set it to 'other_models_only'. If you only want
897
-     *                                        this model's default where conditions added to the query, use
898
-     *                                        'this_model_only'. If you want to use all default where conditions
899
-     *                                        (default), set to 'all'.
900
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
901
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
902
-     *                                        everything? Or should we only show the current user items they should be
903
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
904
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
905
-     *                                        }
906
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
907
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
908
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
909
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
910
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
911
-     *                                        array( array(
912
-     *                                        'OR'=>array(
913
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
914
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
915
-     *                                        )
916
-     *                                        ),
917
-     *                                        'limit'=>10,
918
-     *                                        'group_by'=>'TXN_ID'
919
-     *                                        ));
920
-     *                                        get all the answers to the question titled "shirt size" for event with id
921
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
922
-     *                                        'Question.QST_display_text'=>'shirt size',
923
-     *                                        'Registration.Event.EVT_ID'=>12
924
-     *                                        ),
925
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
926
-     *                                        ));
927
-     * @throws \EE_Error
928
-     */
929
-    public function get_all($query_params = array())
930
-    {
931
-        if (isset($query_params['limit'])
932
-            && ! isset($query_params['group_by'])
933
-        ) {
934
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
935
-        }
936
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
937
-    }
938
-
939
-
940
-
941
-    /**
942
-     * Modifies the query parameters so we only get back model objects
943
-     * that "belong" to the current user
944
-     *
945
-     * @param array $query_params @see EEM_Base::get_all()
946
-     * @return array like EEM_Base::get_all
947
-     */
948
-    public function alter_query_params_to_only_include_mine($query_params = array())
949
-    {
950
-        $wp_user_field_name = $this->wp_user_field_name();
951
-        if ($wp_user_field_name) {
952
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
953
-        }
954
-        return $query_params;
955
-    }
956
-
957
-
958
-
959
-    /**
960
-     * Returns the name of the field's name that points to the WP_User table
961
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
962
-     * foreign key to the WP_User table)
963
-     *
964
-     * @return string|boolean string on success, boolean false when there is no
965
-     * foreign key to the WP_User table
966
-     */
967
-    public function wp_user_field_name()
968
-    {
969
-        try {
970
-            if (! empty($this->_model_chain_to_wp_user)) {
971
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
972
-                $last_model_name = end($models_to_follow_to_wp_users);
973
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
974
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
975
-            } else {
976
-                $model_with_fk_to_wp_users = $this;
977
-                $model_chain_to_wp_user = '';
978
-            }
979
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
980
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
981
-        } catch (EE_Error $e) {
982
-            return false;
983
-        }
984
-    }
985
-
986
-
987
-
988
-    /**
989
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
990
-     * (or transiently-related model) has a foreign key to the wp_users table;
991
-     * useful for finding if model objects of this type are 'owned' by the current user.
992
-     * This is an empty string when the foreign key is on this model and when it isn't,
993
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
994
-     * (or transiently-related model)
995
-     *
996
-     * @return string
997
-     */
998
-    public function model_chain_to_wp_user()
999
-    {
1000
-        return $this->_model_chain_to_wp_user;
1001
-    }
1002
-
1003
-
1004
-
1005
-    /**
1006
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1007
-     * like how registrations don't have a foreign key to wp_users, but the
1008
-     * events they are for are), or is unrelated to wp users.
1009
-     * generally available
1010
-     *
1011
-     * @return boolean
1012
-     */
1013
-    public function is_owned()
1014
-    {
1015
-        if ($this->model_chain_to_wp_user()) {
1016
-            return true;
1017
-        } else {
1018
-            try {
1019
-                $this->get_foreign_key_to('WP_User');
1020
-                return true;
1021
-            } catch (EE_Error $e) {
1022
-                return false;
1023
-            }
1024
-        }
1025
-    }
1026
-
1027
-
1028
-
1029
-    /**
1030
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1031
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1032
-     * the model)
1033
-     *
1034
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1035
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1037
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1038
-     *                                  override this and set the select to "*", or a specific column name, like
1039
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
-     *                                  the aliases used to refer to this selection, and values are to be
1042
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
-     * @throws \EE_Error
1046
-     */
1047
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1048
-    {
1049
-        // remember the custom selections, if any, and type cast as array
1050
-        // (unless $columns_to_select is an object, then just set as an empty array)
1051
-        // Note: (array) 'some string' === array( 'some string' )
1052
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1053
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1054
-        $select_expressions = $columns_to_select !== null
1055
-            ? $this->_construct_select_from_input($columns_to_select)
1056
-            : $this->_construct_default_select_sql($model_query_info);
1057
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1058
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1059
-    }
1060
-
1061
-
1062
-
1063
-    /**
1064
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1065
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1066
-     * take care of joins, field preparation etc.
1067
-     *
1068
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1069
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1070
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1071
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1072
-     *                                  override this and set the select to "*", or a specific column name, like
1073
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1074
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1075
-     *                                  the aliases used to refer to this selection, and values are to be
1076
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1077
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1078
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1079
-     * @throws \EE_Error
1080
-     */
1081
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1082
-    {
1083
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1084
-    }
1085
-
1086
-
1087
-
1088
-    /**
1089
-     * For creating a custom select statement
1090
-     *
1091
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1092
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1093
-     *                                 SQL, and 1=>is the datatype
1094
-     * @throws EE_Error
1095
-     * @return string
1096
-     */
1097
-    private function _construct_select_from_input($columns_to_select)
1098
-    {
1099
-        if (is_array($columns_to_select)) {
1100
-            $select_sql_array = array();
1101
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1102
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1103
-                    throw new EE_Error(
1104
-                        sprintf(
1105
-                            __(
1106
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1107
-                                "event_espresso"
1108
-                            ),
1109
-                            $selection_and_datatype,
1110
-                            $alias
1111
-                        )
1112
-                    );
1113
-                }
1114
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1115
-                    throw new EE_Error(
1116
-                        sprintf(
1117
-                            __(
1118
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1119
-                                "event_espresso"
1120
-                            ),
1121
-                            $selection_and_datatype[1],
1122
-                            $selection_and_datatype[0],
1123
-                            $alias,
1124
-                            implode(",", $this->_valid_wpdb_data_types)
1125
-                        )
1126
-                    );
1127
-                }
1128
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1129
-            }
1130
-            $columns_to_select_string = implode(", ", $select_sql_array);
1131
-        } else {
1132
-            $columns_to_select_string = $columns_to_select;
1133
-        }
1134
-        return $columns_to_select_string;
1135
-    }
1136
-
1137
-
1138
-
1139
-    /**
1140
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1141
-     *
1142
-     * @return string
1143
-     * @throws \EE_Error
1144
-     */
1145
-    public function primary_key_name()
1146
-    {
1147
-        return $this->get_primary_key_field()->get_name();
1148
-    }
1149
-
1150
-
1151
-
1152
-    /**
1153
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1154
-     * If there is no primary key on this model, $id is treated as primary key string
1155
-     *
1156
-     * @param mixed $id int or string, depending on the type of the model's primary key
1157
-     * @return EE_Base_Class
1158
-     */
1159
-    public function get_one_by_ID($id)
1160
-    {
1161
-        if ($this->get_from_entity_map($id)) {
1162
-            return $this->get_from_entity_map($id);
1163
-        }
1164
-        return $this->get_one(
1165
-            $this->alter_query_params_to_restrict_by_ID(
1166
-                $id,
1167
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1168
-            )
1169
-        );
1170
-    }
1171
-
1172
-
1173
-
1174
-    /**
1175
-     * Alters query parameters to only get items with this ID are returned.
1176
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1177
-     * or could just be a simple primary key ID
1178
-     *
1179
-     * @param int   $id
1180
-     * @param array $query_params
1181
-     * @return array of normal query params, @see EEM_Base::get_all
1182
-     * @throws \EE_Error
1183
-     */
1184
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1185
-    {
1186
-        if (! isset($query_params[0])) {
1187
-            $query_params[0] = array();
1188
-        }
1189
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1190
-        if ($conditions_from_id === null) {
1191
-            $query_params[0][$this->primary_key_name()] = $id;
1192
-        } else {
1193
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1194
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1195
-        }
1196
-        return $query_params;
1197
-    }
1198
-
1199
-
1200
-
1201
-    /**
1202
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1203
-     * array. If no item is found, null is returned.
1204
-     *
1205
-     * @param array $query_params like EEM_Base's $query_params variable.
1206
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1207
-     * @throws \EE_Error
1208
-     */
1209
-    public function get_one($query_params = array())
1210
-    {
1211
-        if (! is_array($query_params)) {
1212
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1213
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1214
-                    gettype($query_params)), '4.6.0');
1215
-            $query_params = array();
1216
-        }
1217
-        $query_params['limit'] = 1;
1218
-        $items = $this->get_all($query_params);
1219
-        if (empty($items)) {
1220
-            return null;
1221
-        } else {
1222
-            return array_shift($items);
1223
-        }
1224
-    }
1225
-
1226
-
1227
-
1228
-    /**
1229
-     * Returns the next x number of items in sequence from the given value as
1230
-     * found in the database matching the given query conditions.
1231
-     *
1232
-     * @param mixed $current_field_value    Value used for the reference point.
1233
-     * @param null  $field_to_order_by      What field is used for the
1234
-     *                                      reference point.
1235
-     * @param int   $limit                  How many to return.
1236
-     * @param array $query_params           Extra conditions on the query.
1237
-     * @param null  $columns_to_select      If left null, then an array of
1238
-     *                                      EE_Base_Class objects is returned,
1239
-     *                                      otherwise you can indicate just the
1240
-     *                                      columns you want returned.
1241
-     * @return EE_Base_Class[]|array
1242
-     * @throws \EE_Error
1243
-     */
1244
-    public function next_x(
1245
-        $current_field_value,
1246
-        $field_to_order_by = null,
1247
-        $limit = 1,
1248
-        $query_params = array(),
1249
-        $columns_to_select = null
1250
-    ) {
1251
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1252
-            $columns_to_select);
1253
-    }
1254
-
1255
-
1256
-
1257
-    /**
1258
-     * Returns the previous x number of items in sequence from the given value
1259
-     * as found in the database matching the given query conditions.
1260
-     *
1261
-     * @param mixed $current_field_value    Value used for the reference point.
1262
-     * @param null  $field_to_order_by      What field is used for the
1263
-     *                                      reference point.
1264
-     * @param int   $limit                  How many to return.
1265
-     * @param array $query_params           Extra conditions on the query.
1266
-     * @param null  $columns_to_select      If left null, then an array of
1267
-     *                                      EE_Base_Class objects is returned,
1268
-     *                                      otherwise you can indicate just the
1269
-     *                                      columns you want returned.
1270
-     * @return EE_Base_Class[]|array
1271
-     * @throws \EE_Error
1272
-     */
1273
-    public function previous_x(
1274
-        $current_field_value,
1275
-        $field_to_order_by = null,
1276
-        $limit = 1,
1277
-        $query_params = array(),
1278
-        $columns_to_select = null
1279
-    ) {
1280
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1281
-            $columns_to_select);
1282
-    }
1283
-
1284
-
1285
-
1286
-    /**
1287
-     * Returns the next item in sequence from the given value as found in the
1288
-     * database matching the given query conditions.
1289
-     *
1290
-     * @param mixed $current_field_value    Value used for the reference point.
1291
-     * @param null  $field_to_order_by      What field is used for the
1292
-     *                                      reference point.
1293
-     * @param array $query_params           Extra conditions on the query.
1294
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1295
-     *                                      object is returned, otherwise you
1296
-     *                                      can indicate just the columns you
1297
-     *                                      want and a single array indexed by
1298
-     *                                      the columns will be returned.
1299
-     * @return EE_Base_Class|null|array()
1300
-     * @throws \EE_Error
1301
-     */
1302
-    public function next(
1303
-        $current_field_value,
1304
-        $field_to_order_by = null,
1305
-        $query_params = array(),
1306
-        $columns_to_select = null
1307
-    ) {
1308
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1309
-            $columns_to_select);
1310
-        return empty($results) ? null : reset($results);
1311
-    }
1312
-
1313
-
1314
-
1315
-    /**
1316
-     * Returns the previous item in sequence from the given value as found in
1317
-     * the database matching the given query conditions.
1318
-     *
1319
-     * @param mixed $current_field_value    Value used for the reference point.
1320
-     * @param null  $field_to_order_by      What field is used for the
1321
-     *                                      reference point.
1322
-     * @param array $query_params           Extra conditions on the query.
1323
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1324
-     *                                      object is returned, otherwise you
1325
-     *                                      can indicate just the columns you
1326
-     *                                      want and a single array indexed by
1327
-     *                                      the columns will be returned.
1328
-     * @return EE_Base_Class|null|array()
1329
-     * @throws EE_Error
1330
-     */
1331
-    public function previous(
1332
-        $current_field_value,
1333
-        $field_to_order_by = null,
1334
-        $query_params = array(),
1335
-        $columns_to_select = null
1336
-    ) {
1337
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1338
-            $columns_to_select);
1339
-        return empty($results) ? null : reset($results);
1340
-    }
1341
-
1342
-
1343
-
1344
-    /**
1345
-     * Returns the a consecutive number of items in sequence from the given
1346
-     * value as found in the database matching the given query conditions.
1347
-     *
1348
-     * @param mixed  $current_field_value   Value used for the reference point.
1349
-     * @param string $operand               What operand is used for the sequence.
1350
-     * @param string $field_to_order_by     What field is used for the reference point.
1351
-     * @param int    $limit                 How many to return.
1352
-     * @param array  $query_params          Extra conditions on the query.
1353
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1354
-     *                                      otherwise you can indicate just the columns you want returned.
1355
-     * @return EE_Base_Class[]|array
1356
-     * @throws EE_Error
1357
-     */
1358
-    protected function _get_consecutive(
1359
-        $current_field_value,
1360
-        $operand = '>',
1361
-        $field_to_order_by = null,
1362
-        $limit = 1,
1363
-        $query_params = array(),
1364
-        $columns_to_select = null
1365
-    ) {
1366
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1367
-        if (empty($field_to_order_by)) {
1368
-            if ($this->has_primary_key_field()) {
1369
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1370
-            } else {
1371
-                if (WP_DEBUG) {
1372
-                    throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1373
-                        'event_espresso'));
1374
-                }
1375
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1376
-                return array();
1377
-            }
1378
-        }
1379
-        if (! is_array($query_params)) {
1380
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1381
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1382
-                    gettype($query_params)), '4.6.0');
1383
-            $query_params = array();
1384
-        }
1385
-        //let's add the where query param for consecutive look up.
1386
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1387
-        $query_params['limit'] = $limit;
1388
-        //set direction
1389
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1390
-        $query_params['order_by'] = $operand === '>'
1391
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1392
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1393
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1394
-        if (empty($columns_to_select)) {
1395
-            return $this->get_all($query_params);
1396
-        } else {
1397
-            //getting just the fields
1398
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1399
-        }
1400
-    }
1401
-
1402
-
1403
-
1404
-    /**
1405
-     * This sets the _timezone property after model object has been instantiated.
1406
-     *
1407
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1408
-     */
1409
-    public function set_timezone($timezone)
1410
-    {
1411
-        if ($timezone !== null) {
1412
-            $this->_timezone = $timezone;
1413
-        }
1414
-        //note we need to loop through relations and set the timezone on those objects as well.
1415
-        foreach ($this->_model_relations as $relation) {
1416
-            $relation->set_timezone($timezone);
1417
-        }
1418
-        //and finally we do the same for any datetime fields
1419
-        foreach ($this->_fields as $field) {
1420
-            if ($field instanceof EE_Datetime_Field) {
1421
-                $field->set_timezone($timezone);
1422
-            }
1423
-        }
1424
-    }
1425
-
1426
-
1427
-
1428
-    /**
1429
-     * This just returns whatever is set for the current timezone.
1430
-     *
1431
-     * @access public
1432
-     * @return string
1433
-     */
1434
-    public function get_timezone()
1435
-    {
1436
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1437
-        if (empty($this->_timezone)) {
1438
-            foreach ($this->_fields as $field) {
1439
-                if ($field instanceof EE_Datetime_Field) {
1440
-                    $this->set_timezone($field->get_timezone());
1441
-                    break;
1442
-                }
1443
-            }
1444
-        }
1445
-        //if timezone STILL empty then return the default timezone for the site.
1446
-        if (empty($this->_timezone)) {
1447
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1448
-        }
1449
-        return $this->_timezone;
1450
-    }
1451
-
1452
-
1453
-
1454
-    /**
1455
-     * This returns the date formats set for the given field name and also ensures that
1456
-     * $this->_timezone property is set correctly.
1457
-     *
1458
-     * @since 4.6.x
1459
-     * @param string $field_name The name of the field the formats are being retrieved for.
1460
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1461
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1462
-     * @return array formats in an array with the date format first, and the time format last.
1463
-     */
1464
-    public function get_formats_for($field_name, $pretty = false)
1465
-    {
1466
-        $field_settings = $this->field_settings_for($field_name);
1467
-        //if not a valid EE_Datetime_Field then throw error
1468
-        if (! $field_settings instanceof EE_Datetime_Field) {
1469
-            throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1470
-                'event_espresso'), $field_name));
1471
-        }
1472
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1473
-        //the field.
1474
-        $this->_timezone = $field_settings->get_timezone();
1475
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1476
-    }
1477
-
1478
-
1479
-
1480
-    /**
1481
-     * This returns the current time in a format setup for a query on this model.
1482
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1483
-     * it will return:
1484
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1485
-     *  NOW
1486
-     *  - or a unix timestamp (equivalent to time())
1487
-     *
1488
-     * @since 4.6.x
1489
-     * @param string $field_name       The field the current time is needed for.
1490
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1491
-     *                                 formatted string matching the set format for the field in the set timezone will
1492
-     *                                 be returned.
1493
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1494
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1495
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1496
-     *                                 exception is triggered.
1497
-     */
1498
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1499
-    {
1500
-        $formats = $this->get_formats_for($field_name);
1501
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1502
-        if ($timestamp) {
1503
-            return $DateTime->format('U');
1504
-        }
1505
-        //not returning timestamp, so return formatted string in timezone.
1506
-        switch ($what) {
1507
-            case 'time' :
1508
-                return $DateTime->format($formats[1]);
1509
-                break;
1510
-            case 'date' :
1511
-                return $DateTime->format($formats[0]);
1512
-                break;
1513
-            default :
1514
-                return $DateTime->format(implode(' ', $formats));
1515
-                break;
1516
-        }
1517
-    }
1518
-
1519
-
1520
-
1521
-    /**
1522
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1523
-     * for the model are.  Returns a DateTime object.
1524
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1525
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1526
-     * ignored.
1527
-     *
1528
-     * @param string $field_name      The field being setup.
1529
-     * @param string $timestring      The date time string being used.
1530
-     * @param string $incoming_format The format for the time string.
1531
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1532
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1533
-     *                                format is
1534
-     *                                'U', this is ignored.
1535
-     * @return DateTime
1536
-     * @throws \EE_Error
1537
-     */
1538
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1539
-    {
1540
-        //just using this to ensure the timezone is set correctly internally
1541
-        $this->get_formats_for($field_name);
1542
-        //load EEH_DTT_Helper
1543
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1544
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1545
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1546
-    }
1547
-
1548
-
1549
-
1550
-    /**
1551
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1552
-     *
1553
-     * @return EE_Table_Base[]
1554
-     */
1555
-    public function get_tables()
1556
-    {
1557
-        return $this->_tables;
1558
-    }
1559
-
1560
-
1561
-
1562
-    /**
1563
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1564
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1565
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1566
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1567
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1568
-     * model object with EVT_ID = 1
1569
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1570
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1571
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1572
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1573
-     * are not specified)
1574
-     *
1575
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1576
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1577
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1578
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1579
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1580
-     *                                         ID=34, we'd use this method as follows:
1581
-     *                                         EEM_Transaction::instance()->update(
1582
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1583
-     *                                         array(array('TXN_ID'=>34)));
1584
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1585
-     *                                         in client code into what's expected to be stored on each field. Eg,
1586
-     *                                         consider updating Question's QST_admin_label field is of type
1587
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1588
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1589
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1590
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1591
-     *                                         TRUE, it is assumed that you've already called
1592
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1593
-     *                                         malicious javascript. However, if
1594
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1595
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1596
-     *                                         and every other field, before insertion. We provide this parameter
1597
-     *                                         because model objects perform their prepare_for_set function on all
1598
-     *                                         their values, and so don't need to be called again (and in many cases,
1599
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1600
-     *                                         prepare_for_set method...)
1601
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1602
-     *                                         in this model's entity map according to $fields_n_values that match
1603
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1604
-     *                                         by setting this to FALSE, but be aware that model objects being used
1605
-     *                                         could get out-of-sync with the database
1606
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1607
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1608
-     *                                         bad)
1609
-     * @throws \EE_Error
1610
-     */
1611
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1612
-    {
1613
-        if (! is_array($query_params)) {
1614
-            EE_Error::doing_it_wrong('EEM_Base::update',
1615
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1616
-                    gettype($query_params)), '4.6.0');
1617
-            $query_params = array();
1618
-        }
1619
-        /**
1620
-         * Action called before a model update call has been made.
1621
-         *
1622
-         * @param EEM_Base $model
1623
-         * @param array    $fields_n_values the updated fields and their new values
1624
-         * @param array    $query_params    @see EEM_Base::get_all()
1625
-         */
1626
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1627
-        /**
1628
-         * Filters the fields about to be updated given the query parameters. You can provide the
1629
-         * $query_params to $this->get_all() to find exactly which records will be updated
1630
-         *
1631
-         * @param array    $fields_n_values fields and their new values
1632
-         * @param EEM_Base $model           the model being queried
1633
-         * @param array    $query_params    see EEM_Base::get_all()
1634
-         */
1635
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1636
-            $query_params);
1637
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1638
-        //to do that, for each table, verify that it's PK isn't null.
1639
-        $tables = $this->get_tables();
1640
-        //and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1641
-        //NOTE: we should make this code more efficient by NOT querying twice
1642
-        //before the real update, but that needs to first go through ALPHA testing
1643
-        //as it's dangerous. says Mike August 8 2014
1644
-        //we want to make sure the default_where strategy is ignored
1645
-        $this->_ignore_where_strategy = true;
1646
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1647
-        foreach ($wpdb_select_results as $wpdb_result) {
1648
-            // type cast stdClass as array
1649
-            $wpdb_result = (array)$wpdb_result;
1650
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1651
-            if ($this->has_primary_key_field()) {
1652
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1653
-            } else {
1654
-                //if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1655
-                $main_table_pk_value = null;
1656
-            }
1657
-            //if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1658
-            //and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1659
-            if (count($tables) > 1) {
1660
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1661
-                //in that table, and so we'll want to insert one
1662
-                foreach ($tables as $table_obj) {
1663
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1664
-                    //if there is no private key for this table on the results, it means there's no entry
1665
-                    //in this table, right? so insert a row in the current table, using any fields available
1666
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1667
-                           && $wpdb_result[$this_table_pk_column])
1668
-                    ) {
1669
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1670
-                            $main_table_pk_value);
1671
-                        //if we died here, report the error
1672
-                        if (! $success) {
1673
-                            return false;
1674
-                        }
1675
-                    }
1676
-                }
1677
-            }
1678
-            //				//and now check that if we have cached any models by that ID on the model, that
1679
-            //				//they also get updated properly
1680
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1681
-            //				if( $model_object ){
1682
-            //					foreach( $fields_n_values as $field => $value ){
1683
-            //						$model_object->set($field, $value);
1684
-            //let's make sure default_where strategy is followed now
1685
-            $this->_ignore_where_strategy = false;
1686
-        }
1687
-        //if we want to keep model objects in sync, AND
1688
-        //if this wasn't called from a model object (to update itself)
1689
-        //then we want to make sure we keep all the existing
1690
-        //model objects in sync with the db
1691
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1692
-            if ($this->has_primary_key_field()) {
1693
-                $model_objs_affected_ids = $this->get_col($query_params);
1694
-            } else {
1695
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1696
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1697
-                $model_objs_affected_ids = array();
1698
-                foreach ($models_affected_key_columns as $row) {
1699
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1700
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1701
-                }
1702
-            }
1703
-            if (! $model_objs_affected_ids) {
1704
-                //wait wait wait- if nothing was affected let's stop here
1705
-                return 0;
1706
-            }
1707
-            foreach ($model_objs_affected_ids as $id) {
1708
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1709
-                if ($model_obj_in_entity_map) {
1710
-                    foreach ($fields_n_values as $field => $new_value) {
1711
-                        $model_obj_in_entity_map->set($field, $new_value);
1712
-                    }
1713
-                }
1714
-            }
1715
-            //if there is a primary key on this model, we can now do a slight optimization
1716
-            if ($this->has_primary_key_field()) {
1717
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1718
-                $query_params = array(
1719
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1720
-                    'limit'                    => count($model_objs_affected_ids),
1721
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1722
-                );
1723
-            }
1724
-        }
1725
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1726
-        $SQL = "UPDATE "
1727
-               . $model_query_info->get_full_join_sql()
1728
-               . " SET "
1729
-               . $this->_construct_update_sql($fields_n_values)
1730
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1731
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1732
-        /**
1733
-         * Action called after a model update call has been made.
1734
-         *
1735
-         * @param EEM_Base $model
1736
-         * @param array    $fields_n_values the updated fields and their new values
1737
-         * @param array    $query_params    @see EEM_Base::get_all()
1738
-         * @param int      $rows_affected
1739
-         */
1740
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1741
-        return $rows_affected;//how many supposedly got updated
1742
-    }
1743
-
1744
-
1745
-
1746
-    /**
1747
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1748
-     * are teh values of the field specified (or by default the primary key field)
1749
-     * that matched the query params. Note that you should pass the name of the
1750
-     * model FIELD, not the database table's column name.
1751
-     *
1752
-     * @param array  $query_params @see EEM_Base::get_all()
1753
-     * @param string $field_to_select
1754
-     * @return array just like $wpdb->get_col()
1755
-     * @throws \EE_Error
1756
-     */
1757
-    public function get_col($query_params = array(), $field_to_select = null)
1758
-    {
1759
-        if ($field_to_select) {
1760
-            $field = $this->field_settings_for($field_to_select);
1761
-        } elseif ($this->has_primary_key_field()) {
1762
-            $field = $this->get_primary_key_field();
1763
-        } else {
1764
-            //no primary key, just grab the first column
1765
-            $field = reset($this->field_settings());
1766
-        }
1767
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1768
-        $select_expressions = $field->get_qualified_column();
1769
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1770
-        return $this->_do_wpdb_query('get_col', array($SQL));
1771
-    }
1772
-
1773
-
1774
-
1775
-    /**
1776
-     * Returns a single column value for a single row from the database
1777
-     *
1778
-     * @param array  $query_params    @see EEM_Base::get_all()
1779
-     * @param string $field_to_select @see EEM_Base::get_col()
1780
-     * @return string
1781
-     * @throws \EE_Error
1782
-     */
1783
-    public function get_var($query_params = array(), $field_to_select = null)
1784
-    {
1785
-        $query_params['limit'] = 1;
1786
-        $col = $this->get_col($query_params, $field_to_select);
1787
-        if (! empty($col)) {
1788
-            return reset($col);
1789
-        } else {
1790
-            return null;
1791
-        }
1792
-    }
1793
-
1794
-
1795
-
1796
-    /**
1797
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1798
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1799
-     * injection, but currently no further filtering is done
1800
-     *
1801
-     * @global      $wpdb
1802
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1803
-     *                               be updated to in the DB
1804
-     * @return string of SQL
1805
-     * @throws \EE_Error
1806
-     */
1807
-    public function _construct_update_sql($fields_n_values)
1808
-    {
1809
-        /** @type WPDB $wpdb */
1810
-        global $wpdb;
1811
-        $cols_n_values = array();
1812
-        foreach ($fields_n_values as $field_name => $value) {
1813
-            $field_obj = $this->field_settings_for($field_name);
1814
-            //if the value is NULL, we want to assign the value to that.
1815
-            //wpdb->prepare doesn't really handle that properly
1816
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1817
-            $value_sql = $prepared_value === null ? 'NULL'
1818
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1819
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1820
-        }
1821
-        return implode(",", $cols_n_values);
1822
-    }
1823
-
1824
-
1825
-
1826
-    /**
1827
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1828
-     * Performs a HARD delete, meaning the database row should always be removed,
1829
-     * not just have a flag field on it switched
1830
-     * Wrapper for EEM_Base::delete_permanently()
1831
-     *
1832
-     * @param mixed $id
1833
-     * @return boolean whether the row got deleted or not
1834
-     * @throws \EE_Error
1835
-     */
1836
-    public function delete_permanently_by_ID($id)
1837
-    {
1838
-        return $this->delete_permanently(
1839
-            array(
1840
-                array($this->get_primary_key_field()->get_name() => $id),
1841
-                'limit' => 1,
1842
-            )
1843
-        );
1844
-    }
1845
-
1846
-
1847
-
1848
-    /**
1849
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1850
-     * Wrapper for EEM_Base::delete()
1851
-     *
1852
-     * @param mixed $id
1853
-     * @return boolean whether the row got deleted or not
1854
-     * @throws \EE_Error
1855
-     */
1856
-    public function delete_by_ID($id)
1857
-    {
1858
-        return $this->delete(
1859
-            array(
1860
-                array($this->get_primary_key_field()->get_name() => $id),
1861
-                'limit' => 1,
1862
-            )
1863
-        );
1864
-    }
1865
-
1866
-
1867
-
1868
-    /**
1869
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1870
-     * meaning if the model has a field that indicates its been "trashed" or
1871
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1872
-     *
1873
-     * @see EEM_Base::delete_permanently
1874
-     * @param array   $query_params
1875
-     * @param boolean $allow_blocking
1876
-     * @return int how many rows got deleted
1877
-     * @throws \EE_Error
1878
-     */
1879
-    public function delete($query_params, $allow_blocking = true)
1880
-    {
1881
-        return $this->delete_permanently($query_params, $allow_blocking);
1882
-    }
1883
-
1884
-
1885
-
1886
-    /**
1887
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1888
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1889
-     * as archived, not actually deleted
1890
-     *
1891
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1892
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1893
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1894
-     *                                deletes regardless of other objects which may depend on it. Its generally
1895
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1896
-     *                                DB
1897
-     * @return int how many rows got deleted
1898
-     * @throws \EE_Error
1899
-     */
1900
-    public function delete_permanently($query_params, $allow_blocking = true)
1901
-    {
1902
-        /**
1903
-         * Action called just before performing a real deletion query. You can use the
1904
-         * model and its $query_params to find exactly which items will be deleted
1905
-         *
1906
-         * @param EEM_Base $model
1907
-         * @param array    $query_params   @see EEM_Base::get_all()
1908
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1909
-         *                                 to block (prevent) this deletion
1910
-         */
1911
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1912
-        //some MySQL databases may be running safe mode, which may restrict
1913
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1914
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1915
-        //to delete them
1916
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1917
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1918
-        if ($deletion_where) {
1919
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1920
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1921
-            $table_aliases = array_keys($this->_tables);
1922
-            $SQL = "DELETE "
1923
-                   . implode(", ", $table_aliases)
1924
-                   . " FROM "
1925
-                   . $model_query_info->get_full_join_sql()
1926
-                   . " WHERE "
1927
-                   . $deletion_where;
1928
-            //		/echo "delete sql:$SQL";
1929
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1930
-        } else {
1931
-            $rows_deleted = 0;
1932
-        }
1933
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1934
-        if ($this->has_primary_key_field()) {
1935
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1936
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1937
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1938
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1939
-                }
1940
-            }
1941
-        }
1942
-        /**
1943
-         * Action called just after performing a real deletion query. Although at this point the
1944
-         * items should have been deleted
1945
-         *
1946
-         * @param EEM_Base $model
1947
-         * @param array    $query_params @see EEM_Base::get_all()
1948
-         * @param int      $rows_deleted
1949
-         */
1950
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1951
-        return $rows_deleted;//how many supposedly got deleted
1952
-    }
1953
-
1954
-
1955
-
1956
-    /**
1957
-     * Checks all the relations that throw error messages when there are blocking related objects
1958
-     * for related model objects. If there are any related model objects on those relations,
1959
-     * adds an EE_Error, and return true
1960
-     *
1961
-     * @param EE_Base_Class|int $this_model_obj_or_id
1962
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1963
-     *                                                 should be ignored when determining whether there are related
1964
-     *                                                 model objects which block this model object's deletion. Useful
1965
-     *                                                 if you know A is related to B and are considering deleting A,
1966
-     *                                                 but want to see if A has any other objects blocking its deletion
1967
-     *                                                 before removing the relation between A and B
1968
-     * @return boolean
1969
-     * @throws \EE_Error
1970
-     */
1971
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1972
-    {
1973
-        //first, if $ignore_this_model_obj was supplied, get its model
1974
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1975
-            $ignored_model = $ignore_this_model_obj->get_model();
1976
-        } else {
1977
-            $ignored_model = null;
1978
-        }
1979
-        //now check all the relations of $this_model_obj_or_id and see if there
1980
-        //are any related model objects blocking it?
1981
-        $is_blocked = false;
1982
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1983
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1984
-                //if $ignore_this_model_obj was supplied, then for the query
1985
-                //on that model needs to be told to ignore $ignore_this_model_obj
1986
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1987
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1988
-                        array(
1989
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1990
-                                '!=',
1991
-                                $ignore_this_model_obj->ID(),
1992
-                            ),
1993
-                        ),
1994
-                    ));
1995
-                } else {
1996
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1997
-                }
1998
-                if ($related_model_objects) {
1999
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2000
-                    $is_blocked = true;
2001
-                }
2002
-            }
2003
-        }
2004
-        return $is_blocked;
2005
-    }
2006
-
2007
-
2008
-
2009
-    /**
2010
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2011
-     * well.
2012
-     *
2013
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2014
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2015
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
2016
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
2017
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
2018
-     *                                      easily corrupt your DB
2019
-     * @throws EE_Error
2020
-     * @return string    everything that comes after the WHERE statement.
2021
-     */
2022
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2023
-    {
2024
-        if ($this->has_primary_key_field()) {
2025
-            $primary_table = $this->_get_main_table();
2026
-            $other_tables = $this->_get_other_tables();
2027
-            $deletes = $query = array();
2028
-            foreach ($objects_for_deletion as $delete_object) {
2029
-                //before we mark this object for deletion,
2030
-                //make sure there's no related objects blocking its deletion (if we're checking)
2031
-                if (
2032
-                    $allow_blocking
2033
-                    && $this->delete_is_blocked_by_related_models(
2034
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
2035
-                    )
2036
-                ) {
2037
-                    continue;
2038
-                }
2039
-                //primary table deletes
2040
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2041
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2042
-                }
2043
-                //other tables
2044
-                if (! empty($other_tables)) {
2045
-                    foreach ($other_tables as $ot) {
2046
-                        //first check if we've got the foreign key column here.
2047
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2048
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2049
-                        }
2050
-                        // wait! it's entirely possible that we'll have a the primary key
2051
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
2052
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2053
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2054
-                        }
2055
-                        // finally, it is possible that the fk for this table is found
2056
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
2057
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2058
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2059
-                        }
2060
-                    }
2061
-                }
2062
-            }
2063
-            //we should have deletes now, so let's just go through and setup the where statement
2064
-            foreach ($deletes as $column => $values) {
2065
-                //make sure we have unique $values;
2066
-                $values = array_unique($values);
2067
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2068
-            }
2069
-            return ! empty($query) ? implode(' AND ', $query) : '';
2070
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2071
-            $ways_to_identify_a_row = array();
2072
-            $fields = $this->get_combined_primary_key_fields();
2073
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2074
-            foreach ($objects_for_deletion as $delete_object) {
2075
-                $values_for_each_cpk_for_a_row = array();
2076
-                foreach ($fields as $cpk_field) {
2077
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2078
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2079
-                                                           . "="
2080
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
2081
-                    }
2082
-                }
2083
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2084
-            }
2085
-            return implode(" OR ", $ways_to_identify_a_row);
2086
-        } else {
2087
-            //so there's no primary key and no combined key...
2088
-            //sorry, can't help you
2089
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2090
-                "event_espresso"), get_class($this)));
2091
-        }
2092
-    }
2093
-
2094
-
2095
-
2096
-    /**
2097
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2098
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2099
-     * column
2100
-     *
2101
-     * @param array  $query_params   like EEM_Base::get_all's
2102
-     * @param string $field_to_count field on model to count by (not column name)
2103
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2104
-     *                               that by the setting $distinct to TRUE;
2105
-     * @return int
2106
-     * @throws \EE_Error
2107
-     */
2108
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2109
-    {
2110
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2111
-        if ($field_to_count) {
2112
-            $field_obj = $this->field_settings_for($field_to_count);
2113
-            $column_to_count = $field_obj->get_qualified_column();
2114
-        } elseif ($this->has_primary_key_field()) {
2115
-            $pk_field_obj = $this->get_primary_key_field();
2116
-            $column_to_count = $pk_field_obj->get_qualified_column();
2117
-        } else {
2118
-            //there's no primary key
2119
-            //if we're counting distinct items, and there's no primary key,
2120
-            //we need to list out the columns for distinction;
2121
-            //otherwise we can just use star
2122
-            if ($distinct) {
2123
-                $columns_to_use = array();
2124
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2125
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2126
-                }
2127
-                $column_to_count = implode(',', $columns_to_use);
2128
-            } else {
2129
-                $column_to_count = '*';
2130
-            }
2131
-        }
2132
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2133
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2134
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2135
-    }
2136
-
2137
-
2138
-
2139
-    /**
2140
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2141
-     *
2142
-     * @param array  $query_params like EEM_Base::get_all
2143
-     * @param string $field_to_sum name of field (array key in $_fields array)
2144
-     * @return float
2145
-     * @throws \EE_Error
2146
-     */
2147
-    public function sum($query_params, $field_to_sum = null)
2148
-    {
2149
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2150
-        if ($field_to_sum) {
2151
-            $field_obj = $this->field_settings_for($field_to_sum);
2152
-        } else {
2153
-            $field_obj = $this->get_primary_key_field();
2154
-        }
2155
-        $column_to_count = $field_obj->get_qualified_column();
2156
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2157
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2158
-        $data_type = $field_obj->get_wpdb_data_type();
2159
-        if ($data_type === '%d' || $data_type === '%s') {
2160
-            return (float)$return_value;
2161
-        } else {//must be %f
2162
-            return (float)$return_value;
2163
-        }
2164
-    }
2165
-
2166
-
2167
-
2168
-    /**
2169
-     * Just calls the specified method on $wpdb with the given arguments
2170
-     * Consolidates a little extra error handling code
2171
-     *
2172
-     * @param string $wpdb_method
2173
-     * @param array  $arguments_to_provide
2174
-     * @throws EE_Error
2175
-     * @global wpdb  $wpdb
2176
-     * @return mixed
2177
-     */
2178
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2179
-    {
2180
-        //if we're in maintenance mode level 2, DON'T run any queries
2181
-        //because level 2 indicates the database needs updating and
2182
-        //is probably out of sync with the code
2183
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2184
-            throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2185
-                "event_espresso")));
2186
-        }
2187
-        /** @type WPDB $wpdb */
2188
-        global $wpdb;
2189
-        if (! method_exists($wpdb, $wpdb_method)) {
2190
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2191
-                'event_espresso'), $wpdb_method));
2192
-        }
2193
-        if (WP_DEBUG) {
2194
-            $old_show_errors_value = $wpdb->show_errors;
2195
-            $wpdb->show_errors(false);
2196
-        }
2197
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2198
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2199
-        if (WP_DEBUG) {
2200
-            $wpdb->show_errors($old_show_errors_value);
2201
-            if (! empty($wpdb->last_error)) {
2202
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2203
-            } elseif ($result === false) {
2204
-                throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2205
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2206
-            }
2207
-        } elseif ($result === false) {
2208
-            EE_Error::add_error(
2209
-                sprintf(
2210
-                    __('A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2211
-                        'event_espresso'),
2212
-                    $wpdb_method,
2213
-                    var_export($arguments_to_provide, true),
2214
-                    $wpdb->last_error
2215
-                ),
2216
-                __FILE__,
2217
-                __FUNCTION__,
2218
-                __LINE__
2219
-            );
2220
-        }
2221
-        return $result;
2222
-    }
2223
-
2224
-
2225
-
2226
-    /**
2227
-     * Attempts to run the indicated WPDB method with the provided arguments,
2228
-     * and if there's an error tries to verify the DB is correct. Uses
2229
-     * the static property EEM_Base::$_db_verification_level to determine whether
2230
-     * we should try to fix the EE core db, the addons, or just give up
2231
-     *
2232
-     * @param string $wpdb_method
2233
-     * @param array  $arguments_to_provide
2234
-     * @return mixed
2235
-     */
2236
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2237
-    {
2238
-        /** @type WPDB $wpdb */
2239
-        global $wpdb;
2240
-        $wpdb->last_error = null;
2241
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2242
-        // was there an error running the query? but we don't care on new activations
2243
-        // (we're going to setup the DB anyway on new activations)
2244
-        if (($result === false || ! empty($wpdb->last_error))
2245
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2246
-        ) {
2247
-            switch (EEM_Base::$_db_verification_level) {
2248
-                case EEM_Base::db_verified_none :
2249
-                    // let's double-check core's DB
2250
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2251
-                    break;
2252
-                case EEM_Base::db_verified_core :
2253
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2254
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2255
-                    break;
2256
-                case EEM_Base::db_verified_addons :
2257
-                    // ummmm... you in trouble
2258
-                    return $result;
2259
-                    break;
2260
-            }
2261
-            if (! empty($error_message)) {
2262
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2263
-                trigger_error($error_message);
2264
-            }
2265
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2266
-        }
2267
-        return $result;
2268
-    }
2269
-
2270
-
2271
-
2272
-    /**
2273
-     * Verifies the EE core database is up-to-date and records that we've done it on
2274
-     * EEM_Base::$_db_verification_level
2275
-     *
2276
-     * @param string $wpdb_method
2277
-     * @param array  $arguments_to_provide
2278
-     * @return string
2279
-     */
2280
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2281
-    {
2282
-        /** @type WPDB $wpdb */
2283
-        global $wpdb;
2284
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2285
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2286
-        $error_message = sprintf(
2287
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2288
-                'event_espresso'),
2289
-            $wpdb->last_error,
2290
-            $wpdb_method,
2291
-            wp_json_encode($arguments_to_provide)
2292
-        );
2293
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2294
-        return $error_message;
2295
-    }
2296
-
2297
-
2298
-
2299
-    /**
2300
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2301
-     * EEM_Base::$_db_verification_level
2302
-     *
2303
-     * @param $wpdb_method
2304
-     * @param $arguments_to_provide
2305
-     * @return string
2306
-     */
2307
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2308
-    {
2309
-        /** @type WPDB $wpdb */
2310
-        global $wpdb;
2311
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2312
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2313
-        $error_message = sprintf(
2314
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2315
-                'event_espresso'),
2316
-            $wpdb->last_error,
2317
-            $wpdb_method,
2318
-            wp_json_encode($arguments_to_provide)
2319
-        );
2320
-        EE_System::instance()->initialize_addons();
2321
-        return $error_message;
2322
-    }
2323
-
2324
-
2325
-
2326
-    /**
2327
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2328
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2329
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2330
-     * ..."
2331
-     *
2332
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2333
-     * @return string
2334
-     */
2335
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2336
-    {
2337
-        return " FROM " . $model_query_info->get_full_join_sql() .
2338
-               $model_query_info->get_where_sql() .
2339
-               $model_query_info->get_group_by_sql() .
2340
-               $model_query_info->get_having_sql() .
2341
-               $model_query_info->get_order_by_sql() .
2342
-               $model_query_info->get_limit_sql();
2343
-    }
2344
-
2345
-
2346
-
2347
-    /**
2348
-     * Set to easily debug the next X queries ran from this model.
2349
-     *
2350
-     * @param int $count
2351
-     */
2352
-    public function show_next_x_db_queries($count = 1)
2353
-    {
2354
-        $this->_show_next_x_db_queries = $count;
2355
-    }
2356
-
2357
-
2358
-
2359
-    /**
2360
-     * @param $sql_query
2361
-     */
2362
-    public function show_db_query_if_previously_requested($sql_query)
2363
-    {
2364
-        if ($this->_show_next_x_db_queries > 0) {
2365
-            echo $sql_query;
2366
-            $this->_show_next_x_db_queries--;
2367
-        }
2368
-    }
2369
-
2370
-
2371
-
2372
-    /**
2373
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2374
-     * There are the 3 cases:
2375
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2376
-     * $otherModelObject has no ID, it is first saved.
2377
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2378
-     * has no ID, it is first saved.
2379
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2380
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2381
-     * join table
2382
-     *
2383
-     * @param        EE_Base_Class                     /int $thisModelObject
2384
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2385
-     * @param string $relationName                     , key in EEM_Base::_relations
2386
-     *                                                 an attendee to a group, you also want to specify which role they
2387
-     *                                                 will have in that group. So you would use this parameter to
2388
-     *                                                 specify array('role-column-name'=>'role-id')
2389
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2390
-     *                                                 to for relation to methods that allow you to further specify
2391
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2392
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2393
-     *                                                 because these will be inserted in any new rows created as well.
2394
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2395
-     * @throws \EE_Error
2396
-     */
2397
-    public function add_relationship_to(
2398
-        $id_or_obj,
2399
-        $other_model_id_or_obj,
2400
-        $relationName,
2401
-        $extra_join_model_fields_n_values = array()
2402
-    ) {
2403
-        $relation_obj = $this->related_settings_for($relationName);
2404
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2405
-    }
2406
-
2407
-
2408
-
2409
-    /**
2410
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2411
-     * There are the 3 cases:
2412
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2413
-     * error
2414
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2415
-     * an error
2416
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2417
-     *
2418
-     * @param        EE_Base_Class /int $id_or_obj
2419
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2420
-     * @param string $relationName key in EEM_Base::_relations
2421
-     * @return boolean of success
2422
-     * @throws \EE_Error
2423
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2424
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2425
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2426
-     *                             because these will be inserted in any new rows created as well.
2427
-     */
2428
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2429
-    {
2430
-        $relation_obj = $this->related_settings_for($relationName);
2431
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2432
-    }
2433
-
2434
-
2435
-
2436
-    /**
2437
-     * @param mixed           $id_or_obj
2438
-     * @param string          $relationName
2439
-     * @param array           $where_query_params
2440
-     * @param EE_Base_Class[] objects to which relations were removed
2441
-     * @return \EE_Base_Class[]
2442
-     * @throws \EE_Error
2443
-     */
2444
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2445
-    {
2446
-        $relation_obj = $this->related_settings_for($relationName);
2447
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2448
-    }
2449
-
2450
-
2451
-
2452
-    /**
2453
-     * Gets all the related items of the specified $model_name, using $query_params.
2454
-     * Note: by default, we remove the "default query params"
2455
-     * because we want to get even deleted items etc.
2456
-     *
2457
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2458
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2459
-     * @param array  $query_params like EEM_Base::get_all
2460
-     * @return EE_Base_Class[]
2461
-     * @throws \EE_Error
2462
-     */
2463
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2464
-    {
2465
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2466
-        $relation_settings = $this->related_settings_for($model_name);
2467
-        return $relation_settings->get_all_related($model_obj, $query_params);
2468
-    }
2469
-
2470
-
2471
-
2472
-    /**
2473
-     * Deletes all the model objects across the relation indicated by $model_name
2474
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2475
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2476
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2477
-     *
2478
-     * @param EE_Base_Class|int|string $id_or_obj
2479
-     * @param string                   $model_name
2480
-     * @param array                    $query_params
2481
-     * @return int how many deleted
2482
-     * @throws \EE_Error
2483
-     */
2484
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2485
-    {
2486
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2487
-        $relation_settings = $this->related_settings_for($model_name);
2488
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2489
-    }
2490
-
2491
-
2492
-
2493
-    /**
2494
-     * Hard deletes all the model objects across the relation indicated by $model_name
2495
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2496
-     * the model objects can't be hard deleted because of blocking related model objects,
2497
-     * just does a soft-delete on them instead.
2498
-     *
2499
-     * @param EE_Base_Class|int|string $id_or_obj
2500
-     * @param string                   $model_name
2501
-     * @param array                    $query_params
2502
-     * @return int how many deleted
2503
-     * @throws \EE_Error
2504
-     */
2505
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2506
-    {
2507
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2508
-        $relation_settings = $this->related_settings_for($model_name);
2509
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2510
-    }
2511
-
2512
-
2513
-
2514
-    /**
2515
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2516
-     * unless otherwise specified in the $query_params
2517
-     *
2518
-     * @param        int             /EE_Base_Class $id_or_obj
2519
-     * @param string $model_name     like 'Event', or 'Registration'
2520
-     * @param array  $query_params   like EEM_Base::get_all's
2521
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2522
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2523
-     *                               that by the setting $distinct to TRUE;
2524
-     * @return int
2525
-     * @throws \EE_Error
2526
-     */
2527
-    public function count_related(
2528
-        $id_or_obj,
2529
-        $model_name,
2530
-        $query_params = array(),
2531
-        $field_to_count = null,
2532
-        $distinct = false
2533
-    ) {
2534
-        $related_model = $this->get_related_model_obj($model_name);
2535
-        //we're just going to use the query params on the related model's normal get_all query,
2536
-        //except add a condition to say to match the current mod
2537
-        if (! isset($query_params['default_where_conditions'])) {
2538
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2539
-        }
2540
-        $this_model_name = $this->get_this_model_name();
2541
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2542
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2543
-        return $related_model->count($query_params, $field_to_count, $distinct);
2544
-    }
2545
-
2546
-
2547
-
2548
-    /**
2549
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2550
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2551
-     *
2552
-     * @param        int           /EE_Base_Class $id_or_obj
2553
-     * @param string $model_name   like 'Event', or 'Registration'
2554
-     * @param array  $query_params like EEM_Base::get_all's
2555
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2556
-     * @return float
2557
-     * @throws \EE_Error
2558
-     */
2559
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2560
-    {
2561
-        $related_model = $this->get_related_model_obj($model_name);
2562
-        if (! is_array($query_params)) {
2563
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2564
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2565
-                    gettype($query_params)), '4.6.0');
2566
-            $query_params = array();
2567
-        }
2568
-        //we're just going to use the query params on the related model's normal get_all query,
2569
-        //except add a condition to say to match the current mod
2570
-        if (! isset($query_params['default_where_conditions'])) {
2571
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2572
-        }
2573
-        $this_model_name = $this->get_this_model_name();
2574
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2575
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2576
-        return $related_model->sum($query_params, $field_to_sum);
2577
-    }
2578
-
2579
-
2580
-
2581
-    /**
2582
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2583
-     * $modelObject
2584
-     *
2585
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2586
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2587
-     * @param array               $query_params     like EEM_Base::get_all's
2588
-     * @return EE_Base_Class
2589
-     * @throws \EE_Error
2590
-     */
2591
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2592
-    {
2593
-        $query_params['limit'] = 1;
2594
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2595
-        if ($results) {
2596
-            return array_shift($results);
2597
-        } else {
2598
-            return null;
2599
-        }
2600
-    }
2601
-
2602
-
2603
-
2604
-    /**
2605
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2606
-     *
2607
-     * @return string
2608
-     */
2609
-    public function get_this_model_name()
2610
-    {
2611
-        return str_replace("EEM_", "", get_class($this));
2612
-    }
2613
-
2614
-
2615
-
2616
-    /**
2617
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2618
-     *
2619
-     * @return EE_Any_Foreign_Model_Name_Field
2620
-     * @throws EE_Error
2621
-     */
2622
-    public function get_field_containing_related_model_name()
2623
-    {
2624
-        foreach ($this->field_settings(true) as $field) {
2625
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2626
-                $field_with_model_name = $field;
2627
-            }
2628
-        }
2629
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2630
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2631
-                $this->get_this_model_name()));
2632
-        }
2633
-        return $field_with_model_name;
2634
-    }
2635
-
2636
-
2637
-
2638
-    /**
2639
-     * Inserts a new entry into the database, for each table.
2640
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2641
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2642
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2643
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2644
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2645
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2646
-     *
2647
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2648
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2649
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2650
-     *                              of EEM_Base)
2651
-     * @return int new primary key on main table that got inserted
2652
-     * @throws EE_Error
2653
-     */
2654
-    public function insert($field_n_values)
2655
-    {
2656
-        /**
2657
-         * Filters the fields and their values before inserting an item using the models
2658
-         *
2659
-         * @param array    $fields_n_values keys are the fields and values are their new values
2660
-         * @param EEM_Base $model           the model used
2661
-         */
2662
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2663
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2664
-            $main_table = $this->_get_main_table();
2665
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2666
-            if ($new_id !== false) {
2667
-                foreach ($this->_get_other_tables() as $other_table) {
2668
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2669
-                }
2670
-            }
2671
-            /**
2672
-             * Done just after attempting to insert a new model object
2673
-             *
2674
-             * @param EEM_Base   $model           used
2675
-             * @param array      $fields_n_values fields and their values
2676
-             * @param int|string the              ID of the newly-inserted model object
2677
-             */
2678
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2679
-            return $new_id;
2680
-        } else {
2681
-            return false;
2682
-        }
2683
-    }
2684
-
2685
-
2686
-
2687
-    /**
2688
-     * Checks that the result would satisfy the unique indexes on this model
2689
-     *
2690
-     * @param array  $field_n_values
2691
-     * @param string $action
2692
-     * @return boolean
2693
-     * @throws \EE_Error
2694
-     */
2695
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2696
-    {
2697
-        foreach ($this->unique_indexes() as $index_name => $index) {
2698
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2699
-            if ($this->exists(array($uniqueness_where_params))) {
2700
-                EE_Error::add_error(
2701
-                    sprintf(
2702
-                        __(
2703
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2704
-                            "event_espresso"
2705
-                        ),
2706
-                        $action,
2707
-                        $this->_get_class_name(),
2708
-                        $index_name,
2709
-                        implode(",", $index->field_names()),
2710
-                        http_build_query($uniqueness_where_params)
2711
-                    ),
2712
-                    __FILE__,
2713
-                    __FUNCTION__,
2714
-                    __LINE__
2715
-                );
2716
-                return false;
2717
-            }
2718
-        }
2719
-        return true;
2720
-    }
2721
-
2722
-
2723
-
2724
-    /**
2725
-     * Checks the database for an item that conflicts (ie, if this item were
2726
-     * saved to the DB would break some uniqueness requirement, like a primary key
2727
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2728
-     * can be either an EE_Base_Class or an array of fields n values
2729
-     *
2730
-     * @param EE_Base_Class|array $obj_or_fields_array
2731
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2732
-     *                                                 when looking for conflicts
2733
-     *                                                 (ie, if false, we ignore the model object's primary key
2734
-     *                                                 when finding "conflicts". If true, it's also considered).
2735
-     *                                                 Only works for INT primary key,
2736
-     *                                                 STRING primary keys cannot be ignored
2737
-     * @throws EE_Error
2738
-     * @return EE_Base_Class|array
2739
-     */
2740
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2741
-    {
2742
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2743
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2744
-        } elseif (is_array($obj_or_fields_array)) {
2745
-            $fields_n_values = $obj_or_fields_array;
2746
-        } else {
2747
-            throw new EE_Error(
2748
-                sprintf(
2749
-                    __(
2750
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2751
-                        "event_espresso"
2752
-                    ),
2753
-                    get_class($this),
2754
-                    $obj_or_fields_array
2755
-                )
2756
-            );
2757
-        }
2758
-        $query_params = array();
2759
-        if ($this->has_primary_key_field()
2760
-            && ($include_primary_key
2761
-                || $this->get_primary_key_field()
2762
-                   instanceof
2763
-                   EE_Primary_Key_String_Field)
2764
-            && isset($fields_n_values[$this->primary_key_name()])
2765
-        ) {
2766
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2767
-        }
2768
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2769
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2770
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2771
-        }
2772
-        //if there is nothing to base this search on, then we shouldn't find anything
2773
-        if (empty($query_params)) {
2774
-            return array();
2775
-        } else {
2776
-            return $this->get_one($query_params);
2777
-        }
2778
-    }
2779
-
2780
-
2781
-
2782
-    /**
2783
-     * Like count, but is optimized and returns a boolean instead of an int
2784
-     *
2785
-     * @param array $query_params
2786
-     * @return boolean
2787
-     * @throws \EE_Error
2788
-     */
2789
-    public function exists($query_params)
2790
-    {
2791
-        $query_params['limit'] = 1;
2792
-        return $this->count($query_params) > 0;
2793
-    }
2794
-
2795
-
2796
-
2797
-    /**
2798
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2799
-     *
2800
-     * @param int|string $id
2801
-     * @return boolean
2802
-     * @throws \EE_Error
2803
-     */
2804
-    public function exists_by_ID($id)
2805
-    {
2806
-        return $this->exists(
2807
-            array(
2808
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2809
-                array(
2810
-                    $this->primary_key_name() => $id,
2811
-                ),
2812
-            )
2813
-        );
2814
-    }
2815
-
2816
-
2817
-
2818
-    /**
2819
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2820
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2821
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2822
-     * on the main table)
2823
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2824
-     * cases where we want to call it directly rather than via insert().
2825
-     *
2826
-     * @access   protected
2827
-     * @param EE_Table_Base $table
2828
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2829
-     *                                       float
2830
-     * @param int           $new_id          for now we assume only int keys
2831
-     * @throws EE_Error
2832
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2833
-     * @return int ID of new row inserted, or FALSE on failure
2834
-     */
2835
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2836
-    {
2837
-        global $wpdb;
2838
-        $insertion_col_n_values = array();
2839
-        $format_for_insertion = array();
2840
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2841
-        foreach ($fields_on_table as $field_name => $field_obj) {
2842
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2843
-            if ($field_obj->is_auto_increment()) {
2844
-                continue;
2845
-            }
2846
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2847
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2848
-            if ($prepared_value !== null) {
2849
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2850
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2851
-            }
2852
-        }
2853
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2854
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2855
-            //so add the fk to the main table as a column
2856
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2857
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2858
-        }
2859
-        //insert the new entry
2860
-        $result = $this->_do_wpdb_query('insert',
2861
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2862
-        if ($result === false) {
2863
-            return false;
2864
-        }
2865
-        //ok, now what do we return for the ID of the newly-inserted thing?
2866
-        if ($this->has_primary_key_field()) {
2867
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2868
-                return $wpdb->insert_id;
2869
-            } else {
2870
-                //it's not an auto-increment primary key, so
2871
-                //it must have been supplied
2872
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2873
-            }
2874
-        } else {
2875
-            //we can't return a  primary key because there is none. instead return
2876
-            //a unique string indicating this model
2877
-            return $this->get_index_primary_key_string($fields_n_values);
2878
-        }
2879
-    }
2880
-
2881
-
2882
-
2883
-    /**
2884
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2885
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2886
-     * and there is no default, we pass it along. WPDB will take care of it)
2887
-     *
2888
-     * @param EE_Model_Field_Base $field_obj
2889
-     * @param array               $fields_n_values
2890
-     * @return mixed string|int|float depending on what the table column will be expecting
2891
-     * @throws \EE_Error
2892
-     */
2893
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2894
-    {
2895
-        //if this field doesn't allow nullable, don't allow it
2896
-        if (! $field_obj->is_nullable()
2897
-            && (
2898
-                ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2899
-        ) {
2900
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2901
-        }
2902
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2903
-            : null;
2904
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2905
-    }
2906
-
2907
-
2908
-
2909
-    /**
2910
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2911
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2912
-     * the field's prepare_for_set() method.
2913
-     *
2914
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2915
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2916
-     *                                   top of file)
2917
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2918
-     *                                   $value is a custom selection
2919
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2920
-     */
2921
-    private function _prepare_value_for_use_in_db($value, $field)
2922
-    {
2923
-        if ($field && $field instanceof EE_Model_Field_Base) {
2924
-            switch ($this->_values_already_prepared_by_model_object) {
2925
-                /** @noinspection PhpMissingBreakStatementInspection */
2926
-                case self::not_prepared_by_model_object:
2927
-                    $value = $field->prepare_for_set($value);
2928
-                //purposefully left out "return"
2929
-                case self::prepared_by_model_object:
2930
-                    $value = $field->prepare_for_use_in_db($value);
2931
-                case self::prepared_for_use_in_db:
2932
-                    //leave the value alone
2933
-            }
2934
-            return $value;
2935
-        } else {
2936
-            return $value;
2937
-        }
2938
-    }
2939
-
2940
-
2941
-
2942
-    /**
2943
-     * Returns the main table on this model
2944
-     *
2945
-     * @return EE_Primary_Table
2946
-     * @throws EE_Error
2947
-     */
2948
-    protected function _get_main_table()
2949
-    {
2950
-        foreach ($this->_tables as $table) {
2951
-            if ($table instanceof EE_Primary_Table) {
2952
-                return $table;
2953
-            }
2954
-        }
2955
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2956
-            'event_espresso'), get_class($this)));
2957
-    }
2958
-
2959
-
2960
-
2961
-    /**
2962
-     * table
2963
-     * returns EE_Primary_Table table name
2964
-     *
2965
-     * @return string
2966
-     * @throws \EE_Error
2967
-     */
2968
-    public function table()
2969
-    {
2970
-        return $this->_get_main_table()->get_table_name();
2971
-    }
2972
-
2973
-
2974
-
2975
-    /**
2976
-     * table
2977
-     * returns first EE_Secondary_Table table name
2978
-     *
2979
-     * @return string
2980
-     */
2981
-    public function second_table()
2982
-    {
2983
-        // grab second table from tables array
2984
-        $second_table = end($this->_tables);
2985
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2986
-    }
2987
-
2988
-
2989
-
2990
-    /**
2991
-     * get_table_obj_by_alias
2992
-     * returns table name given it's alias
2993
-     *
2994
-     * @param string $table_alias
2995
-     * @return EE_Primary_Table | EE_Secondary_Table
2996
-     */
2997
-    public function get_table_obj_by_alias($table_alias = '')
2998
-    {
2999
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3000
-    }
3001
-
3002
-
3003
-
3004
-    /**
3005
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3006
-     *
3007
-     * @return EE_Secondary_Table[]
3008
-     */
3009
-    protected function _get_other_tables()
3010
-    {
3011
-        $other_tables = array();
3012
-        foreach ($this->_tables as $table_alias => $table) {
3013
-            if ($table instanceof EE_Secondary_Table) {
3014
-                $other_tables[$table_alias] = $table;
3015
-            }
3016
-        }
3017
-        return $other_tables;
3018
-    }
3019
-
3020
-
3021
-
3022
-    /**
3023
-     * Finds all the fields that correspond to the given table
3024
-     *
3025
-     * @param string $table_alias , array key in EEM_Base::_tables
3026
-     * @return EE_Model_Field_Base[]
3027
-     */
3028
-    public function _get_fields_for_table($table_alias)
3029
-    {
3030
-        return $this->_fields[$table_alias];
3031
-    }
3032
-
3033
-
3034
-
3035
-    /**
3036
-     * Recurses through all the where parameters, and finds all the related models we'll need
3037
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3038
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3039
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3040
-     * related Registration, Transaction, and Payment models.
3041
-     *
3042
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3043
-     * @return EE_Model_Query_Info_Carrier
3044
-     * @throws \EE_Error
3045
-     */
3046
-    public function _extract_related_models_from_query($query_params)
3047
-    {
3048
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3049
-        if (array_key_exists(0, $query_params)) {
3050
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3051
-        }
3052
-        if (array_key_exists('group_by', $query_params)) {
3053
-            if (is_array($query_params['group_by'])) {
3054
-                $this->_extract_related_models_from_sub_params_array_values(
3055
-                    $query_params['group_by'],
3056
-                    $query_info_carrier,
3057
-                    'group_by'
3058
-                );
3059
-            } elseif (! empty ($query_params['group_by'])) {
3060
-                $this->_extract_related_model_info_from_query_param(
3061
-                    $query_params['group_by'],
3062
-                    $query_info_carrier,
3063
-                    'group_by'
3064
-                );
3065
-            }
3066
-        }
3067
-        if (array_key_exists('having', $query_params)) {
3068
-            $this->_extract_related_models_from_sub_params_array_keys(
3069
-                $query_params[0],
3070
-                $query_info_carrier,
3071
-                'having'
3072
-            );
3073
-        }
3074
-        if (array_key_exists('order_by', $query_params)) {
3075
-            if (is_array($query_params['order_by'])) {
3076
-                $this->_extract_related_models_from_sub_params_array_keys(
3077
-                    $query_params['order_by'],
3078
-                    $query_info_carrier,
3079
-                    'order_by'
3080
-                );
3081
-            } elseif (! empty($query_params['order_by'])) {
3082
-                $this->_extract_related_model_info_from_query_param(
3083
-                    $query_params['order_by'],
3084
-                    $query_info_carrier,
3085
-                    'order_by'
3086
-                );
3087
-            }
3088
-        }
3089
-        if (array_key_exists('force_join', $query_params)) {
3090
-            $this->_extract_related_models_from_sub_params_array_values(
3091
-                $query_params['force_join'],
3092
-                $query_info_carrier,
3093
-                'force_join'
3094
-            );
3095
-        }
3096
-        return $query_info_carrier;
3097
-    }
3098
-
3099
-
3100
-
3101
-    /**
3102
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3103
-     *
3104
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3105
-     *                                                      $query_params['having']
3106
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3107
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3108
-     * @throws EE_Error
3109
-     * @return \EE_Model_Query_Info_Carrier
3110
-     */
3111
-    private function _extract_related_models_from_sub_params_array_keys(
3112
-        $sub_query_params,
3113
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3114
-        $query_param_type
3115
-    ) {
3116
-        if (! empty($sub_query_params)) {
3117
-            $sub_query_params = (array)$sub_query_params;
3118
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3119
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3120
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3121
-                    $query_param_type);
3122
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3123
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3124
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3125
-                //of array('Registration.TXN_ID'=>23)
3126
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3127
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3128
-                    if (! is_array($possibly_array_of_params)) {
3129
-                        throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3130
-                            "event_espresso"),
3131
-                            $param, $possibly_array_of_params));
3132
-                    } else {
3133
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3134
-                            $model_query_info_carrier, $query_param_type);
3135
-                    }
3136
-                } elseif ($query_param_type === 0 //ie WHERE
3137
-                          && is_array($possibly_array_of_params)
3138
-                          && isset($possibly_array_of_params[2])
3139
-                          && $possibly_array_of_params[2] == true
3140
-                ) {
3141
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3142
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3143
-                    //from which we should extract query parameters!
3144
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3145
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3146
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3147
-                    }
3148
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3149
-                        $model_query_info_carrier, $query_param_type);
3150
-                }
3151
-            }
3152
-        }
3153
-        return $model_query_info_carrier;
3154
-    }
3155
-
3156
-
3157
-
3158
-    /**
3159
-     * For extracting related models from forced_joins, where the array values contain the info about what
3160
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3161
-     *
3162
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3163
-     *                                                      $query_params['having']
3164
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3165
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3166
-     * @throws EE_Error
3167
-     * @return \EE_Model_Query_Info_Carrier
3168
-     */
3169
-    private function _extract_related_models_from_sub_params_array_values(
3170
-        $sub_query_params,
3171
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3172
-        $query_param_type
3173
-    ) {
3174
-        if (! empty($sub_query_params)) {
3175
-            if (! is_array($sub_query_params)) {
3176
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3177
-                    $sub_query_params));
3178
-            }
3179
-            foreach ($sub_query_params as $param) {
3180
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3181
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3182
-                    $query_param_type);
3183
-            }
3184
-        }
3185
-        return $model_query_info_carrier;
3186
-    }
3187
-
3188
-
3189
-
3190
-    /**
3191
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3192
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3193
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3194
-     * but use them in a different order. Eg, we need to know what models we are querying
3195
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3196
-     * other models before we can finalize the where clause SQL.
3197
-     *
3198
-     * @param array $query_params
3199
-     * @throws EE_Error
3200
-     * @return EE_Model_Query_Info_Carrier
3201
-     */
3202
-    public function _create_model_query_info_carrier($query_params)
3203
-    {
3204
-        if (! is_array($query_params)) {
3205
-            EE_Error::doing_it_wrong(
3206
-                'EEM_Base::_create_model_query_info_carrier',
3207
-                sprintf(
3208
-                    __(
3209
-                        '$query_params should be an array, you passed a variable of type %s',
3210
-                        'event_espresso'
3211
-                    ),
3212
-                    gettype($query_params)
3213
-                ),
3214
-                '4.6.0'
3215
-            );
3216
-            $query_params = array();
3217
-        }
3218
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3219
-        //first check if we should alter the query to account for caps or not
3220
-        //because the caps might require us to do extra joins
3221
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3222
-            $query_params[0] = $where_query_params = array_replace_recursive(
3223
-                $where_query_params,
3224
-                $this->caps_where_conditions(
3225
-                    $query_params['caps']
3226
-                )
3227
-            );
3228
-        }
3229
-        $query_object = $this->_extract_related_models_from_query($query_params);
3230
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3231
-        foreach ($where_query_params as $key => $value) {
3232
-            if (is_int($key)) {
3233
-                throw new EE_Error(
3234
-                    sprintf(
3235
-                        __(
3236
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3237
-                            "event_espresso"
3238
-                        ),
3239
-                        $key,
3240
-                        var_export($value, true),
3241
-                        var_export($query_params, true),
3242
-                        get_class($this)
3243
-                    )
3244
-                );
3245
-            }
3246
-        }
3247
-        if (
3248
-            array_key_exists('default_where_conditions', $query_params)
3249
-            && ! empty($query_params['default_where_conditions'])
3250
-        ) {
3251
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3252
-        } else {
3253
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3254
-        }
3255
-        $where_query_params = array_merge(
3256
-            $this->_get_default_where_conditions_for_models_in_query(
3257
-                $query_object,
3258
-                $use_default_where_conditions,
3259
-                $where_query_params
3260
-            ),
3261
-            $where_query_params
3262
-        );
3263
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3264
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3265
-        // So we need to setup a subquery and use that for the main join.
3266
-        // Note for now this only works on the primary table for the model.
3267
-        // So for instance, you could set the limit array like this:
3268
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3269
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3270
-            $query_object->set_main_model_join_sql(
3271
-                $this->_construct_limit_join_select(
3272
-                    $query_params['on_join_limit'][0],
3273
-                    $query_params['on_join_limit'][1]
3274
-                )
3275
-            );
3276
-        }
3277
-        //set limit
3278
-        if (array_key_exists('limit', $query_params)) {
3279
-            if (is_array($query_params['limit'])) {
3280
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3281
-                    $e = sprintf(
3282
-                        __(
3283
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3284
-                            "event_espresso"
3285
-                        ),
3286
-                        http_build_query($query_params['limit'])
3287
-                    );
3288
-                    throw new EE_Error($e . "|" . $e);
3289
-                }
3290
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3291
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3292
-            } elseif (! empty ($query_params['limit'])) {
3293
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3294
-            }
3295
-        }
3296
-        //set order by
3297
-        if (array_key_exists('order_by', $query_params)) {
3298
-            if (is_array($query_params['order_by'])) {
3299
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3300
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3301
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3302
-                if (array_key_exists('order', $query_params)) {
3303
-                    throw new EE_Error(
3304
-                        sprintf(
3305
-                            __(
3306
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3307
-                                "event_espresso"
3308
-                            ),
3309
-                            get_class($this),
3310
-                            implode(", ", array_keys($query_params['order_by'])),
3311
-                            implode(", ", $query_params['order_by']),
3312
-                            $query_params['order']
3313
-                        )
3314
-                    );
3315
-                }
3316
-                $this->_extract_related_models_from_sub_params_array_keys(
3317
-                    $query_params['order_by'],
3318
-                    $query_object,
3319
-                    'order_by'
3320
-                );
3321
-                //assume it's an array of fields to order by
3322
-                $order_array = array();
3323
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3324
-                    $order = $this->_extract_order($order);
3325
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3326
-                }
3327
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3328
-            } elseif (! empty ($query_params['order_by'])) {
3329
-                $this->_extract_related_model_info_from_query_param(
3330
-                    $query_params['order_by'],
3331
-                    $query_object,
3332
-                    'order',
3333
-                    $query_params['order_by']
3334
-                );
3335
-                $order = isset($query_params['order'])
3336
-                    ? $this->_extract_order($query_params['order'])
3337
-                    : 'DESC';
3338
-                $query_object->set_order_by_sql(
3339
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3340
-                );
3341
-            }
3342
-        }
3343
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3344
-        if (! array_key_exists('order_by', $query_params)
3345
-            && array_key_exists('order', $query_params)
3346
-            && ! empty($query_params['order'])
3347
-        ) {
3348
-            $pk_field = $this->get_primary_key_field();
3349
-            $order = $this->_extract_order($query_params['order']);
3350
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3351
-        }
3352
-        //set group by
3353
-        if (array_key_exists('group_by', $query_params)) {
3354
-            if (is_array($query_params['group_by'])) {
3355
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3356
-                $group_by_array = array();
3357
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3358
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3359
-                }
3360
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3361
-            } elseif (! empty ($query_params['group_by'])) {
3362
-                $query_object->set_group_by_sql(
3363
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3364
-                );
3365
-            }
3366
-        }
3367
-        //set having
3368
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3369
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3370
-        }
3371
-        //now, just verify they didn't pass anything wack
3372
-        foreach ($query_params as $query_key => $query_value) {
3373
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3374
-                throw new EE_Error(
3375
-                    sprintf(
3376
-                        __(
3377
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3378
-                            'event_espresso'
3379
-                        ),
3380
-                        $query_key,
3381
-                        get_class($this),
3382
-                        //						print_r( $this->_allowed_query_params, TRUE )
3383
-                        implode(',', $this->_allowed_query_params)
3384
-                    )
3385
-                );
3386
-            }
3387
-        }
3388
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3389
-        if (empty($main_model_join_sql)) {
3390
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3391
-        }
3392
-        return $query_object;
3393
-    }
3394
-
3395
-
3396
-
3397
-    /**
3398
-     * Gets the where conditions that should be imposed on the query based on the
3399
-     * context (eg reading frontend, backend, edit or delete).
3400
-     *
3401
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3402
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3403
-     * @throws \EE_Error
3404
-     */
3405
-    public function caps_where_conditions($context = self::caps_read)
3406
-    {
3407
-        EEM_Base::verify_is_valid_cap_context($context);
3408
-        $cap_where_conditions = array();
3409
-        $cap_restrictions = $this->caps_missing($context);
3410
-        /**
3411
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3412
-         */
3413
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3414
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3415
-                $restriction_if_no_cap->get_default_where_conditions());
3416
-        }
3417
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3418
-            $cap_restrictions);
3419
-    }
3420
-
3421
-
3422
-
3423
-    /**
3424
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3425
-     * otherwise throws an exception
3426
-     *
3427
-     * @param string $should_be_order_string
3428
-     * @return string either ASC, asc, DESC or desc
3429
-     * @throws EE_Error
3430
-     */
3431
-    private function _extract_order($should_be_order_string)
3432
-    {
3433
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3434
-            return $should_be_order_string;
3435
-        } else {
3436
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3437
-                "event_espresso"), get_class($this), $should_be_order_string));
3438
-        }
3439
-    }
3440
-
3441
-
3442
-
3443
-    /**
3444
-     * Looks at all the models which are included in this query, and asks each
3445
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3446
-     * so they can be merged
3447
-     *
3448
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3449
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3450
-     *                                                                  'none' means NO default where conditions will
3451
-     *                                                                  be used AT ALL during this query.
3452
-     *                                                                  'other_models_only' means default where
3453
-     *                                                                  conditions from other models will be used, but
3454
-     *                                                                  not for this primary model. 'all', the default,
3455
-     *                                                                  means default where conditions will apply as
3456
-     *                                                                  normal
3457
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3458
-     * @throws EE_Error
3459
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3460
-     */
3461
-    private function _get_default_where_conditions_for_models_in_query(
3462
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3463
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3464
-        $where_query_params = array()
3465
-    ) {
3466
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3467
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3468
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3469
-                "event_espresso"), $use_default_where_conditions,
3470
-                implode(", ", $allowed_used_default_where_conditions_values)));
3471
-        }
3472
-        $universal_query_params = array();
3473
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3474
-            $universal_query_params = $this->_get_default_where_conditions();
3475
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3476
-            $universal_query_params = $this->_get_minimum_where_conditions();
3477
-        }
3478
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3479
-            $related_model = $this->get_related_model_obj($model_name);
3480
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3481
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3482
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3483
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3484
-            } else {
3485
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3486
-                continue;
3487
-            }
3488
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3489
-                $related_model_universal_where_params,
3490
-                $where_query_params,
3491
-                $related_model,
3492
-                $model_relation_path
3493
-            );
3494
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3495
-                $universal_query_params,
3496
-                $overrides
3497
-            );
3498
-        }
3499
-        return $universal_query_params;
3500
-    }
3501
-
3502
-
3503
-
3504
-    /**
3505
-     * Determines whether or not we should use default where conditions for the model in question
3506
-     * (this model, or other related models).
3507
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3508
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3509
-     * We should use default where conditions on related models when they requested to use default where conditions
3510
-     * on all models, or specifically just on other related models
3511
-     * @param      $default_where_conditions_value
3512
-     * @param bool $for_this_model false means this is for OTHER related models
3513
-     * @return bool
3514
-     */
3515
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3516
-    {
3517
-        return (
3518
-                   $for_this_model
3519
-                   && in_array(
3520
-                       $default_where_conditions_value,
3521
-                       array(
3522
-                           EEM_Base::default_where_conditions_all,
3523
-                           EEM_Base::default_where_conditions_this_only,
3524
-                           EEM_Base::default_where_conditions_minimum_others,
3525
-                       ),
3526
-                       true
3527
-                   )
3528
-               )
3529
-               || (
3530
-                   ! $for_this_model
3531
-                   && in_array(
3532
-                       $default_where_conditions_value,
3533
-                       array(
3534
-                           EEM_Base::default_where_conditions_all,
3535
-                           EEM_Base::default_where_conditions_others_only,
3536
-                       ),
3537
-                       true
3538
-                   )
3539
-               );
3540
-    }
3541
-
3542
-    /**
3543
-     * Determines whether or not we should use default minimum conditions for the model in question
3544
-     * (this model, or other related models).
3545
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3546
-     * where conditions.
3547
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3548
-     * on this model or others
3549
-     * @param      $default_where_conditions_value
3550
-     * @param bool $for_this_model false means this is for OTHER related models
3551
-     * @return bool
3552
-     */
3553
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3554
-    {
3555
-        return (
3556
-                   $for_this_model
3557
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3558
-               )
3559
-               || (
3560
-                   ! $for_this_model
3561
-                   && in_array(
3562
-                       $default_where_conditions_value,
3563
-                       array(
3564
-                           EEM_Base::default_where_conditions_minimum_others,
3565
-                           EEM_Base::default_where_conditions_minimum_all,
3566
-                       ),
3567
-                       true
3568
-                   )
3569
-               );
3570
-    }
3571
-
3572
-
3573
-    /**
3574
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3575
-     * then we also add a special where condition which allows for that model's primary key
3576
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3577
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3578
-     *
3579
-     * @param array    $default_where_conditions
3580
-     * @param array    $provided_where_conditions
3581
-     * @param EEM_Base $model
3582
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3583
-     * @return array like EEM_Base::get_all's $query_params[0]
3584
-     * @throws \EE_Error
3585
-     */
3586
-    private function _override_defaults_or_make_null_friendly(
3587
-        $default_where_conditions,
3588
-        $provided_where_conditions,
3589
-        $model,
3590
-        $model_relation_path
3591
-    ) {
3592
-        $null_friendly_where_conditions = array();
3593
-        $none_overridden = true;
3594
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3595
-        foreach ($default_where_conditions as $key => $val) {
3596
-            if (isset($provided_where_conditions[$key])) {
3597
-                $none_overridden = false;
3598
-            } else {
3599
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3600
-            }
3601
-        }
3602
-        if ($none_overridden && $default_where_conditions) {
3603
-            if ($model->has_primary_key_field()) {
3604
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3605
-                                                                                . "."
3606
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3607
-            }/*else{
32
+	//admin posty
33
+	//basic -> grants access to mine -> if they don't have it, select none
34
+	//*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
+	//*_published -> grants access to published -> if they dont have it, select non-published
37
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
39
+	//frontend posty
40
+	//by default has access to published
41
+	//basic -> grants access to mine that arent published, and all published
42
+	//*_others ->grants access to others that arent private, all mine
43
+	//*_private -> grants full access
44
+	//frontend non-posty
45
+	//like admin posty
46
+	//category-y
47
+	//assign -> grants access to join-table
48
+	//(delete, edit)
49
+	//payment-method-y
50
+	//for each registered payment method,
51
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
+	/**
53
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
56
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
+	 *
58
+	 * @var boolean
59
+	 */
60
+	private $_values_already_prepared_by_model_object = 0;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the data is just like form input that needs to have the model fields'
65
+	 * prepare_for_set and prepare_for_use_in_db called on it
66
+	 */
67
+	const not_prepared_by_model_object = 0;
68
+
69
+	/**
70
+	 * when $_values_already_prepared_by_model_object equals this, we
71
+	 * assume this value is coming from a model object and doesn't need to have
72
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
73
+	 */
74
+	const prepared_by_model_object = 1;
75
+
76
+	/**
77
+	 * when $_values_already_prepared_by_model_object equals this, we assume
78
+	 * the values are already to be used in the database (ie no processing is done
79
+	 * on them by the model's fields)
80
+	 */
81
+	const prepared_for_use_in_db = 2;
82
+
83
+
84
+	protected $singular_item = 'Item';
85
+
86
+	protected $plural_item   = 'Items';
87
+
88
+	/**
89
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
+	 */
91
+	protected $_tables;
92
+
93
+	/**
94
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
+	 *
98
+	 * @var \EE_Model_Field_Base[] $_fields
99
+	 */
100
+	protected $_fields;
101
+
102
+	/**
103
+	 * array of different kinds of relations
104
+	 *
105
+	 * @var \EE_Model_Relation_Base[] $_model_relations
106
+	 */
107
+	protected $_model_relations;
108
+
109
+	/**
110
+	 * @var \EE_Index[] $_indexes
111
+	 */
112
+	protected $_indexes = array();
113
+
114
+	/**
115
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
116
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
+	 * by setting the same columns as used in these queries in the query yourself.
118
+	 *
119
+	 * @var EE_Default_Where_Conditions
120
+	 */
121
+	protected $_default_where_conditions_strategy;
122
+
123
+	/**
124
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
+	 * This is particularly useful when you want something between 'none' and 'default'
126
+	 *
127
+	 * @var EE_Default_Where_Conditions
128
+	 */
129
+	protected $_minimum_where_conditions_strategy;
130
+
131
+	/**
132
+	 * String describing how to find the "owner" of this model's objects.
133
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
+	 * But when there isn't, this indicates which related model, or transiently-related model,
135
+	 * has the foreign key to the wp_users table.
136
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
+	 * related to events, and events have a foreign key to wp_users.
138
+	 * On EEM_Transaction, this would be 'Transaction.Event'
139
+	 *
140
+	 * @var string
141
+	 */
142
+	protected $_model_chain_to_wp_user = '';
143
+
144
+	/**
145
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
+	 * don't need it (particularly CPT models)
147
+	 *
148
+	 * @var bool
149
+	 */
150
+	protected $_ignore_where_strategy = false;
151
+
152
+	/**
153
+	 * String used in caps relating to this model. Eg, if the caps relating to this
154
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
+	 *
156
+	 * @var string. If null it hasn't been initialized yet. If false then we
157
+	 * have indicated capabilities don't apply to this
158
+	 */
159
+	protected $_caps_slug = null;
160
+
161
+	/**
162
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
+	 * and next-level keys are capability names, and each's value is a
164
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
166
+	 * and then each capability in the corresponding sub-array that they're missing
167
+	 * adds the where conditions onto the query.
168
+	 *
169
+	 * @var array
170
+	 */
171
+	protected $_cap_restrictions = array(
172
+		self::caps_read       => array(),
173
+		self::caps_read_admin => array(),
174
+		self::caps_edit       => array(),
175
+		self::caps_delete     => array(),
176
+	);
177
+
178
+	/**
179
+	 * Array defining which cap restriction generators to use to create default
180
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
181
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
+	 * automatically set this to false (not just null).
184
+	 *
185
+	 * @var EE_Restriction_Generator_Base[]
186
+	 */
187
+	protected $_cap_restriction_generators = array();
188
+
189
+	/**
190
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
+	 */
192
+	const caps_read       = 'read';
193
+
194
+	const caps_read_admin = 'read_admin';
195
+
196
+	const caps_edit       = 'edit';
197
+
198
+	const caps_delete     = 'delete';
199
+
200
+	/**
201
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
+	 * maps to 'read' because when looking for relevant permissions we're going to use
204
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
205
+	 *
206
+	 * @var array
207
+	 */
208
+	protected $_cap_contexts_to_cap_action_map = array(
209
+		self::caps_read       => 'read',
210
+		self::caps_read_admin => 'read',
211
+		self::caps_edit       => 'edit',
212
+		self::caps_delete     => 'delete',
213
+	);
214
+
215
+	/**
216
+	 * Timezone
217
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
+	 * EE_Datetime_Field data type will have access to it.
221
+	 *
222
+	 * @var string
223
+	 */
224
+	protected $_timezone;
225
+
226
+
227
+	/**
228
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
+	 * multisite.
230
+	 *
231
+	 * @var int
232
+	 */
233
+	protected static $_model_query_blog_id;
234
+
235
+	/**
236
+	 * A copy of _fields, except the array keys are the model names pointed to by
237
+	 * the field
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cache_foreign_key_to_fields = array();
242
+
243
+	/**
244
+	 * Cached list of all the fields on the model, indexed by their name
245
+	 *
246
+	 * @var EE_Model_Field_Base[]
247
+	 */
248
+	private $_cached_fields = null;
249
+
250
+	/**
251
+	 * Cached list of all the fields on the model, except those that are
252
+	 * marked as only pertinent to the database
253
+	 *
254
+	 * @var EE_Model_Field_Base[]
255
+	 */
256
+	private $_cached_fields_non_db_only = null;
257
+
258
+	/**
259
+	 * A cached reference to the primary key for quick lookup
260
+	 *
261
+	 * @var EE_Model_Field_Base
262
+	 */
263
+	private $_primary_key_field = null;
264
+
265
+	/**
266
+	 * Flag indicating whether this model has a primary key or not
267
+	 *
268
+	 * @var boolean
269
+	 */
270
+	protected $_has_primary_key_field = null;
271
+
272
+	/**
273
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
274
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
+	 *
276
+	 * @var boolean
277
+	 */
278
+	protected $_wp_core_model = false;
279
+
280
+	/**
281
+	 *    List of valid operators that can be used for querying.
282
+	 * The keys are all operators we'll accept, the values are the real SQL
283
+	 * operators used
284
+	 *
285
+	 * @var array
286
+	 */
287
+	protected $_valid_operators = array(
288
+		'='           => '=',
289
+		'<='          => '<=',
290
+		'<'           => '<',
291
+		'>='          => '>=',
292
+		'>'           => '>',
293
+		'!='          => '!=',
294
+		'LIKE'        => 'LIKE',
295
+		'like'        => 'LIKE',
296
+		'NOT_LIKE'    => 'NOT LIKE',
297
+		'not_like'    => 'NOT LIKE',
298
+		'NOT LIKE'    => 'NOT LIKE',
299
+		'not like'    => 'NOT LIKE',
300
+		'IN'          => 'IN',
301
+		'in'          => 'IN',
302
+		'NOT_IN'      => 'NOT IN',
303
+		'not_in'      => 'NOT IN',
304
+		'NOT IN'      => 'NOT IN',
305
+		'not in'      => 'NOT IN',
306
+		'between'     => 'BETWEEN',
307
+		'BETWEEN'     => 'BETWEEN',
308
+		'IS_NOT_NULL' => 'IS NOT NULL',
309
+		'is_not_null' => 'IS NOT NULL',
310
+		'IS NOT NULL' => 'IS NOT NULL',
311
+		'is not null' => 'IS NOT NULL',
312
+		'IS_NULL'     => 'IS NULL',
313
+		'is_null'     => 'IS NULL',
314
+		'IS NULL'     => 'IS NULL',
315
+		'is null'     => 'IS NULL',
316
+		'REGEXP'      => 'REGEXP',
317
+		'regexp'      => 'REGEXP',
318
+		'NOT_REGEXP'  => 'NOT REGEXP',
319
+		'not_regexp'  => 'NOT REGEXP',
320
+		'NOT REGEXP'  => 'NOT REGEXP',
321
+		'not regexp'  => 'NOT REGEXP',
322
+	);
323
+
324
+	/**
325
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
+	 *
327
+	 * @var array
328
+	 */
329
+	protected $_in_style_operators = array('IN', 'NOT IN');
330
+
331
+	/**
332
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
+	 * '12-31-2012'"
334
+	 *
335
+	 * @var array
336
+	 */
337
+	protected $_between_style_operators = array('BETWEEN');
338
+
339
+	/**
340
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
+	 * on a join table.
342
+	 *
343
+	 * @var array
344
+	 */
345
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
+
347
+	/**
348
+	 * Allowed values for $query_params['order'] for ordering in queries
349
+	 *
350
+	 * @var array
351
+	 */
352
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
+
354
+	/**
355
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
357
+	 *
358
+	 * @var array
359
+	 */
360
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
+
362
+	/**
363
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
365
+	 *
366
+	 * @var array
367
+	 */
368
+	private $_allowed_query_params = array(
369
+		0,
370
+		'limit',
371
+		'order_by',
372
+		'group_by',
373
+		'having',
374
+		'force_join',
375
+		'order',
376
+		'on_join_limit',
377
+		'default_where_conditions',
378
+		'caps',
379
+	);
380
+
381
+	/**
382
+	 * All the data types that can be used in $wpdb->prepare statements.
383
+	 *
384
+	 * @var array
385
+	 */
386
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
+
388
+	/**
389
+	 *    EE_Registry Object
390
+	 *
391
+	 * @var    object
392
+	 * @access    protected
393
+	 */
394
+	protected $EE = null;
395
+
396
+
397
+	/**
398
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
+	 *
400
+	 * @var int
401
+	 */
402
+	protected $_show_next_x_db_queries = 0;
403
+
404
+	/**
405
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
+	 *
408
+	 * @var array
409
+	 */
410
+	protected $_custom_selections = array();
411
+
412
+	/**
413
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
+	 * caches every model object we've fetched from the DB on this request
415
+	 *
416
+	 * @var array
417
+	 */
418
+	protected $_entity_map;
419
+
420
+	/**
421
+	 * constant used to show EEM_Base has not yet verified the db on this http request
422
+	 */
423
+	const db_verified_none = 0;
424
+
425
+	/**
426
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
427
+	 * but not the addons' dbs
428
+	 */
429
+	const db_verified_core = 1;
430
+
431
+	/**
432
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
+	 * the EE core db too)
434
+	 */
435
+	const db_verified_addons = 2;
436
+
437
+	/**
438
+	 * indicates whether an EEM_Base child has already re-verified the DB
439
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
440
+	 * looking like EEM_Base::db_verified_*
441
+	 *
442
+	 * @var int - 0 = none, 1 = core, 2 = addons
443
+	 */
444
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
445
+
446
+	/**
447
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
448
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
449
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
450
+	 */
451
+	const default_where_conditions_all = 'all';
452
+
453
+	/**
454
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
455
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
456
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
457
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
458
+	 *        models which share tables with other models, this can return data for the wrong model.
459
+	 */
460
+	const default_where_conditions_this_only = 'this_model_only';
461
+
462
+	/**
463
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
464
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
465
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
466
+	 */
467
+	const default_where_conditions_others_only = 'other_models_only';
468
+
469
+	/**
470
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
471
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
472
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
473
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
474
+	 *        (regardless of whether those events and venues are trashed)
475
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
476
+	 *        events.
477
+	 */
478
+	const default_where_conditions_minimum_all = 'minimum';
479
+
480
+	/**
481
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
482
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
483
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
484
+	 *        not)
485
+	 */
486
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
487
+
488
+	/**
489
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
490
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
491
+	 *        it's possible it will return table entries for other models. You should use
492
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
493
+	 */
494
+	const default_where_conditions_none = 'none';
495
+
496
+
497
+
498
+	/**
499
+	 * About all child constructors:
500
+	 * they should define the _tables, _fields and _model_relations arrays.
501
+	 * Should ALWAYS be called after child constructor.
502
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
503
+	 * finalizes constructing all the object's attributes.
504
+	 * Generally, rather than requiring a child to code
505
+	 * $this->_tables = array(
506
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
507
+	 *        ...);
508
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
509
+	 * each EE_Table has a function to set the table's alias after the constructor, using
510
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
511
+	 * do something similar.
512
+	 *
513
+	 * @param null $timezone
514
+	 * @throws \EE_Error
515
+	 */
516
+	protected function __construct($timezone = null)
517
+	{
518
+		// check that the model has not been loaded too soon
519
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
520
+			throw new EE_Error (
521
+				sprintf(
522
+					__('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
523
+						'event_espresso'),
524
+					get_class($this)
525
+				)
526
+			);
527
+		}
528
+		/**
529
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
530
+		 */
531
+		if (empty(EEM_Base::$_model_query_blog_id)) {
532
+			EEM_Base::set_model_query_blog_id();
533
+		}
534
+		/**
535
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
536
+		 * just use EE_Register_Model_Extension
537
+		 *
538
+		 * @var EE_Table_Base[] $_tables
539
+		 */
540
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
541
+		foreach ($this->_tables as $table_alias => $table_obj) {
542
+			/** @var $table_obj EE_Table_Base */
543
+			$table_obj->_construct_finalize_with_alias($table_alias);
544
+			if ($table_obj instanceof EE_Secondary_Table) {
545
+				/** @var $table_obj EE_Secondary_Table */
546
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
547
+			}
548
+		}
549
+		/**
550
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
551
+		 * EE_Register_Model_Extension
552
+		 *
553
+		 * @param EE_Model_Field_Base[] $_fields
554
+		 */
555
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
556
+		$this->_invalidate_field_caches();
557
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
558
+			if (! array_key_exists($table_alias, $this->_tables)) {
559
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
560
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
561
+			}
562
+			foreach ($fields_for_table as $field_name => $field_obj) {
563
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
564
+				//primary key field base has a slightly different _construct_finalize
565
+				/** @var $field_obj EE_Model_Field_Base */
566
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
567
+			}
568
+		}
569
+		// everything is related to Extra_Meta
570
+		if (get_class($this) !== 'EEM_Extra_Meta') {
571
+			//make extra meta related to everything, but don't block deleting things just
572
+			//because they have related extra meta info. For now just orphan those extra meta
573
+			//in the future we should automatically delete them
574
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
575
+		}
576
+		//and change logs
577
+		if (get_class($this) !== 'EEM_Change_Log') {
578
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
579
+		}
580
+		/**
581
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
582
+		 * EE_Register_Model_Extension
583
+		 *
584
+		 * @param EE_Model_Relation_Base[] $_model_relations
585
+		 */
586
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
587
+			$this->_model_relations);
588
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
589
+			/** @var $relation_obj EE_Model_Relation_Base */
590
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
591
+		}
592
+		foreach ($this->_indexes as $index_name => $index_obj) {
593
+			/** @var $index_obj EE_Index */
594
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
595
+		}
596
+		$this->set_timezone($timezone);
597
+		//finalize default where condition strategy, or set default
598
+		if (! $this->_default_where_conditions_strategy) {
599
+			//nothing was set during child constructor, so set default
600
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
601
+		}
602
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
603
+		if (! $this->_minimum_where_conditions_strategy) {
604
+			//nothing was set during child constructor, so set default
605
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
606
+		}
607
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
608
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
609
+		//to indicate to NOT set it, set it to the logical default
610
+		if ($this->_caps_slug === null) {
611
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
612
+		}
613
+		//initialize the standard cap restriction generators if none were specified by the child constructor
614
+		if ($this->_cap_restriction_generators !== false) {
615
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
616
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
617
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
618
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
619
+						new EE_Restriction_Generator_Protected(),
620
+						$cap_context,
621
+						$this
622
+					);
623
+				}
624
+			}
625
+		}
626
+		//if there are cap restriction generators, use them to make the default cap restrictions
627
+		if ($this->_cap_restriction_generators !== false) {
628
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
629
+				if (! $generator_object) {
630
+					continue;
631
+				}
632
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
633
+					throw new EE_Error(
634
+						sprintf(
635
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
636
+								'event_espresso'),
637
+							$context,
638
+							$this->get_this_model_name()
639
+						)
640
+					);
641
+				}
642
+				$action = $this->cap_action_for_context($context);
643
+				if (! $generator_object->construction_finalized()) {
644
+					$generator_object->_construct_finalize($this, $action);
645
+				}
646
+			}
647
+		}
648
+		do_action('AHEE__' . get_class($this) . '__construct__end');
649
+	}
650
+
651
+
652
+
653
+	/**
654
+	 * Generates the cap restrictions for the given context, or if they were
655
+	 * already generated just gets what's cached
656
+	 *
657
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
658
+	 * @return EE_Default_Where_Conditions[]
659
+	 */
660
+	protected function _generate_cap_restrictions($context)
661
+	{
662
+		if (isset($this->_cap_restriction_generators[$context])
663
+			&& $this->_cap_restriction_generators[$context]
664
+			   instanceof
665
+			   EE_Restriction_Generator_Base
666
+		) {
667
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
668
+		} else {
669
+			return array();
670
+		}
671
+	}
672
+
673
+
674
+
675
+	/**
676
+	 * Used to set the $_model_query_blog_id static property.
677
+	 *
678
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
679
+	 *                      value for get_current_blog_id() will be used.
680
+	 */
681
+	public static function set_model_query_blog_id($blog_id = 0)
682
+	{
683
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
684
+	}
685
+
686
+
687
+
688
+	/**
689
+	 * Returns whatever is set as the internal $model_query_blog_id.
690
+	 *
691
+	 * @return int
692
+	 */
693
+	public static function get_model_query_blog_id()
694
+	{
695
+		return EEM_Base::$_model_query_blog_id;
696
+	}
697
+
698
+
699
+
700
+	/**
701
+	 *        This function is a singleton method used to instantiate the Espresso_model object
702
+	 *
703
+	 * @access public
704
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
705
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
706
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
707
+	 *                         timezone in the 'timezone_string' wp option)
708
+	 * @return static (as in the concrete child class)
709
+	 */
710
+	public static function instance($timezone = null)
711
+	{
712
+		// check if instance of Espresso_model already exists
713
+		if (! static::$_instance instanceof static) {
714
+			// instantiate Espresso_model
715
+			static::$_instance = new static($timezone);
716
+		}
717
+		//we might have a timezone set, let set_timezone decide what to do with it
718
+		static::$_instance->set_timezone($timezone);
719
+		// Espresso_model object
720
+		return static::$_instance;
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * resets the model and returns it
727
+	 *
728
+	 * @param null | string $timezone
729
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
730
+	 * all its properties reset; if it wasn't instantiated, returns null)
731
+	 */
732
+	public static function reset($timezone = null)
733
+	{
734
+		if (static::$_instance instanceof EEM_Base) {
735
+			//let's try to NOT swap out the current instance for a new one
736
+			//because if someone has a reference to it, we can't remove their reference
737
+			//so it's best to keep using the same reference, but change the original object
738
+			//reset all its properties to their original values as defined in the class
739
+			$r = new ReflectionClass(get_class(static::$_instance));
740
+			$static_properties = $r->getStaticProperties();
741
+			foreach ($r->getDefaultProperties() as $property => $value) {
742
+				//don't set instance to null like it was originally,
743
+				//but it's static anyways, and we're ignoring static properties (for now at least)
744
+				if (! isset($static_properties[$property])) {
745
+					static::$_instance->{$property} = $value;
746
+				}
747
+			}
748
+			//and then directly call its constructor again, like we would if we
749
+			//were creating a new one
750
+			static::$_instance->__construct($timezone);
751
+			return self::instance();
752
+		}
753
+		return null;
754
+	}
755
+
756
+
757
+
758
+	/**
759
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
760
+	 *
761
+	 * @param  boolean $translated return localized strings or JUST the array.
762
+	 * @return array
763
+	 * @throws \EE_Error
764
+	 */
765
+	public function status_array($translated = false)
766
+	{
767
+		if (! array_key_exists('Status', $this->_model_relations)) {
768
+			return array();
769
+		}
770
+		$model_name = $this->get_this_model_name();
771
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
772
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
773
+		$status_array = array();
774
+		foreach ($stati as $status) {
775
+			$status_array[$status->ID()] = $status->get('STS_code');
776
+		}
777
+		return $translated
778
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
779
+			: $status_array;
780
+	}
781
+
782
+
783
+
784
+	/**
785
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
786
+	 *
787
+	 * @param array $query_params             {
788
+	 * @var array $0 (where) array {
789
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
790
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
791
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
792
+	 *                                        conditions based on related models (and even
793
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
794
+	 *                                        name. Eg,
795
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
796
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
797
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
798
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
799
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
800
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
801
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
802
+	 *                                        to Venues (even when each of those models actually consisted of two
803
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
804
+	 *                                        just having
805
+	 *                                        "Venue.VNU_ID", you could have
806
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
807
+	 *                                        events are related to Registrations, which are related to Attendees). You
808
+	 *                                        can take it even further with
809
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
810
+	 *                                        (from the default of '='), change the value to an numerically-indexed
811
+	 *                                        array, where the first item in the list is the operator. eg: array(
812
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
813
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
814
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
815
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
816
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
817
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
818
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
819
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
820
+	 *                                        the value is a field, simply provide a third array item (true) to the
821
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
822
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
823
+	 *                                        Note: you can also use related model field names like you would any other
824
+	 *                                        field name. eg:
825
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
826
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
827
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
828
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
829
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
830
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
831
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
832
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
833
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
834
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
835
+	 *                                        "stick" until you specify an AND. eg
836
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
837
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
838
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
839
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
840
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
841
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
842
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
843
+	 *                                        too, eg:
844
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
845
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
846
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
847
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
848
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
849
+	 *                                        the OFFSET, the 2nd is the LIMIT
850
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
851
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
852
+	 *                                        following format array('on_join_limit'
853
+	 *                                        => array( 'table_alias', array(1,2) ) ).
854
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
855
+	 *                                        values are either 'ASC' or 'DESC'.
856
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
857
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
858
+	 *                                        DESC..." respectively. Like the
859
+	 *                                        'where' conditions, these fields can be on related models. Eg
860
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
861
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
862
+	 *                                        Attendee, Price, Datetime, etc.)
863
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
864
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
865
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
866
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
867
+	 *                                        order by the primary key. Eg,
868
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
869
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
870
+	 *                                        DTT_EVT_start) or
871
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
872
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
873
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
874
+	 *                                        'group_by'=>'VNU_ID', or
875
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
876
+	 *                                        if no
877
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
878
+	 *                                        model's primary key (or combined primary keys). This avoids some
879
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
880
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
881
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
882
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
883
+	 *                                        results)
884
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
885
+	 *                                        array where values are models to be joined in the query.Eg
886
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
887
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
888
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
889
+	 *                                        related models which belongs to the current model
890
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
891
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
892
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
893
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
894
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
895
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
896
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
897
+	 *                                        this model's default where conditions added to the query, use
898
+	 *                                        'this_model_only'. If you want to use all default where conditions
899
+	 *                                        (default), set to 'all'.
900
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
901
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
902
+	 *                                        everything? Or should we only show the current user items they should be
903
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
904
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
905
+	 *                                        }
906
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
907
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
908
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
909
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
910
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
911
+	 *                                        array( array(
912
+	 *                                        'OR'=>array(
913
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
914
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
915
+	 *                                        )
916
+	 *                                        ),
917
+	 *                                        'limit'=>10,
918
+	 *                                        'group_by'=>'TXN_ID'
919
+	 *                                        ));
920
+	 *                                        get all the answers to the question titled "shirt size" for event with id
921
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
922
+	 *                                        'Question.QST_display_text'=>'shirt size',
923
+	 *                                        'Registration.Event.EVT_ID'=>12
924
+	 *                                        ),
925
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
926
+	 *                                        ));
927
+	 * @throws \EE_Error
928
+	 */
929
+	public function get_all($query_params = array())
930
+	{
931
+		if (isset($query_params['limit'])
932
+			&& ! isset($query_params['group_by'])
933
+		) {
934
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
935
+		}
936
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
937
+	}
938
+
939
+
940
+
941
+	/**
942
+	 * Modifies the query parameters so we only get back model objects
943
+	 * that "belong" to the current user
944
+	 *
945
+	 * @param array $query_params @see EEM_Base::get_all()
946
+	 * @return array like EEM_Base::get_all
947
+	 */
948
+	public function alter_query_params_to_only_include_mine($query_params = array())
949
+	{
950
+		$wp_user_field_name = $this->wp_user_field_name();
951
+		if ($wp_user_field_name) {
952
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
953
+		}
954
+		return $query_params;
955
+	}
956
+
957
+
958
+
959
+	/**
960
+	 * Returns the name of the field's name that points to the WP_User table
961
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
962
+	 * foreign key to the WP_User table)
963
+	 *
964
+	 * @return string|boolean string on success, boolean false when there is no
965
+	 * foreign key to the WP_User table
966
+	 */
967
+	public function wp_user_field_name()
968
+	{
969
+		try {
970
+			if (! empty($this->_model_chain_to_wp_user)) {
971
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
972
+				$last_model_name = end($models_to_follow_to_wp_users);
973
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
974
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
975
+			} else {
976
+				$model_with_fk_to_wp_users = $this;
977
+				$model_chain_to_wp_user = '';
978
+			}
979
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
980
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
981
+		} catch (EE_Error $e) {
982
+			return false;
983
+		}
984
+	}
985
+
986
+
987
+
988
+	/**
989
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
990
+	 * (or transiently-related model) has a foreign key to the wp_users table;
991
+	 * useful for finding if model objects of this type are 'owned' by the current user.
992
+	 * This is an empty string when the foreign key is on this model and when it isn't,
993
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
994
+	 * (or transiently-related model)
995
+	 *
996
+	 * @return string
997
+	 */
998
+	public function model_chain_to_wp_user()
999
+	{
1000
+		return $this->_model_chain_to_wp_user;
1001
+	}
1002
+
1003
+
1004
+
1005
+	/**
1006
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1007
+	 * like how registrations don't have a foreign key to wp_users, but the
1008
+	 * events they are for are), or is unrelated to wp users.
1009
+	 * generally available
1010
+	 *
1011
+	 * @return boolean
1012
+	 */
1013
+	public function is_owned()
1014
+	{
1015
+		if ($this->model_chain_to_wp_user()) {
1016
+			return true;
1017
+		} else {
1018
+			try {
1019
+				$this->get_foreign_key_to('WP_User');
1020
+				return true;
1021
+			} catch (EE_Error $e) {
1022
+				return false;
1023
+			}
1024
+		}
1025
+	}
1026
+
1027
+
1028
+
1029
+	/**
1030
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1031
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1032
+	 * the model)
1033
+	 *
1034
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1035
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1037
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1038
+	 *                                  override this and set the select to "*", or a specific column name, like
1039
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
+	 *                                  the aliases used to refer to this selection, and values are to be
1042
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
+	 * @throws \EE_Error
1046
+	 */
1047
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1048
+	{
1049
+		// remember the custom selections, if any, and type cast as array
1050
+		// (unless $columns_to_select is an object, then just set as an empty array)
1051
+		// Note: (array) 'some string' === array( 'some string' )
1052
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1053
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1054
+		$select_expressions = $columns_to_select !== null
1055
+			? $this->_construct_select_from_input($columns_to_select)
1056
+			: $this->_construct_default_select_sql($model_query_info);
1057
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1058
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1059
+	}
1060
+
1061
+
1062
+
1063
+	/**
1064
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1065
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1066
+	 * take care of joins, field preparation etc.
1067
+	 *
1068
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1069
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1070
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1071
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1072
+	 *                                  override this and set the select to "*", or a specific column name, like
1073
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1074
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1075
+	 *                                  the aliases used to refer to this selection, and values are to be
1076
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1077
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1078
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1079
+	 * @throws \EE_Error
1080
+	 */
1081
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1082
+	{
1083
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1084
+	}
1085
+
1086
+
1087
+
1088
+	/**
1089
+	 * For creating a custom select statement
1090
+	 *
1091
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1092
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1093
+	 *                                 SQL, and 1=>is the datatype
1094
+	 * @throws EE_Error
1095
+	 * @return string
1096
+	 */
1097
+	private function _construct_select_from_input($columns_to_select)
1098
+	{
1099
+		if (is_array($columns_to_select)) {
1100
+			$select_sql_array = array();
1101
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1102
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1103
+					throw new EE_Error(
1104
+						sprintf(
1105
+							__(
1106
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1107
+								"event_espresso"
1108
+							),
1109
+							$selection_and_datatype,
1110
+							$alias
1111
+						)
1112
+					);
1113
+				}
1114
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1115
+					throw new EE_Error(
1116
+						sprintf(
1117
+							__(
1118
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1119
+								"event_espresso"
1120
+							),
1121
+							$selection_and_datatype[1],
1122
+							$selection_and_datatype[0],
1123
+							$alias,
1124
+							implode(",", $this->_valid_wpdb_data_types)
1125
+						)
1126
+					);
1127
+				}
1128
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1129
+			}
1130
+			$columns_to_select_string = implode(", ", $select_sql_array);
1131
+		} else {
1132
+			$columns_to_select_string = $columns_to_select;
1133
+		}
1134
+		return $columns_to_select_string;
1135
+	}
1136
+
1137
+
1138
+
1139
+	/**
1140
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1141
+	 *
1142
+	 * @return string
1143
+	 * @throws \EE_Error
1144
+	 */
1145
+	public function primary_key_name()
1146
+	{
1147
+		return $this->get_primary_key_field()->get_name();
1148
+	}
1149
+
1150
+
1151
+
1152
+	/**
1153
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1154
+	 * If there is no primary key on this model, $id is treated as primary key string
1155
+	 *
1156
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1157
+	 * @return EE_Base_Class
1158
+	 */
1159
+	public function get_one_by_ID($id)
1160
+	{
1161
+		if ($this->get_from_entity_map($id)) {
1162
+			return $this->get_from_entity_map($id);
1163
+		}
1164
+		return $this->get_one(
1165
+			$this->alter_query_params_to_restrict_by_ID(
1166
+				$id,
1167
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1168
+			)
1169
+		);
1170
+	}
1171
+
1172
+
1173
+
1174
+	/**
1175
+	 * Alters query parameters to only get items with this ID are returned.
1176
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1177
+	 * or could just be a simple primary key ID
1178
+	 *
1179
+	 * @param int   $id
1180
+	 * @param array $query_params
1181
+	 * @return array of normal query params, @see EEM_Base::get_all
1182
+	 * @throws \EE_Error
1183
+	 */
1184
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1185
+	{
1186
+		if (! isset($query_params[0])) {
1187
+			$query_params[0] = array();
1188
+		}
1189
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1190
+		if ($conditions_from_id === null) {
1191
+			$query_params[0][$this->primary_key_name()] = $id;
1192
+		} else {
1193
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1194
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1195
+		}
1196
+		return $query_params;
1197
+	}
1198
+
1199
+
1200
+
1201
+	/**
1202
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1203
+	 * array. If no item is found, null is returned.
1204
+	 *
1205
+	 * @param array $query_params like EEM_Base's $query_params variable.
1206
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1207
+	 * @throws \EE_Error
1208
+	 */
1209
+	public function get_one($query_params = array())
1210
+	{
1211
+		if (! is_array($query_params)) {
1212
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1213
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1214
+					gettype($query_params)), '4.6.0');
1215
+			$query_params = array();
1216
+		}
1217
+		$query_params['limit'] = 1;
1218
+		$items = $this->get_all($query_params);
1219
+		if (empty($items)) {
1220
+			return null;
1221
+		} else {
1222
+			return array_shift($items);
1223
+		}
1224
+	}
1225
+
1226
+
1227
+
1228
+	/**
1229
+	 * Returns the next x number of items in sequence from the given value as
1230
+	 * found in the database matching the given query conditions.
1231
+	 *
1232
+	 * @param mixed $current_field_value    Value used for the reference point.
1233
+	 * @param null  $field_to_order_by      What field is used for the
1234
+	 *                                      reference point.
1235
+	 * @param int   $limit                  How many to return.
1236
+	 * @param array $query_params           Extra conditions on the query.
1237
+	 * @param null  $columns_to_select      If left null, then an array of
1238
+	 *                                      EE_Base_Class objects is returned,
1239
+	 *                                      otherwise you can indicate just the
1240
+	 *                                      columns you want returned.
1241
+	 * @return EE_Base_Class[]|array
1242
+	 * @throws \EE_Error
1243
+	 */
1244
+	public function next_x(
1245
+		$current_field_value,
1246
+		$field_to_order_by = null,
1247
+		$limit = 1,
1248
+		$query_params = array(),
1249
+		$columns_to_select = null
1250
+	) {
1251
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1252
+			$columns_to_select);
1253
+	}
1254
+
1255
+
1256
+
1257
+	/**
1258
+	 * Returns the previous x number of items in sequence from the given value
1259
+	 * as found in the database matching the given query conditions.
1260
+	 *
1261
+	 * @param mixed $current_field_value    Value used for the reference point.
1262
+	 * @param null  $field_to_order_by      What field is used for the
1263
+	 *                                      reference point.
1264
+	 * @param int   $limit                  How many to return.
1265
+	 * @param array $query_params           Extra conditions on the query.
1266
+	 * @param null  $columns_to_select      If left null, then an array of
1267
+	 *                                      EE_Base_Class objects is returned,
1268
+	 *                                      otherwise you can indicate just the
1269
+	 *                                      columns you want returned.
1270
+	 * @return EE_Base_Class[]|array
1271
+	 * @throws \EE_Error
1272
+	 */
1273
+	public function previous_x(
1274
+		$current_field_value,
1275
+		$field_to_order_by = null,
1276
+		$limit = 1,
1277
+		$query_params = array(),
1278
+		$columns_to_select = null
1279
+	) {
1280
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1281
+			$columns_to_select);
1282
+	}
1283
+
1284
+
1285
+
1286
+	/**
1287
+	 * Returns the next item in sequence from the given value as found in the
1288
+	 * database matching the given query conditions.
1289
+	 *
1290
+	 * @param mixed $current_field_value    Value used for the reference point.
1291
+	 * @param null  $field_to_order_by      What field is used for the
1292
+	 *                                      reference point.
1293
+	 * @param array $query_params           Extra conditions on the query.
1294
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1295
+	 *                                      object is returned, otherwise you
1296
+	 *                                      can indicate just the columns you
1297
+	 *                                      want and a single array indexed by
1298
+	 *                                      the columns will be returned.
1299
+	 * @return EE_Base_Class|null|array()
1300
+	 * @throws \EE_Error
1301
+	 */
1302
+	public function next(
1303
+		$current_field_value,
1304
+		$field_to_order_by = null,
1305
+		$query_params = array(),
1306
+		$columns_to_select = null
1307
+	) {
1308
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1309
+			$columns_to_select);
1310
+		return empty($results) ? null : reset($results);
1311
+	}
1312
+
1313
+
1314
+
1315
+	/**
1316
+	 * Returns the previous item in sequence from the given value as found in
1317
+	 * the database matching the given query conditions.
1318
+	 *
1319
+	 * @param mixed $current_field_value    Value used for the reference point.
1320
+	 * @param null  $field_to_order_by      What field is used for the
1321
+	 *                                      reference point.
1322
+	 * @param array $query_params           Extra conditions on the query.
1323
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1324
+	 *                                      object is returned, otherwise you
1325
+	 *                                      can indicate just the columns you
1326
+	 *                                      want and a single array indexed by
1327
+	 *                                      the columns will be returned.
1328
+	 * @return EE_Base_Class|null|array()
1329
+	 * @throws EE_Error
1330
+	 */
1331
+	public function previous(
1332
+		$current_field_value,
1333
+		$field_to_order_by = null,
1334
+		$query_params = array(),
1335
+		$columns_to_select = null
1336
+	) {
1337
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1338
+			$columns_to_select);
1339
+		return empty($results) ? null : reset($results);
1340
+	}
1341
+
1342
+
1343
+
1344
+	/**
1345
+	 * Returns the a consecutive number of items in sequence from the given
1346
+	 * value as found in the database matching the given query conditions.
1347
+	 *
1348
+	 * @param mixed  $current_field_value   Value used for the reference point.
1349
+	 * @param string $operand               What operand is used for the sequence.
1350
+	 * @param string $field_to_order_by     What field is used for the reference point.
1351
+	 * @param int    $limit                 How many to return.
1352
+	 * @param array  $query_params          Extra conditions on the query.
1353
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1354
+	 *                                      otherwise you can indicate just the columns you want returned.
1355
+	 * @return EE_Base_Class[]|array
1356
+	 * @throws EE_Error
1357
+	 */
1358
+	protected function _get_consecutive(
1359
+		$current_field_value,
1360
+		$operand = '>',
1361
+		$field_to_order_by = null,
1362
+		$limit = 1,
1363
+		$query_params = array(),
1364
+		$columns_to_select = null
1365
+	) {
1366
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1367
+		if (empty($field_to_order_by)) {
1368
+			if ($this->has_primary_key_field()) {
1369
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1370
+			} else {
1371
+				if (WP_DEBUG) {
1372
+					throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1373
+						'event_espresso'));
1374
+				}
1375
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1376
+				return array();
1377
+			}
1378
+		}
1379
+		if (! is_array($query_params)) {
1380
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1381
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1382
+					gettype($query_params)), '4.6.0');
1383
+			$query_params = array();
1384
+		}
1385
+		//let's add the where query param for consecutive look up.
1386
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1387
+		$query_params['limit'] = $limit;
1388
+		//set direction
1389
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1390
+		$query_params['order_by'] = $operand === '>'
1391
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1392
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1393
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1394
+		if (empty($columns_to_select)) {
1395
+			return $this->get_all($query_params);
1396
+		} else {
1397
+			//getting just the fields
1398
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1399
+		}
1400
+	}
1401
+
1402
+
1403
+
1404
+	/**
1405
+	 * This sets the _timezone property after model object has been instantiated.
1406
+	 *
1407
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1408
+	 */
1409
+	public function set_timezone($timezone)
1410
+	{
1411
+		if ($timezone !== null) {
1412
+			$this->_timezone = $timezone;
1413
+		}
1414
+		//note we need to loop through relations and set the timezone on those objects as well.
1415
+		foreach ($this->_model_relations as $relation) {
1416
+			$relation->set_timezone($timezone);
1417
+		}
1418
+		//and finally we do the same for any datetime fields
1419
+		foreach ($this->_fields as $field) {
1420
+			if ($field instanceof EE_Datetime_Field) {
1421
+				$field->set_timezone($timezone);
1422
+			}
1423
+		}
1424
+	}
1425
+
1426
+
1427
+
1428
+	/**
1429
+	 * This just returns whatever is set for the current timezone.
1430
+	 *
1431
+	 * @access public
1432
+	 * @return string
1433
+	 */
1434
+	public function get_timezone()
1435
+	{
1436
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1437
+		if (empty($this->_timezone)) {
1438
+			foreach ($this->_fields as $field) {
1439
+				if ($field instanceof EE_Datetime_Field) {
1440
+					$this->set_timezone($field->get_timezone());
1441
+					break;
1442
+				}
1443
+			}
1444
+		}
1445
+		//if timezone STILL empty then return the default timezone for the site.
1446
+		if (empty($this->_timezone)) {
1447
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1448
+		}
1449
+		return $this->_timezone;
1450
+	}
1451
+
1452
+
1453
+
1454
+	/**
1455
+	 * This returns the date formats set for the given field name and also ensures that
1456
+	 * $this->_timezone property is set correctly.
1457
+	 *
1458
+	 * @since 4.6.x
1459
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1460
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1461
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1462
+	 * @return array formats in an array with the date format first, and the time format last.
1463
+	 */
1464
+	public function get_formats_for($field_name, $pretty = false)
1465
+	{
1466
+		$field_settings = $this->field_settings_for($field_name);
1467
+		//if not a valid EE_Datetime_Field then throw error
1468
+		if (! $field_settings instanceof EE_Datetime_Field) {
1469
+			throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1470
+				'event_espresso'), $field_name));
1471
+		}
1472
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1473
+		//the field.
1474
+		$this->_timezone = $field_settings->get_timezone();
1475
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1476
+	}
1477
+
1478
+
1479
+
1480
+	/**
1481
+	 * This returns the current time in a format setup for a query on this model.
1482
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1483
+	 * it will return:
1484
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1485
+	 *  NOW
1486
+	 *  - or a unix timestamp (equivalent to time())
1487
+	 *
1488
+	 * @since 4.6.x
1489
+	 * @param string $field_name       The field the current time is needed for.
1490
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1491
+	 *                                 formatted string matching the set format for the field in the set timezone will
1492
+	 *                                 be returned.
1493
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1494
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1495
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1496
+	 *                                 exception is triggered.
1497
+	 */
1498
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1499
+	{
1500
+		$formats = $this->get_formats_for($field_name);
1501
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1502
+		if ($timestamp) {
1503
+			return $DateTime->format('U');
1504
+		}
1505
+		//not returning timestamp, so return formatted string in timezone.
1506
+		switch ($what) {
1507
+			case 'time' :
1508
+				return $DateTime->format($formats[1]);
1509
+				break;
1510
+			case 'date' :
1511
+				return $DateTime->format($formats[0]);
1512
+				break;
1513
+			default :
1514
+				return $DateTime->format(implode(' ', $formats));
1515
+				break;
1516
+		}
1517
+	}
1518
+
1519
+
1520
+
1521
+	/**
1522
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1523
+	 * for the model are.  Returns a DateTime object.
1524
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1525
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1526
+	 * ignored.
1527
+	 *
1528
+	 * @param string $field_name      The field being setup.
1529
+	 * @param string $timestring      The date time string being used.
1530
+	 * @param string $incoming_format The format for the time string.
1531
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1532
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1533
+	 *                                format is
1534
+	 *                                'U', this is ignored.
1535
+	 * @return DateTime
1536
+	 * @throws \EE_Error
1537
+	 */
1538
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1539
+	{
1540
+		//just using this to ensure the timezone is set correctly internally
1541
+		$this->get_formats_for($field_name);
1542
+		//load EEH_DTT_Helper
1543
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1544
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1545
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1546
+	}
1547
+
1548
+
1549
+
1550
+	/**
1551
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1552
+	 *
1553
+	 * @return EE_Table_Base[]
1554
+	 */
1555
+	public function get_tables()
1556
+	{
1557
+		return $this->_tables;
1558
+	}
1559
+
1560
+
1561
+
1562
+	/**
1563
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1564
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1565
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1566
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1567
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1568
+	 * model object with EVT_ID = 1
1569
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1570
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1571
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1572
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1573
+	 * are not specified)
1574
+	 *
1575
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1576
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1577
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1578
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1579
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1580
+	 *                                         ID=34, we'd use this method as follows:
1581
+	 *                                         EEM_Transaction::instance()->update(
1582
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1583
+	 *                                         array(array('TXN_ID'=>34)));
1584
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1585
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1586
+	 *                                         consider updating Question's QST_admin_label field is of type
1587
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1588
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1589
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1590
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1591
+	 *                                         TRUE, it is assumed that you've already called
1592
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1593
+	 *                                         malicious javascript. However, if
1594
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1595
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1596
+	 *                                         and every other field, before insertion. We provide this parameter
1597
+	 *                                         because model objects perform their prepare_for_set function on all
1598
+	 *                                         their values, and so don't need to be called again (and in many cases,
1599
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1600
+	 *                                         prepare_for_set method...)
1601
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1602
+	 *                                         in this model's entity map according to $fields_n_values that match
1603
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1604
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1605
+	 *                                         could get out-of-sync with the database
1606
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1607
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1608
+	 *                                         bad)
1609
+	 * @throws \EE_Error
1610
+	 */
1611
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1612
+	{
1613
+		if (! is_array($query_params)) {
1614
+			EE_Error::doing_it_wrong('EEM_Base::update',
1615
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1616
+					gettype($query_params)), '4.6.0');
1617
+			$query_params = array();
1618
+		}
1619
+		/**
1620
+		 * Action called before a model update call has been made.
1621
+		 *
1622
+		 * @param EEM_Base $model
1623
+		 * @param array    $fields_n_values the updated fields and their new values
1624
+		 * @param array    $query_params    @see EEM_Base::get_all()
1625
+		 */
1626
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1627
+		/**
1628
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1629
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1630
+		 *
1631
+		 * @param array    $fields_n_values fields and their new values
1632
+		 * @param EEM_Base $model           the model being queried
1633
+		 * @param array    $query_params    see EEM_Base::get_all()
1634
+		 */
1635
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1636
+			$query_params);
1637
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1638
+		//to do that, for each table, verify that it's PK isn't null.
1639
+		$tables = $this->get_tables();
1640
+		//and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1641
+		//NOTE: we should make this code more efficient by NOT querying twice
1642
+		//before the real update, but that needs to first go through ALPHA testing
1643
+		//as it's dangerous. says Mike August 8 2014
1644
+		//we want to make sure the default_where strategy is ignored
1645
+		$this->_ignore_where_strategy = true;
1646
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1647
+		foreach ($wpdb_select_results as $wpdb_result) {
1648
+			// type cast stdClass as array
1649
+			$wpdb_result = (array)$wpdb_result;
1650
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1651
+			if ($this->has_primary_key_field()) {
1652
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1653
+			} else {
1654
+				//if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1655
+				$main_table_pk_value = null;
1656
+			}
1657
+			//if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1658
+			//and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1659
+			if (count($tables) > 1) {
1660
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1661
+				//in that table, and so we'll want to insert one
1662
+				foreach ($tables as $table_obj) {
1663
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1664
+					//if there is no private key for this table on the results, it means there's no entry
1665
+					//in this table, right? so insert a row in the current table, using any fields available
1666
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1667
+						   && $wpdb_result[$this_table_pk_column])
1668
+					) {
1669
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1670
+							$main_table_pk_value);
1671
+						//if we died here, report the error
1672
+						if (! $success) {
1673
+							return false;
1674
+						}
1675
+					}
1676
+				}
1677
+			}
1678
+			//				//and now check that if we have cached any models by that ID on the model, that
1679
+			//				//they also get updated properly
1680
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1681
+			//				if( $model_object ){
1682
+			//					foreach( $fields_n_values as $field => $value ){
1683
+			//						$model_object->set($field, $value);
1684
+			//let's make sure default_where strategy is followed now
1685
+			$this->_ignore_where_strategy = false;
1686
+		}
1687
+		//if we want to keep model objects in sync, AND
1688
+		//if this wasn't called from a model object (to update itself)
1689
+		//then we want to make sure we keep all the existing
1690
+		//model objects in sync with the db
1691
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1692
+			if ($this->has_primary_key_field()) {
1693
+				$model_objs_affected_ids = $this->get_col($query_params);
1694
+			} else {
1695
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1696
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1697
+				$model_objs_affected_ids = array();
1698
+				foreach ($models_affected_key_columns as $row) {
1699
+					$combined_index_key = $this->get_index_primary_key_string($row);
1700
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1701
+				}
1702
+			}
1703
+			if (! $model_objs_affected_ids) {
1704
+				//wait wait wait- if nothing was affected let's stop here
1705
+				return 0;
1706
+			}
1707
+			foreach ($model_objs_affected_ids as $id) {
1708
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1709
+				if ($model_obj_in_entity_map) {
1710
+					foreach ($fields_n_values as $field => $new_value) {
1711
+						$model_obj_in_entity_map->set($field, $new_value);
1712
+					}
1713
+				}
1714
+			}
1715
+			//if there is a primary key on this model, we can now do a slight optimization
1716
+			if ($this->has_primary_key_field()) {
1717
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1718
+				$query_params = array(
1719
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1720
+					'limit'                    => count($model_objs_affected_ids),
1721
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1722
+				);
1723
+			}
1724
+		}
1725
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1726
+		$SQL = "UPDATE "
1727
+			   . $model_query_info->get_full_join_sql()
1728
+			   . " SET "
1729
+			   . $this->_construct_update_sql($fields_n_values)
1730
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1731
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1732
+		/**
1733
+		 * Action called after a model update call has been made.
1734
+		 *
1735
+		 * @param EEM_Base $model
1736
+		 * @param array    $fields_n_values the updated fields and their new values
1737
+		 * @param array    $query_params    @see EEM_Base::get_all()
1738
+		 * @param int      $rows_affected
1739
+		 */
1740
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1741
+		return $rows_affected;//how many supposedly got updated
1742
+	}
1743
+
1744
+
1745
+
1746
+	/**
1747
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1748
+	 * are teh values of the field specified (or by default the primary key field)
1749
+	 * that matched the query params. Note that you should pass the name of the
1750
+	 * model FIELD, not the database table's column name.
1751
+	 *
1752
+	 * @param array  $query_params @see EEM_Base::get_all()
1753
+	 * @param string $field_to_select
1754
+	 * @return array just like $wpdb->get_col()
1755
+	 * @throws \EE_Error
1756
+	 */
1757
+	public function get_col($query_params = array(), $field_to_select = null)
1758
+	{
1759
+		if ($field_to_select) {
1760
+			$field = $this->field_settings_for($field_to_select);
1761
+		} elseif ($this->has_primary_key_field()) {
1762
+			$field = $this->get_primary_key_field();
1763
+		} else {
1764
+			//no primary key, just grab the first column
1765
+			$field = reset($this->field_settings());
1766
+		}
1767
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1768
+		$select_expressions = $field->get_qualified_column();
1769
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1770
+		return $this->_do_wpdb_query('get_col', array($SQL));
1771
+	}
1772
+
1773
+
1774
+
1775
+	/**
1776
+	 * Returns a single column value for a single row from the database
1777
+	 *
1778
+	 * @param array  $query_params    @see EEM_Base::get_all()
1779
+	 * @param string $field_to_select @see EEM_Base::get_col()
1780
+	 * @return string
1781
+	 * @throws \EE_Error
1782
+	 */
1783
+	public function get_var($query_params = array(), $field_to_select = null)
1784
+	{
1785
+		$query_params['limit'] = 1;
1786
+		$col = $this->get_col($query_params, $field_to_select);
1787
+		if (! empty($col)) {
1788
+			return reset($col);
1789
+		} else {
1790
+			return null;
1791
+		}
1792
+	}
1793
+
1794
+
1795
+
1796
+	/**
1797
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1798
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1799
+	 * injection, but currently no further filtering is done
1800
+	 *
1801
+	 * @global      $wpdb
1802
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1803
+	 *                               be updated to in the DB
1804
+	 * @return string of SQL
1805
+	 * @throws \EE_Error
1806
+	 */
1807
+	public function _construct_update_sql($fields_n_values)
1808
+	{
1809
+		/** @type WPDB $wpdb */
1810
+		global $wpdb;
1811
+		$cols_n_values = array();
1812
+		foreach ($fields_n_values as $field_name => $value) {
1813
+			$field_obj = $this->field_settings_for($field_name);
1814
+			//if the value is NULL, we want to assign the value to that.
1815
+			//wpdb->prepare doesn't really handle that properly
1816
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1817
+			$value_sql = $prepared_value === null ? 'NULL'
1818
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1819
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1820
+		}
1821
+		return implode(",", $cols_n_values);
1822
+	}
1823
+
1824
+
1825
+
1826
+	/**
1827
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1828
+	 * Performs a HARD delete, meaning the database row should always be removed,
1829
+	 * not just have a flag field on it switched
1830
+	 * Wrapper for EEM_Base::delete_permanently()
1831
+	 *
1832
+	 * @param mixed $id
1833
+	 * @return boolean whether the row got deleted or not
1834
+	 * @throws \EE_Error
1835
+	 */
1836
+	public function delete_permanently_by_ID($id)
1837
+	{
1838
+		return $this->delete_permanently(
1839
+			array(
1840
+				array($this->get_primary_key_field()->get_name() => $id),
1841
+				'limit' => 1,
1842
+			)
1843
+		);
1844
+	}
1845
+
1846
+
1847
+
1848
+	/**
1849
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1850
+	 * Wrapper for EEM_Base::delete()
1851
+	 *
1852
+	 * @param mixed $id
1853
+	 * @return boolean whether the row got deleted or not
1854
+	 * @throws \EE_Error
1855
+	 */
1856
+	public function delete_by_ID($id)
1857
+	{
1858
+		return $this->delete(
1859
+			array(
1860
+				array($this->get_primary_key_field()->get_name() => $id),
1861
+				'limit' => 1,
1862
+			)
1863
+		);
1864
+	}
1865
+
1866
+
1867
+
1868
+	/**
1869
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1870
+	 * meaning if the model has a field that indicates its been "trashed" or
1871
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1872
+	 *
1873
+	 * @see EEM_Base::delete_permanently
1874
+	 * @param array   $query_params
1875
+	 * @param boolean $allow_blocking
1876
+	 * @return int how many rows got deleted
1877
+	 * @throws \EE_Error
1878
+	 */
1879
+	public function delete($query_params, $allow_blocking = true)
1880
+	{
1881
+		return $this->delete_permanently($query_params, $allow_blocking);
1882
+	}
1883
+
1884
+
1885
+
1886
+	/**
1887
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1888
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1889
+	 * as archived, not actually deleted
1890
+	 *
1891
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1892
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1893
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1894
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1895
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1896
+	 *                                DB
1897
+	 * @return int how many rows got deleted
1898
+	 * @throws \EE_Error
1899
+	 */
1900
+	public function delete_permanently($query_params, $allow_blocking = true)
1901
+	{
1902
+		/**
1903
+		 * Action called just before performing a real deletion query. You can use the
1904
+		 * model and its $query_params to find exactly which items will be deleted
1905
+		 *
1906
+		 * @param EEM_Base $model
1907
+		 * @param array    $query_params   @see EEM_Base::get_all()
1908
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1909
+		 *                                 to block (prevent) this deletion
1910
+		 */
1911
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1912
+		//some MySQL databases may be running safe mode, which may restrict
1913
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1914
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1915
+		//to delete them
1916
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1917
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1918
+		if ($deletion_where) {
1919
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1920
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1921
+			$table_aliases = array_keys($this->_tables);
1922
+			$SQL = "DELETE "
1923
+				   . implode(", ", $table_aliases)
1924
+				   . " FROM "
1925
+				   . $model_query_info->get_full_join_sql()
1926
+				   . " WHERE "
1927
+				   . $deletion_where;
1928
+			//		/echo "delete sql:$SQL";
1929
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1930
+		} else {
1931
+			$rows_deleted = 0;
1932
+		}
1933
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1934
+		if ($this->has_primary_key_field()) {
1935
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1936
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1937
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1938
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1939
+				}
1940
+			}
1941
+		}
1942
+		/**
1943
+		 * Action called just after performing a real deletion query. Although at this point the
1944
+		 * items should have been deleted
1945
+		 *
1946
+		 * @param EEM_Base $model
1947
+		 * @param array    $query_params @see EEM_Base::get_all()
1948
+		 * @param int      $rows_deleted
1949
+		 */
1950
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1951
+		return $rows_deleted;//how many supposedly got deleted
1952
+	}
1953
+
1954
+
1955
+
1956
+	/**
1957
+	 * Checks all the relations that throw error messages when there are blocking related objects
1958
+	 * for related model objects. If there are any related model objects on those relations,
1959
+	 * adds an EE_Error, and return true
1960
+	 *
1961
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1962
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1963
+	 *                                                 should be ignored when determining whether there are related
1964
+	 *                                                 model objects which block this model object's deletion. Useful
1965
+	 *                                                 if you know A is related to B and are considering deleting A,
1966
+	 *                                                 but want to see if A has any other objects blocking its deletion
1967
+	 *                                                 before removing the relation between A and B
1968
+	 * @return boolean
1969
+	 * @throws \EE_Error
1970
+	 */
1971
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1972
+	{
1973
+		//first, if $ignore_this_model_obj was supplied, get its model
1974
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1975
+			$ignored_model = $ignore_this_model_obj->get_model();
1976
+		} else {
1977
+			$ignored_model = null;
1978
+		}
1979
+		//now check all the relations of $this_model_obj_or_id and see if there
1980
+		//are any related model objects blocking it?
1981
+		$is_blocked = false;
1982
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1983
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1984
+				//if $ignore_this_model_obj was supplied, then for the query
1985
+				//on that model needs to be told to ignore $ignore_this_model_obj
1986
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1987
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1988
+						array(
1989
+							$ignored_model->get_primary_key_field()->get_name() => array(
1990
+								'!=',
1991
+								$ignore_this_model_obj->ID(),
1992
+							),
1993
+						),
1994
+					));
1995
+				} else {
1996
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1997
+				}
1998
+				if ($related_model_objects) {
1999
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2000
+					$is_blocked = true;
2001
+				}
2002
+			}
2003
+		}
2004
+		return $is_blocked;
2005
+	}
2006
+
2007
+
2008
+
2009
+	/**
2010
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2011
+	 * well.
2012
+	 *
2013
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2014
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2015
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
2016
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
2017
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
2018
+	 *                                      easily corrupt your DB
2019
+	 * @throws EE_Error
2020
+	 * @return string    everything that comes after the WHERE statement.
2021
+	 */
2022
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2023
+	{
2024
+		if ($this->has_primary_key_field()) {
2025
+			$primary_table = $this->_get_main_table();
2026
+			$other_tables = $this->_get_other_tables();
2027
+			$deletes = $query = array();
2028
+			foreach ($objects_for_deletion as $delete_object) {
2029
+				//before we mark this object for deletion,
2030
+				//make sure there's no related objects blocking its deletion (if we're checking)
2031
+				if (
2032
+					$allow_blocking
2033
+					&& $this->delete_is_blocked_by_related_models(
2034
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
2035
+					)
2036
+				) {
2037
+					continue;
2038
+				}
2039
+				//primary table deletes
2040
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2041
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2042
+				}
2043
+				//other tables
2044
+				if (! empty($other_tables)) {
2045
+					foreach ($other_tables as $ot) {
2046
+						//first check if we've got the foreign key column here.
2047
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2048
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
2049
+						}
2050
+						// wait! it's entirely possible that we'll have a the primary key
2051
+						// for this table in here, if it's a foreign key for one of the other secondary tables
2052
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2053
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2054
+						}
2055
+						// finally, it is possible that the fk for this table is found
2056
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
2057
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2058
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
2059
+						}
2060
+					}
2061
+				}
2062
+			}
2063
+			//we should have deletes now, so let's just go through and setup the where statement
2064
+			foreach ($deletes as $column => $values) {
2065
+				//make sure we have unique $values;
2066
+				$values = array_unique($values);
2067
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
2068
+			}
2069
+			return ! empty($query) ? implode(' AND ', $query) : '';
2070
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2071
+			$ways_to_identify_a_row = array();
2072
+			$fields = $this->get_combined_primary_key_fields();
2073
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2074
+			foreach ($objects_for_deletion as $delete_object) {
2075
+				$values_for_each_cpk_for_a_row = array();
2076
+				foreach ($fields as $cpk_field) {
2077
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2078
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2079
+														   . "="
2080
+														   . $delete_object[$cpk_field->get_qualified_column()];
2081
+					}
2082
+				}
2083
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2084
+			}
2085
+			return implode(" OR ", $ways_to_identify_a_row);
2086
+		} else {
2087
+			//so there's no primary key and no combined key...
2088
+			//sorry, can't help you
2089
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2090
+				"event_espresso"), get_class($this)));
2091
+		}
2092
+	}
2093
+
2094
+
2095
+
2096
+	/**
2097
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2098
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2099
+	 * column
2100
+	 *
2101
+	 * @param array  $query_params   like EEM_Base::get_all's
2102
+	 * @param string $field_to_count field on model to count by (not column name)
2103
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2104
+	 *                               that by the setting $distinct to TRUE;
2105
+	 * @return int
2106
+	 * @throws \EE_Error
2107
+	 */
2108
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2109
+	{
2110
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2111
+		if ($field_to_count) {
2112
+			$field_obj = $this->field_settings_for($field_to_count);
2113
+			$column_to_count = $field_obj->get_qualified_column();
2114
+		} elseif ($this->has_primary_key_field()) {
2115
+			$pk_field_obj = $this->get_primary_key_field();
2116
+			$column_to_count = $pk_field_obj->get_qualified_column();
2117
+		} else {
2118
+			//there's no primary key
2119
+			//if we're counting distinct items, and there's no primary key,
2120
+			//we need to list out the columns for distinction;
2121
+			//otherwise we can just use star
2122
+			if ($distinct) {
2123
+				$columns_to_use = array();
2124
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2125
+					$columns_to_use[] = $field_obj->get_qualified_column();
2126
+				}
2127
+				$column_to_count = implode(',', $columns_to_use);
2128
+			} else {
2129
+				$column_to_count = '*';
2130
+			}
2131
+		}
2132
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2133
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2134
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2135
+	}
2136
+
2137
+
2138
+
2139
+	/**
2140
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2141
+	 *
2142
+	 * @param array  $query_params like EEM_Base::get_all
2143
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2144
+	 * @return float
2145
+	 * @throws \EE_Error
2146
+	 */
2147
+	public function sum($query_params, $field_to_sum = null)
2148
+	{
2149
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2150
+		if ($field_to_sum) {
2151
+			$field_obj = $this->field_settings_for($field_to_sum);
2152
+		} else {
2153
+			$field_obj = $this->get_primary_key_field();
2154
+		}
2155
+		$column_to_count = $field_obj->get_qualified_column();
2156
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2157
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2158
+		$data_type = $field_obj->get_wpdb_data_type();
2159
+		if ($data_type === '%d' || $data_type === '%s') {
2160
+			return (float)$return_value;
2161
+		} else {//must be %f
2162
+			return (float)$return_value;
2163
+		}
2164
+	}
2165
+
2166
+
2167
+
2168
+	/**
2169
+	 * Just calls the specified method on $wpdb with the given arguments
2170
+	 * Consolidates a little extra error handling code
2171
+	 *
2172
+	 * @param string $wpdb_method
2173
+	 * @param array  $arguments_to_provide
2174
+	 * @throws EE_Error
2175
+	 * @global wpdb  $wpdb
2176
+	 * @return mixed
2177
+	 */
2178
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2179
+	{
2180
+		//if we're in maintenance mode level 2, DON'T run any queries
2181
+		//because level 2 indicates the database needs updating and
2182
+		//is probably out of sync with the code
2183
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2184
+			throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2185
+				"event_espresso")));
2186
+		}
2187
+		/** @type WPDB $wpdb */
2188
+		global $wpdb;
2189
+		if (! method_exists($wpdb, $wpdb_method)) {
2190
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2191
+				'event_espresso'), $wpdb_method));
2192
+		}
2193
+		if (WP_DEBUG) {
2194
+			$old_show_errors_value = $wpdb->show_errors;
2195
+			$wpdb->show_errors(false);
2196
+		}
2197
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2198
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2199
+		if (WP_DEBUG) {
2200
+			$wpdb->show_errors($old_show_errors_value);
2201
+			if (! empty($wpdb->last_error)) {
2202
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2203
+			} elseif ($result === false) {
2204
+				throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2205
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2206
+			}
2207
+		} elseif ($result === false) {
2208
+			EE_Error::add_error(
2209
+				sprintf(
2210
+					__('A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2211
+						'event_espresso'),
2212
+					$wpdb_method,
2213
+					var_export($arguments_to_provide, true),
2214
+					$wpdb->last_error
2215
+				),
2216
+				__FILE__,
2217
+				__FUNCTION__,
2218
+				__LINE__
2219
+			);
2220
+		}
2221
+		return $result;
2222
+	}
2223
+
2224
+
2225
+
2226
+	/**
2227
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2228
+	 * and if there's an error tries to verify the DB is correct. Uses
2229
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2230
+	 * we should try to fix the EE core db, the addons, or just give up
2231
+	 *
2232
+	 * @param string $wpdb_method
2233
+	 * @param array  $arguments_to_provide
2234
+	 * @return mixed
2235
+	 */
2236
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2237
+	{
2238
+		/** @type WPDB $wpdb */
2239
+		global $wpdb;
2240
+		$wpdb->last_error = null;
2241
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2242
+		// was there an error running the query? but we don't care on new activations
2243
+		// (we're going to setup the DB anyway on new activations)
2244
+		if (($result === false || ! empty($wpdb->last_error))
2245
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2246
+		) {
2247
+			switch (EEM_Base::$_db_verification_level) {
2248
+				case EEM_Base::db_verified_none :
2249
+					// let's double-check core's DB
2250
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2251
+					break;
2252
+				case EEM_Base::db_verified_core :
2253
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2254
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2255
+					break;
2256
+				case EEM_Base::db_verified_addons :
2257
+					// ummmm... you in trouble
2258
+					return $result;
2259
+					break;
2260
+			}
2261
+			if (! empty($error_message)) {
2262
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2263
+				trigger_error($error_message);
2264
+			}
2265
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2266
+		}
2267
+		return $result;
2268
+	}
2269
+
2270
+
2271
+
2272
+	/**
2273
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2274
+	 * EEM_Base::$_db_verification_level
2275
+	 *
2276
+	 * @param string $wpdb_method
2277
+	 * @param array  $arguments_to_provide
2278
+	 * @return string
2279
+	 */
2280
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2281
+	{
2282
+		/** @type WPDB $wpdb */
2283
+		global $wpdb;
2284
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2285
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2286
+		$error_message = sprintf(
2287
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2288
+				'event_espresso'),
2289
+			$wpdb->last_error,
2290
+			$wpdb_method,
2291
+			wp_json_encode($arguments_to_provide)
2292
+		);
2293
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2294
+		return $error_message;
2295
+	}
2296
+
2297
+
2298
+
2299
+	/**
2300
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2301
+	 * EEM_Base::$_db_verification_level
2302
+	 *
2303
+	 * @param $wpdb_method
2304
+	 * @param $arguments_to_provide
2305
+	 * @return string
2306
+	 */
2307
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2308
+	{
2309
+		/** @type WPDB $wpdb */
2310
+		global $wpdb;
2311
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2312
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2313
+		$error_message = sprintf(
2314
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2315
+				'event_espresso'),
2316
+			$wpdb->last_error,
2317
+			$wpdb_method,
2318
+			wp_json_encode($arguments_to_provide)
2319
+		);
2320
+		EE_System::instance()->initialize_addons();
2321
+		return $error_message;
2322
+	}
2323
+
2324
+
2325
+
2326
+	/**
2327
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2328
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2329
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2330
+	 * ..."
2331
+	 *
2332
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2333
+	 * @return string
2334
+	 */
2335
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2336
+	{
2337
+		return " FROM " . $model_query_info->get_full_join_sql() .
2338
+			   $model_query_info->get_where_sql() .
2339
+			   $model_query_info->get_group_by_sql() .
2340
+			   $model_query_info->get_having_sql() .
2341
+			   $model_query_info->get_order_by_sql() .
2342
+			   $model_query_info->get_limit_sql();
2343
+	}
2344
+
2345
+
2346
+
2347
+	/**
2348
+	 * Set to easily debug the next X queries ran from this model.
2349
+	 *
2350
+	 * @param int $count
2351
+	 */
2352
+	public function show_next_x_db_queries($count = 1)
2353
+	{
2354
+		$this->_show_next_x_db_queries = $count;
2355
+	}
2356
+
2357
+
2358
+
2359
+	/**
2360
+	 * @param $sql_query
2361
+	 */
2362
+	public function show_db_query_if_previously_requested($sql_query)
2363
+	{
2364
+		if ($this->_show_next_x_db_queries > 0) {
2365
+			echo $sql_query;
2366
+			$this->_show_next_x_db_queries--;
2367
+		}
2368
+	}
2369
+
2370
+
2371
+
2372
+	/**
2373
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2374
+	 * There are the 3 cases:
2375
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2376
+	 * $otherModelObject has no ID, it is first saved.
2377
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2378
+	 * has no ID, it is first saved.
2379
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2380
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2381
+	 * join table
2382
+	 *
2383
+	 * @param        EE_Base_Class                     /int $thisModelObject
2384
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2385
+	 * @param string $relationName                     , key in EEM_Base::_relations
2386
+	 *                                                 an attendee to a group, you also want to specify which role they
2387
+	 *                                                 will have in that group. So you would use this parameter to
2388
+	 *                                                 specify array('role-column-name'=>'role-id')
2389
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2390
+	 *                                                 to for relation to methods that allow you to further specify
2391
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2392
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2393
+	 *                                                 because these will be inserted in any new rows created as well.
2394
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2395
+	 * @throws \EE_Error
2396
+	 */
2397
+	public function add_relationship_to(
2398
+		$id_or_obj,
2399
+		$other_model_id_or_obj,
2400
+		$relationName,
2401
+		$extra_join_model_fields_n_values = array()
2402
+	) {
2403
+		$relation_obj = $this->related_settings_for($relationName);
2404
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2405
+	}
2406
+
2407
+
2408
+
2409
+	/**
2410
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2411
+	 * There are the 3 cases:
2412
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2413
+	 * error
2414
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2415
+	 * an error
2416
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2417
+	 *
2418
+	 * @param        EE_Base_Class /int $id_or_obj
2419
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2420
+	 * @param string $relationName key in EEM_Base::_relations
2421
+	 * @return boolean of success
2422
+	 * @throws \EE_Error
2423
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2424
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2425
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2426
+	 *                             because these will be inserted in any new rows created as well.
2427
+	 */
2428
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2429
+	{
2430
+		$relation_obj = $this->related_settings_for($relationName);
2431
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2432
+	}
2433
+
2434
+
2435
+
2436
+	/**
2437
+	 * @param mixed           $id_or_obj
2438
+	 * @param string          $relationName
2439
+	 * @param array           $where_query_params
2440
+	 * @param EE_Base_Class[] objects to which relations were removed
2441
+	 * @return \EE_Base_Class[]
2442
+	 * @throws \EE_Error
2443
+	 */
2444
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2445
+	{
2446
+		$relation_obj = $this->related_settings_for($relationName);
2447
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2448
+	}
2449
+
2450
+
2451
+
2452
+	/**
2453
+	 * Gets all the related items of the specified $model_name, using $query_params.
2454
+	 * Note: by default, we remove the "default query params"
2455
+	 * because we want to get even deleted items etc.
2456
+	 *
2457
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2458
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2459
+	 * @param array  $query_params like EEM_Base::get_all
2460
+	 * @return EE_Base_Class[]
2461
+	 * @throws \EE_Error
2462
+	 */
2463
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2464
+	{
2465
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2466
+		$relation_settings = $this->related_settings_for($model_name);
2467
+		return $relation_settings->get_all_related($model_obj, $query_params);
2468
+	}
2469
+
2470
+
2471
+
2472
+	/**
2473
+	 * Deletes all the model objects across the relation indicated by $model_name
2474
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2475
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2476
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2477
+	 *
2478
+	 * @param EE_Base_Class|int|string $id_or_obj
2479
+	 * @param string                   $model_name
2480
+	 * @param array                    $query_params
2481
+	 * @return int how many deleted
2482
+	 * @throws \EE_Error
2483
+	 */
2484
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2485
+	{
2486
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2487
+		$relation_settings = $this->related_settings_for($model_name);
2488
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2489
+	}
2490
+
2491
+
2492
+
2493
+	/**
2494
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2495
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2496
+	 * the model objects can't be hard deleted because of blocking related model objects,
2497
+	 * just does a soft-delete on them instead.
2498
+	 *
2499
+	 * @param EE_Base_Class|int|string $id_or_obj
2500
+	 * @param string                   $model_name
2501
+	 * @param array                    $query_params
2502
+	 * @return int how many deleted
2503
+	 * @throws \EE_Error
2504
+	 */
2505
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2506
+	{
2507
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2508
+		$relation_settings = $this->related_settings_for($model_name);
2509
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2510
+	}
2511
+
2512
+
2513
+
2514
+	/**
2515
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2516
+	 * unless otherwise specified in the $query_params
2517
+	 *
2518
+	 * @param        int             /EE_Base_Class $id_or_obj
2519
+	 * @param string $model_name     like 'Event', or 'Registration'
2520
+	 * @param array  $query_params   like EEM_Base::get_all's
2521
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2522
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2523
+	 *                               that by the setting $distinct to TRUE;
2524
+	 * @return int
2525
+	 * @throws \EE_Error
2526
+	 */
2527
+	public function count_related(
2528
+		$id_or_obj,
2529
+		$model_name,
2530
+		$query_params = array(),
2531
+		$field_to_count = null,
2532
+		$distinct = false
2533
+	) {
2534
+		$related_model = $this->get_related_model_obj($model_name);
2535
+		//we're just going to use the query params on the related model's normal get_all query,
2536
+		//except add a condition to say to match the current mod
2537
+		if (! isset($query_params['default_where_conditions'])) {
2538
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2539
+		}
2540
+		$this_model_name = $this->get_this_model_name();
2541
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2542
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2543
+		return $related_model->count($query_params, $field_to_count, $distinct);
2544
+	}
2545
+
2546
+
2547
+
2548
+	/**
2549
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2550
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2551
+	 *
2552
+	 * @param        int           /EE_Base_Class $id_or_obj
2553
+	 * @param string $model_name   like 'Event', or 'Registration'
2554
+	 * @param array  $query_params like EEM_Base::get_all's
2555
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2556
+	 * @return float
2557
+	 * @throws \EE_Error
2558
+	 */
2559
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2560
+	{
2561
+		$related_model = $this->get_related_model_obj($model_name);
2562
+		if (! is_array($query_params)) {
2563
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2564
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2565
+					gettype($query_params)), '4.6.0');
2566
+			$query_params = array();
2567
+		}
2568
+		//we're just going to use the query params on the related model's normal get_all query,
2569
+		//except add a condition to say to match the current mod
2570
+		if (! isset($query_params['default_where_conditions'])) {
2571
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2572
+		}
2573
+		$this_model_name = $this->get_this_model_name();
2574
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2575
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2576
+		return $related_model->sum($query_params, $field_to_sum);
2577
+	}
2578
+
2579
+
2580
+
2581
+	/**
2582
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2583
+	 * $modelObject
2584
+	 *
2585
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2586
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2587
+	 * @param array               $query_params     like EEM_Base::get_all's
2588
+	 * @return EE_Base_Class
2589
+	 * @throws \EE_Error
2590
+	 */
2591
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2592
+	{
2593
+		$query_params['limit'] = 1;
2594
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2595
+		if ($results) {
2596
+			return array_shift($results);
2597
+		} else {
2598
+			return null;
2599
+		}
2600
+	}
2601
+
2602
+
2603
+
2604
+	/**
2605
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2606
+	 *
2607
+	 * @return string
2608
+	 */
2609
+	public function get_this_model_name()
2610
+	{
2611
+		return str_replace("EEM_", "", get_class($this));
2612
+	}
2613
+
2614
+
2615
+
2616
+	/**
2617
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2618
+	 *
2619
+	 * @return EE_Any_Foreign_Model_Name_Field
2620
+	 * @throws EE_Error
2621
+	 */
2622
+	public function get_field_containing_related_model_name()
2623
+	{
2624
+		foreach ($this->field_settings(true) as $field) {
2625
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2626
+				$field_with_model_name = $field;
2627
+			}
2628
+		}
2629
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2630
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2631
+				$this->get_this_model_name()));
2632
+		}
2633
+		return $field_with_model_name;
2634
+	}
2635
+
2636
+
2637
+
2638
+	/**
2639
+	 * Inserts a new entry into the database, for each table.
2640
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2641
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2642
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2643
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2644
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2645
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2646
+	 *
2647
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2648
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2649
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2650
+	 *                              of EEM_Base)
2651
+	 * @return int new primary key on main table that got inserted
2652
+	 * @throws EE_Error
2653
+	 */
2654
+	public function insert($field_n_values)
2655
+	{
2656
+		/**
2657
+		 * Filters the fields and their values before inserting an item using the models
2658
+		 *
2659
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2660
+		 * @param EEM_Base $model           the model used
2661
+		 */
2662
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2663
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2664
+			$main_table = $this->_get_main_table();
2665
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2666
+			if ($new_id !== false) {
2667
+				foreach ($this->_get_other_tables() as $other_table) {
2668
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2669
+				}
2670
+			}
2671
+			/**
2672
+			 * Done just after attempting to insert a new model object
2673
+			 *
2674
+			 * @param EEM_Base   $model           used
2675
+			 * @param array      $fields_n_values fields and their values
2676
+			 * @param int|string the              ID of the newly-inserted model object
2677
+			 */
2678
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2679
+			return $new_id;
2680
+		} else {
2681
+			return false;
2682
+		}
2683
+	}
2684
+
2685
+
2686
+
2687
+	/**
2688
+	 * Checks that the result would satisfy the unique indexes on this model
2689
+	 *
2690
+	 * @param array  $field_n_values
2691
+	 * @param string $action
2692
+	 * @return boolean
2693
+	 * @throws \EE_Error
2694
+	 */
2695
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2696
+	{
2697
+		foreach ($this->unique_indexes() as $index_name => $index) {
2698
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2699
+			if ($this->exists(array($uniqueness_where_params))) {
2700
+				EE_Error::add_error(
2701
+					sprintf(
2702
+						__(
2703
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2704
+							"event_espresso"
2705
+						),
2706
+						$action,
2707
+						$this->_get_class_name(),
2708
+						$index_name,
2709
+						implode(",", $index->field_names()),
2710
+						http_build_query($uniqueness_where_params)
2711
+					),
2712
+					__FILE__,
2713
+					__FUNCTION__,
2714
+					__LINE__
2715
+				);
2716
+				return false;
2717
+			}
2718
+		}
2719
+		return true;
2720
+	}
2721
+
2722
+
2723
+
2724
+	/**
2725
+	 * Checks the database for an item that conflicts (ie, if this item were
2726
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2727
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2728
+	 * can be either an EE_Base_Class or an array of fields n values
2729
+	 *
2730
+	 * @param EE_Base_Class|array $obj_or_fields_array
2731
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2732
+	 *                                                 when looking for conflicts
2733
+	 *                                                 (ie, if false, we ignore the model object's primary key
2734
+	 *                                                 when finding "conflicts". If true, it's also considered).
2735
+	 *                                                 Only works for INT primary key,
2736
+	 *                                                 STRING primary keys cannot be ignored
2737
+	 * @throws EE_Error
2738
+	 * @return EE_Base_Class|array
2739
+	 */
2740
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2741
+	{
2742
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2743
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2744
+		} elseif (is_array($obj_or_fields_array)) {
2745
+			$fields_n_values = $obj_or_fields_array;
2746
+		} else {
2747
+			throw new EE_Error(
2748
+				sprintf(
2749
+					__(
2750
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2751
+						"event_espresso"
2752
+					),
2753
+					get_class($this),
2754
+					$obj_or_fields_array
2755
+				)
2756
+			);
2757
+		}
2758
+		$query_params = array();
2759
+		if ($this->has_primary_key_field()
2760
+			&& ($include_primary_key
2761
+				|| $this->get_primary_key_field()
2762
+				   instanceof
2763
+				   EE_Primary_Key_String_Field)
2764
+			&& isset($fields_n_values[$this->primary_key_name()])
2765
+		) {
2766
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2767
+		}
2768
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2769
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2770
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2771
+		}
2772
+		//if there is nothing to base this search on, then we shouldn't find anything
2773
+		if (empty($query_params)) {
2774
+			return array();
2775
+		} else {
2776
+			return $this->get_one($query_params);
2777
+		}
2778
+	}
2779
+
2780
+
2781
+
2782
+	/**
2783
+	 * Like count, but is optimized and returns a boolean instead of an int
2784
+	 *
2785
+	 * @param array $query_params
2786
+	 * @return boolean
2787
+	 * @throws \EE_Error
2788
+	 */
2789
+	public function exists($query_params)
2790
+	{
2791
+		$query_params['limit'] = 1;
2792
+		return $this->count($query_params) > 0;
2793
+	}
2794
+
2795
+
2796
+
2797
+	/**
2798
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2799
+	 *
2800
+	 * @param int|string $id
2801
+	 * @return boolean
2802
+	 * @throws \EE_Error
2803
+	 */
2804
+	public function exists_by_ID($id)
2805
+	{
2806
+		return $this->exists(
2807
+			array(
2808
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2809
+				array(
2810
+					$this->primary_key_name() => $id,
2811
+				),
2812
+			)
2813
+		);
2814
+	}
2815
+
2816
+
2817
+
2818
+	/**
2819
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2820
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2821
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2822
+	 * on the main table)
2823
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2824
+	 * cases where we want to call it directly rather than via insert().
2825
+	 *
2826
+	 * @access   protected
2827
+	 * @param EE_Table_Base $table
2828
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2829
+	 *                                       float
2830
+	 * @param int           $new_id          for now we assume only int keys
2831
+	 * @throws EE_Error
2832
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2833
+	 * @return int ID of new row inserted, or FALSE on failure
2834
+	 */
2835
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2836
+	{
2837
+		global $wpdb;
2838
+		$insertion_col_n_values = array();
2839
+		$format_for_insertion = array();
2840
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2841
+		foreach ($fields_on_table as $field_name => $field_obj) {
2842
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2843
+			if ($field_obj->is_auto_increment()) {
2844
+				continue;
2845
+			}
2846
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2847
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2848
+			if ($prepared_value !== null) {
2849
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2850
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2851
+			}
2852
+		}
2853
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2854
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2855
+			//so add the fk to the main table as a column
2856
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2857
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2858
+		}
2859
+		//insert the new entry
2860
+		$result = $this->_do_wpdb_query('insert',
2861
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2862
+		if ($result === false) {
2863
+			return false;
2864
+		}
2865
+		//ok, now what do we return for the ID of the newly-inserted thing?
2866
+		if ($this->has_primary_key_field()) {
2867
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2868
+				return $wpdb->insert_id;
2869
+			} else {
2870
+				//it's not an auto-increment primary key, so
2871
+				//it must have been supplied
2872
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2873
+			}
2874
+		} else {
2875
+			//we can't return a  primary key because there is none. instead return
2876
+			//a unique string indicating this model
2877
+			return $this->get_index_primary_key_string($fields_n_values);
2878
+		}
2879
+	}
2880
+
2881
+
2882
+
2883
+	/**
2884
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2885
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2886
+	 * and there is no default, we pass it along. WPDB will take care of it)
2887
+	 *
2888
+	 * @param EE_Model_Field_Base $field_obj
2889
+	 * @param array               $fields_n_values
2890
+	 * @return mixed string|int|float depending on what the table column will be expecting
2891
+	 * @throws \EE_Error
2892
+	 */
2893
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2894
+	{
2895
+		//if this field doesn't allow nullable, don't allow it
2896
+		if (! $field_obj->is_nullable()
2897
+			&& (
2898
+				! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2899
+		) {
2900
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2901
+		}
2902
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2903
+			: null;
2904
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2905
+	}
2906
+
2907
+
2908
+
2909
+	/**
2910
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2911
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2912
+	 * the field's prepare_for_set() method.
2913
+	 *
2914
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2915
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2916
+	 *                                   top of file)
2917
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2918
+	 *                                   $value is a custom selection
2919
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2920
+	 */
2921
+	private function _prepare_value_for_use_in_db($value, $field)
2922
+	{
2923
+		if ($field && $field instanceof EE_Model_Field_Base) {
2924
+			switch ($this->_values_already_prepared_by_model_object) {
2925
+				/** @noinspection PhpMissingBreakStatementInspection */
2926
+				case self::not_prepared_by_model_object:
2927
+					$value = $field->prepare_for_set($value);
2928
+				//purposefully left out "return"
2929
+				case self::prepared_by_model_object:
2930
+					$value = $field->prepare_for_use_in_db($value);
2931
+				case self::prepared_for_use_in_db:
2932
+					//leave the value alone
2933
+			}
2934
+			return $value;
2935
+		} else {
2936
+			return $value;
2937
+		}
2938
+	}
2939
+
2940
+
2941
+
2942
+	/**
2943
+	 * Returns the main table on this model
2944
+	 *
2945
+	 * @return EE_Primary_Table
2946
+	 * @throws EE_Error
2947
+	 */
2948
+	protected function _get_main_table()
2949
+	{
2950
+		foreach ($this->_tables as $table) {
2951
+			if ($table instanceof EE_Primary_Table) {
2952
+				return $table;
2953
+			}
2954
+		}
2955
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2956
+			'event_espresso'), get_class($this)));
2957
+	}
2958
+
2959
+
2960
+
2961
+	/**
2962
+	 * table
2963
+	 * returns EE_Primary_Table table name
2964
+	 *
2965
+	 * @return string
2966
+	 * @throws \EE_Error
2967
+	 */
2968
+	public function table()
2969
+	{
2970
+		return $this->_get_main_table()->get_table_name();
2971
+	}
2972
+
2973
+
2974
+
2975
+	/**
2976
+	 * table
2977
+	 * returns first EE_Secondary_Table table name
2978
+	 *
2979
+	 * @return string
2980
+	 */
2981
+	public function second_table()
2982
+	{
2983
+		// grab second table from tables array
2984
+		$second_table = end($this->_tables);
2985
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2986
+	}
2987
+
2988
+
2989
+
2990
+	/**
2991
+	 * get_table_obj_by_alias
2992
+	 * returns table name given it's alias
2993
+	 *
2994
+	 * @param string $table_alias
2995
+	 * @return EE_Primary_Table | EE_Secondary_Table
2996
+	 */
2997
+	public function get_table_obj_by_alias($table_alias = '')
2998
+	{
2999
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3000
+	}
3001
+
3002
+
3003
+
3004
+	/**
3005
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3006
+	 *
3007
+	 * @return EE_Secondary_Table[]
3008
+	 */
3009
+	protected function _get_other_tables()
3010
+	{
3011
+		$other_tables = array();
3012
+		foreach ($this->_tables as $table_alias => $table) {
3013
+			if ($table instanceof EE_Secondary_Table) {
3014
+				$other_tables[$table_alias] = $table;
3015
+			}
3016
+		}
3017
+		return $other_tables;
3018
+	}
3019
+
3020
+
3021
+
3022
+	/**
3023
+	 * Finds all the fields that correspond to the given table
3024
+	 *
3025
+	 * @param string $table_alias , array key in EEM_Base::_tables
3026
+	 * @return EE_Model_Field_Base[]
3027
+	 */
3028
+	public function _get_fields_for_table($table_alias)
3029
+	{
3030
+		return $this->_fields[$table_alias];
3031
+	}
3032
+
3033
+
3034
+
3035
+	/**
3036
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3037
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3038
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3039
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3040
+	 * related Registration, Transaction, and Payment models.
3041
+	 *
3042
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3043
+	 * @return EE_Model_Query_Info_Carrier
3044
+	 * @throws \EE_Error
3045
+	 */
3046
+	public function _extract_related_models_from_query($query_params)
3047
+	{
3048
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3049
+		if (array_key_exists(0, $query_params)) {
3050
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3051
+		}
3052
+		if (array_key_exists('group_by', $query_params)) {
3053
+			if (is_array($query_params['group_by'])) {
3054
+				$this->_extract_related_models_from_sub_params_array_values(
3055
+					$query_params['group_by'],
3056
+					$query_info_carrier,
3057
+					'group_by'
3058
+				);
3059
+			} elseif (! empty ($query_params['group_by'])) {
3060
+				$this->_extract_related_model_info_from_query_param(
3061
+					$query_params['group_by'],
3062
+					$query_info_carrier,
3063
+					'group_by'
3064
+				);
3065
+			}
3066
+		}
3067
+		if (array_key_exists('having', $query_params)) {
3068
+			$this->_extract_related_models_from_sub_params_array_keys(
3069
+				$query_params[0],
3070
+				$query_info_carrier,
3071
+				'having'
3072
+			);
3073
+		}
3074
+		if (array_key_exists('order_by', $query_params)) {
3075
+			if (is_array($query_params['order_by'])) {
3076
+				$this->_extract_related_models_from_sub_params_array_keys(
3077
+					$query_params['order_by'],
3078
+					$query_info_carrier,
3079
+					'order_by'
3080
+				);
3081
+			} elseif (! empty($query_params['order_by'])) {
3082
+				$this->_extract_related_model_info_from_query_param(
3083
+					$query_params['order_by'],
3084
+					$query_info_carrier,
3085
+					'order_by'
3086
+				);
3087
+			}
3088
+		}
3089
+		if (array_key_exists('force_join', $query_params)) {
3090
+			$this->_extract_related_models_from_sub_params_array_values(
3091
+				$query_params['force_join'],
3092
+				$query_info_carrier,
3093
+				'force_join'
3094
+			);
3095
+		}
3096
+		return $query_info_carrier;
3097
+	}
3098
+
3099
+
3100
+
3101
+	/**
3102
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3103
+	 *
3104
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3105
+	 *                                                      $query_params['having']
3106
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3107
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3108
+	 * @throws EE_Error
3109
+	 * @return \EE_Model_Query_Info_Carrier
3110
+	 */
3111
+	private function _extract_related_models_from_sub_params_array_keys(
3112
+		$sub_query_params,
3113
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3114
+		$query_param_type
3115
+	) {
3116
+		if (! empty($sub_query_params)) {
3117
+			$sub_query_params = (array)$sub_query_params;
3118
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3119
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3120
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3121
+					$query_param_type);
3122
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3123
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3124
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3125
+				//of array('Registration.TXN_ID'=>23)
3126
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3127
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3128
+					if (! is_array($possibly_array_of_params)) {
3129
+						throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3130
+							"event_espresso"),
3131
+							$param, $possibly_array_of_params));
3132
+					} else {
3133
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3134
+							$model_query_info_carrier, $query_param_type);
3135
+					}
3136
+				} elseif ($query_param_type === 0 //ie WHERE
3137
+						  && is_array($possibly_array_of_params)
3138
+						  && isset($possibly_array_of_params[2])
3139
+						  && $possibly_array_of_params[2] == true
3140
+				) {
3141
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3142
+					//indicating that $possible_array_of_params[1] is actually a field name,
3143
+					//from which we should extract query parameters!
3144
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3145
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3146
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3147
+					}
3148
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3149
+						$model_query_info_carrier, $query_param_type);
3150
+				}
3151
+			}
3152
+		}
3153
+		return $model_query_info_carrier;
3154
+	}
3155
+
3156
+
3157
+
3158
+	/**
3159
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3160
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3161
+	 *
3162
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3163
+	 *                                                      $query_params['having']
3164
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3165
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3166
+	 * @throws EE_Error
3167
+	 * @return \EE_Model_Query_Info_Carrier
3168
+	 */
3169
+	private function _extract_related_models_from_sub_params_array_values(
3170
+		$sub_query_params,
3171
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3172
+		$query_param_type
3173
+	) {
3174
+		if (! empty($sub_query_params)) {
3175
+			if (! is_array($sub_query_params)) {
3176
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3177
+					$sub_query_params));
3178
+			}
3179
+			foreach ($sub_query_params as $param) {
3180
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3181
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3182
+					$query_param_type);
3183
+			}
3184
+		}
3185
+		return $model_query_info_carrier;
3186
+	}
3187
+
3188
+
3189
+
3190
+	/**
3191
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3192
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3193
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3194
+	 * but use them in a different order. Eg, we need to know what models we are querying
3195
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3196
+	 * other models before we can finalize the where clause SQL.
3197
+	 *
3198
+	 * @param array $query_params
3199
+	 * @throws EE_Error
3200
+	 * @return EE_Model_Query_Info_Carrier
3201
+	 */
3202
+	public function _create_model_query_info_carrier($query_params)
3203
+	{
3204
+		if (! is_array($query_params)) {
3205
+			EE_Error::doing_it_wrong(
3206
+				'EEM_Base::_create_model_query_info_carrier',
3207
+				sprintf(
3208
+					__(
3209
+						'$query_params should be an array, you passed a variable of type %s',
3210
+						'event_espresso'
3211
+					),
3212
+					gettype($query_params)
3213
+				),
3214
+				'4.6.0'
3215
+			);
3216
+			$query_params = array();
3217
+		}
3218
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3219
+		//first check if we should alter the query to account for caps or not
3220
+		//because the caps might require us to do extra joins
3221
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3222
+			$query_params[0] = $where_query_params = array_replace_recursive(
3223
+				$where_query_params,
3224
+				$this->caps_where_conditions(
3225
+					$query_params['caps']
3226
+				)
3227
+			);
3228
+		}
3229
+		$query_object = $this->_extract_related_models_from_query($query_params);
3230
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3231
+		foreach ($where_query_params as $key => $value) {
3232
+			if (is_int($key)) {
3233
+				throw new EE_Error(
3234
+					sprintf(
3235
+						__(
3236
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3237
+							"event_espresso"
3238
+						),
3239
+						$key,
3240
+						var_export($value, true),
3241
+						var_export($query_params, true),
3242
+						get_class($this)
3243
+					)
3244
+				);
3245
+			}
3246
+		}
3247
+		if (
3248
+			array_key_exists('default_where_conditions', $query_params)
3249
+			&& ! empty($query_params['default_where_conditions'])
3250
+		) {
3251
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3252
+		} else {
3253
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3254
+		}
3255
+		$where_query_params = array_merge(
3256
+			$this->_get_default_where_conditions_for_models_in_query(
3257
+				$query_object,
3258
+				$use_default_where_conditions,
3259
+				$where_query_params
3260
+			),
3261
+			$where_query_params
3262
+		);
3263
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3264
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3265
+		// So we need to setup a subquery and use that for the main join.
3266
+		// Note for now this only works on the primary table for the model.
3267
+		// So for instance, you could set the limit array like this:
3268
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3269
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3270
+			$query_object->set_main_model_join_sql(
3271
+				$this->_construct_limit_join_select(
3272
+					$query_params['on_join_limit'][0],
3273
+					$query_params['on_join_limit'][1]
3274
+				)
3275
+			);
3276
+		}
3277
+		//set limit
3278
+		if (array_key_exists('limit', $query_params)) {
3279
+			if (is_array($query_params['limit'])) {
3280
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3281
+					$e = sprintf(
3282
+						__(
3283
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3284
+							"event_espresso"
3285
+						),
3286
+						http_build_query($query_params['limit'])
3287
+					);
3288
+					throw new EE_Error($e . "|" . $e);
3289
+				}
3290
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3291
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3292
+			} elseif (! empty ($query_params['limit'])) {
3293
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3294
+			}
3295
+		}
3296
+		//set order by
3297
+		if (array_key_exists('order_by', $query_params)) {
3298
+			if (is_array($query_params['order_by'])) {
3299
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3300
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3301
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3302
+				if (array_key_exists('order', $query_params)) {
3303
+					throw new EE_Error(
3304
+						sprintf(
3305
+							__(
3306
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3307
+								"event_espresso"
3308
+							),
3309
+							get_class($this),
3310
+							implode(", ", array_keys($query_params['order_by'])),
3311
+							implode(", ", $query_params['order_by']),
3312
+							$query_params['order']
3313
+						)
3314
+					);
3315
+				}
3316
+				$this->_extract_related_models_from_sub_params_array_keys(
3317
+					$query_params['order_by'],
3318
+					$query_object,
3319
+					'order_by'
3320
+				);
3321
+				//assume it's an array of fields to order by
3322
+				$order_array = array();
3323
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3324
+					$order = $this->_extract_order($order);
3325
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3326
+				}
3327
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3328
+			} elseif (! empty ($query_params['order_by'])) {
3329
+				$this->_extract_related_model_info_from_query_param(
3330
+					$query_params['order_by'],
3331
+					$query_object,
3332
+					'order',
3333
+					$query_params['order_by']
3334
+				);
3335
+				$order = isset($query_params['order'])
3336
+					? $this->_extract_order($query_params['order'])
3337
+					: 'DESC';
3338
+				$query_object->set_order_by_sql(
3339
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3340
+				);
3341
+			}
3342
+		}
3343
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3344
+		if (! array_key_exists('order_by', $query_params)
3345
+			&& array_key_exists('order', $query_params)
3346
+			&& ! empty($query_params['order'])
3347
+		) {
3348
+			$pk_field = $this->get_primary_key_field();
3349
+			$order = $this->_extract_order($query_params['order']);
3350
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3351
+		}
3352
+		//set group by
3353
+		if (array_key_exists('group_by', $query_params)) {
3354
+			if (is_array($query_params['group_by'])) {
3355
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3356
+				$group_by_array = array();
3357
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3358
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3359
+				}
3360
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3361
+			} elseif (! empty ($query_params['group_by'])) {
3362
+				$query_object->set_group_by_sql(
3363
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3364
+				);
3365
+			}
3366
+		}
3367
+		//set having
3368
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3369
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3370
+		}
3371
+		//now, just verify they didn't pass anything wack
3372
+		foreach ($query_params as $query_key => $query_value) {
3373
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3374
+				throw new EE_Error(
3375
+					sprintf(
3376
+						__(
3377
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3378
+							'event_espresso'
3379
+						),
3380
+						$query_key,
3381
+						get_class($this),
3382
+						//						print_r( $this->_allowed_query_params, TRUE )
3383
+						implode(',', $this->_allowed_query_params)
3384
+					)
3385
+				);
3386
+			}
3387
+		}
3388
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3389
+		if (empty($main_model_join_sql)) {
3390
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3391
+		}
3392
+		return $query_object;
3393
+	}
3394
+
3395
+
3396
+
3397
+	/**
3398
+	 * Gets the where conditions that should be imposed on the query based on the
3399
+	 * context (eg reading frontend, backend, edit or delete).
3400
+	 *
3401
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3402
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3403
+	 * @throws \EE_Error
3404
+	 */
3405
+	public function caps_where_conditions($context = self::caps_read)
3406
+	{
3407
+		EEM_Base::verify_is_valid_cap_context($context);
3408
+		$cap_where_conditions = array();
3409
+		$cap_restrictions = $this->caps_missing($context);
3410
+		/**
3411
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3412
+		 */
3413
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3414
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3415
+				$restriction_if_no_cap->get_default_where_conditions());
3416
+		}
3417
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3418
+			$cap_restrictions);
3419
+	}
3420
+
3421
+
3422
+
3423
+	/**
3424
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3425
+	 * otherwise throws an exception
3426
+	 *
3427
+	 * @param string $should_be_order_string
3428
+	 * @return string either ASC, asc, DESC or desc
3429
+	 * @throws EE_Error
3430
+	 */
3431
+	private function _extract_order($should_be_order_string)
3432
+	{
3433
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3434
+			return $should_be_order_string;
3435
+		} else {
3436
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3437
+				"event_espresso"), get_class($this), $should_be_order_string));
3438
+		}
3439
+	}
3440
+
3441
+
3442
+
3443
+	/**
3444
+	 * Looks at all the models which are included in this query, and asks each
3445
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3446
+	 * so they can be merged
3447
+	 *
3448
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3449
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3450
+	 *                                                                  'none' means NO default where conditions will
3451
+	 *                                                                  be used AT ALL during this query.
3452
+	 *                                                                  'other_models_only' means default where
3453
+	 *                                                                  conditions from other models will be used, but
3454
+	 *                                                                  not for this primary model. 'all', the default,
3455
+	 *                                                                  means default where conditions will apply as
3456
+	 *                                                                  normal
3457
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3458
+	 * @throws EE_Error
3459
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3460
+	 */
3461
+	private function _get_default_where_conditions_for_models_in_query(
3462
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3463
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3464
+		$where_query_params = array()
3465
+	) {
3466
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3467
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3468
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3469
+				"event_espresso"), $use_default_where_conditions,
3470
+				implode(", ", $allowed_used_default_where_conditions_values)));
3471
+		}
3472
+		$universal_query_params = array();
3473
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3474
+			$universal_query_params = $this->_get_default_where_conditions();
3475
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3476
+			$universal_query_params = $this->_get_minimum_where_conditions();
3477
+		}
3478
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3479
+			$related_model = $this->get_related_model_obj($model_name);
3480
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3481
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3482
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3483
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3484
+			} else {
3485
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3486
+				continue;
3487
+			}
3488
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3489
+				$related_model_universal_where_params,
3490
+				$where_query_params,
3491
+				$related_model,
3492
+				$model_relation_path
3493
+			);
3494
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3495
+				$universal_query_params,
3496
+				$overrides
3497
+			);
3498
+		}
3499
+		return $universal_query_params;
3500
+	}
3501
+
3502
+
3503
+
3504
+	/**
3505
+	 * Determines whether or not we should use default where conditions for the model in question
3506
+	 * (this model, or other related models).
3507
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3508
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3509
+	 * We should use default where conditions on related models when they requested to use default where conditions
3510
+	 * on all models, or specifically just on other related models
3511
+	 * @param      $default_where_conditions_value
3512
+	 * @param bool $for_this_model false means this is for OTHER related models
3513
+	 * @return bool
3514
+	 */
3515
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3516
+	{
3517
+		return (
3518
+				   $for_this_model
3519
+				   && in_array(
3520
+					   $default_where_conditions_value,
3521
+					   array(
3522
+						   EEM_Base::default_where_conditions_all,
3523
+						   EEM_Base::default_where_conditions_this_only,
3524
+						   EEM_Base::default_where_conditions_minimum_others,
3525
+					   ),
3526
+					   true
3527
+				   )
3528
+			   )
3529
+			   || (
3530
+				   ! $for_this_model
3531
+				   && in_array(
3532
+					   $default_where_conditions_value,
3533
+					   array(
3534
+						   EEM_Base::default_where_conditions_all,
3535
+						   EEM_Base::default_where_conditions_others_only,
3536
+					   ),
3537
+					   true
3538
+				   )
3539
+			   );
3540
+	}
3541
+
3542
+	/**
3543
+	 * Determines whether or not we should use default minimum conditions for the model in question
3544
+	 * (this model, or other related models).
3545
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3546
+	 * where conditions.
3547
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3548
+	 * on this model or others
3549
+	 * @param      $default_where_conditions_value
3550
+	 * @param bool $for_this_model false means this is for OTHER related models
3551
+	 * @return bool
3552
+	 */
3553
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3554
+	{
3555
+		return (
3556
+				   $for_this_model
3557
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3558
+			   )
3559
+			   || (
3560
+				   ! $for_this_model
3561
+				   && in_array(
3562
+					   $default_where_conditions_value,
3563
+					   array(
3564
+						   EEM_Base::default_where_conditions_minimum_others,
3565
+						   EEM_Base::default_where_conditions_minimum_all,
3566
+					   ),
3567
+					   true
3568
+				   )
3569
+			   );
3570
+	}
3571
+
3572
+
3573
+	/**
3574
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3575
+	 * then we also add a special where condition which allows for that model's primary key
3576
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3577
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3578
+	 *
3579
+	 * @param array    $default_where_conditions
3580
+	 * @param array    $provided_where_conditions
3581
+	 * @param EEM_Base $model
3582
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3583
+	 * @return array like EEM_Base::get_all's $query_params[0]
3584
+	 * @throws \EE_Error
3585
+	 */
3586
+	private function _override_defaults_or_make_null_friendly(
3587
+		$default_where_conditions,
3588
+		$provided_where_conditions,
3589
+		$model,
3590
+		$model_relation_path
3591
+	) {
3592
+		$null_friendly_where_conditions = array();
3593
+		$none_overridden = true;
3594
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3595
+		foreach ($default_where_conditions as $key => $val) {
3596
+			if (isset($provided_where_conditions[$key])) {
3597
+				$none_overridden = false;
3598
+			} else {
3599
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3600
+			}
3601
+		}
3602
+		if ($none_overridden && $default_where_conditions) {
3603
+			if ($model->has_primary_key_field()) {
3604
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3605
+																				. "."
3606
+																				. $model->primary_key_name()] = array('IS NULL');
3607
+			}/*else{
3608 3608
 				//@todo NO PK, use other defaults
3609 3609
 			}*/
3610
-        }
3611
-        return $null_friendly_where_conditions;
3612
-    }
3613
-
3614
-
3615
-
3616
-    /**
3617
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3618
-     * default where conditions on all get_all, update, and delete queries done by this model.
3619
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3620
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3621
-     *
3622
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3623
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3624
-     */
3625
-    private function _get_default_where_conditions($model_relation_path = null)
3626
-    {
3627
-        if ($this->_ignore_where_strategy) {
3628
-            return array();
3629
-        }
3630
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3631
-    }
3632
-
3633
-
3634
-
3635
-    /**
3636
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3637
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3638
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3639
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3640
-     * Similar to _get_default_where_conditions
3641
-     *
3642
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3643
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3644
-     */
3645
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3646
-    {
3647
-        if ($this->_ignore_where_strategy) {
3648
-            return array();
3649
-        }
3650
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3651
-    }
3652
-
3653
-
3654
-
3655
-    /**
3656
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3657
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3658
-     *
3659
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3660
-     * @return string
3661
-     * @throws \EE_Error
3662
-     */
3663
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3664
-    {
3665
-        $selects = $this->_get_columns_to_select_for_this_model();
3666
-        foreach (
3667
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3668
-            $name_of_other_model_included
3669
-        ) {
3670
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3671
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3672
-            foreach ($other_model_selects as $key => $value) {
3673
-                $selects[] = $value;
3674
-            }
3675
-        }
3676
-        return implode(", ", $selects);
3677
-    }
3678
-
3679
-
3680
-
3681
-    /**
3682
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3683
-     * So that's going to be the columns for all the fields on the model
3684
-     *
3685
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3686
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3687
-     */
3688
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3689
-    {
3690
-        $fields = $this->field_settings();
3691
-        $selects = array();
3692
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3693
-            $this->get_this_model_name());
3694
-        foreach ($fields as $field_obj) {
3695
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3696
-                         . $field_obj->get_table_alias()
3697
-                         . "."
3698
-                         . $field_obj->get_table_column()
3699
-                         . " AS '"
3700
-                         . $table_alias_with_model_relation_chain_prefix
3701
-                         . $field_obj->get_table_alias()
3702
-                         . "."
3703
-                         . $field_obj->get_table_column()
3704
-                         . "'";
3705
-        }
3706
-        //make sure we are also getting the PKs of each table
3707
-        $tables = $this->get_tables();
3708
-        if (count($tables) > 1) {
3709
-            foreach ($tables as $table_obj) {
3710
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3711
-                                       . $table_obj->get_fully_qualified_pk_column();
3712
-                if (! in_array($qualified_pk_column, $selects)) {
3713
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3714
-                }
3715
-            }
3716
-        }
3717
-        return $selects;
3718
-    }
3719
-
3720
-
3721
-
3722
-    /**
3723
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3724
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3725
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3726
-     * SQL for joining, and the data types
3727
-     *
3728
-     * @param null|string                 $original_query_param
3729
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3730
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3731
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3732
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3733
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3734
-     *                                                          or 'Registration's
3735
-     * @param string                      $original_query_param what it originally was (eg
3736
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3737
-     *                                                          matches $query_param
3738
-     * @throws EE_Error
3739
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3740
-     */
3741
-    private function _extract_related_model_info_from_query_param(
3742
-        $query_param,
3743
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3744
-        $query_param_type,
3745
-        $original_query_param = null
3746
-    ) {
3747
-        if ($original_query_param === null) {
3748
-            $original_query_param = $query_param;
3749
-        }
3750
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3751
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3752
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3753
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3754
-        //check to see if we have a field on this model
3755
-        $this_model_fields = $this->field_settings(true);
3756
-        if (array_key_exists($query_param, $this_model_fields)) {
3757
-            if ($allow_fields) {
3758
-                return;
3759
-            } else {
3760
-                throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3761
-                    "event_espresso"),
3762
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3763
-            }
3764
-        } //check if this is a special logic query param
3765
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3766
-            if ($allow_logic_query_params) {
3767
-                return;
3768
-            } else {
3769
-                throw new EE_Error(
3770
-                    sprintf(
3771
-                        __('Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3772
-                            'event_espresso'),
3773
-                        implode('", "', $this->_logic_query_param_keys),
3774
-                        $query_param,
3775
-                        get_class($this),
3776
-                        '<br />',
3777
-                        "\t"
3778
-                        . ' $passed_in_query_info = <pre>'
3779
-                        . print_r($passed_in_query_info, true)
3780
-                        . '</pre>'
3781
-                        . "\n\t"
3782
-                        . ' $query_param_type = '
3783
-                        . $query_param_type
3784
-                        . "\n\t"
3785
-                        . ' $original_query_param = '
3786
-                        . $original_query_param
3787
-                    )
3788
-                );
3789
-            }
3790
-        } //check if it's a custom selection
3791
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3792
-            return;
3793
-        }
3794
-        //check if has a model name at the beginning
3795
-        //and
3796
-        //check if it's a field on a related model
3797
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3798
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3799
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3800
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3801
-                if ($query_param === '') {
3802
-                    //nothing left to $query_param
3803
-                    //we should actually end in a field name, not a model like this!
3804
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3805
-                        "event_espresso"),
3806
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3807
-                } else {
3808
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3809
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3810
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3811
-                    return;
3812
-                }
3813
-            } elseif ($query_param === $valid_related_model_name) {
3814
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3815
-                return;
3816
-            }
3817
-        }
3818
-        //ok so $query_param didn't start with a model name
3819
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3820
-        //it's wack, that's what it is
3821
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3822
-            "event_espresso"),
3823
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3824
-    }
3825
-
3826
-
3827
-
3828
-    /**
3829
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3830
-     * and store it on $passed_in_query_info
3831
-     *
3832
-     * @param string                      $model_name
3833
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3834
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3835
-     *                                                          model and $model_name. Eg, if we are querying Event,
3836
-     *                                                          and are adding a join to 'Payment' with the original
3837
-     *                                                          query param key
3838
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3839
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3840
-     *                                                          Payment wants to add default query params so that it
3841
-     *                                                          will know what models to prepend onto its default query
3842
-     *                                                          params or in case it wants to rename tables (in case
3843
-     *                                                          there are multiple joins to the same table)
3844
-     * @return void
3845
-     * @throws \EE_Error
3846
-     */
3847
-    private function _add_join_to_model(
3848
-        $model_name,
3849
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3850
-        $original_query_param
3851
-    ) {
3852
-        $relation_obj = $this->related_settings_for($model_name);
3853
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3854
-        //check if the relation is HABTM, because then we're essentially doing two joins
3855
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3856
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3857
-            $join_model_obj = $relation_obj->get_join_model();
3858
-            //replace the model specified with the join model for this relation chain, whi
3859
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3860
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3861
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3862
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3863
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3864
-            $passed_in_query_info->merge($new_query_info);
3865
-        }
3866
-        //now just join to the other table pointed to by the relation object, and add its data types
3867
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3868
-            array($model_relation_chain => $model_name),
3869
-            $relation_obj->get_join_statement($model_relation_chain));
3870
-        $passed_in_query_info->merge($new_query_info);
3871
-    }
3872
-
3873
-
3874
-
3875
-    /**
3876
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3877
-     *
3878
-     * @param array $where_params like EEM_Base::get_all
3879
-     * @return string of SQL
3880
-     * @throws \EE_Error
3881
-     */
3882
-    private function _construct_where_clause($where_params)
3883
-    {
3884
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3885
-        if ($SQL) {
3886
-            return " WHERE " . $SQL;
3887
-        } else {
3888
-            return '';
3889
-        }
3890
-    }
3891
-
3892
-
3893
-
3894
-    /**
3895
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3896
-     * and should be passed HAVING parameters, not WHERE parameters
3897
-     *
3898
-     * @param array $having_params
3899
-     * @return string
3900
-     * @throws \EE_Error
3901
-     */
3902
-    private function _construct_having_clause($having_params)
3903
-    {
3904
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3905
-        if ($SQL) {
3906
-            return " HAVING " . $SQL;
3907
-        } else {
3908
-            return '';
3909
-        }
3910
-    }
3911
-
3912
-
3913
-
3914
-    /**
3915
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3916
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3917
-     * EEM_Attendee.
3918
-     *
3919
-     * @param string $field_name
3920
-     * @param string $model_name
3921
-     * @return EE_Model_Field_Base
3922
-     * @throws EE_Error
3923
-     */
3924
-    protected function _get_field_on_model($field_name, $model_name)
3925
-    {
3926
-        $model_class = 'EEM_' . $model_name;
3927
-        $model_filepath = $model_class . ".model.php";
3928
-        if (is_readable($model_filepath)) {
3929
-            require_once($model_filepath);
3930
-            $model_instance = call_user_func($model_name . "::instance");
3931
-            /* @var $model_instance EEM_Base */
3932
-            return $model_instance->field_settings_for($field_name);
3933
-        } else {
3934
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3935
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3936
-        }
3937
-    }
3938
-
3939
-
3940
-
3941
-    /**
3942
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3943
-     * Event_Meta.meta_value = 'foo'))"
3944
-     *
3945
-     * @param array  $where_params see EEM_Base::get_all for documentation
3946
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3947
-     * @throws EE_Error
3948
-     * @return string of SQL
3949
-     */
3950
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3951
-    {
3952
-        $where_clauses = array();
3953
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3954
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3955
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3956
-                switch ($query_param) {
3957
-                    case 'not':
3958
-                    case 'NOT':
3959
-                        $where_clauses[] = "! ("
3960
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3961
-                                $glue)
3962
-                                           . ")";
3963
-                        break;
3964
-                    case 'and':
3965
-                    case 'AND':
3966
-                        $where_clauses[] = " ("
3967
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3968
-                                ' AND ')
3969
-                                           . ")";
3970
-                        break;
3971
-                    case 'or':
3972
-                    case 'OR':
3973
-                        $where_clauses[] = " ("
3974
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3975
-                                ' OR ')
3976
-                                           . ")";
3977
-                        break;
3978
-                }
3979
-            } else {
3980
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3981
-                //if it's not a normal field, maybe it's a custom selection?
3982
-                if (! $field_obj) {
3983
-                    if (isset($this->_custom_selections[$query_param][1])) {
3984
-                        $field_obj = $this->_custom_selections[$query_param][1];
3985
-                    } else {
3986
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3987
-                            "event_espresso"), $query_param));
3988
-                    }
3989
-                }
3990
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3991
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3992
-            }
3993
-        }
3994
-        return $where_clauses ? implode($glue, $where_clauses) : '';
3995
-    }
3996
-
3997
-
3998
-
3999
-    /**
4000
-     * Takes the input parameter and extract the table name (alias) and column name
4001
-     *
4002
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4003
-     * @throws EE_Error
4004
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4005
-     */
4006
-    private function _deduce_column_name_from_query_param($query_param)
4007
-    {
4008
-        $field = $this->_deduce_field_from_query_param($query_param);
4009
-        if ($field) {
4010
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4011
-                $query_param);
4012
-            return $table_alias_prefix . $field->get_qualified_column();
4013
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4014
-            //maybe it's custom selection item?
4015
-            //if so, just use it as the "column name"
4016
-            return $query_param;
4017
-        } else {
4018
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4019
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4020
-        }
4021
-    }
4022
-
4023
-
4024
-
4025
-    /**
4026
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4027
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4028
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4029
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4030
-     *
4031
-     * @param string $condition_query_param_key
4032
-     * @return string
4033
-     */
4034
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4035
-    {
4036
-        $pos_of_star = strpos($condition_query_param_key, '*');
4037
-        if ($pos_of_star === false) {
4038
-            return $condition_query_param_key;
4039
-        } else {
4040
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4041
-            return $condition_query_param_sans_star;
4042
-        }
4043
-    }
4044
-
4045
-
4046
-
4047
-    /**
4048
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4049
-     *
4050
-     * @param                            mixed      array | string    $op_and_value
4051
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4052
-     * @throws EE_Error
4053
-     * @return string
4054
-     */
4055
-    private function _construct_op_and_value($op_and_value, $field_obj)
4056
-    {
4057
-        if (is_array($op_and_value)) {
4058
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4059
-            if (! $operator) {
4060
-                $php_array_like_string = array();
4061
-                foreach ($op_and_value as $key => $value) {
4062
-                    $php_array_like_string[] = "$key=>$value";
4063
-                }
4064
-                throw new EE_Error(
4065
-                    sprintf(
4066
-                        __(
4067
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4068
-                            "event_espresso"
4069
-                        ),
4070
-                        implode(",", $php_array_like_string)
4071
-                    )
4072
-                );
4073
-            }
4074
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4075
-        } else {
4076
-            $operator = '=';
4077
-            $value = $op_and_value;
4078
-        }
4079
-        //check to see if the value is actually another field
4080
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4081
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4082
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4083
-            //in this case, the value should be an array, or at least a comma-separated list
4084
-            //it will need to handle a little differently
4085
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4086
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4087
-            return $operator . SP . $cleaned_value;
4088
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4089
-            //the value should be an array with count of two.
4090
-            if (count($value) !== 2) {
4091
-                throw new EE_Error(
4092
-                    sprintf(
4093
-                        __(
4094
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4095
-                            'event_espresso'
4096
-                        ),
4097
-                        "BETWEEN"
4098
-                    )
4099
-                );
4100
-            }
4101
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4102
-            return $operator . SP . $cleaned_value;
4103
-        } elseif (in_array($operator, $this->_null_style_operators)) {
4104
-            if ($value !== null) {
4105
-                throw new EE_Error(
4106
-                    sprintf(
4107
-                        __(
4108
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4109
-                            "event_espresso"
4110
-                        ),
4111
-                        $value,
4112
-                        $operator
4113
-                    )
4114
-                );
4115
-            }
4116
-            return $operator;
4117
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
4118
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4119
-            //remove other junk. So just treat it as a string.
4120
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4121
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4122
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4123
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4124
-            throw new EE_Error(
4125
-                sprintf(
4126
-                    __(
4127
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4128
-                        'event_espresso'
4129
-                    ),
4130
-                    $operator,
4131
-                    $operator
4132
-                )
4133
-            );
4134
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4135
-            throw new EE_Error(
4136
-                sprintf(
4137
-                    __(
4138
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4139
-                        'event_espresso'
4140
-                    ),
4141
-                    $operator,
4142
-                    $operator
4143
-                )
4144
-            );
4145
-        } else {
4146
-            throw new EE_Error(
4147
-                sprintf(
4148
-                    __(
4149
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4150
-                        "event_espresso"
4151
-                    ),
4152
-                    http_build_query($op_and_value)
4153
-                )
4154
-            );
4155
-        }
4156
-    }
4157
-
4158
-
4159
-
4160
-    /**
4161
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4162
-     *
4163
-     * @param array                      $values
4164
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4165
-     *                                              '%s'
4166
-     * @return string
4167
-     * @throws \EE_Error
4168
-     */
4169
-    public function _construct_between_value($values, $field_obj)
4170
-    {
4171
-        $cleaned_values = array();
4172
-        foreach ($values as $value) {
4173
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4174
-        }
4175
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4176
-    }
4177
-
4178
-
4179
-
4180
-    /**
4181
-     * Takes an array or a comma-separated list of $values and cleans them
4182
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4183
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4184
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4185
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4186
-     *
4187
-     * @param mixed                      $values    array or comma-separated string
4188
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4189
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4190
-     * @throws \EE_Error
4191
-     */
4192
-    public function _construct_in_value($values, $field_obj)
4193
-    {
4194
-        //check if the value is a CSV list
4195
-        if (is_string($values)) {
4196
-            //in which case, turn it into an array
4197
-            $values = explode(",", $values);
4198
-        }
4199
-        $cleaned_values = array();
4200
-        foreach ($values as $value) {
4201
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4202
-        }
4203
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4204
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4205
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4206
-        if (empty($cleaned_values)) {
4207
-            $all_fields = $this->field_settings();
4208
-            $a_field = array_shift($all_fields);
4209
-            $main_table = $this->_get_main_table();
4210
-            $cleaned_values[] = "SELECT "
4211
-                                . $a_field->get_table_column()
4212
-                                . " FROM "
4213
-                                . $main_table->get_table_name()
4214
-                                . " WHERE FALSE";
4215
-        }
4216
-        return "(" . implode(",", $cleaned_values) . ")";
4217
-    }
4218
-
4219
-
4220
-
4221
-    /**
4222
-     * @param mixed                      $value
4223
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4224
-     * @throws EE_Error
4225
-     * @return false|null|string
4226
-     */
4227
-    private function _wpdb_prepare_using_field($value, $field_obj)
4228
-    {
4229
-        /** @type WPDB $wpdb */
4230
-        global $wpdb;
4231
-        if ($field_obj instanceof EE_Model_Field_Base) {
4232
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4233
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4234
-        } else {//$field_obj should really just be a data type
4235
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4236
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4237
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4238
-            }
4239
-            return $wpdb->prepare($field_obj, $value);
4240
-        }
4241
-    }
4242
-
4243
-
4244
-
4245
-    /**
4246
-     * Takes the input parameter and finds the model field that it indicates.
4247
-     *
4248
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4249
-     * @throws EE_Error
4250
-     * @return EE_Model_Field_Base
4251
-     */
4252
-    protected function _deduce_field_from_query_param($query_param_name)
4253
-    {
4254
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4255
-        //which will help us find the database table and column
4256
-        $query_param_parts = explode(".", $query_param_name);
4257
-        if (empty($query_param_parts)) {
4258
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4259
-                'event_espresso'), $query_param_name));
4260
-        }
4261
-        $number_of_parts = count($query_param_parts);
4262
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4263
-        if ($number_of_parts === 1) {
4264
-            $field_name = $last_query_param_part;
4265
-            $model_obj = $this;
4266
-        } else {// $number_of_parts >= 2
4267
-            //the last part is the column name, and there are only 2parts. therefore...
4268
-            $field_name = $last_query_param_part;
4269
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4270
-        }
4271
-        try {
4272
-            return $model_obj->field_settings_for($field_name);
4273
-        } catch (EE_Error $e) {
4274
-            return null;
4275
-        }
4276
-    }
4277
-
4278
-
4279
-
4280
-    /**
4281
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4282
-     * alias and column which corresponds to it
4283
-     *
4284
-     * @param string $field_name
4285
-     * @throws EE_Error
4286
-     * @return string
4287
-     */
4288
-    public function _get_qualified_column_for_field($field_name)
4289
-    {
4290
-        $all_fields = $this->field_settings();
4291
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4292
-        if ($field) {
4293
-            return $field->get_qualified_column();
4294
-        } else {
4295
-            throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4296
-                'event_espresso'), $field_name, get_class($this)));
4297
-        }
4298
-    }
4299
-
4300
-
4301
-
4302
-    /**
4303
-     * constructs the select use on special limit joins
4304
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4305
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4306
-     * (as that is typically where the limits would be set).
4307
-     *
4308
-     * @param  string       $table_alias The table the select is being built for
4309
-     * @param  mixed|string $limit       The limit for this select
4310
-     * @return string                The final select join element for the query.
4311
-     */
4312
-    public function _construct_limit_join_select($table_alias, $limit)
4313
-    {
4314
-        $SQL = '';
4315
-        foreach ($this->_tables as $table_obj) {
4316
-            if ($table_obj instanceof EE_Primary_Table) {
4317
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4318
-                    ? $table_obj->get_select_join_limit($limit)
4319
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4320
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4321
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4322
-                    ? $table_obj->get_select_join_limit_join($limit)
4323
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4324
-            }
4325
-        }
4326
-        return $SQL;
4327
-    }
4328
-
4329
-
4330
-
4331
-    /**
4332
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4333
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4334
-     *
4335
-     * @return string SQL
4336
-     * @throws \EE_Error
4337
-     */
4338
-    public function _construct_internal_join()
4339
-    {
4340
-        $SQL = $this->_get_main_table()->get_table_sql();
4341
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4342
-        return $SQL;
4343
-    }
4344
-
4345
-
4346
-
4347
-    /**
4348
-     * Constructs the SQL for joining all the tables on this model.
4349
-     * Normally $alias should be the primary table's alias, but in cases where
4350
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4351
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4352
-     * alias, this will construct SQL like:
4353
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4354
-     * With $alias being a secondary table's alias, this will construct SQL like:
4355
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4356
-     *
4357
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4358
-     * @return string
4359
-     */
4360
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4361
-    {
4362
-        $SQL = '';
4363
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4364
-        foreach ($this->_tables as $table_obj) {
4365
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4366
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4367
-                    //so we're joining to this table, meaning the table is already in
4368
-                    //the FROM statement, BUT the primary table isn't. So we want
4369
-                    //to add the inverse join sql
4370
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4371
-                } else {
4372
-                    //just add a regular JOIN to this table from the primary table
4373
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4374
-                }
4375
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4376
-        }
4377
-        return $SQL;
4378
-    }
4379
-
4380
-
4381
-
4382
-    /**
4383
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4384
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4385
-     * their data type (eg, '%s', '%d', etc)
4386
-     *
4387
-     * @return array
4388
-     */
4389
-    public function _get_data_types()
4390
-    {
4391
-        $data_types = array();
4392
-        foreach ($this->field_settings() as $field_obj) {
4393
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4394
-            /** @var $field_obj EE_Model_Field_Base */
4395
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4396
-        }
4397
-        return $data_types;
4398
-    }
4399
-
4400
-
4401
-
4402
-    /**
4403
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4404
-     *
4405
-     * @param string $model_name
4406
-     * @throws EE_Error
4407
-     * @return EEM_Base
4408
-     */
4409
-    public function get_related_model_obj($model_name)
4410
-    {
4411
-        $model_classname = "EEM_" . $model_name;
4412
-        if (! class_exists($model_classname)) {
4413
-            throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4414
-                'event_espresso'), $model_name, $model_classname));
4415
-        }
4416
-        return call_user_func($model_classname . "::instance");
4417
-    }
4418
-
4419
-
4420
-
4421
-    /**
4422
-     * Returns the array of EE_ModelRelations for this model.
4423
-     *
4424
-     * @return EE_Model_Relation_Base[]
4425
-     */
4426
-    public function relation_settings()
4427
-    {
4428
-        return $this->_model_relations;
4429
-    }
4430
-
4431
-
4432
-
4433
-    /**
4434
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4435
-     * because without THOSE models, this model probably doesn't have much purpose.
4436
-     * (Eg, without an event, datetimes have little purpose.)
4437
-     *
4438
-     * @return EE_Belongs_To_Relation[]
4439
-     */
4440
-    public function belongs_to_relations()
4441
-    {
4442
-        $belongs_to_relations = array();
4443
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4444
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4445
-                $belongs_to_relations[$model_name] = $relation_obj;
4446
-            }
4447
-        }
4448
-        return $belongs_to_relations;
4449
-    }
4450
-
4451
-
4452
-
4453
-    /**
4454
-     * Returns the specified EE_Model_Relation, or throws an exception
4455
-     *
4456
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4457
-     * @throws EE_Error
4458
-     * @return EE_Model_Relation_Base
4459
-     */
4460
-    public function related_settings_for($relation_name)
4461
-    {
4462
-        $relatedModels = $this->relation_settings();
4463
-        if (! array_key_exists($relation_name, $relatedModels)) {
4464
-            throw new EE_Error(
4465
-                sprintf(
4466
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4467
-                        'event_espresso'),
4468
-                    $relation_name,
4469
-                    $this->_get_class_name(),
4470
-                    implode(', ', array_keys($relatedModels))
4471
-                )
4472
-            );
4473
-        }
4474
-        return $relatedModels[$relation_name];
4475
-    }
4476
-
4477
-
4478
-
4479
-    /**
4480
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4481
-     * fields
4482
-     *
4483
-     * @param string $fieldName
4484
-     * @throws EE_Error
4485
-     * @return EE_Model_Field_Base
4486
-     */
4487
-    public function field_settings_for($fieldName)
4488
-    {
4489
-        $fieldSettings = $this->field_settings(true);
4490
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4491
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4492
-                get_class($this)));
4493
-        }
4494
-        return $fieldSettings[$fieldName];
4495
-    }
4496
-
4497
-
4498
-
4499
-    /**
4500
-     * Checks if this field exists on this model
4501
-     *
4502
-     * @param string $fieldName a key in the model's _field_settings array
4503
-     * @return boolean
4504
-     */
4505
-    public function has_field($fieldName)
4506
-    {
4507
-        $fieldSettings = $this->field_settings(true);
4508
-        if (isset($fieldSettings[$fieldName])) {
4509
-            return true;
4510
-        } else {
4511
-            return false;
4512
-        }
4513
-    }
4514
-
4515
-
4516
-
4517
-    /**
4518
-     * Returns whether or not this model has a relation to the specified model
4519
-     *
4520
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4521
-     * @return boolean
4522
-     */
4523
-    public function has_relation($relation_name)
4524
-    {
4525
-        $relations = $this->relation_settings();
4526
-        if (isset($relations[$relation_name])) {
4527
-            return true;
4528
-        } else {
4529
-            return false;
4530
-        }
4531
-    }
4532
-
4533
-
4534
-
4535
-    /**
4536
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4537
-     * Eg, on EE_Answer that would be ANS_ID field object
4538
-     *
4539
-     * @param $field_obj
4540
-     * @return boolean
4541
-     */
4542
-    public function is_primary_key_field($field_obj)
4543
-    {
4544
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4545
-    }
4546
-
4547
-
4548
-
4549
-    /**
4550
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4551
-     * Eg, on EE_Answer that would be ANS_ID field object
4552
-     *
4553
-     * @return EE_Model_Field_Base
4554
-     * @throws EE_Error
4555
-     */
4556
-    public function get_primary_key_field()
4557
-    {
4558
-        if ($this->_primary_key_field === null) {
4559
-            foreach ($this->field_settings(true) as $field_obj) {
4560
-                if ($this->is_primary_key_field($field_obj)) {
4561
-                    $this->_primary_key_field = $field_obj;
4562
-                    break;
4563
-                }
4564
-            }
4565
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4566
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4567
-                    get_class($this)));
4568
-            }
4569
-        }
4570
-        return $this->_primary_key_field;
4571
-    }
4572
-
4573
-
4574
-
4575
-    /**
4576
-     * Returns whether or not not there is a primary key on this model.
4577
-     * Internally does some caching.
4578
-     *
4579
-     * @return boolean
4580
-     */
4581
-    public function has_primary_key_field()
4582
-    {
4583
-        if ($this->_has_primary_key_field === null) {
4584
-            try {
4585
-                $this->get_primary_key_field();
4586
-                $this->_has_primary_key_field = true;
4587
-            } catch (EE_Error $e) {
4588
-                $this->_has_primary_key_field = false;
4589
-            }
4590
-        }
4591
-        return $this->_has_primary_key_field;
4592
-    }
4593
-
4594
-
4595
-
4596
-    /**
4597
-     * Finds the first field of type $field_class_name.
4598
-     *
4599
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4600
-     *                                 EE_Foreign_Key_Field, etc
4601
-     * @return EE_Model_Field_Base or null if none is found
4602
-     */
4603
-    public function get_a_field_of_type($field_class_name)
4604
-    {
4605
-        foreach ($this->field_settings() as $field) {
4606
-            if ($field instanceof $field_class_name) {
4607
-                return $field;
4608
-            }
4609
-        }
4610
-        return null;
4611
-    }
4612
-
4613
-
4614
-
4615
-    /**
4616
-     * Gets a foreign key field pointing to model.
4617
-     *
4618
-     * @param string $model_name eg Event, Registration, not EEM_Event
4619
-     * @return EE_Foreign_Key_Field_Base
4620
-     * @throws EE_Error
4621
-     */
4622
-    public function get_foreign_key_to($model_name)
4623
-    {
4624
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4625
-            foreach ($this->field_settings() as $field) {
4626
-                if (
4627
-                    $field instanceof EE_Foreign_Key_Field_Base
4628
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4629
-                ) {
4630
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4631
-                    break;
4632
-                }
4633
-            }
4634
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4635
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4636
-                    'event_espresso'), $model_name, get_class($this)));
4637
-            }
4638
-        }
4639
-        return $this->_cache_foreign_key_to_fields[$model_name];
4640
-    }
4641
-
4642
-
4643
-
4644
-    /**
4645
-     * Gets the actual table for the table alias
4646
-     *
4647
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4648
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4649
-     *                            Either one works
4650
-     * @return EE_Table_Base
4651
-     */
4652
-    public function get_table_for_alias($table_alias)
4653
-    {
4654
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4655
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4656
-    }
4657
-
4658
-
4659
-
4660
-    /**
4661
-     * Returns a flat array of all field son this model, instead of organizing them
4662
-     * by table_alias as they are in the constructor.
4663
-     *
4664
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4665
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4666
-     */
4667
-    public function field_settings($include_db_only_fields = false)
4668
-    {
4669
-        if ($include_db_only_fields) {
4670
-            if ($this->_cached_fields === null) {
4671
-                $this->_cached_fields = array();
4672
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4673
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4674
-                        $this->_cached_fields[$field_name] = $field_obj;
4675
-                    }
4676
-                }
4677
-            }
4678
-            return $this->_cached_fields;
4679
-        } else {
4680
-            if ($this->_cached_fields_non_db_only === null) {
4681
-                $this->_cached_fields_non_db_only = array();
4682
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4683
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4684
-                        /** @var $field_obj EE_Model_Field_Base */
4685
-                        if (! $field_obj->is_db_only_field()) {
4686
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4687
-                        }
4688
-                    }
4689
-                }
4690
-            }
4691
-            return $this->_cached_fields_non_db_only;
4692
-        }
4693
-    }
4694
-
4695
-
4696
-
4697
-    /**
4698
-     *        cycle though array of attendees and create objects out of each item
4699
-     *
4700
-     * @access        private
4701
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4702
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4703
-     *                           numerically indexed)
4704
-     * @throws \EE_Error
4705
-     */
4706
-    protected function _create_objects($rows = array())
4707
-    {
4708
-        $array_of_objects = array();
4709
-        if (empty($rows)) {
4710
-            return array();
4711
-        }
4712
-        $count_if_model_has_no_primary_key = 0;
4713
-        $has_primary_key = $this->has_primary_key_field();
4714
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4715
-        foreach ((array)$rows as $row) {
4716
-            if (empty($row)) {
4717
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4718
-                return array();
4719
-            }
4720
-            //check if we've already set this object in the results array,
4721
-            //in which case there's no need to process it further (again)
4722
-            if ($has_primary_key) {
4723
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4724
-                    $row,
4725
-                    $primary_key_field->get_qualified_column(),
4726
-                    $primary_key_field->get_table_column()
4727
-                );
4728
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4729
-                    continue;
4730
-                }
4731
-            }
4732
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4733
-            if (! $classInstance) {
4734
-                throw new EE_Error(
4735
-                    sprintf(
4736
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4737
-                        $this->get_this_model_name(),
4738
-                        http_build_query($row)
4739
-                    )
4740
-                );
4741
-            }
4742
-            //set the timezone on the instantiated objects
4743
-            $classInstance->set_timezone($this->_timezone);
4744
-            //make sure if there is any timezone setting present that we set the timezone for the object
4745
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4746
-            $array_of_objects[$key] = $classInstance;
4747
-            //also, for all the relations of type BelongsTo, see if we can cache
4748
-            //those related models
4749
-            //(we could do this for other relations too, but if there are conditions
4750
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4751
-            //so it requires a little more thought than just caching them immediately...)
4752
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4753
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4754
-                    //check if this model's INFO is present. If so, cache it on the model
4755
-                    $other_model = $relation_obj->get_other_model();
4756
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4757
-                    //if we managed to make a model object from the results, cache it on the main model object
4758
-                    if ($other_model_obj_maybe) {
4759
-                        //set timezone on these other model objects if they are present
4760
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4761
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4762
-                    }
4763
-                }
4764
-            }
4765
-        }
4766
-        return $array_of_objects;
4767
-    }
4768
-
4769
-
4770
-
4771
-    /**
4772
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4773
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4774
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4775
-     * object (as set in the model_field!).
4776
-     *
4777
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4778
-     */
4779
-    public function create_default_object()
4780
-    {
4781
-        $this_model_fields_and_values = array();
4782
-        //setup the row using default values;
4783
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4784
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4785
-        }
4786
-        $className = $this->_get_class_name();
4787
-        $classInstance = EE_Registry::instance()
4788
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4789
-        return $classInstance;
4790
-    }
4791
-
4792
-
4793
-
4794
-    /**
4795
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4796
-     *                             or an stdClass where each property is the name of a column,
4797
-     * @return EE_Base_Class
4798
-     * @throws \EE_Error
4799
-     */
4800
-    public function instantiate_class_from_array_or_object($cols_n_values)
4801
-    {
4802
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4803
-            $cols_n_values = get_object_vars($cols_n_values);
4804
-        }
4805
-        $primary_key = null;
4806
-        //make sure the array only has keys that are fields/columns on this model
4807
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4808
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4809
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4810
-        }
4811
-        $className = $this->_get_class_name();
4812
-        //check we actually found results that we can use to build our model object
4813
-        //if not, return null
4814
-        if ($this->has_primary_key_field()) {
4815
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4816
-                return null;
4817
-            }
4818
-        } else if ($this->unique_indexes()) {
4819
-            $first_column = reset($this_model_fields_n_values);
4820
-            if (empty($first_column)) {
4821
-                return null;
4822
-            }
4823
-        }
4824
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4825
-        if ($primary_key) {
4826
-            $classInstance = $this->get_from_entity_map($primary_key);
4827
-            if (! $classInstance) {
4828
-                $classInstance = EE_Registry::instance()
4829
-                                            ->load_class($className,
4830
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4831
-                // add this new object to the entity map
4832
-                $classInstance = $this->add_to_entity_map($classInstance);
4833
-            }
4834
-        } else {
4835
-            $classInstance = EE_Registry::instance()
4836
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4837
-                                            true, false);
4838
-        }
4839
-        //it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4840
-        $this->set_timezone($classInstance->get_timezone());
4841
-        return $classInstance;
4842
-    }
4843
-
4844
-
4845
-
4846
-    /**
4847
-     * Gets the model object from the  entity map if it exists
4848
-     *
4849
-     * @param int|string $id the ID of the model object
4850
-     * @return EE_Base_Class
4851
-     */
4852
-    public function get_from_entity_map($id)
4853
-    {
4854
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4855
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4856
-    }
4857
-
4858
-
4859
-
4860
-    /**
4861
-     * add_to_entity_map
4862
-     * Adds the object to the model's entity mappings
4863
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4864
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4865
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4866
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4867
-     *        then this method should be called immediately after the update query
4868
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4869
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4870
-     *
4871
-     * @param    EE_Base_Class $object
4872
-     * @throws EE_Error
4873
-     * @return \EE_Base_Class
4874
-     */
4875
-    public function add_to_entity_map(EE_Base_Class $object)
4876
-    {
4877
-        $className = $this->_get_class_name();
4878
-        if (! $object instanceof $className) {
4879
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4880
-                is_object($object) ? get_class($object) : $object, $className));
4881
-        }
4882
-        /** @var $object EE_Base_Class */
4883
-        if (! $object->ID()) {
4884
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4885
-                "event_espresso"), get_class($this)));
4886
-        }
4887
-        // double check it's not already there
4888
-        $classInstance = $this->get_from_entity_map($object->ID());
4889
-        if ($classInstance) {
4890
-            return $classInstance;
4891
-        } else {
4892
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4893
-            return $object;
4894
-        }
4895
-    }
4896
-
4897
-
4898
-
4899
-    /**
4900
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4901
-     * if no identifier is provided, then the entire entity map is emptied
4902
-     *
4903
-     * @param int|string $id the ID of the model object
4904
-     * @return boolean
4905
-     */
4906
-    public function clear_entity_map($id = null)
4907
-    {
4908
-        if (empty($id)) {
4909
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4910
-            return true;
4911
-        }
4912
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4913
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4914
-            return true;
4915
-        }
4916
-        return false;
4917
-    }
4918
-
4919
-
4920
-
4921
-    /**
4922
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4923
-     * Given an array where keys are column (or column alias) names and values,
4924
-     * returns an array of their corresponding field names and database values
4925
-     *
4926
-     * @param array $cols_n_values
4927
-     * @return array
4928
-     */
4929
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4930
-    {
4931
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4932
-    }
4933
-
4934
-
4935
-
4936
-    /**
4937
-     * _deduce_fields_n_values_from_cols_n_values
4938
-     * Given an array where keys are column (or column alias) names and values,
4939
-     * returns an array of their corresponding field names and database values
4940
-     *
4941
-     * @param string $cols_n_values
4942
-     * @return array
4943
-     */
4944
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4945
-    {
4946
-        $this_model_fields_n_values = array();
4947
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
4948
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4949
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4950
-            //there is a primary key on this table and its not set. Use defaults for all its columns
4951
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
4952
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4953
-                    if (! $field_obj->is_db_only_field()) {
4954
-                        //prepare field as if its coming from db
4955
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4956
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4957
-                    }
4958
-                }
4959
-            } else {
4960
-                //the table's rows existed. Use their values
4961
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4962
-                    if (! $field_obj->is_db_only_field()) {
4963
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4964
-                            $cols_n_values, $field_obj->get_qualified_column(),
4965
-                            $field_obj->get_table_column()
4966
-                        );
4967
-                    }
4968
-                }
4969
-            }
4970
-        }
4971
-        return $this_model_fields_n_values;
4972
-    }
4973
-
4974
-
4975
-
4976
-    /**
4977
-     * @param $cols_n_values
4978
-     * @param $qualified_column
4979
-     * @param $regular_column
4980
-     * @return null
4981
-     */
4982
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4983
-    {
4984
-        $value = null;
4985
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4986
-        //does the field on the model relate to this column retrieved from the db?
4987
-        //or is it a db-only field? (not relating to the model)
4988
-        if (isset($cols_n_values[$qualified_column])) {
4989
-            $value = $cols_n_values[$qualified_column];
4990
-        } elseif (isset($cols_n_values[$regular_column])) {
4991
-            $value = $cols_n_values[$regular_column];
4992
-        }
4993
-        return $value;
4994
-    }
4995
-
4996
-
4997
-
4998
-    /**
4999
-     * refresh_entity_map_from_db
5000
-     * Makes sure the model object in the entity map at $id assumes the values
5001
-     * of the database (opposite of EE_base_Class::save())
5002
-     *
5003
-     * @param int|string $id
5004
-     * @return EE_Base_Class
5005
-     * @throws \EE_Error
5006
-     */
5007
-    public function refresh_entity_map_from_db($id)
5008
-    {
5009
-        $obj_in_map = $this->get_from_entity_map($id);
5010
-        if ($obj_in_map) {
5011
-            $wpdb_results = $this->_get_all_wpdb_results(
5012
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5013
-            );
5014
-            if ($wpdb_results && is_array($wpdb_results)) {
5015
-                $one_row = reset($wpdb_results);
5016
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5017
-                    $obj_in_map->set_from_db($field_name, $db_value);
5018
-                }
5019
-                //clear the cache of related model objects
5020
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5021
-                    $obj_in_map->clear_cache($relation_name, null, true);
5022
-                }
5023
-            }
5024
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5025
-            return $obj_in_map;
5026
-        } else {
5027
-            return $this->get_one_by_ID($id);
5028
-        }
5029
-    }
5030
-
5031
-
5032
-
5033
-    /**
5034
-     * refresh_entity_map_with
5035
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5036
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5037
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5038
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5039
-     *
5040
-     * @param int|string    $id
5041
-     * @param EE_Base_Class $replacing_model_obj
5042
-     * @return \EE_Base_Class
5043
-     * @throws \EE_Error
5044
-     */
5045
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5046
-    {
5047
-        $obj_in_map = $this->get_from_entity_map($id);
5048
-        if ($obj_in_map) {
5049
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5050
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5051
-                    $obj_in_map->set($field_name, $value);
5052
-                }
5053
-                //make the model object in the entity map's cache match the $replacing_model_obj
5054
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5055
-                    $obj_in_map->clear_cache($relation_name, null, true);
5056
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5057
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5058
-                    }
5059
-                }
5060
-            }
5061
-            return $obj_in_map;
5062
-        } else {
5063
-            $this->add_to_entity_map($replacing_model_obj);
5064
-            return $replacing_model_obj;
5065
-        }
5066
-    }
5067
-
5068
-
5069
-
5070
-    /**
5071
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5072
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5073
-     * require_once($this->_getClassName().".class.php");
5074
-     *
5075
-     * @return string
5076
-     */
5077
-    private function _get_class_name()
5078
-    {
5079
-        return "EE_" . $this->get_this_model_name();
5080
-    }
5081
-
5082
-
5083
-
5084
-    /**
5085
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5086
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5087
-     * it would be 'Events'.
5088
-     *
5089
-     * @param int $quantity
5090
-     * @return string
5091
-     */
5092
-    public function item_name($quantity = 1)
5093
-    {
5094
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5095
-    }
5096
-
5097
-
5098
-
5099
-    /**
5100
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5101
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5102
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5103
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5104
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5105
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5106
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5107
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5108
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5109
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5110
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5111
-     *        return $previousReturnValue.$returnString;
5112
-     * }
5113
-     * require('EEM_Answer.model.php');
5114
-     * $answer=EEM_Answer::instance();
5115
-     * echo $answer->my_callback('monkeys',100);
5116
-     * //will output "you called my_callback! and passed args:monkeys,100"
5117
-     *
5118
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5119
-     * @param array  $args       array of original arguments passed to the function
5120
-     * @throws EE_Error
5121
-     * @return mixed whatever the plugin which calls add_filter decides
5122
-     */
5123
-    public function __call($methodName, $args)
5124
-    {
5125
-        $className = get_class($this);
5126
-        $tagName = "FHEE__{$className}__{$methodName}";
5127
-        if (! has_filter($tagName)) {
5128
-            throw new EE_Error(
5129
-                sprintf(
5130
-                    __('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5131
-                        'event_espresso'),
5132
-                    $methodName,
5133
-                    $className,
5134
-                    $tagName,
5135
-                    '<br />'
5136
-                )
5137
-            );
5138
-        }
5139
-        return apply_filters($tagName, null, $this, $args);
5140
-    }
5141
-
5142
-
5143
-
5144
-    /**
5145
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5146
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5147
-     *
5148
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5149
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5150
-     *                                                       the object's class name
5151
-     *                                                       or object's ID
5152
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5153
-     *                                                       exists in the database. If it does not, we add it
5154
-     * @throws EE_Error
5155
-     * @return EE_Base_Class
5156
-     */
5157
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5158
-    {
5159
-        $className = $this->_get_class_name();
5160
-        if ($base_class_obj_or_id instanceof $className) {
5161
-            $model_object = $base_class_obj_or_id;
5162
-        } else {
5163
-            $primary_key_field = $this->get_primary_key_field();
5164
-            if (
5165
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5166
-                && (
5167
-                    is_int($base_class_obj_or_id)
5168
-                    || is_string($base_class_obj_or_id)
5169
-                )
5170
-            ) {
5171
-                // assume it's an ID.
5172
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5173
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5174
-            } else if (
5175
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5176
-                && is_string($base_class_obj_or_id)
5177
-            ) {
5178
-                // assume its a string representation of the object
5179
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5180
-            } else {
5181
-                throw new EE_Error(
5182
-                    sprintf(
5183
-                        __(
5184
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5185
-                            'event_espresso'
5186
-                        ),
5187
-                        $base_class_obj_or_id,
5188
-                        $this->_get_class_name(),
5189
-                        print_r($base_class_obj_or_id, true)
5190
-                    )
5191
-                );
5192
-            }
5193
-        }
5194
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5195
-            $model_object->save();
5196
-        }
5197
-        return $model_object;
5198
-    }
5199
-
5200
-
5201
-
5202
-    /**
5203
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5204
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5205
-     * returns it ID.
5206
-     *
5207
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5208
-     * @return int|string depending on the type of this model object's ID
5209
-     * @throws EE_Error
5210
-     */
5211
-    public function ensure_is_ID($base_class_obj_or_id)
5212
-    {
5213
-        $className = $this->_get_class_name();
5214
-        if ($base_class_obj_or_id instanceof $className) {
5215
-            /** @var $base_class_obj_or_id EE_Base_Class */
5216
-            $id = $base_class_obj_or_id->ID();
5217
-        } elseif (is_int($base_class_obj_or_id)) {
5218
-            //assume it's an ID
5219
-            $id = $base_class_obj_or_id;
5220
-        } elseif (is_string($base_class_obj_or_id)) {
5221
-            //assume its a string representation of the object
5222
-            $id = $base_class_obj_or_id;
5223
-        } else {
5224
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5225
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5226
-                print_r($base_class_obj_or_id, true)));
5227
-        }
5228
-        return $id;
5229
-    }
5230
-
5231
-
5232
-
5233
-    /**
5234
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5235
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5236
-     * been sanitized and converted into the appropriate domain.
5237
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5238
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5239
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5240
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5241
-     * $EVT = EEM_Event::instance(); $old_setting =
5242
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5243
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5244
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5245
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5246
-     *
5247
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5248
-     * @return void
5249
-     */
5250
-    public function assume_values_already_prepared_by_model_object(
5251
-        $values_already_prepared = self::not_prepared_by_model_object
5252
-    ) {
5253
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5254
-    }
5255
-
5256
-
5257
-
5258
-    /**
5259
-     * Read comments for assume_values_already_prepared_by_model_object()
5260
-     *
5261
-     * @return int
5262
-     */
5263
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5264
-    {
5265
-        return $this->_values_already_prepared_by_model_object;
5266
-    }
5267
-
5268
-
5269
-
5270
-    /**
5271
-     * Gets all the indexes on this model
5272
-     *
5273
-     * @return EE_Index[]
5274
-     */
5275
-    public function indexes()
5276
-    {
5277
-        return $this->_indexes;
5278
-    }
5279
-
5280
-
5281
-
5282
-    /**
5283
-     * Gets all the Unique Indexes on this model
5284
-     *
5285
-     * @return EE_Unique_Index[]
5286
-     */
5287
-    public function unique_indexes()
5288
-    {
5289
-        $unique_indexes = array();
5290
-        foreach ($this->_indexes as $name => $index) {
5291
-            if ($index instanceof EE_Unique_Index) {
5292
-                $unique_indexes [$name] = $index;
5293
-            }
5294
-        }
5295
-        return $unique_indexes;
5296
-    }
5297
-
5298
-
5299
-
5300
-    /**
5301
-     * Gets all the fields which, when combined, make the primary key.
5302
-     * This is usually just an array with 1 element (the primary key), but in cases
5303
-     * where there is no primary key, it's a combination of fields as defined
5304
-     * on a primary index
5305
-     *
5306
-     * @return EE_Model_Field_Base[] indexed by the field's name
5307
-     * @throws \EE_Error
5308
-     */
5309
-    public function get_combined_primary_key_fields()
5310
-    {
5311
-        foreach ($this->indexes() as $index) {
5312
-            if ($index instanceof EE_Primary_Key_Index) {
5313
-                return $index->fields();
5314
-            }
5315
-        }
5316
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5317
-    }
5318
-
5319
-
5320
-
5321
-    /**
5322
-     * Used to build a primary key string (when the model has no primary key),
5323
-     * which can be used a unique string to identify this model object.
5324
-     *
5325
-     * @param array $cols_n_values keys are field names, values are their values
5326
-     * @return string
5327
-     * @throws \EE_Error
5328
-     */
5329
-    public function get_index_primary_key_string($cols_n_values)
5330
-    {
5331
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5332
-            $this->get_combined_primary_key_fields());
5333
-        return http_build_query($cols_n_values_for_primary_key_index);
5334
-    }
5335
-
5336
-
5337
-
5338
-    /**
5339
-     * Gets the field values from the primary key string
5340
-     *
5341
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5342
-     * @param string $index_primary_key_string
5343
-     * @return null|array
5344
-     * @throws \EE_Error
5345
-     */
5346
-    public function parse_index_primary_key_string($index_primary_key_string)
5347
-    {
5348
-        $key_fields = $this->get_combined_primary_key_fields();
5349
-        //check all of them are in the $id
5350
-        $key_vals_in_combined_pk = array();
5351
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5352
-        foreach ($key_fields as $key_field_name => $field_obj) {
5353
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5354
-                return null;
5355
-            }
5356
-        }
5357
-        return $key_vals_in_combined_pk;
5358
-    }
5359
-
5360
-
5361
-
5362
-    /**
5363
-     * verifies that an array of key-value pairs for model fields has a key
5364
-     * for each field comprising the primary key index
5365
-     *
5366
-     * @param array $key_vals
5367
-     * @return boolean
5368
-     * @throws \EE_Error
5369
-     */
5370
-    public function has_all_combined_primary_key_fields($key_vals)
5371
-    {
5372
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5373
-        foreach ($keys_it_should_have as $key) {
5374
-            if (! isset($key_vals[$key])) {
5375
-                return false;
5376
-            }
5377
-        }
5378
-        return true;
5379
-    }
5380
-
5381
-
5382
-
5383
-    /**
5384
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5385
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5386
-     *
5387
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5388
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5389
-     * @throws EE_Error
5390
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5391
-     *                                                              indexed)
5392
-     */
5393
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5394
-    {
5395
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5396
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5397
-        } elseif (is_array($model_object_or_attributes_array)) {
5398
-            $attributes_array = $model_object_or_attributes_array;
5399
-        } else {
5400
-            throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5401
-                "event_espresso"), $model_object_or_attributes_array));
5402
-        }
5403
-        //even copies obviously won't have the same ID, so remove the primary key
5404
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5405
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5406
-            unset($attributes_array[$this->primary_key_name()]);
5407
-        }
5408
-        if (isset($query_params[0])) {
5409
-            $query_params[0] = array_merge($attributes_array, $query_params);
5410
-        } else {
5411
-            $query_params[0] = $attributes_array;
5412
-        }
5413
-        return $this->get_all($query_params);
5414
-    }
5415
-
5416
-
5417
-
5418
-    /**
5419
-     * Gets the first copy we find. See get_all_copies for more details
5420
-     *
5421
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5422
-     * @param array $query_params
5423
-     * @return EE_Base_Class
5424
-     * @throws \EE_Error
5425
-     */
5426
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5427
-    {
5428
-        if (! is_array($query_params)) {
5429
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5430
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5431
-                    gettype($query_params)), '4.6.0');
5432
-            $query_params = array();
5433
-        }
5434
-        $query_params['limit'] = 1;
5435
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5436
-        if (is_array($copies)) {
5437
-            return array_shift($copies);
5438
-        } else {
5439
-            return null;
5440
-        }
5441
-    }
5442
-
5443
-
5444
-
5445
-    /**
5446
-     * Updates the item with the specified id. Ignores default query parameters because
5447
-     * we have specified the ID, and its assumed we KNOW what we're doing
5448
-     *
5449
-     * @param array      $fields_n_values keys are field names, values are their new values
5450
-     * @param int|string $id              the value of the primary key to update
5451
-     * @return int number of rows updated
5452
-     * @throws \EE_Error
5453
-     */
5454
-    public function update_by_ID($fields_n_values, $id)
5455
-    {
5456
-        $query_params = array(
5457
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5458
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5459
-        );
5460
-        return $this->update($fields_n_values, $query_params);
5461
-    }
5462
-
5463
-
5464
-
5465
-    /**
5466
-     * Changes an operator which was supplied to the models into one usable in SQL
5467
-     *
5468
-     * @param string $operator_supplied
5469
-     * @return string an operator which can be used in SQL
5470
-     * @throws EE_Error
5471
-     */
5472
-    private function _prepare_operator_for_sql($operator_supplied)
5473
-    {
5474
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5475
-            : null;
5476
-        if ($sql_operator) {
5477
-            return $sql_operator;
5478
-        } else {
5479
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5480
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5481
-        }
5482
-    }
5483
-
5484
-
5485
-
5486
-    /**
5487
-     * Gets an array where keys are the primary keys and values are their 'names'
5488
-     * (as determined by the model object's name() function, which is often overridden)
5489
-     *
5490
-     * @param array $query_params like get_all's
5491
-     * @return string[]
5492
-     * @throws \EE_Error
5493
-     */
5494
-    public function get_all_names($query_params = array())
5495
-    {
5496
-        $objs = $this->get_all($query_params);
5497
-        $names = array();
5498
-        foreach ($objs as $obj) {
5499
-            $names[$obj->ID()] = $obj->name();
5500
-        }
5501
-        return $names;
5502
-    }
5503
-
5504
-
5505
-
5506
-    /**
5507
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5508
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5509
-     * this is duplicated effort and reduces efficiency) you would be better to use
5510
-     * array_keys() on $model_objects.
5511
-     *
5512
-     * @param \EE_Base_Class[] $model_objects
5513
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5514
-     *                                               in the returned array
5515
-     * @return array
5516
-     * @throws \EE_Error
5517
-     */
5518
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5519
-    {
5520
-        if (! $this->has_primary_key_field()) {
5521
-            if (WP_DEBUG) {
5522
-                EE_Error::add_error(
5523
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5524
-                    __FILE__,
5525
-                    __FUNCTION__,
5526
-                    __LINE__
5527
-                );
5528
-            }
5529
-        }
5530
-        $IDs = array();
5531
-        foreach ($model_objects as $model_object) {
5532
-            $id = $model_object->ID();
5533
-            if (! $id) {
5534
-                if ($filter_out_empty_ids) {
5535
-                    continue;
5536
-                }
5537
-                if (WP_DEBUG) {
5538
-                    EE_Error::add_error(
5539
-                        __(
5540
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5541
-                            'event_espresso'
5542
-                        ),
5543
-                        __FILE__,
5544
-                        __FUNCTION__,
5545
-                        __LINE__
5546
-                    );
5547
-                }
5548
-            }
5549
-            $IDs[] = $id;
5550
-        }
5551
-        return $IDs;
5552
-    }
5553
-
5554
-
5555
-
5556
-    /**
5557
-     * Returns the string used in capabilities relating to this model. If there
5558
-     * are no capabilities that relate to this model returns false
5559
-     *
5560
-     * @return string|false
5561
-     */
5562
-    public function cap_slug()
5563
-    {
5564
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5565
-    }
5566
-
5567
-
5568
-
5569
-    /**
5570
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5571
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5572
-     * only returns the cap restrictions array in that context (ie, the array
5573
-     * at that key)
5574
-     *
5575
-     * @param string $context
5576
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5577
-     * @throws \EE_Error
5578
-     */
5579
-    public function cap_restrictions($context = EEM_Base::caps_read)
5580
-    {
5581
-        EEM_Base::verify_is_valid_cap_context($context);
5582
-        //check if we ought to run the restriction generator first
5583
-        if (
5584
-            isset($this->_cap_restriction_generators[$context])
5585
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5586
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5587
-        ) {
5588
-            $this->_cap_restrictions[$context] = array_merge(
5589
-                $this->_cap_restrictions[$context],
5590
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5591
-            );
5592
-        }
5593
-        //and make sure we've finalized the construction of each restriction
5594
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5595
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5596
-                $where_conditions_obj->_finalize_construct($this);
5597
-            }
5598
-        }
5599
-        return $this->_cap_restrictions[$context];
5600
-    }
5601
-
5602
-
5603
-
5604
-    /**
5605
-     * Indicating whether or not this model thinks its a wp core model
5606
-     *
5607
-     * @return boolean
5608
-     */
5609
-    public function is_wp_core_model()
5610
-    {
5611
-        return $this->_wp_core_model;
5612
-    }
5613
-
5614
-
5615
-
5616
-    /**
5617
-     * Gets all the caps that are missing which impose a restriction on
5618
-     * queries made in this context
5619
-     *
5620
-     * @param string $context one of EEM_Base::caps_ constants
5621
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5622
-     * @throws \EE_Error
5623
-     */
5624
-    public function caps_missing($context = EEM_Base::caps_read)
5625
-    {
5626
-        $missing_caps = array();
5627
-        $cap_restrictions = $this->cap_restrictions($context);
5628
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5629
-            if (! EE_Capabilities::instance()
5630
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5631
-            ) {
5632
-                $missing_caps[$cap] = $restriction_if_no_cap;
5633
-            }
5634
-        }
5635
-        return $missing_caps;
5636
-    }
5637
-
5638
-
5639
-
5640
-    /**
5641
-     * Gets the mapping from capability contexts to action strings used in capability names
5642
-     *
5643
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5644
-     * one of 'read', 'edit', or 'delete'
5645
-     */
5646
-    public function cap_contexts_to_cap_action_map()
5647
-    {
5648
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5649
-            $this);
5650
-    }
5651
-
5652
-
5653
-
5654
-    /**
5655
-     * Gets the action string for the specified capability context
5656
-     *
5657
-     * @param string $context
5658
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5659
-     * @throws \EE_Error
5660
-     */
5661
-    public function cap_action_for_context($context)
5662
-    {
5663
-        $mapping = $this->cap_contexts_to_cap_action_map();
5664
-        if (isset($mapping[$context])) {
5665
-            return $mapping[$context];
5666
-        }
5667
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5668
-            return $action;
5669
-        }
5670
-        throw new EE_Error(
5671
-            sprintf(
5672
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5673
-                $context,
5674
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5675
-            )
5676
-        );
5677
-    }
5678
-
5679
-
5680
-
5681
-    /**
5682
-     * Returns all the capability contexts which are valid when querying models
5683
-     *
5684
-     * @return array
5685
-     */
5686
-    public static function valid_cap_contexts()
5687
-    {
5688
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5689
-            self::caps_read,
5690
-            self::caps_read_admin,
5691
-            self::caps_edit,
5692
-            self::caps_delete,
5693
-        ));
5694
-    }
5695
-
5696
-
5697
-
5698
-    /**
5699
-     * Returns all valid options for 'default_where_conditions'
5700
-     *
5701
-     * @return array
5702
-     */
5703
-    public static function valid_default_where_conditions()
5704
-    {
5705
-        return array(
5706
-            EEM_Base::default_where_conditions_all,
5707
-            EEM_Base::default_where_conditions_this_only,
5708
-            EEM_Base::default_where_conditions_others_only,
5709
-            EEM_Base::default_where_conditions_minimum_all,
5710
-            EEM_Base::default_where_conditions_minimum_others,
5711
-            EEM_Base::default_where_conditions_none
5712
-        );
5713
-    }
5714
-
5715
-    // public static function default_where_conditions_full
5716
-    /**
5717
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5718
-     *
5719
-     * @param string $context
5720
-     * @return bool
5721
-     * @throws \EE_Error
5722
-     */
5723
-    static public function verify_is_valid_cap_context($context)
5724
-    {
5725
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5726
-        if (in_array($context, $valid_cap_contexts)) {
5727
-            return true;
5728
-        } else {
5729
-            throw new EE_Error(
5730
-                sprintf(
5731
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5732
-                        'event_espresso'),
5733
-                    $context,
5734
-                    'EEM_Base',
5735
-                    implode(',', $valid_cap_contexts)
5736
-                )
5737
-            );
5738
-        }
5739
-    }
5740
-
5741
-
5742
-
5743
-    /**
5744
-     * Clears all the models field caches. This is only useful when a sub-class
5745
-     * might have added a field or something and these caches might be invalidated
5746
-     */
5747
-    protected function _invalidate_field_caches()
5748
-    {
5749
-        $this->_cache_foreign_key_to_fields = array();
5750
-        $this->_cached_fields = null;
5751
-        $this->_cached_fields_non_db_only = null;
5752
-    }
5753
-
5754
-
5755
-
5756
-    /**
5757
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5758
-     * (eg "and", "or", "not").
5759
-     *
5760
-     * @return array
5761
-     */
5762
-    public function logic_query_param_keys()
5763
-    {
5764
-        return $this->_logic_query_param_keys;
5765
-    }
5766
-
5767
-
5768
-
5769
-    /**
5770
-     * Determines whether or not the where query param array key is for a logic query param.
5771
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5772
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5773
-     *
5774
-     * @param $query_param_key
5775
-     * @return bool
5776
-     */
5777
-    public function is_logic_query_param_key($query_param_key)
5778
-    {
5779
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5780
-            if ($query_param_key === $logic_query_param_key
5781
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5782
-            ) {
5783
-                return true;
5784
-            }
5785
-        }
5786
-        return false;
5787
-    }
3610
+		}
3611
+		return $null_friendly_where_conditions;
3612
+	}
3613
+
3614
+
3615
+
3616
+	/**
3617
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3618
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3619
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3620
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3621
+	 *
3622
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3623
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3624
+	 */
3625
+	private function _get_default_where_conditions($model_relation_path = null)
3626
+	{
3627
+		if ($this->_ignore_where_strategy) {
3628
+			return array();
3629
+		}
3630
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3631
+	}
3632
+
3633
+
3634
+
3635
+	/**
3636
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3637
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3638
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3639
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3640
+	 * Similar to _get_default_where_conditions
3641
+	 *
3642
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3643
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3644
+	 */
3645
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3646
+	{
3647
+		if ($this->_ignore_where_strategy) {
3648
+			return array();
3649
+		}
3650
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3651
+	}
3652
+
3653
+
3654
+
3655
+	/**
3656
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3657
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3658
+	 *
3659
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3660
+	 * @return string
3661
+	 * @throws \EE_Error
3662
+	 */
3663
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3664
+	{
3665
+		$selects = $this->_get_columns_to_select_for_this_model();
3666
+		foreach (
3667
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3668
+			$name_of_other_model_included
3669
+		) {
3670
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3671
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3672
+			foreach ($other_model_selects as $key => $value) {
3673
+				$selects[] = $value;
3674
+			}
3675
+		}
3676
+		return implode(", ", $selects);
3677
+	}
3678
+
3679
+
3680
+
3681
+	/**
3682
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3683
+	 * So that's going to be the columns for all the fields on the model
3684
+	 *
3685
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3686
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3687
+	 */
3688
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3689
+	{
3690
+		$fields = $this->field_settings();
3691
+		$selects = array();
3692
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3693
+			$this->get_this_model_name());
3694
+		foreach ($fields as $field_obj) {
3695
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3696
+						 . $field_obj->get_table_alias()
3697
+						 . "."
3698
+						 . $field_obj->get_table_column()
3699
+						 . " AS '"
3700
+						 . $table_alias_with_model_relation_chain_prefix
3701
+						 . $field_obj->get_table_alias()
3702
+						 . "."
3703
+						 . $field_obj->get_table_column()
3704
+						 . "'";
3705
+		}
3706
+		//make sure we are also getting the PKs of each table
3707
+		$tables = $this->get_tables();
3708
+		if (count($tables) > 1) {
3709
+			foreach ($tables as $table_obj) {
3710
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3711
+									   . $table_obj->get_fully_qualified_pk_column();
3712
+				if (! in_array($qualified_pk_column, $selects)) {
3713
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3714
+				}
3715
+			}
3716
+		}
3717
+		return $selects;
3718
+	}
3719
+
3720
+
3721
+
3722
+	/**
3723
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3724
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3725
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3726
+	 * SQL for joining, and the data types
3727
+	 *
3728
+	 * @param null|string                 $original_query_param
3729
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3730
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3731
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3732
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3733
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3734
+	 *                                                          or 'Registration's
3735
+	 * @param string                      $original_query_param what it originally was (eg
3736
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3737
+	 *                                                          matches $query_param
3738
+	 * @throws EE_Error
3739
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3740
+	 */
3741
+	private function _extract_related_model_info_from_query_param(
3742
+		$query_param,
3743
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3744
+		$query_param_type,
3745
+		$original_query_param = null
3746
+	) {
3747
+		if ($original_query_param === null) {
3748
+			$original_query_param = $query_param;
3749
+		}
3750
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3751
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3752
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3753
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3754
+		//check to see if we have a field on this model
3755
+		$this_model_fields = $this->field_settings(true);
3756
+		if (array_key_exists($query_param, $this_model_fields)) {
3757
+			if ($allow_fields) {
3758
+				return;
3759
+			} else {
3760
+				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3761
+					"event_espresso"),
3762
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3763
+			}
3764
+		} //check if this is a special logic query param
3765
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3766
+			if ($allow_logic_query_params) {
3767
+				return;
3768
+			} else {
3769
+				throw new EE_Error(
3770
+					sprintf(
3771
+						__('Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
3772
+							'event_espresso'),
3773
+						implode('", "', $this->_logic_query_param_keys),
3774
+						$query_param,
3775
+						get_class($this),
3776
+						'<br />',
3777
+						"\t"
3778
+						. ' $passed_in_query_info = <pre>'
3779
+						. print_r($passed_in_query_info, true)
3780
+						. '</pre>'
3781
+						. "\n\t"
3782
+						. ' $query_param_type = '
3783
+						. $query_param_type
3784
+						. "\n\t"
3785
+						. ' $original_query_param = '
3786
+						. $original_query_param
3787
+					)
3788
+				);
3789
+			}
3790
+		} //check if it's a custom selection
3791
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3792
+			return;
3793
+		}
3794
+		//check if has a model name at the beginning
3795
+		//and
3796
+		//check if it's a field on a related model
3797
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3798
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3799
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3800
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3801
+				if ($query_param === '') {
3802
+					//nothing left to $query_param
3803
+					//we should actually end in a field name, not a model like this!
3804
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3805
+						"event_espresso"),
3806
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3807
+				} else {
3808
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3809
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3810
+						$passed_in_query_info, $query_param_type, $original_query_param);
3811
+					return;
3812
+				}
3813
+			} elseif ($query_param === $valid_related_model_name) {
3814
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3815
+				return;
3816
+			}
3817
+		}
3818
+		//ok so $query_param didn't start with a model name
3819
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3820
+		//it's wack, that's what it is
3821
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3822
+			"event_espresso"),
3823
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3824
+	}
3825
+
3826
+
3827
+
3828
+	/**
3829
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3830
+	 * and store it on $passed_in_query_info
3831
+	 *
3832
+	 * @param string                      $model_name
3833
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3834
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3835
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3836
+	 *                                                          and are adding a join to 'Payment' with the original
3837
+	 *                                                          query param key
3838
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3839
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3840
+	 *                                                          Payment wants to add default query params so that it
3841
+	 *                                                          will know what models to prepend onto its default query
3842
+	 *                                                          params or in case it wants to rename tables (in case
3843
+	 *                                                          there are multiple joins to the same table)
3844
+	 * @return void
3845
+	 * @throws \EE_Error
3846
+	 */
3847
+	private function _add_join_to_model(
3848
+		$model_name,
3849
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3850
+		$original_query_param
3851
+	) {
3852
+		$relation_obj = $this->related_settings_for($model_name);
3853
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3854
+		//check if the relation is HABTM, because then we're essentially doing two joins
3855
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3856
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3857
+			$join_model_obj = $relation_obj->get_join_model();
3858
+			//replace the model specified with the join model for this relation chain, whi
3859
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3860
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3861
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3862
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3863
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3864
+			$passed_in_query_info->merge($new_query_info);
3865
+		}
3866
+		//now just join to the other table pointed to by the relation object, and add its data types
3867
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3868
+			array($model_relation_chain => $model_name),
3869
+			$relation_obj->get_join_statement($model_relation_chain));
3870
+		$passed_in_query_info->merge($new_query_info);
3871
+	}
3872
+
3873
+
3874
+
3875
+	/**
3876
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3877
+	 *
3878
+	 * @param array $where_params like EEM_Base::get_all
3879
+	 * @return string of SQL
3880
+	 * @throws \EE_Error
3881
+	 */
3882
+	private function _construct_where_clause($where_params)
3883
+	{
3884
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3885
+		if ($SQL) {
3886
+			return " WHERE " . $SQL;
3887
+		} else {
3888
+			return '';
3889
+		}
3890
+	}
3891
+
3892
+
3893
+
3894
+	/**
3895
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3896
+	 * and should be passed HAVING parameters, not WHERE parameters
3897
+	 *
3898
+	 * @param array $having_params
3899
+	 * @return string
3900
+	 * @throws \EE_Error
3901
+	 */
3902
+	private function _construct_having_clause($having_params)
3903
+	{
3904
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3905
+		if ($SQL) {
3906
+			return " HAVING " . $SQL;
3907
+		} else {
3908
+			return '';
3909
+		}
3910
+	}
3911
+
3912
+
3913
+
3914
+	/**
3915
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3916
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3917
+	 * EEM_Attendee.
3918
+	 *
3919
+	 * @param string $field_name
3920
+	 * @param string $model_name
3921
+	 * @return EE_Model_Field_Base
3922
+	 * @throws EE_Error
3923
+	 */
3924
+	protected function _get_field_on_model($field_name, $model_name)
3925
+	{
3926
+		$model_class = 'EEM_' . $model_name;
3927
+		$model_filepath = $model_class . ".model.php";
3928
+		if (is_readable($model_filepath)) {
3929
+			require_once($model_filepath);
3930
+			$model_instance = call_user_func($model_name . "::instance");
3931
+			/* @var $model_instance EEM_Base */
3932
+			return $model_instance->field_settings_for($field_name);
3933
+		} else {
3934
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3935
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3936
+		}
3937
+	}
3938
+
3939
+
3940
+
3941
+	/**
3942
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3943
+	 * Event_Meta.meta_value = 'foo'))"
3944
+	 *
3945
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3946
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3947
+	 * @throws EE_Error
3948
+	 * @return string of SQL
3949
+	 */
3950
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3951
+	{
3952
+		$where_clauses = array();
3953
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3954
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3955
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3956
+				switch ($query_param) {
3957
+					case 'not':
3958
+					case 'NOT':
3959
+						$where_clauses[] = "! ("
3960
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3961
+								$glue)
3962
+										   . ")";
3963
+						break;
3964
+					case 'and':
3965
+					case 'AND':
3966
+						$where_clauses[] = " ("
3967
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3968
+								' AND ')
3969
+										   . ")";
3970
+						break;
3971
+					case 'or':
3972
+					case 'OR':
3973
+						$where_clauses[] = " ("
3974
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3975
+								' OR ')
3976
+										   . ")";
3977
+						break;
3978
+				}
3979
+			} else {
3980
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3981
+				//if it's not a normal field, maybe it's a custom selection?
3982
+				if (! $field_obj) {
3983
+					if (isset($this->_custom_selections[$query_param][1])) {
3984
+						$field_obj = $this->_custom_selections[$query_param][1];
3985
+					} else {
3986
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3987
+							"event_espresso"), $query_param));
3988
+					}
3989
+				}
3990
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3991
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3992
+			}
3993
+		}
3994
+		return $where_clauses ? implode($glue, $where_clauses) : '';
3995
+	}
3996
+
3997
+
3998
+
3999
+	/**
4000
+	 * Takes the input parameter and extract the table name (alias) and column name
4001
+	 *
4002
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4003
+	 * @throws EE_Error
4004
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4005
+	 */
4006
+	private function _deduce_column_name_from_query_param($query_param)
4007
+	{
4008
+		$field = $this->_deduce_field_from_query_param($query_param);
4009
+		if ($field) {
4010
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4011
+				$query_param);
4012
+			return $table_alias_prefix . $field->get_qualified_column();
4013
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4014
+			//maybe it's custom selection item?
4015
+			//if so, just use it as the "column name"
4016
+			return $query_param;
4017
+		} else {
4018
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4019
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4020
+		}
4021
+	}
4022
+
4023
+
4024
+
4025
+	/**
4026
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4027
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4028
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4029
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4030
+	 *
4031
+	 * @param string $condition_query_param_key
4032
+	 * @return string
4033
+	 */
4034
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4035
+	{
4036
+		$pos_of_star = strpos($condition_query_param_key, '*');
4037
+		if ($pos_of_star === false) {
4038
+			return $condition_query_param_key;
4039
+		} else {
4040
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4041
+			return $condition_query_param_sans_star;
4042
+		}
4043
+	}
4044
+
4045
+
4046
+
4047
+	/**
4048
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4049
+	 *
4050
+	 * @param                            mixed      array | string    $op_and_value
4051
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4052
+	 * @throws EE_Error
4053
+	 * @return string
4054
+	 */
4055
+	private function _construct_op_and_value($op_and_value, $field_obj)
4056
+	{
4057
+		if (is_array($op_and_value)) {
4058
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4059
+			if (! $operator) {
4060
+				$php_array_like_string = array();
4061
+				foreach ($op_and_value as $key => $value) {
4062
+					$php_array_like_string[] = "$key=>$value";
4063
+				}
4064
+				throw new EE_Error(
4065
+					sprintf(
4066
+						__(
4067
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4068
+							"event_espresso"
4069
+						),
4070
+						implode(",", $php_array_like_string)
4071
+					)
4072
+				);
4073
+			}
4074
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4075
+		} else {
4076
+			$operator = '=';
4077
+			$value = $op_and_value;
4078
+		}
4079
+		//check to see if the value is actually another field
4080
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4081
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4082
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4083
+			//in this case, the value should be an array, or at least a comma-separated list
4084
+			//it will need to handle a little differently
4085
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4086
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4087
+			return $operator . SP . $cleaned_value;
4088
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4089
+			//the value should be an array with count of two.
4090
+			if (count($value) !== 2) {
4091
+				throw new EE_Error(
4092
+					sprintf(
4093
+						__(
4094
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4095
+							'event_espresso'
4096
+						),
4097
+						"BETWEEN"
4098
+					)
4099
+				);
4100
+			}
4101
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4102
+			return $operator . SP . $cleaned_value;
4103
+		} elseif (in_array($operator, $this->_null_style_operators)) {
4104
+			if ($value !== null) {
4105
+				throw new EE_Error(
4106
+					sprintf(
4107
+						__(
4108
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4109
+							"event_espresso"
4110
+						),
4111
+						$value,
4112
+						$operator
4113
+					)
4114
+				);
4115
+			}
4116
+			return $operator;
4117
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
4118
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4119
+			//remove other junk. So just treat it as a string.
4120
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4121
+		} elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4122
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4123
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4124
+			throw new EE_Error(
4125
+				sprintf(
4126
+					__(
4127
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4128
+						'event_espresso'
4129
+					),
4130
+					$operator,
4131
+					$operator
4132
+				)
4133
+			);
4134
+		} elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4135
+			throw new EE_Error(
4136
+				sprintf(
4137
+					__(
4138
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4139
+						'event_espresso'
4140
+					),
4141
+					$operator,
4142
+					$operator
4143
+				)
4144
+			);
4145
+		} else {
4146
+			throw new EE_Error(
4147
+				sprintf(
4148
+					__(
4149
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4150
+						"event_espresso"
4151
+					),
4152
+					http_build_query($op_and_value)
4153
+				)
4154
+			);
4155
+		}
4156
+	}
4157
+
4158
+
4159
+
4160
+	/**
4161
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4162
+	 *
4163
+	 * @param array                      $values
4164
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4165
+	 *                                              '%s'
4166
+	 * @return string
4167
+	 * @throws \EE_Error
4168
+	 */
4169
+	public function _construct_between_value($values, $field_obj)
4170
+	{
4171
+		$cleaned_values = array();
4172
+		foreach ($values as $value) {
4173
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4174
+		}
4175
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4176
+	}
4177
+
4178
+
4179
+
4180
+	/**
4181
+	 * Takes an array or a comma-separated list of $values and cleans them
4182
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4183
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4184
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4185
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4186
+	 *
4187
+	 * @param mixed                      $values    array or comma-separated string
4188
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4189
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4190
+	 * @throws \EE_Error
4191
+	 */
4192
+	public function _construct_in_value($values, $field_obj)
4193
+	{
4194
+		//check if the value is a CSV list
4195
+		if (is_string($values)) {
4196
+			//in which case, turn it into an array
4197
+			$values = explode(",", $values);
4198
+		}
4199
+		$cleaned_values = array();
4200
+		foreach ($values as $value) {
4201
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4202
+		}
4203
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4204
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4205
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4206
+		if (empty($cleaned_values)) {
4207
+			$all_fields = $this->field_settings();
4208
+			$a_field = array_shift($all_fields);
4209
+			$main_table = $this->_get_main_table();
4210
+			$cleaned_values[] = "SELECT "
4211
+								. $a_field->get_table_column()
4212
+								. " FROM "
4213
+								. $main_table->get_table_name()
4214
+								. " WHERE FALSE";
4215
+		}
4216
+		return "(" . implode(",", $cleaned_values) . ")";
4217
+	}
4218
+
4219
+
4220
+
4221
+	/**
4222
+	 * @param mixed                      $value
4223
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4224
+	 * @throws EE_Error
4225
+	 * @return false|null|string
4226
+	 */
4227
+	private function _wpdb_prepare_using_field($value, $field_obj)
4228
+	{
4229
+		/** @type WPDB $wpdb */
4230
+		global $wpdb;
4231
+		if ($field_obj instanceof EE_Model_Field_Base) {
4232
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4233
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4234
+		} else {//$field_obj should really just be a data type
4235
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4236
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4237
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4238
+			}
4239
+			return $wpdb->prepare($field_obj, $value);
4240
+		}
4241
+	}
4242
+
4243
+
4244
+
4245
+	/**
4246
+	 * Takes the input parameter and finds the model field that it indicates.
4247
+	 *
4248
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4249
+	 * @throws EE_Error
4250
+	 * @return EE_Model_Field_Base
4251
+	 */
4252
+	protected function _deduce_field_from_query_param($query_param_name)
4253
+	{
4254
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4255
+		//which will help us find the database table and column
4256
+		$query_param_parts = explode(".", $query_param_name);
4257
+		if (empty($query_param_parts)) {
4258
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4259
+				'event_espresso'), $query_param_name));
4260
+		}
4261
+		$number_of_parts = count($query_param_parts);
4262
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4263
+		if ($number_of_parts === 1) {
4264
+			$field_name = $last_query_param_part;
4265
+			$model_obj = $this;
4266
+		} else {// $number_of_parts >= 2
4267
+			//the last part is the column name, and there are only 2parts. therefore...
4268
+			$field_name = $last_query_param_part;
4269
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4270
+		}
4271
+		try {
4272
+			return $model_obj->field_settings_for($field_name);
4273
+		} catch (EE_Error $e) {
4274
+			return null;
4275
+		}
4276
+	}
4277
+
4278
+
4279
+
4280
+	/**
4281
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4282
+	 * alias and column which corresponds to it
4283
+	 *
4284
+	 * @param string $field_name
4285
+	 * @throws EE_Error
4286
+	 * @return string
4287
+	 */
4288
+	public function _get_qualified_column_for_field($field_name)
4289
+	{
4290
+		$all_fields = $this->field_settings();
4291
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4292
+		if ($field) {
4293
+			return $field->get_qualified_column();
4294
+		} else {
4295
+			throw new EE_Error(sprintf(__("There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4296
+				'event_espresso'), $field_name, get_class($this)));
4297
+		}
4298
+	}
4299
+
4300
+
4301
+
4302
+	/**
4303
+	 * constructs the select use on special limit joins
4304
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4305
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4306
+	 * (as that is typically where the limits would be set).
4307
+	 *
4308
+	 * @param  string       $table_alias The table the select is being built for
4309
+	 * @param  mixed|string $limit       The limit for this select
4310
+	 * @return string                The final select join element for the query.
4311
+	 */
4312
+	public function _construct_limit_join_select($table_alias, $limit)
4313
+	{
4314
+		$SQL = '';
4315
+		foreach ($this->_tables as $table_obj) {
4316
+			if ($table_obj instanceof EE_Primary_Table) {
4317
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4318
+					? $table_obj->get_select_join_limit($limit)
4319
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4320
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4321
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4322
+					? $table_obj->get_select_join_limit_join($limit)
4323
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4324
+			}
4325
+		}
4326
+		return $SQL;
4327
+	}
4328
+
4329
+
4330
+
4331
+	/**
4332
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4333
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4334
+	 *
4335
+	 * @return string SQL
4336
+	 * @throws \EE_Error
4337
+	 */
4338
+	public function _construct_internal_join()
4339
+	{
4340
+		$SQL = $this->_get_main_table()->get_table_sql();
4341
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4342
+		return $SQL;
4343
+	}
4344
+
4345
+
4346
+
4347
+	/**
4348
+	 * Constructs the SQL for joining all the tables on this model.
4349
+	 * Normally $alias should be the primary table's alias, but in cases where
4350
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4351
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4352
+	 * alias, this will construct SQL like:
4353
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4354
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4355
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4356
+	 *
4357
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4358
+	 * @return string
4359
+	 */
4360
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4361
+	{
4362
+		$SQL = '';
4363
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4364
+		foreach ($this->_tables as $table_obj) {
4365
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4366
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4367
+					//so we're joining to this table, meaning the table is already in
4368
+					//the FROM statement, BUT the primary table isn't. So we want
4369
+					//to add the inverse join sql
4370
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4371
+				} else {
4372
+					//just add a regular JOIN to this table from the primary table
4373
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4374
+				}
4375
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4376
+		}
4377
+		return $SQL;
4378
+	}
4379
+
4380
+
4381
+
4382
+	/**
4383
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4384
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4385
+	 * their data type (eg, '%s', '%d', etc)
4386
+	 *
4387
+	 * @return array
4388
+	 */
4389
+	public function _get_data_types()
4390
+	{
4391
+		$data_types = array();
4392
+		foreach ($this->field_settings() as $field_obj) {
4393
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4394
+			/** @var $field_obj EE_Model_Field_Base */
4395
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4396
+		}
4397
+		return $data_types;
4398
+	}
4399
+
4400
+
4401
+
4402
+	/**
4403
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4404
+	 *
4405
+	 * @param string $model_name
4406
+	 * @throws EE_Error
4407
+	 * @return EEM_Base
4408
+	 */
4409
+	public function get_related_model_obj($model_name)
4410
+	{
4411
+		$model_classname = "EEM_" . $model_name;
4412
+		if (! class_exists($model_classname)) {
4413
+			throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4414
+				'event_espresso'), $model_name, $model_classname));
4415
+		}
4416
+		return call_user_func($model_classname . "::instance");
4417
+	}
4418
+
4419
+
4420
+
4421
+	/**
4422
+	 * Returns the array of EE_ModelRelations for this model.
4423
+	 *
4424
+	 * @return EE_Model_Relation_Base[]
4425
+	 */
4426
+	public function relation_settings()
4427
+	{
4428
+		return $this->_model_relations;
4429
+	}
4430
+
4431
+
4432
+
4433
+	/**
4434
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4435
+	 * because without THOSE models, this model probably doesn't have much purpose.
4436
+	 * (Eg, without an event, datetimes have little purpose.)
4437
+	 *
4438
+	 * @return EE_Belongs_To_Relation[]
4439
+	 */
4440
+	public function belongs_to_relations()
4441
+	{
4442
+		$belongs_to_relations = array();
4443
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4444
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4445
+				$belongs_to_relations[$model_name] = $relation_obj;
4446
+			}
4447
+		}
4448
+		return $belongs_to_relations;
4449
+	}
4450
+
4451
+
4452
+
4453
+	/**
4454
+	 * Returns the specified EE_Model_Relation, or throws an exception
4455
+	 *
4456
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4457
+	 * @throws EE_Error
4458
+	 * @return EE_Model_Relation_Base
4459
+	 */
4460
+	public function related_settings_for($relation_name)
4461
+	{
4462
+		$relatedModels = $this->relation_settings();
4463
+		if (! array_key_exists($relation_name, $relatedModels)) {
4464
+			throw new EE_Error(
4465
+				sprintf(
4466
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4467
+						'event_espresso'),
4468
+					$relation_name,
4469
+					$this->_get_class_name(),
4470
+					implode(', ', array_keys($relatedModels))
4471
+				)
4472
+			);
4473
+		}
4474
+		return $relatedModels[$relation_name];
4475
+	}
4476
+
4477
+
4478
+
4479
+	/**
4480
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4481
+	 * fields
4482
+	 *
4483
+	 * @param string $fieldName
4484
+	 * @throws EE_Error
4485
+	 * @return EE_Model_Field_Base
4486
+	 */
4487
+	public function field_settings_for($fieldName)
4488
+	{
4489
+		$fieldSettings = $this->field_settings(true);
4490
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4491
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4492
+				get_class($this)));
4493
+		}
4494
+		return $fieldSettings[$fieldName];
4495
+	}
4496
+
4497
+
4498
+
4499
+	/**
4500
+	 * Checks if this field exists on this model
4501
+	 *
4502
+	 * @param string $fieldName a key in the model's _field_settings array
4503
+	 * @return boolean
4504
+	 */
4505
+	public function has_field($fieldName)
4506
+	{
4507
+		$fieldSettings = $this->field_settings(true);
4508
+		if (isset($fieldSettings[$fieldName])) {
4509
+			return true;
4510
+		} else {
4511
+			return false;
4512
+		}
4513
+	}
4514
+
4515
+
4516
+
4517
+	/**
4518
+	 * Returns whether or not this model has a relation to the specified model
4519
+	 *
4520
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4521
+	 * @return boolean
4522
+	 */
4523
+	public function has_relation($relation_name)
4524
+	{
4525
+		$relations = $this->relation_settings();
4526
+		if (isset($relations[$relation_name])) {
4527
+			return true;
4528
+		} else {
4529
+			return false;
4530
+		}
4531
+	}
4532
+
4533
+
4534
+
4535
+	/**
4536
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4537
+	 * Eg, on EE_Answer that would be ANS_ID field object
4538
+	 *
4539
+	 * @param $field_obj
4540
+	 * @return boolean
4541
+	 */
4542
+	public function is_primary_key_field($field_obj)
4543
+	{
4544
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4545
+	}
4546
+
4547
+
4548
+
4549
+	/**
4550
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4551
+	 * Eg, on EE_Answer that would be ANS_ID field object
4552
+	 *
4553
+	 * @return EE_Model_Field_Base
4554
+	 * @throws EE_Error
4555
+	 */
4556
+	public function get_primary_key_field()
4557
+	{
4558
+		if ($this->_primary_key_field === null) {
4559
+			foreach ($this->field_settings(true) as $field_obj) {
4560
+				if ($this->is_primary_key_field($field_obj)) {
4561
+					$this->_primary_key_field = $field_obj;
4562
+					break;
4563
+				}
4564
+			}
4565
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4566
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4567
+					get_class($this)));
4568
+			}
4569
+		}
4570
+		return $this->_primary_key_field;
4571
+	}
4572
+
4573
+
4574
+
4575
+	/**
4576
+	 * Returns whether or not not there is a primary key on this model.
4577
+	 * Internally does some caching.
4578
+	 *
4579
+	 * @return boolean
4580
+	 */
4581
+	public function has_primary_key_field()
4582
+	{
4583
+		if ($this->_has_primary_key_field === null) {
4584
+			try {
4585
+				$this->get_primary_key_field();
4586
+				$this->_has_primary_key_field = true;
4587
+			} catch (EE_Error $e) {
4588
+				$this->_has_primary_key_field = false;
4589
+			}
4590
+		}
4591
+		return $this->_has_primary_key_field;
4592
+	}
4593
+
4594
+
4595
+
4596
+	/**
4597
+	 * Finds the first field of type $field_class_name.
4598
+	 *
4599
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4600
+	 *                                 EE_Foreign_Key_Field, etc
4601
+	 * @return EE_Model_Field_Base or null if none is found
4602
+	 */
4603
+	public function get_a_field_of_type($field_class_name)
4604
+	{
4605
+		foreach ($this->field_settings() as $field) {
4606
+			if ($field instanceof $field_class_name) {
4607
+				return $field;
4608
+			}
4609
+		}
4610
+		return null;
4611
+	}
4612
+
4613
+
4614
+
4615
+	/**
4616
+	 * Gets a foreign key field pointing to model.
4617
+	 *
4618
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4619
+	 * @return EE_Foreign_Key_Field_Base
4620
+	 * @throws EE_Error
4621
+	 */
4622
+	public function get_foreign_key_to($model_name)
4623
+	{
4624
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4625
+			foreach ($this->field_settings() as $field) {
4626
+				if (
4627
+					$field instanceof EE_Foreign_Key_Field_Base
4628
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4629
+				) {
4630
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4631
+					break;
4632
+				}
4633
+			}
4634
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4635
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4636
+					'event_espresso'), $model_name, get_class($this)));
4637
+			}
4638
+		}
4639
+		return $this->_cache_foreign_key_to_fields[$model_name];
4640
+	}
4641
+
4642
+
4643
+
4644
+	/**
4645
+	 * Gets the actual table for the table alias
4646
+	 *
4647
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4648
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4649
+	 *                            Either one works
4650
+	 * @return EE_Table_Base
4651
+	 */
4652
+	public function get_table_for_alias($table_alias)
4653
+	{
4654
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4655
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4656
+	}
4657
+
4658
+
4659
+
4660
+	/**
4661
+	 * Returns a flat array of all field son this model, instead of organizing them
4662
+	 * by table_alias as they are in the constructor.
4663
+	 *
4664
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4665
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4666
+	 */
4667
+	public function field_settings($include_db_only_fields = false)
4668
+	{
4669
+		if ($include_db_only_fields) {
4670
+			if ($this->_cached_fields === null) {
4671
+				$this->_cached_fields = array();
4672
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4673
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4674
+						$this->_cached_fields[$field_name] = $field_obj;
4675
+					}
4676
+				}
4677
+			}
4678
+			return $this->_cached_fields;
4679
+		} else {
4680
+			if ($this->_cached_fields_non_db_only === null) {
4681
+				$this->_cached_fields_non_db_only = array();
4682
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4683
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4684
+						/** @var $field_obj EE_Model_Field_Base */
4685
+						if (! $field_obj->is_db_only_field()) {
4686
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4687
+						}
4688
+					}
4689
+				}
4690
+			}
4691
+			return $this->_cached_fields_non_db_only;
4692
+		}
4693
+	}
4694
+
4695
+
4696
+
4697
+	/**
4698
+	 *        cycle though array of attendees and create objects out of each item
4699
+	 *
4700
+	 * @access        private
4701
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4702
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4703
+	 *                           numerically indexed)
4704
+	 * @throws \EE_Error
4705
+	 */
4706
+	protected function _create_objects($rows = array())
4707
+	{
4708
+		$array_of_objects = array();
4709
+		if (empty($rows)) {
4710
+			return array();
4711
+		}
4712
+		$count_if_model_has_no_primary_key = 0;
4713
+		$has_primary_key = $this->has_primary_key_field();
4714
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4715
+		foreach ((array)$rows as $row) {
4716
+			if (empty($row)) {
4717
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4718
+				return array();
4719
+			}
4720
+			//check if we've already set this object in the results array,
4721
+			//in which case there's no need to process it further (again)
4722
+			if ($has_primary_key) {
4723
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4724
+					$row,
4725
+					$primary_key_field->get_qualified_column(),
4726
+					$primary_key_field->get_table_column()
4727
+				);
4728
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4729
+					continue;
4730
+				}
4731
+			}
4732
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4733
+			if (! $classInstance) {
4734
+				throw new EE_Error(
4735
+					sprintf(
4736
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4737
+						$this->get_this_model_name(),
4738
+						http_build_query($row)
4739
+					)
4740
+				);
4741
+			}
4742
+			//set the timezone on the instantiated objects
4743
+			$classInstance->set_timezone($this->_timezone);
4744
+			//make sure if there is any timezone setting present that we set the timezone for the object
4745
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4746
+			$array_of_objects[$key] = $classInstance;
4747
+			//also, for all the relations of type BelongsTo, see if we can cache
4748
+			//those related models
4749
+			//(we could do this for other relations too, but if there are conditions
4750
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4751
+			//so it requires a little more thought than just caching them immediately...)
4752
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4753
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4754
+					//check if this model's INFO is present. If so, cache it on the model
4755
+					$other_model = $relation_obj->get_other_model();
4756
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4757
+					//if we managed to make a model object from the results, cache it on the main model object
4758
+					if ($other_model_obj_maybe) {
4759
+						//set timezone on these other model objects if they are present
4760
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4761
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4762
+					}
4763
+				}
4764
+			}
4765
+		}
4766
+		return $array_of_objects;
4767
+	}
4768
+
4769
+
4770
+
4771
+	/**
4772
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4773
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4774
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4775
+	 * object (as set in the model_field!).
4776
+	 *
4777
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4778
+	 */
4779
+	public function create_default_object()
4780
+	{
4781
+		$this_model_fields_and_values = array();
4782
+		//setup the row using default values;
4783
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4784
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4785
+		}
4786
+		$className = $this->_get_class_name();
4787
+		$classInstance = EE_Registry::instance()
4788
+									->load_class($className, array($this_model_fields_and_values), false, false);
4789
+		return $classInstance;
4790
+	}
4791
+
4792
+
4793
+
4794
+	/**
4795
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4796
+	 *                             or an stdClass where each property is the name of a column,
4797
+	 * @return EE_Base_Class
4798
+	 * @throws \EE_Error
4799
+	 */
4800
+	public function instantiate_class_from_array_or_object($cols_n_values)
4801
+	{
4802
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4803
+			$cols_n_values = get_object_vars($cols_n_values);
4804
+		}
4805
+		$primary_key = null;
4806
+		//make sure the array only has keys that are fields/columns on this model
4807
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4808
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4809
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4810
+		}
4811
+		$className = $this->_get_class_name();
4812
+		//check we actually found results that we can use to build our model object
4813
+		//if not, return null
4814
+		if ($this->has_primary_key_field()) {
4815
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4816
+				return null;
4817
+			}
4818
+		} else if ($this->unique_indexes()) {
4819
+			$first_column = reset($this_model_fields_n_values);
4820
+			if (empty($first_column)) {
4821
+				return null;
4822
+			}
4823
+		}
4824
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4825
+		if ($primary_key) {
4826
+			$classInstance = $this->get_from_entity_map($primary_key);
4827
+			if (! $classInstance) {
4828
+				$classInstance = EE_Registry::instance()
4829
+											->load_class($className,
4830
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4831
+				// add this new object to the entity map
4832
+				$classInstance = $this->add_to_entity_map($classInstance);
4833
+			}
4834
+		} else {
4835
+			$classInstance = EE_Registry::instance()
4836
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4837
+											true, false);
4838
+		}
4839
+		//it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4840
+		$this->set_timezone($classInstance->get_timezone());
4841
+		return $classInstance;
4842
+	}
4843
+
4844
+
4845
+
4846
+	/**
4847
+	 * Gets the model object from the  entity map if it exists
4848
+	 *
4849
+	 * @param int|string $id the ID of the model object
4850
+	 * @return EE_Base_Class
4851
+	 */
4852
+	public function get_from_entity_map($id)
4853
+	{
4854
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4855
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4856
+	}
4857
+
4858
+
4859
+
4860
+	/**
4861
+	 * add_to_entity_map
4862
+	 * Adds the object to the model's entity mappings
4863
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4864
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4865
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4866
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4867
+	 *        then this method should be called immediately after the update query
4868
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4869
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4870
+	 *
4871
+	 * @param    EE_Base_Class $object
4872
+	 * @throws EE_Error
4873
+	 * @return \EE_Base_Class
4874
+	 */
4875
+	public function add_to_entity_map(EE_Base_Class $object)
4876
+	{
4877
+		$className = $this->_get_class_name();
4878
+		if (! $object instanceof $className) {
4879
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4880
+				is_object($object) ? get_class($object) : $object, $className));
4881
+		}
4882
+		/** @var $object EE_Base_Class */
4883
+		if (! $object->ID()) {
4884
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4885
+				"event_espresso"), get_class($this)));
4886
+		}
4887
+		// double check it's not already there
4888
+		$classInstance = $this->get_from_entity_map($object->ID());
4889
+		if ($classInstance) {
4890
+			return $classInstance;
4891
+		} else {
4892
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4893
+			return $object;
4894
+		}
4895
+	}
4896
+
4897
+
4898
+
4899
+	/**
4900
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4901
+	 * if no identifier is provided, then the entire entity map is emptied
4902
+	 *
4903
+	 * @param int|string $id the ID of the model object
4904
+	 * @return boolean
4905
+	 */
4906
+	public function clear_entity_map($id = null)
4907
+	{
4908
+		if (empty($id)) {
4909
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4910
+			return true;
4911
+		}
4912
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4913
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4914
+			return true;
4915
+		}
4916
+		return false;
4917
+	}
4918
+
4919
+
4920
+
4921
+	/**
4922
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4923
+	 * Given an array where keys are column (or column alias) names and values,
4924
+	 * returns an array of their corresponding field names and database values
4925
+	 *
4926
+	 * @param array $cols_n_values
4927
+	 * @return array
4928
+	 */
4929
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4930
+	{
4931
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4932
+	}
4933
+
4934
+
4935
+
4936
+	/**
4937
+	 * _deduce_fields_n_values_from_cols_n_values
4938
+	 * Given an array where keys are column (or column alias) names and values,
4939
+	 * returns an array of their corresponding field names and database values
4940
+	 *
4941
+	 * @param string $cols_n_values
4942
+	 * @return array
4943
+	 */
4944
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4945
+	{
4946
+		$this_model_fields_n_values = array();
4947
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
4948
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4949
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4950
+			//there is a primary key on this table and its not set. Use defaults for all its columns
4951
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
4952
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4953
+					if (! $field_obj->is_db_only_field()) {
4954
+						//prepare field as if its coming from db
4955
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4956
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4957
+					}
4958
+				}
4959
+			} else {
4960
+				//the table's rows existed. Use their values
4961
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4962
+					if (! $field_obj->is_db_only_field()) {
4963
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4964
+							$cols_n_values, $field_obj->get_qualified_column(),
4965
+							$field_obj->get_table_column()
4966
+						);
4967
+					}
4968
+				}
4969
+			}
4970
+		}
4971
+		return $this_model_fields_n_values;
4972
+	}
4973
+
4974
+
4975
+
4976
+	/**
4977
+	 * @param $cols_n_values
4978
+	 * @param $qualified_column
4979
+	 * @param $regular_column
4980
+	 * @return null
4981
+	 */
4982
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4983
+	{
4984
+		$value = null;
4985
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4986
+		//does the field on the model relate to this column retrieved from the db?
4987
+		//or is it a db-only field? (not relating to the model)
4988
+		if (isset($cols_n_values[$qualified_column])) {
4989
+			$value = $cols_n_values[$qualified_column];
4990
+		} elseif (isset($cols_n_values[$regular_column])) {
4991
+			$value = $cols_n_values[$regular_column];
4992
+		}
4993
+		return $value;
4994
+	}
4995
+
4996
+
4997
+
4998
+	/**
4999
+	 * refresh_entity_map_from_db
5000
+	 * Makes sure the model object in the entity map at $id assumes the values
5001
+	 * of the database (opposite of EE_base_Class::save())
5002
+	 *
5003
+	 * @param int|string $id
5004
+	 * @return EE_Base_Class
5005
+	 * @throws \EE_Error
5006
+	 */
5007
+	public function refresh_entity_map_from_db($id)
5008
+	{
5009
+		$obj_in_map = $this->get_from_entity_map($id);
5010
+		if ($obj_in_map) {
5011
+			$wpdb_results = $this->_get_all_wpdb_results(
5012
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5013
+			);
5014
+			if ($wpdb_results && is_array($wpdb_results)) {
5015
+				$one_row = reset($wpdb_results);
5016
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5017
+					$obj_in_map->set_from_db($field_name, $db_value);
5018
+				}
5019
+				//clear the cache of related model objects
5020
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5021
+					$obj_in_map->clear_cache($relation_name, null, true);
5022
+				}
5023
+			}
5024
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5025
+			return $obj_in_map;
5026
+		} else {
5027
+			return $this->get_one_by_ID($id);
5028
+		}
5029
+	}
5030
+
5031
+
5032
+
5033
+	/**
5034
+	 * refresh_entity_map_with
5035
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5036
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5037
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5038
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5039
+	 *
5040
+	 * @param int|string    $id
5041
+	 * @param EE_Base_Class $replacing_model_obj
5042
+	 * @return \EE_Base_Class
5043
+	 * @throws \EE_Error
5044
+	 */
5045
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5046
+	{
5047
+		$obj_in_map = $this->get_from_entity_map($id);
5048
+		if ($obj_in_map) {
5049
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5050
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5051
+					$obj_in_map->set($field_name, $value);
5052
+				}
5053
+				//make the model object in the entity map's cache match the $replacing_model_obj
5054
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5055
+					$obj_in_map->clear_cache($relation_name, null, true);
5056
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5057
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5058
+					}
5059
+				}
5060
+			}
5061
+			return $obj_in_map;
5062
+		} else {
5063
+			$this->add_to_entity_map($replacing_model_obj);
5064
+			return $replacing_model_obj;
5065
+		}
5066
+	}
5067
+
5068
+
5069
+
5070
+	/**
5071
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5072
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5073
+	 * require_once($this->_getClassName().".class.php");
5074
+	 *
5075
+	 * @return string
5076
+	 */
5077
+	private function _get_class_name()
5078
+	{
5079
+		return "EE_" . $this->get_this_model_name();
5080
+	}
5081
+
5082
+
5083
+
5084
+	/**
5085
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5086
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5087
+	 * it would be 'Events'.
5088
+	 *
5089
+	 * @param int $quantity
5090
+	 * @return string
5091
+	 */
5092
+	public function item_name($quantity = 1)
5093
+	{
5094
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5095
+	}
5096
+
5097
+
5098
+
5099
+	/**
5100
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5101
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5102
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5103
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5104
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5105
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5106
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5107
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5108
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5109
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5110
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5111
+	 *        return $previousReturnValue.$returnString;
5112
+	 * }
5113
+	 * require('EEM_Answer.model.php');
5114
+	 * $answer=EEM_Answer::instance();
5115
+	 * echo $answer->my_callback('monkeys',100);
5116
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5117
+	 *
5118
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5119
+	 * @param array  $args       array of original arguments passed to the function
5120
+	 * @throws EE_Error
5121
+	 * @return mixed whatever the plugin which calls add_filter decides
5122
+	 */
5123
+	public function __call($methodName, $args)
5124
+	{
5125
+		$className = get_class($this);
5126
+		$tagName = "FHEE__{$className}__{$methodName}";
5127
+		if (! has_filter($tagName)) {
5128
+			throw new EE_Error(
5129
+				sprintf(
5130
+					__('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5131
+						'event_espresso'),
5132
+					$methodName,
5133
+					$className,
5134
+					$tagName,
5135
+					'<br />'
5136
+				)
5137
+			);
5138
+		}
5139
+		return apply_filters($tagName, null, $this, $args);
5140
+	}
5141
+
5142
+
5143
+
5144
+	/**
5145
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5146
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5147
+	 *
5148
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5149
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5150
+	 *                                                       the object's class name
5151
+	 *                                                       or object's ID
5152
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5153
+	 *                                                       exists in the database. If it does not, we add it
5154
+	 * @throws EE_Error
5155
+	 * @return EE_Base_Class
5156
+	 */
5157
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5158
+	{
5159
+		$className = $this->_get_class_name();
5160
+		if ($base_class_obj_or_id instanceof $className) {
5161
+			$model_object = $base_class_obj_or_id;
5162
+		} else {
5163
+			$primary_key_field = $this->get_primary_key_field();
5164
+			if (
5165
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5166
+				&& (
5167
+					is_int($base_class_obj_or_id)
5168
+					|| is_string($base_class_obj_or_id)
5169
+				)
5170
+			) {
5171
+				// assume it's an ID.
5172
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5173
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5174
+			} else if (
5175
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5176
+				&& is_string($base_class_obj_or_id)
5177
+			) {
5178
+				// assume its a string representation of the object
5179
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5180
+			} else {
5181
+				throw new EE_Error(
5182
+					sprintf(
5183
+						__(
5184
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5185
+							'event_espresso'
5186
+						),
5187
+						$base_class_obj_or_id,
5188
+						$this->_get_class_name(),
5189
+						print_r($base_class_obj_or_id, true)
5190
+					)
5191
+				);
5192
+			}
5193
+		}
5194
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5195
+			$model_object->save();
5196
+		}
5197
+		return $model_object;
5198
+	}
5199
+
5200
+
5201
+
5202
+	/**
5203
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5204
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5205
+	 * returns it ID.
5206
+	 *
5207
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5208
+	 * @return int|string depending on the type of this model object's ID
5209
+	 * @throws EE_Error
5210
+	 */
5211
+	public function ensure_is_ID($base_class_obj_or_id)
5212
+	{
5213
+		$className = $this->_get_class_name();
5214
+		if ($base_class_obj_or_id instanceof $className) {
5215
+			/** @var $base_class_obj_or_id EE_Base_Class */
5216
+			$id = $base_class_obj_or_id->ID();
5217
+		} elseif (is_int($base_class_obj_or_id)) {
5218
+			//assume it's an ID
5219
+			$id = $base_class_obj_or_id;
5220
+		} elseif (is_string($base_class_obj_or_id)) {
5221
+			//assume its a string representation of the object
5222
+			$id = $base_class_obj_or_id;
5223
+		} else {
5224
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5225
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5226
+				print_r($base_class_obj_or_id, true)));
5227
+		}
5228
+		return $id;
5229
+	}
5230
+
5231
+
5232
+
5233
+	/**
5234
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5235
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5236
+	 * been sanitized and converted into the appropriate domain.
5237
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5238
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5239
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5240
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5241
+	 * $EVT = EEM_Event::instance(); $old_setting =
5242
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5243
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5244
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5245
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5246
+	 *
5247
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5248
+	 * @return void
5249
+	 */
5250
+	public function assume_values_already_prepared_by_model_object(
5251
+		$values_already_prepared = self::not_prepared_by_model_object
5252
+	) {
5253
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5254
+	}
5255
+
5256
+
5257
+
5258
+	/**
5259
+	 * Read comments for assume_values_already_prepared_by_model_object()
5260
+	 *
5261
+	 * @return int
5262
+	 */
5263
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5264
+	{
5265
+		return $this->_values_already_prepared_by_model_object;
5266
+	}
5267
+
5268
+
5269
+
5270
+	/**
5271
+	 * Gets all the indexes on this model
5272
+	 *
5273
+	 * @return EE_Index[]
5274
+	 */
5275
+	public function indexes()
5276
+	{
5277
+		return $this->_indexes;
5278
+	}
5279
+
5280
+
5281
+
5282
+	/**
5283
+	 * Gets all the Unique Indexes on this model
5284
+	 *
5285
+	 * @return EE_Unique_Index[]
5286
+	 */
5287
+	public function unique_indexes()
5288
+	{
5289
+		$unique_indexes = array();
5290
+		foreach ($this->_indexes as $name => $index) {
5291
+			if ($index instanceof EE_Unique_Index) {
5292
+				$unique_indexes [$name] = $index;
5293
+			}
5294
+		}
5295
+		return $unique_indexes;
5296
+	}
5297
+
5298
+
5299
+
5300
+	/**
5301
+	 * Gets all the fields which, when combined, make the primary key.
5302
+	 * This is usually just an array with 1 element (the primary key), but in cases
5303
+	 * where there is no primary key, it's a combination of fields as defined
5304
+	 * on a primary index
5305
+	 *
5306
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5307
+	 * @throws \EE_Error
5308
+	 */
5309
+	public function get_combined_primary_key_fields()
5310
+	{
5311
+		foreach ($this->indexes() as $index) {
5312
+			if ($index instanceof EE_Primary_Key_Index) {
5313
+				return $index->fields();
5314
+			}
5315
+		}
5316
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5317
+	}
5318
+
5319
+
5320
+
5321
+	/**
5322
+	 * Used to build a primary key string (when the model has no primary key),
5323
+	 * which can be used a unique string to identify this model object.
5324
+	 *
5325
+	 * @param array $cols_n_values keys are field names, values are their values
5326
+	 * @return string
5327
+	 * @throws \EE_Error
5328
+	 */
5329
+	public function get_index_primary_key_string($cols_n_values)
5330
+	{
5331
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5332
+			$this->get_combined_primary_key_fields());
5333
+		return http_build_query($cols_n_values_for_primary_key_index);
5334
+	}
5335
+
5336
+
5337
+
5338
+	/**
5339
+	 * Gets the field values from the primary key string
5340
+	 *
5341
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5342
+	 * @param string $index_primary_key_string
5343
+	 * @return null|array
5344
+	 * @throws \EE_Error
5345
+	 */
5346
+	public function parse_index_primary_key_string($index_primary_key_string)
5347
+	{
5348
+		$key_fields = $this->get_combined_primary_key_fields();
5349
+		//check all of them are in the $id
5350
+		$key_vals_in_combined_pk = array();
5351
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5352
+		foreach ($key_fields as $key_field_name => $field_obj) {
5353
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5354
+				return null;
5355
+			}
5356
+		}
5357
+		return $key_vals_in_combined_pk;
5358
+	}
5359
+
5360
+
5361
+
5362
+	/**
5363
+	 * verifies that an array of key-value pairs for model fields has a key
5364
+	 * for each field comprising the primary key index
5365
+	 *
5366
+	 * @param array $key_vals
5367
+	 * @return boolean
5368
+	 * @throws \EE_Error
5369
+	 */
5370
+	public function has_all_combined_primary_key_fields($key_vals)
5371
+	{
5372
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5373
+		foreach ($keys_it_should_have as $key) {
5374
+			if (! isset($key_vals[$key])) {
5375
+				return false;
5376
+			}
5377
+		}
5378
+		return true;
5379
+	}
5380
+
5381
+
5382
+
5383
+	/**
5384
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5385
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5386
+	 *
5387
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5388
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5389
+	 * @throws EE_Error
5390
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5391
+	 *                                                              indexed)
5392
+	 */
5393
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5394
+	{
5395
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5396
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5397
+		} elseif (is_array($model_object_or_attributes_array)) {
5398
+			$attributes_array = $model_object_or_attributes_array;
5399
+		} else {
5400
+			throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5401
+				"event_espresso"), $model_object_or_attributes_array));
5402
+		}
5403
+		//even copies obviously won't have the same ID, so remove the primary key
5404
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5405
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5406
+			unset($attributes_array[$this->primary_key_name()]);
5407
+		}
5408
+		if (isset($query_params[0])) {
5409
+			$query_params[0] = array_merge($attributes_array, $query_params);
5410
+		} else {
5411
+			$query_params[0] = $attributes_array;
5412
+		}
5413
+		return $this->get_all($query_params);
5414
+	}
5415
+
5416
+
5417
+
5418
+	/**
5419
+	 * Gets the first copy we find. See get_all_copies for more details
5420
+	 *
5421
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5422
+	 * @param array $query_params
5423
+	 * @return EE_Base_Class
5424
+	 * @throws \EE_Error
5425
+	 */
5426
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5427
+	{
5428
+		if (! is_array($query_params)) {
5429
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5430
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5431
+					gettype($query_params)), '4.6.0');
5432
+			$query_params = array();
5433
+		}
5434
+		$query_params['limit'] = 1;
5435
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5436
+		if (is_array($copies)) {
5437
+			return array_shift($copies);
5438
+		} else {
5439
+			return null;
5440
+		}
5441
+	}
5442
+
5443
+
5444
+
5445
+	/**
5446
+	 * Updates the item with the specified id. Ignores default query parameters because
5447
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5448
+	 *
5449
+	 * @param array      $fields_n_values keys are field names, values are their new values
5450
+	 * @param int|string $id              the value of the primary key to update
5451
+	 * @return int number of rows updated
5452
+	 * @throws \EE_Error
5453
+	 */
5454
+	public function update_by_ID($fields_n_values, $id)
5455
+	{
5456
+		$query_params = array(
5457
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5458
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5459
+		);
5460
+		return $this->update($fields_n_values, $query_params);
5461
+	}
5462
+
5463
+
5464
+
5465
+	/**
5466
+	 * Changes an operator which was supplied to the models into one usable in SQL
5467
+	 *
5468
+	 * @param string $operator_supplied
5469
+	 * @return string an operator which can be used in SQL
5470
+	 * @throws EE_Error
5471
+	 */
5472
+	private function _prepare_operator_for_sql($operator_supplied)
5473
+	{
5474
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5475
+			: null;
5476
+		if ($sql_operator) {
5477
+			return $sql_operator;
5478
+		} else {
5479
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5480
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5481
+		}
5482
+	}
5483
+
5484
+
5485
+
5486
+	/**
5487
+	 * Gets an array where keys are the primary keys and values are their 'names'
5488
+	 * (as determined by the model object's name() function, which is often overridden)
5489
+	 *
5490
+	 * @param array $query_params like get_all's
5491
+	 * @return string[]
5492
+	 * @throws \EE_Error
5493
+	 */
5494
+	public function get_all_names($query_params = array())
5495
+	{
5496
+		$objs = $this->get_all($query_params);
5497
+		$names = array();
5498
+		foreach ($objs as $obj) {
5499
+			$names[$obj->ID()] = $obj->name();
5500
+		}
5501
+		return $names;
5502
+	}
5503
+
5504
+
5505
+
5506
+	/**
5507
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5508
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5509
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5510
+	 * array_keys() on $model_objects.
5511
+	 *
5512
+	 * @param \EE_Base_Class[] $model_objects
5513
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5514
+	 *                                               in the returned array
5515
+	 * @return array
5516
+	 * @throws \EE_Error
5517
+	 */
5518
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5519
+	{
5520
+		if (! $this->has_primary_key_field()) {
5521
+			if (WP_DEBUG) {
5522
+				EE_Error::add_error(
5523
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5524
+					__FILE__,
5525
+					__FUNCTION__,
5526
+					__LINE__
5527
+				);
5528
+			}
5529
+		}
5530
+		$IDs = array();
5531
+		foreach ($model_objects as $model_object) {
5532
+			$id = $model_object->ID();
5533
+			if (! $id) {
5534
+				if ($filter_out_empty_ids) {
5535
+					continue;
5536
+				}
5537
+				if (WP_DEBUG) {
5538
+					EE_Error::add_error(
5539
+						__(
5540
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5541
+							'event_espresso'
5542
+						),
5543
+						__FILE__,
5544
+						__FUNCTION__,
5545
+						__LINE__
5546
+					);
5547
+				}
5548
+			}
5549
+			$IDs[] = $id;
5550
+		}
5551
+		return $IDs;
5552
+	}
5553
+
5554
+
5555
+
5556
+	/**
5557
+	 * Returns the string used in capabilities relating to this model. If there
5558
+	 * are no capabilities that relate to this model returns false
5559
+	 *
5560
+	 * @return string|false
5561
+	 */
5562
+	public function cap_slug()
5563
+	{
5564
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5565
+	}
5566
+
5567
+
5568
+
5569
+	/**
5570
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5571
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5572
+	 * only returns the cap restrictions array in that context (ie, the array
5573
+	 * at that key)
5574
+	 *
5575
+	 * @param string $context
5576
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5577
+	 * @throws \EE_Error
5578
+	 */
5579
+	public function cap_restrictions($context = EEM_Base::caps_read)
5580
+	{
5581
+		EEM_Base::verify_is_valid_cap_context($context);
5582
+		//check if we ought to run the restriction generator first
5583
+		if (
5584
+			isset($this->_cap_restriction_generators[$context])
5585
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5586
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5587
+		) {
5588
+			$this->_cap_restrictions[$context] = array_merge(
5589
+				$this->_cap_restrictions[$context],
5590
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5591
+			);
5592
+		}
5593
+		//and make sure we've finalized the construction of each restriction
5594
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5595
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5596
+				$where_conditions_obj->_finalize_construct($this);
5597
+			}
5598
+		}
5599
+		return $this->_cap_restrictions[$context];
5600
+	}
5601
+
5602
+
5603
+
5604
+	/**
5605
+	 * Indicating whether or not this model thinks its a wp core model
5606
+	 *
5607
+	 * @return boolean
5608
+	 */
5609
+	public function is_wp_core_model()
5610
+	{
5611
+		return $this->_wp_core_model;
5612
+	}
5613
+
5614
+
5615
+
5616
+	/**
5617
+	 * Gets all the caps that are missing which impose a restriction on
5618
+	 * queries made in this context
5619
+	 *
5620
+	 * @param string $context one of EEM_Base::caps_ constants
5621
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5622
+	 * @throws \EE_Error
5623
+	 */
5624
+	public function caps_missing($context = EEM_Base::caps_read)
5625
+	{
5626
+		$missing_caps = array();
5627
+		$cap_restrictions = $this->cap_restrictions($context);
5628
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5629
+			if (! EE_Capabilities::instance()
5630
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5631
+			) {
5632
+				$missing_caps[$cap] = $restriction_if_no_cap;
5633
+			}
5634
+		}
5635
+		return $missing_caps;
5636
+	}
5637
+
5638
+
5639
+
5640
+	/**
5641
+	 * Gets the mapping from capability contexts to action strings used in capability names
5642
+	 *
5643
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5644
+	 * one of 'read', 'edit', or 'delete'
5645
+	 */
5646
+	public function cap_contexts_to_cap_action_map()
5647
+	{
5648
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5649
+			$this);
5650
+	}
5651
+
5652
+
5653
+
5654
+	/**
5655
+	 * Gets the action string for the specified capability context
5656
+	 *
5657
+	 * @param string $context
5658
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5659
+	 * @throws \EE_Error
5660
+	 */
5661
+	public function cap_action_for_context($context)
5662
+	{
5663
+		$mapping = $this->cap_contexts_to_cap_action_map();
5664
+		if (isset($mapping[$context])) {
5665
+			return $mapping[$context];
5666
+		}
5667
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5668
+			return $action;
5669
+		}
5670
+		throw new EE_Error(
5671
+			sprintf(
5672
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5673
+				$context,
5674
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5675
+			)
5676
+		);
5677
+	}
5678
+
5679
+
5680
+
5681
+	/**
5682
+	 * Returns all the capability contexts which are valid when querying models
5683
+	 *
5684
+	 * @return array
5685
+	 */
5686
+	public static function valid_cap_contexts()
5687
+	{
5688
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5689
+			self::caps_read,
5690
+			self::caps_read_admin,
5691
+			self::caps_edit,
5692
+			self::caps_delete,
5693
+		));
5694
+	}
5695
+
5696
+
5697
+
5698
+	/**
5699
+	 * Returns all valid options for 'default_where_conditions'
5700
+	 *
5701
+	 * @return array
5702
+	 */
5703
+	public static function valid_default_where_conditions()
5704
+	{
5705
+		return array(
5706
+			EEM_Base::default_where_conditions_all,
5707
+			EEM_Base::default_where_conditions_this_only,
5708
+			EEM_Base::default_where_conditions_others_only,
5709
+			EEM_Base::default_where_conditions_minimum_all,
5710
+			EEM_Base::default_where_conditions_minimum_others,
5711
+			EEM_Base::default_where_conditions_none
5712
+		);
5713
+	}
5714
+
5715
+	// public static function default_where_conditions_full
5716
+	/**
5717
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5718
+	 *
5719
+	 * @param string $context
5720
+	 * @return bool
5721
+	 * @throws \EE_Error
5722
+	 */
5723
+	static public function verify_is_valid_cap_context($context)
5724
+	{
5725
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5726
+		if (in_array($context, $valid_cap_contexts)) {
5727
+			return true;
5728
+		} else {
5729
+			throw new EE_Error(
5730
+				sprintf(
5731
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5732
+						'event_espresso'),
5733
+					$context,
5734
+					'EEM_Base',
5735
+					implode(',', $valid_cap_contexts)
5736
+				)
5737
+			);
5738
+		}
5739
+	}
5740
+
5741
+
5742
+
5743
+	/**
5744
+	 * Clears all the models field caches. This is only useful when a sub-class
5745
+	 * might have added a field or something and these caches might be invalidated
5746
+	 */
5747
+	protected function _invalidate_field_caches()
5748
+	{
5749
+		$this->_cache_foreign_key_to_fields = array();
5750
+		$this->_cached_fields = null;
5751
+		$this->_cached_fields_non_db_only = null;
5752
+	}
5753
+
5754
+
5755
+
5756
+	/**
5757
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5758
+	 * (eg "and", "or", "not").
5759
+	 *
5760
+	 * @return array
5761
+	 */
5762
+	public function logic_query_param_keys()
5763
+	{
5764
+		return $this->_logic_query_param_keys;
5765
+	}
5766
+
5767
+
5768
+
5769
+	/**
5770
+	 * Determines whether or not the where query param array key is for a logic query param.
5771
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5772
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5773
+	 *
5774
+	 * @param $query_param_key
5775
+	 * @return bool
5776
+	 */
5777
+	public function is_logic_query_param_key($query_param_key)
5778
+	{
5779
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5780
+			if ($query_param_key === $logic_query_param_key
5781
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5782
+			) {
5783
+				return true;
5784
+			}
5785
+		}
5786
+		return false;
5787
+	}
5788 5788
 
5789 5789
 
5790 5790
 
Please login to merge, or discard this patch.
Spacing   +154 added lines, -154 removed lines patch added patch discarded remove patch
@@ -516,8 +516,8 @@  discard block
 block discarded – undo
516 516
     protected function __construct($timezone = null)
517 517
     {
518 518
         // check that the model has not been loaded too soon
519
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
520
-            throw new EE_Error (
519
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
520
+            throw new EE_Error(
521 521
                 sprintf(
522 522
                     __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
523 523
                         'event_espresso'),
@@ -537,7 +537,7 @@  discard block
 block discarded – undo
537 537
          *
538 538
          * @var EE_Table_Base[] $_tables
539 539
          */
540
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
541 541
         foreach ($this->_tables as $table_alias => $table_obj) {
542 542
             /** @var $table_obj EE_Table_Base */
543 543
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -552,10 +552,10 @@  discard block
 block discarded – undo
552 552
          *
553 553
          * @param EE_Model_Field_Base[] $_fields
554 554
          */
555
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
556 556
         $this->_invalidate_field_caches();
557 557
         foreach ($this->_fields as $table_alias => $fields_for_table) {
558
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
559 559
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
560 560
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
561 561
             }
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
          *
584 584
          * @param EE_Model_Relation_Base[] $_model_relations
585 585
          */
586
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
587 587
             $this->_model_relations);
588 588
         foreach ($this->_model_relations as $model_name => $relation_obj) {
589 589
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -595,12 +595,12 @@  discard block
 block discarded – undo
595 595
         }
596 596
         $this->set_timezone($timezone);
597 597
         //finalize default where condition strategy, or set default
598
-        if (! $this->_default_where_conditions_strategy) {
598
+        if ( ! $this->_default_where_conditions_strategy) {
599 599
             //nothing was set during child constructor, so set default
600 600
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
601 601
         }
602 602
         $this->_default_where_conditions_strategy->_finalize_construct($this);
603
-        if (! $this->_minimum_where_conditions_strategy) {
603
+        if ( ! $this->_minimum_where_conditions_strategy) {
604 604
             //nothing was set during child constructor, so set default
605 605
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
606 606
         }
@@ -613,7 +613,7 @@  discard block
 block discarded – undo
613 613
         //initialize the standard cap restriction generators if none were specified by the child constructor
614 614
         if ($this->_cap_restriction_generators !== false) {
615 615
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
616
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
617 617
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
618 618
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
619 619
                         new EE_Restriction_Generator_Protected(),
@@ -626,10 +626,10 @@  discard block
 block discarded – undo
626 626
         //if there are cap restriction generators, use them to make the default cap restrictions
627 627
         if ($this->_cap_restriction_generators !== false) {
628 628
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
629
-                if (! $generator_object) {
629
+                if ( ! $generator_object) {
630 630
                     continue;
631 631
                 }
632
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
633 633
                     throw new EE_Error(
634 634
                         sprintf(
635 635
                             __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
@@ -640,12 +640,12 @@  discard block
 block discarded – undo
640 640
                     );
641 641
                 }
642 642
                 $action = $this->cap_action_for_context($context);
643
-                if (! $generator_object->construction_finalized()) {
643
+                if ( ! $generator_object->construction_finalized()) {
644 644
                     $generator_object->_construct_finalize($this, $action);
645 645
                 }
646 646
             }
647 647
         }
648
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
+        do_action('AHEE__'.get_class($this).'__construct__end');
649 649
     }
650 650
 
651 651
 
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
      */
681 681
     public static function set_model_query_blog_id($blog_id = 0)
682 682
     {
683
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
684 684
     }
685 685
 
686 686
 
@@ -710,7 +710,7 @@  discard block
 block discarded – undo
710 710
     public static function instance($timezone = null)
711 711
     {
712 712
         // check if instance of Espresso_model already exists
713
-        if (! static::$_instance instanceof static) {
713
+        if ( ! static::$_instance instanceof static) {
714 714
             // instantiate Espresso_model
715 715
             static::$_instance = new static($timezone);
716 716
         }
@@ -741,7 +741,7 @@  discard block
 block discarded – undo
741 741
             foreach ($r->getDefaultProperties() as $property => $value) {
742 742
                 //don't set instance to null like it was originally,
743 743
                 //but it's static anyways, and we're ignoring static properties (for now at least)
744
-                if (! isset($static_properties[$property])) {
744
+                if ( ! isset($static_properties[$property])) {
745 745
                     static::$_instance->{$property} = $value;
746 746
                 }
747 747
             }
@@ -764,7 +764,7 @@  discard block
 block discarded – undo
764 764
      */
765 765
     public function status_array($translated = false)
766 766
     {
767
-        if (! array_key_exists('Status', $this->_model_relations)) {
767
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
768 768
             return array();
769 769
         }
770 770
         $model_name = $this->get_this_model_name();
@@ -967,17 +967,17 @@  discard block
 block discarded – undo
967 967
     public function wp_user_field_name()
968 968
     {
969 969
         try {
970
-            if (! empty($this->_model_chain_to_wp_user)) {
970
+            if ( ! empty($this->_model_chain_to_wp_user)) {
971 971
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
972 972
                 $last_model_name = end($models_to_follow_to_wp_users);
973 973
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
974
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
975 975
             } else {
976 976
                 $model_with_fk_to_wp_users = $this;
977 977
                 $model_chain_to_wp_user = '';
978 978
             }
979 979
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
980
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
980
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
981 981
         } catch (EE_Error $e) {
982 982
             return false;
983 983
         }
@@ -1049,12 +1049,12 @@  discard block
 block discarded – undo
1049 1049
         // remember the custom selections, if any, and type cast as array
1050 1050
         // (unless $columns_to_select is an object, then just set as an empty array)
1051 1051
         // Note: (array) 'some string' === array( 'some string' )
1052
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1053 1053
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1054 1054
         $select_expressions = $columns_to_select !== null
1055 1055
             ? $this->_construct_select_from_input($columns_to_select)
1056 1056
             : $this->_construct_default_select_sql($model_query_info);
1057
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1058 1058
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1059 1059
     }
1060 1060
 
@@ -1099,7 +1099,7 @@  discard block
 block discarded – undo
1099 1099
         if (is_array($columns_to_select)) {
1100 1100
             $select_sql_array = array();
1101 1101
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1102
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1103 1103
                     throw new EE_Error(
1104 1104
                         sprintf(
1105 1105
                             __(
@@ -1111,7 +1111,7 @@  discard block
 block discarded – undo
1111 1111
                         )
1112 1112
                     );
1113 1113
                 }
1114
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1115 1115
                     throw new EE_Error(
1116 1116
                         sprintf(
1117 1117
                             __(
@@ -1183,7 +1183,7 @@  discard block
 block discarded – undo
1183 1183
      */
1184 1184
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1185 1185
     {
1186
-        if (! isset($query_params[0])) {
1186
+        if ( ! isset($query_params[0])) {
1187 1187
             $query_params[0] = array();
1188 1188
         }
1189 1189
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1208,7 +1208,7 @@  discard block
 block discarded – undo
1208 1208
      */
1209 1209
     public function get_one($query_params = array())
1210 1210
     {
1211
-        if (! is_array($query_params)) {
1211
+        if ( ! is_array($query_params)) {
1212 1212
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1213 1213
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1214 1214
                     gettype($query_params)), '4.6.0');
@@ -1376,7 +1376,7 @@  discard block
 block discarded – undo
1376 1376
                 return array();
1377 1377
             }
1378 1378
         }
1379
-        if (! is_array($query_params)) {
1379
+        if ( ! is_array($query_params)) {
1380 1380
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1381 1381
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1382 1382
                     gettype($query_params)), '4.6.0');
@@ -1386,7 +1386,7 @@  discard block
 block discarded – undo
1386 1386
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1387 1387
         $query_params['limit'] = $limit;
1388 1388
         //set direction
1389
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1390 1390
         $query_params['order_by'] = $operand === '>'
1391 1391
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1392 1392
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1465,7 +1465,7 @@  discard block
 block discarded – undo
1465 1465
     {
1466 1466
         $field_settings = $this->field_settings_for($field_name);
1467 1467
         //if not a valid EE_Datetime_Field then throw error
1468
-        if (! $field_settings instanceof EE_Datetime_Field) {
1468
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1469 1469
             throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1470 1470
                 'event_espresso'), $field_name));
1471 1471
         }
@@ -1542,7 +1542,7 @@  discard block
 block discarded – undo
1542 1542
         //load EEH_DTT_Helper
1543 1543
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1544 1544
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1545
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1545
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1546 1546
     }
1547 1547
 
1548 1548
 
@@ -1610,7 +1610,7 @@  discard block
 block discarded – undo
1610 1610
      */
1611 1611
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1612 1612
     {
1613
-        if (! is_array($query_params)) {
1613
+        if ( ! is_array($query_params)) {
1614 1614
             EE_Error::doing_it_wrong('EEM_Base::update',
1615 1615
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1616 1616
                     gettype($query_params)), '4.6.0');
@@ -1632,7 +1632,7 @@  discard block
 block discarded – undo
1632 1632
          * @param EEM_Base $model           the model being queried
1633 1633
          * @param array    $query_params    see EEM_Base::get_all()
1634 1634
          */
1635
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1635
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1636 1636
             $query_params);
1637 1637
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1638 1638
         //to do that, for each table, verify that it's PK isn't null.
@@ -1646,7 +1646,7 @@  discard block
 block discarded – undo
1646 1646
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1647 1647
         foreach ($wpdb_select_results as $wpdb_result) {
1648 1648
             // type cast stdClass as array
1649
-            $wpdb_result = (array)$wpdb_result;
1649
+            $wpdb_result = (array) $wpdb_result;
1650 1650
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1651 1651
             if ($this->has_primary_key_field()) {
1652 1652
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1663,13 +1663,13 @@  discard block
 block discarded – undo
1663 1663
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1664 1664
                     //if there is no private key for this table on the results, it means there's no entry
1665 1665
                     //in this table, right? so insert a row in the current table, using any fields available
1666
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1666
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1667 1667
                            && $wpdb_result[$this_table_pk_column])
1668 1668
                     ) {
1669 1669
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1670 1670
                             $main_table_pk_value);
1671 1671
                         //if we died here, report the error
1672
-                        if (! $success) {
1672
+                        if ( ! $success) {
1673 1673
                             return false;
1674 1674
                         }
1675 1675
                     }
@@ -1700,7 +1700,7 @@  discard block
 block discarded – undo
1700 1700
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1701 1701
                 }
1702 1702
             }
1703
-            if (! $model_objs_affected_ids) {
1703
+            if ( ! $model_objs_affected_ids) {
1704 1704
                 //wait wait wait- if nothing was affected let's stop here
1705 1705
                 return 0;
1706 1706
             }
@@ -1727,7 +1727,7 @@  discard block
 block discarded – undo
1727 1727
                . $model_query_info->get_full_join_sql()
1728 1728
                . " SET "
1729 1729
                . $this->_construct_update_sql($fields_n_values)
1730
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1730
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1731 1731
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1732 1732
         /**
1733 1733
          * Action called after a model update call has been made.
@@ -1738,7 +1738,7 @@  discard block
 block discarded – undo
1738 1738
          * @param int      $rows_affected
1739 1739
          */
1740 1740
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1741
-        return $rows_affected;//how many supposedly got updated
1741
+        return $rows_affected; //how many supposedly got updated
1742 1742
     }
1743 1743
 
1744 1744
 
@@ -1766,7 +1766,7 @@  discard block
 block discarded – undo
1766 1766
         }
1767 1767
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1768 1768
         $select_expressions = $field->get_qualified_column();
1769
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1769
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1770 1770
         return $this->_do_wpdb_query('get_col', array($SQL));
1771 1771
     }
1772 1772
 
@@ -1784,7 +1784,7 @@  discard block
 block discarded – undo
1784 1784
     {
1785 1785
         $query_params['limit'] = 1;
1786 1786
         $col = $this->get_col($query_params, $field_to_select);
1787
-        if (! empty($col)) {
1787
+        if ( ! empty($col)) {
1788 1788
             return reset($col);
1789 1789
         } else {
1790 1790
             return null;
@@ -1816,7 +1816,7 @@  discard block
 block discarded – undo
1816 1816
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1817 1817
             $value_sql = $prepared_value === null ? 'NULL'
1818 1818
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1819
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1819
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1820 1820
         }
1821 1821
         return implode(",", $cols_n_values);
1822 1822
     }
@@ -1948,7 +1948,7 @@  discard block
 block discarded – undo
1948 1948
          * @param int      $rows_deleted
1949 1949
          */
1950 1950
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1951
-        return $rows_deleted;//how many supposedly got deleted
1951
+        return $rows_deleted; //how many supposedly got deleted
1952 1952
     }
1953 1953
 
1954 1954
 
@@ -2041,7 +2041,7 @@  discard block
 block discarded – undo
2041 2041
                     $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
2042 2042
                 }
2043 2043
                 //other tables
2044
-                if (! empty($other_tables)) {
2044
+                if ( ! empty($other_tables)) {
2045 2045
                     foreach ($other_tables as $ot) {
2046 2046
                         //first check if we've got the foreign key column here.
2047 2047
                         if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
@@ -2064,7 +2064,7 @@  discard block
 block discarded – undo
2064 2064
             foreach ($deletes as $column => $values) {
2065 2065
                 //make sure we have unique $values;
2066 2066
                 $values = array_unique($values);
2067
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2067
+                $query[] = $column.' IN('.implode(",", $values).')';
2068 2068
             }
2069 2069
             return ! empty($query) ? implode(' AND ', $query) : '';
2070 2070
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2080,7 +2080,7 @@  discard block
 block discarded – undo
2080 2080
                                                            . $delete_object[$cpk_field->get_qualified_column()];
2081 2081
                     }
2082 2082
                 }
2083
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2083
+                $ways_to_identify_a_row[] = "(".implode(" AND ", $values_for_each_cpk_for_a_row).")";
2084 2084
             }
2085 2085
             return implode(" OR ", $ways_to_identify_a_row);
2086 2086
         } else {
@@ -2129,9 +2129,9 @@  discard block
 block discarded – undo
2129 2129
                 $column_to_count = '*';
2130 2130
             }
2131 2131
         }
2132
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2133
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2134
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2132
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2133
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2134
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2135 2135
     }
2136 2136
 
2137 2137
 
@@ -2153,13 +2153,13 @@  discard block
 block discarded – undo
2153 2153
             $field_obj = $this->get_primary_key_field();
2154 2154
         }
2155 2155
         $column_to_count = $field_obj->get_qualified_column();
2156
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2156
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2157 2157
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2158 2158
         $data_type = $field_obj->get_wpdb_data_type();
2159 2159
         if ($data_type === '%d' || $data_type === '%s') {
2160
-            return (float)$return_value;
2160
+            return (float) $return_value;
2161 2161
         } else {//must be %f
2162
-            return (float)$return_value;
2162
+            return (float) $return_value;
2163 2163
         }
2164 2164
     }
2165 2165
 
@@ -2180,13 +2180,13 @@  discard block
 block discarded – undo
2180 2180
         //if we're in maintenance mode level 2, DON'T run any queries
2181 2181
         //because level 2 indicates the database needs updating and
2182 2182
         //is probably out of sync with the code
2183
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2183
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2184 2184
             throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2185 2185
                 "event_espresso")));
2186 2186
         }
2187 2187
         /** @type WPDB $wpdb */
2188 2188
         global $wpdb;
2189
-        if (! method_exists($wpdb, $wpdb_method)) {
2189
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2190 2190
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2191 2191
                 'event_espresso'), $wpdb_method));
2192 2192
         }
@@ -2198,7 +2198,7 @@  discard block
 block discarded – undo
2198 2198
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2199 2199
         if (WP_DEBUG) {
2200 2200
             $wpdb->show_errors($old_show_errors_value);
2201
-            if (! empty($wpdb->last_error)) {
2201
+            if ( ! empty($wpdb->last_error)) {
2202 2202
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2203 2203
             } elseif ($result === false) {
2204 2204
                 throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
@@ -2258,7 +2258,7 @@  discard block
 block discarded – undo
2258 2258
                     return $result;
2259 2259
                     break;
2260 2260
             }
2261
-            if (! empty($error_message)) {
2261
+            if ( ! empty($error_message)) {
2262 2262
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2263 2263
                 trigger_error($error_message);
2264 2264
             }
@@ -2334,11 +2334,11 @@  discard block
 block discarded – undo
2334 2334
      */
2335 2335
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2336 2336
     {
2337
-        return " FROM " . $model_query_info->get_full_join_sql() .
2338
-               $model_query_info->get_where_sql() .
2339
-               $model_query_info->get_group_by_sql() .
2340
-               $model_query_info->get_having_sql() .
2341
-               $model_query_info->get_order_by_sql() .
2337
+        return " FROM ".$model_query_info->get_full_join_sql().
2338
+               $model_query_info->get_where_sql().
2339
+               $model_query_info->get_group_by_sql().
2340
+               $model_query_info->get_having_sql().
2341
+               $model_query_info->get_order_by_sql().
2342 2342
                $model_query_info->get_limit_sql();
2343 2343
     }
2344 2344
 
@@ -2534,12 +2534,12 @@  discard block
 block discarded – undo
2534 2534
         $related_model = $this->get_related_model_obj($model_name);
2535 2535
         //we're just going to use the query params on the related model's normal get_all query,
2536 2536
         //except add a condition to say to match the current mod
2537
-        if (! isset($query_params['default_where_conditions'])) {
2537
+        if ( ! isset($query_params['default_where_conditions'])) {
2538 2538
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2539 2539
         }
2540 2540
         $this_model_name = $this->get_this_model_name();
2541 2541
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2542
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2542
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2543 2543
         return $related_model->count($query_params, $field_to_count, $distinct);
2544 2544
     }
2545 2545
 
@@ -2559,7 +2559,7 @@  discard block
 block discarded – undo
2559 2559
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2560 2560
     {
2561 2561
         $related_model = $this->get_related_model_obj($model_name);
2562
-        if (! is_array($query_params)) {
2562
+        if ( ! is_array($query_params)) {
2563 2563
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2564 2564
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2565 2565
                     gettype($query_params)), '4.6.0');
@@ -2567,12 +2567,12 @@  discard block
 block discarded – undo
2567 2567
         }
2568 2568
         //we're just going to use the query params on the related model's normal get_all query,
2569 2569
         //except add a condition to say to match the current mod
2570
-        if (! isset($query_params['default_where_conditions'])) {
2570
+        if ( ! isset($query_params['default_where_conditions'])) {
2571 2571
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2572 2572
         }
2573 2573
         $this_model_name = $this->get_this_model_name();
2574 2574
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2575
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2575
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2576 2576
         return $related_model->sum($query_params, $field_to_sum);
2577 2577
     }
2578 2578
 
@@ -2626,7 +2626,7 @@  discard block
 block discarded – undo
2626 2626
                 $field_with_model_name = $field;
2627 2627
             }
2628 2628
         }
2629
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2629
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2630 2630
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2631 2631
                 $this->get_this_model_name()));
2632 2632
         }
@@ -2659,7 +2659,7 @@  discard block
 block discarded – undo
2659 2659
          * @param array    $fields_n_values keys are the fields and values are their new values
2660 2660
          * @param EEM_Base $model           the model used
2661 2661
          */
2662
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2662
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2663 2663
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2664 2664
             $main_table = $this->_get_main_table();
2665 2665
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2767,7 +2767,7 @@  discard block
 block discarded – undo
2767 2767
         }
2768 2768
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2769 2769
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2770
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2770
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2771 2771
         }
2772 2772
         //if there is nothing to base this search on, then we shouldn't find anything
2773 2773
         if (empty($query_params)) {
@@ -2854,7 +2854,7 @@  discard block
 block discarded – undo
2854 2854
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2855 2855
             //so add the fk to the main table as a column
2856 2856
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2857
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2857
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2858 2858
         }
2859 2859
         //insert the new entry
2860 2860
         $result = $this->_do_wpdb_query('insert',
@@ -2893,7 +2893,7 @@  discard block
 block discarded – undo
2893 2893
     protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2894 2894
     {
2895 2895
         //if this field doesn't allow nullable, don't allow it
2896
-        if (! $field_obj->is_nullable()
2896
+        if ( ! $field_obj->is_nullable()
2897 2897
             && (
2898 2898
                 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2899 2899
         ) {
@@ -3056,7 +3056,7 @@  discard block
 block discarded – undo
3056 3056
                     $query_info_carrier,
3057 3057
                     'group_by'
3058 3058
                 );
3059
-            } elseif (! empty ($query_params['group_by'])) {
3059
+            } elseif ( ! empty ($query_params['group_by'])) {
3060 3060
                 $this->_extract_related_model_info_from_query_param(
3061 3061
                     $query_params['group_by'],
3062 3062
                     $query_info_carrier,
@@ -3078,7 +3078,7 @@  discard block
 block discarded – undo
3078 3078
                     $query_info_carrier,
3079 3079
                     'order_by'
3080 3080
                 );
3081
-            } elseif (! empty($query_params['order_by'])) {
3081
+            } elseif ( ! empty($query_params['order_by'])) {
3082 3082
                 $this->_extract_related_model_info_from_query_param(
3083 3083
                     $query_params['order_by'],
3084 3084
                     $query_info_carrier,
@@ -3113,8 +3113,8 @@  discard block
 block discarded – undo
3113 3113
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3114 3114
         $query_param_type
3115 3115
     ) {
3116
-        if (! empty($sub_query_params)) {
3117
-            $sub_query_params = (array)$sub_query_params;
3116
+        if ( ! empty($sub_query_params)) {
3117
+            $sub_query_params = (array) $sub_query_params;
3118 3118
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3119 3119
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3120 3120
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3125,7 +3125,7 @@  discard block
 block discarded – undo
3125 3125
                 //of array('Registration.TXN_ID'=>23)
3126 3126
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3127 3127
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3128
-                    if (! is_array($possibly_array_of_params)) {
3128
+                    if ( ! is_array($possibly_array_of_params)) {
3129 3129
                         throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3130 3130
                             "event_espresso"),
3131 3131
                             $param, $possibly_array_of_params));
@@ -3141,7 +3141,7 @@  discard block
 block discarded – undo
3141 3141
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3142 3142
                     //indicating that $possible_array_of_params[1] is actually a field name,
3143 3143
                     //from which we should extract query parameters!
3144
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3144
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3145 3145
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3146 3146
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3147 3147
                     }
@@ -3171,8 +3171,8 @@  discard block
 block discarded – undo
3171 3171
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3172 3172
         $query_param_type
3173 3173
     ) {
3174
-        if (! empty($sub_query_params)) {
3175
-            if (! is_array($sub_query_params)) {
3174
+        if ( ! empty($sub_query_params)) {
3175
+            if ( ! is_array($sub_query_params)) {
3176 3176
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3177 3177
                     $sub_query_params));
3178 3178
             }
@@ -3201,7 +3201,7 @@  discard block
 block discarded – undo
3201 3201
      */
3202 3202
     public function _create_model_query_info_carrier($query_params)
3203 3203
     {
3204
-        if (! is_array($query_params)) {
3204
+        if ( ! is_array($query_params)) {
3205 3205
             EE_Error::doing_it_wrong(
3206 3206
                 'EEM_Base::_create_model_query_info_carrier',
3207 3207
                 sprintf(
@@ -3277,7 +3277,7 @@  discard block
 block discarded – undo
3277 3277
         //set limit
3278 3278
         if (array_key_exists('limit', $query_params)) {
3279 3279
             if (is_array($query_params['limit'])) {
3280
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3280
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3281 3281
                     $e = sprintf(
3282 3282
                         __(
3283 3283
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3285,12 +3285,12 @@  discard block
 block discarded – undo
3285 3285
                         ),
3286 3286
                         http_build_query($query_params['limit'])
3287 3287
                     );
3288
-                    throw new EE_Error($e . "|" . $e);
3288
+                    throw new EE_Error($e."|".$e);
3289 3289
                 }
3290 3290
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3291
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3292
-            } elseif (! empty ($query_params['limit'])) {
3293
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3291
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3292
+            } elseif ( ! empty ($query_params['limit'])) {
3293
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3294 3294
             }
3295 3295
         }
3296 3296
         //set order by
@@ -3322,10 +3322,10 @@  discard block
 block discarded – undo
3322 3322
                 $order_array = array();
3323 3323
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3324 3324
                     $order = $this->_extract_order($order);
3325
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3325
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3326 3326
                 }
3327
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3328
-            } elseif (! empty ($query_params['order_by'])) {
3327
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3328
+            } elseif ( ! empty ($query_params['order_by'])) {
3329 3329
                 $this->_extract_related_model_info_from_query_param(
3330 3330
                     $query_params['order_by'],
3331 3331
                     $query_object,
@@ -3336,18 +3336,18 @@  discard block
 block discarded – undo
3336 3336
                     ? $this->_extract_order($query_params['order'])
3337 3337
                     : 'DESC';
3338 3338
                 $query_object->set_order_by_sql(
3339
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3339
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3340 3340
                 );
3341 3341
             }
3342 3342
         }
3343 3343
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3344
-        if (! array_key_exists('order_by', $query_params)
3344
+        if ( ! array_key_exists('order_by', $query_params)
3345 3345
             && array_key_exists('order', $query_params)
3346 3346
             && ! empty($query_params['order'])
3347 3347
         ) {
3348 3348
             $pk_field = $this->get_primary_key_field();
3349 3349
             $order = $this->_extract_order($query_params['order']);
3350
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3350
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3351 3351
         }
3352 3352
         //set group by
3353 3353
         if (array_key_exists('group_by', $query_params)) {
@@ -3357,10 +3357,10 @@  discard block
 block discarded – undo
3357 3357
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3358 3358
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3359 3359
                 }
3360
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3361
-            } elseif (! empty ($query_params['group_by'])) {
3360
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3361
+            } elseif ( ! empty ($query_params['group_by'])) {
3362 3362
                 $query_object->set_group_by_sql(
3363
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3363
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3364 3364
                 );
3365 3365
             }
3366 3366
         }
@@ -3370,7 +3370,7 @@  discard block
 block discarded – undo
3370 3370
         }
3371 3371
         //now, just verify they didn't pass anything wack
3372 3372
         foreach ($query_params as $query_key => $query_value) {
3373
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3373
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3374 3374
                 throw new EE_Error(
3375 3375
                     sprintf(
3376 3376
                         __(
@@ -3464,22 +3464,22 @@  discard block
 block discarded – undo
3464 3464
         $where_query_params = array()
3465 3465
     ) {
3466 3466
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3467
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3467
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3468 3468
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3469 3469
                 "event_espresso"), $use_default_where_conditions,
3470 3470
                 implode(", ", $allowed_used_default_where_conditions_values)));
3471 3471
         }
3472 3472
         $universal_query_params = array();
3473
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3473
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3474 3474
             $universal_query_params = $this->_get_default_where_conditions();
3475
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3475
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3476 3476
             $universal_query_params = $this->_get_minimum_where_conditions();
3477 3477
         }
3478 3478
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3479 3479
             $related_model = $this->get_related_model_obj($model_name);
3480
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3480
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3481 3481
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3482
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3482
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3483 3483
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3484 3484
             } else {
3485 3485
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3512,7 +3512,7 @@  discard block
 block discarded – undo
3512 3512
      * @param bool $for_this_model false means this is for OTHER related models
3513 3513
      * @return bool
3514 3514
      */
3515
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3515
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3516 3516
     {
3517 3517
         return (
3518 3518
                    $for_this_model
@@ -3591,7 +3591,7 @@  discard block
 block discarded – undo
3591 3591
     ) {
3592 3592
         $null_friendly_where_conditions = array();
3593 3593
         $none_overridden = true;
3594
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3594
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3595 3595
         foreach ($default_where_conditions as $key => $val) {
3596 3596
             if (isset($provided_where_conditions[$key])) {
3597 3597
                 $none_overridden = false;
@@ -3709,7 +3709,7 @@  discard block
 block discarded – undo
3709 3709
             foreach ($tables as $table_obj) {
3710 3710
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3711 3711
                                        . $table_obj->get_fully_qualified_pk_column();
3712
-                if (! in_array($qualified_pk_column, $selects)) {
3712
+                if ( ! in_array($qualified_pk_column, $selects)) {
3713 3713
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3714 3714
                 }
3715 3715
             }
@@ -3795,9 +3795,9 @@  discard block
 block discarded – undo
3795 3795
         //and
3796 3796
         //check if it's a field on a related model
3797 3797
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3798
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3798
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3799 3799
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3800
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3800
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3801 3801
                 if ($query_param === '') {
3802 3802
                     //nothing left to $query_param
3803 3803
                     //we should actually end in a field name, not a model like this!
@@ -3883,7 +3883,7 @@  discard block
 block discarded – undo
3883 3883
     {
3884 3884
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3885 3885
         if ($SQL) {
3886
-            return " WHERE " . $SQL;
3886
+            return " WHERE ".$SQL;
3887 3887
         } else {
3888 3888
             return '';
3889 3889
         }
@@ -3903,7 +3903,7 @@  discard block
 block discarded – undo
3903 3903
     {
3904 3904
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3905 3905
         if ($SQL) {
3906
-            return " HAVING " . $SQL;
3906
+            return " HAVING ".$SQL;
3907 3907
         } else {
3908 3908
             return '';
3909 3909
         }
@@ -3923,11 +3923,11 @@  discard block
 block discarded – undo
3923 3923
      */
3924 3924
     protected function _get_field_on_model($field_name, $model_name)
3925 3925
     {
3926
-        $model_class = 'EEM_' . $model_name;
3927
-        $model_filepath = $model_class . ".model.php";
3926
+        $model_class = 'EEM_'.$model_name;
3927
+        $model_filepath = $model_class.".model.php";
3928 3928
         if (is_readable($model_filepath)) {
3929 3929
             require_once($model_filepath);
3930
-            $model_instance = call_user_func($model_name . "::instance");
3930
+            $model_instance = call_user_func($model_name."::instance");
3931 3931
             /* @var $model_instance EEM_Base */
3932 3932
             return $model_instance->field_settings_for($field_name);
3933 3933
         } else {
@@ -3951,7 +3951,7 @@  discard block
 block discarded – undo
3951 3951
     {
3952 3952
         $where_clauses = array();
3953 3953
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3954
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3954
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
3955 3955
             if (in_array($query_param, $this->_logic_query_param_keys)) {
3956 3956
                 switch ($query_param) {
3957 3957
                     case 'not':
@@ -3979,7 +3979,7 @@  discard block
 block discarded – undo
3979 3979
             } else {
3980 3980
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
3981 3981
                 //if it's not a normal field, maybe it's a custom selection?
3982
-                if (! $field_obj) {
3982
+                if ( ! $field_obj) {
3983 3983
                     if (isset($this->_custom_selections[$query_param][1])) {
3984 3984
                         $field_obj = $this->_custom_selections[$query_param][1];
3985 3985
                     } else {
@@ -3988,7 +3988,7 @@  discard block
 block discarded – undo
3988 3988
                     }
3989 3989
                 }
3990 3990
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3991
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3991
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
3992 3992
             }
3993 3993
         }
3994 3994
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4009,7 +4009,7 @@  discard block
 block discarded – undo
4009 4009
         if ($field) {
4010 4010
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4011 4011
                 $query_param);
4012
-            return $table_alias_prefix . $field->get_qualified_column();
4012
+            return $table_alias_prefix.$field->get_qualified_column();
4013 4013
         } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4014 4014
             //maybe it's custom selection item?
4015 4015
             //if so, just use it as the "column name"
@@ -4056,7 +4056,7 @@  discard block
 block discarded – undo
4056 4056
     {
4057 4057
         if (is_array($op_and_value)) {
4058 4058
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4059
-            if (! $operator) {
4059
+            if ( ! $operator) {
4060 4060
                 $php_array_like_string = array();
4061 4061
                 foreach ($op_and_value as $key => $value) {
4062 4062
                     $php_array_like_string[] = "$key=>$value";
@@ -4078,13 +4078,13 @@  discard block
 block discarded – undo
4078 4078
         }
4079 4079
         //check to see if the value is actually another field
4080 4080
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4081
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4081
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4082 4082
         } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4083 4083
             //in this case, the value should be an array, or at least a comma-separated list
4084 4084
             //it will need to handle a little differently
4085 4085
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4086 4086
             //note: $cleaned_value has already been run through $wpdb->prepare()
4087
-            return $operator . SP . $cleaned_value;
4087
+            return $operator.SP.$cleaned_value;
4088 4088
         } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4089 4089
             //the value should be an array with count of two.
4090 4090
             if (count($value) !== 2) {
@@ -4099,7 +4099,7 @@  discard block
 block discarded – undo
4099 4099
                 );
4100 4100
             }
4101 4101
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4102
-            return $operator . SP . $cleaned_value;
4102
+            return $operator.SP.$cleaned_value;
4103 4103
         } elseif (in_array($operator, $this->_null_style_operators)) {
4104 4104
             if ($value !== null) {
4105 4105
                 throw new EE_Error(
@@ -4117,9 +4117,9 @@  discard block
 block discarded – undo
4117 4117
         } elseif ($operator === 'LIKE' && ! is_array($value)) {
4118 4118
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4119 4119
             //remove other junk. So just treat it as a string.
4120
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4121
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4122
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4120
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4121
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4122
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4123 4123
         } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4124 4124
             throw new EE_Error(
4125 4125
                 sprintf(
@@ -4131,7 +4131,7 @@  discard block
 block discarded – undo
4131 4131
                     $operator
4132 4132
                 )
4133 4133
             );
4134
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4134
+        } elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4135 4135
             throw new EE_Error(
4136 4136
                 sprintf(
4137 4137
                     __(
@@ -4172,7 +4172,7 @@  discard block
 block discarded – undo
4172 4172
         foreach ($values as $value) {
4173 4173
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4174 4174
         }
4175
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4175
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4176 4176
     }
4177 4177
 
4178 4178
 
@@ -4213,7 +4213,7 @@  discard block
 block discarded – undo
4213 4213
                                 . $main_table->get_table_name()
4214 4214
                                 . " WHERE FALSE";
4215 4215
         }
4216
-        return "(" . implode(",", $cleaned_values) . ")";
4216
+        return "(".implode(",", $cleaned_values).")";
4217 4217
     }
4218 4218
 
4219 4219
 
@@ -4232,7 +4232,7 @@  discard block
 block discarded – undo
4232 4232
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4233 4233
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4234 4234
         } else {//$field_obj should really just be a data type
4235
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4235
+            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4236 4236
                 throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4237 4237
                     $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4238 4238
             }
@@ -4316,11 +4316,11 @@  discard block
 block discarded – undo
4316 4316
             if ($table_obj instanceof EE_Primary_Table) {
4317 4317
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4318 4318
                     ? $table_obj->get_select_join_limit($limit)
4319
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4319
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4320 4320
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4321 4321
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4322 4322
                     ? $table_obj->get_select_join_limit_join($limit)
4323
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4323
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4324 4324
             }
4325 4325
         }
4326 4326
         return $SQL;
@@ -4408,12 +4408,12 @@  discard block
 block discarded – undo
4408 4408
      */
4409 4409
     public function get_related_model_obj($model_name)
4410 4410
     {
4411
-        $model_classname = "EEM_" . $model_name;
4412
-        if (! class_exists($model_classname)) {
4411
+        $model_classname = "EEM_".$model_name;
4412
+        if ( ! class_exists($model_classname)) {
4413 4413
             throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4414 4414
                 'event_espresso'), $model_name, $model_classname));
4415 4415
         }
4416
-        return call_user_func($model_classname . "::instance");
4416
+        return call_user_func($model_classname."::instance");
4417 4417
     }
4418 4418
 
4419 4419
 
@@ -4460,7 +4460,7 @@  discard block
 block discarded – undo
4460 4460
     public function related_settings_for($relation_name)
4461 4461
     {
4462 4462
         $relatedModels = $this->relation_settings();
4463
-        if (! array_key_exists($relation_name, $relatedModels)) {
4463
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4464 4464
             throw new EE_Error(
4465 4465
                 sprintf(
4466 4466
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4487,7 +4487,7 @@  discard block
 block discarded – undo
4487 4487
     public function field_settings_for($fieldName)
4488 4488
     {
4489 4489
         $fieldSettings = $this->field_settings(true);
4490
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4490
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4491 4491
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4492 4492
                 get_class($this)));
4493 4493
         }
@@ -4562,7 +4562,7 @@  discard block
 block discarded – undo
4562 4562
                     break;
4563 4563
                 }
4564 4564
             }
4565
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4565
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4566 4566
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4567 4567
                     get_class($this)));
4568 4568
             }
@@ -4621,7 +4621,7 @@  discard block
 block discarded – undo
4621 4621
      */
4622 4622
     public function get_foreign_key_to($model_name)
4623 4623
     {
4624
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4624
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4625 4625
             foreach ($this->field_settings() as $field) {
4626 4626
                 if (
4627 4627
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4631,7 +4631,7 @@  discard block
 block discarded – undo
4631 4631
                     break;
4632 4632
                 }
4633 4633
             }
4634
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4634
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4635 4635
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4636 4636
                     'event_espresso'), $model_name, get_class($this)));
4637 4637
             }
@@ -4682,7 +4682,7 @@  discard block
 block discarded – undo
4682 4682
                 foreach ($this->_fields as $fields_corresponding_to_table) {
4683 4683
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4684 4684
                         /** @var $field_obj EE_Model_Field_Base */
4685
-                        if (! $field_obj->is_db_only_field()) {
4685
+                        if ( ! $field_obj->is_db_only_field()) {
4686 4686
                             $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4687 4687
                         }
4688 4688
                     }
@@ -4712,7 +4712,7 @@  discard block
 block discarded – undo
4712 4712
         $count_if_model_has_no_primary_key = 0;
4713 4713
         $has_primary_key = $this->has_primary_key_field();
4714 4714
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4715
-        foreach ((array)$rows as $row) {
4715
+        foreach ((array) $rows as $row) {
4716 4716
             if (empty($row)) {
4717 4717
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4718 4718
                 return array();
@@ -4730,7 +4730,7 @@  discard block
 block discarded – undo
4730 4730
                 }
4731 4731
             }
4732 4732
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4733
-            if (! $classInstance) {
4733
+            if ( ! $classInstance) {
4734 4734
                 throw new EE_Error(
4735 4735
                     sprintf(
4736 4736
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -4799,7 +4799,7 @@  discard block
 block discarded – undo
4799 4799
      */
4800 4800
     public function instantiate_class_from_array_or_object($cols_n_values)
4801 4801
     {
4802
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4802
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4803 4803
             $cols_n_values = get_object_vars($cols_n_values);
4804 4804
         }
4805 4805
         $primary_key = null;
@@ -4824,7 +4824,7 @@  discard block
 block discarded – undo
4824 4824
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4825 4825
         if ($primary_key) {
4826 4826
             $classInstance = $this->get_from_entity_map($primary_key);
4827
-            if (! $classInstance) {
4827
+            if ( ! $classInstance) {
4828 4828
                 $classInstance = EE_Registry::instance()
4829 4829
                                             ->load_class($className,
4830 4830
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -4875,12 +4875,12 @@  discard block
 block discarded – undo
4875 4875
     public function add_to_entity_map(EE_Base_Class $object)
4876 4876
     {
4877 4877
         $className = $this->_get_class_name();
4878
-        if (! $object instanceof $className) {
4878
+        if ( ! $object instanceof $className) {
4879 4879
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4880 4880
                 is_object($object) ? get_class($object) : $object, $className));
4881 4881
         }
4882 4882
         /** @var $object EE_Base_Class */
4883
-        if (! $object->ID()) {
4883
+        if ( ! $object->ID()) {
4884 4884
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4885 4885
                 "event_espresso"), get_class($this)));
4886 4886
         }
@@ -4950,7 +4950,7 @@  discard block
 block discarded – undo
4950 4950
             //there is a primary key on this table and its not set. Use defaults for all its columns
4951 4951
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
4952 4952
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4953
-                    if (! $field_obj->is_db_only_field()) {
4953
+                    if ( ! $field_obj->is_db_only_field()) {
4954 4954
                         //prepare field as if its coming from db
4955 4955
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4956 4956
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -4959,7 +4959,7 @@  discard block
 block discarded – undo
4959 4959
             } else {
4960 4960
                 //the table's rows existed. Use their values
4961 4961
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4962
-                    if (! $field_obj->is_db_only_field()) {
4962
+                    if ( ! $field_obj->is_db_only_field()) {
4963 4963
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4964 4964
                             $cols_n_values, $field_obj->get_qualified_column(),
4965 4965
                             $field_obj->get_table_column()
@@ -5076,7 +5076,7 @@  discard block
 block discarded – undo
5076 5076
      */
5077 5077
     private function _get_class_name()
5078 5078
     {
5079
-        return "EE_" . $this->get_this_model_name();
5079
+        return "EE_".$this->get_this_model_name();
5080 5080
     }
5081 5081
 
5082 5082
 
@@ -5091,7 +5091,7 @@  discard block
 block discarded – undo
5091 5091
      */
5092 5092
     public function item_name($quantity = 1)
5093 5093
     {
5094
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5094
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5095 5095
     }
5096 5096
 
5097 5097
 
@@ -5124,7 +5124,7 @@  discard block
 block discarded – undo
5124 5124
     {
5125 5125
         $className = get_class($this);
5126 5126
         $tagName = "FHEE__{$className}__{$methodName}";
5127
-        if (! has_filter($tagName)) {
5127
+        if ( ! has_filter($tagName)) {
5128 5128
             throw new EE_Error(
5129 5129
                 sprintf(
5130 5130
                     __('Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
@@ -5350,7 +5350,7 @@  discard block
 block discarded – undo
5350 5350
         $key_vals_in_combined_pk = array();
5351 5351
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5352 5352
         foreach ($key_fields as $key_field_name => $field_obj) {
5353
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5353
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5354 5354
                 return null;
5355 5355
             }
5356 5356
         }
@@ -5371,7 +5371,7 @@  discard block
 block discarded – undo
5371 5371
     {
5372 5372
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5373 5373
         foreach ($keys_it_should_have as $key) {
5374
-            if (! isset($key_vals[$key])) {
5374
+            if ( ! isset($key_vals[$key])) {
5375 5375
                 return false;
5376 5376
             }
5377 5377
         }
@@ -5425,7 +5425,7 @@  discard block
 block discarded – undo
5425 5425
      */
5426 5426
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5427 5427
     {
5428
-        if (! is_array($query_params)) {
5428
+        if ( ! is_array($query_params)) {
5429 5429
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5430 5430
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5431 5431
                     gettype($query_params)), '4.6.0');
@@ -5517,7 +5517,7 @@  discard block
 block discarded – undo
5517 5517
      */
5518 5518
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5519 5519
     {
5520
-        if (! $this->has_primary_key_field()) {
5520
+        if ( ! $this->has_primary_key_field()) {
5521 5521
             if (WP_DEBUG) {
5522 5522
                 EE_Error::add_error(
5523 5523
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5530,7 +5530,7 @@  discard block
 block discarded – undo
5530 5530
         $IDs = array();
5531 5531
         foreach ($model_objects as $model_object) {
5532 5532
             $id = $model_object->ID();
5533
-            if (! $id) {
5533
+            if ( ! $id) {
5534 5534
                 if ($filter_out_empty_ids) {
5535 5535
                     continue;
5536 5536
                 }
@@ -5626,8 +5626,8 @@  discard block
 block discarded – undo
5626 5626
         $missing_caps = array();
5627 5627
         $cap_restrictions = $this->cap_restrictions($context);
5628 5628
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5629
-            if (! EE_Capabilities::instance()
5630
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5629
+            if ( ! EE_Capabilities::instance()
5630
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5631 5631
             ) {
5632 5632
                 $missing_caps[$cap] = $restriction_if_no_cap;
5633 5633
             }
@@ -5778,7 +5778,7 @@  discard block
 block discarded – undo
5778 5778
     {
5779 5779
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5780 5780
             if ($query_param_key === $logic_query_param_key
5781
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5781
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
5782 5782
             ) {
5783 5783
                 return true;
5784 5784
             }
Please login to merge, or discard this patch.