Completed
Branch FET/11406/add-user-id-notices (d29261)
by
unknown
123:10 queued 109:19
created
core/admin/EE_Admin_Page.core.php 1 patch
Indentation   +4125 added lines, -4125 removed lines patch added patch discarded remove patch
@@ -21,4210 +21,4210 @@
 block discarded – undo
21 21
 {
22 22
 
23 23
 
24
-    //set in _init_page_props()
25
-    public $page_slug;
24
+	//set in _init_page_props()
25
+	public $page_slug;
26 26
 
27
-    public $page_label;
27
+	public $page_label;
28 28
 
29
-    public $page_folder;
29
+	public $page_folder;
30 30
 
31
-    //set in define_page_props()
32
-    protected $_admin_base_url;
31
+	//set in define_page_props()
32
+	protected $_admin_base_url;
33 33
 
34
-    protected $_admin_base_path;
34
+	protected $_admin_base_path;
35 35
 
36
-    protected $_admin_page_title;
36
+	protected $_admin_page_title;
37 37
 
38
-    protected $_labels;
38
+	protected $_labels;
39 39
 
40 40
 
41
-    //set early within EE_Admin_Init
42
-    protected $_wp_page_slug;
41
+	//set early within EE_Admin_Init
42
+	protected $_wp_page_slug;
43 43
 
44
-    //navtabs
45
-    protected $_nav_tabs;
44
+	//navtabs
45
+	protected $_nav_tabs;
46 46
 
47
-    protected $_default_nav_tab_name;
47
+	protected $_default_nav_tab_name;
48 48
 
49
-    /**
50
-     * @var array $_help_tour
51
-     */
52
-    protected $_help_tour = array();
49
+	/**
50
+	 * @var array $_help_tour
51
+	 */
52
+	protected $_help_tour = array();
53 53
 
54 54
 
55
-    //template variables (used by templates)
56
-    protected $_template_path;
55
+	//template variables (used by templates)
56
+	protected $_template_path;
57 57
 
58
-    protected $_column_template_path;
58
+	protected $_column_template_path;
59 59
 
60
-    /**
61
-     * @var array $_template_args
62
-     */
63
-    protected $_template_args = array();
60
+	/**
61
+	 * @var array $_template_args
62
+	 */
63
+	protected $_template_args = array();
64 64
 
65
-    /**
66
-     * this will hold the list table object for a given view.
67
-     *
68
-     * @var EE_Admin_List_Table $_list_table_object
69
-     */
70
-    protected $_list_table_object;
65
+	/**
66
+	 * this will hold the list table object for a given view.
67
+	 *
68
+	 * @var EE_Admin_List_Table $_list_table_object
69
+	 */
70
+	protected $_list_table_object;
71 71
 
72
-    //bools
73
-    protected $_is_UI_request = null; //this starts at null so we can have no header routes progress through two states.
72
+	//bools
73
+	protected $_is_UI_request = null; //this starts at null so we can have no header routes progress through two states.
74 74
 
75
-    protected $_routing;
75
+	protected $_routing;
76 76
 
77
-    //list table args
78
-    protected $_view;
77
+	//list table args
78
+	protected $_view;
79 79
 
80
-    protected $_views;
80
+	protected $_views;
81 81
 
82 82
 
83
-    //action => method pairs used for routing incoming requests
84
-    protected $_page_routes;
83
+	//action => method pairs used for routing incoming requests
84
+	protected $_page_routes;
85 85
 
86
-    /**
87
-     * @var array $_page_config
88
-     */
89
-    protected $_page_config;
86
+	/**
87
+	 * @var array $_page_config
88
+	 */
89
+	protected $_page_config;
90 90
 
91
-    /**
92
-     * the current page route and route config
93
-     *
94
-     * @var string $_route
95
-     */
96
-    protected $_route;
91
+	/**
92
+	 * the current page route and route config
93
+	 *
94
+	 * @var string $_route
95
+	 */
96
+	protected $_route;
97 97
 
98
-    /**
99
-     * @var string $_cpt_route
100
-     */
101
-    protected $_cpt_route;
98
+	/**
99
+	 * @var string $_cpt_route
100
+	 */
101
+	protected $_cpt_route;
102 102
 
103
-    /**
104
-     * @var array $_route_config
105
-     */
106
-    protected $_route_config;
103
+	/**
104
+	 * @var array $_route_config
105
+	 */
106
+	protected $_route_config;
107 107
 
108
-    /**
109
-     * Used to hold default query args for list table routes to help preserve stickiness of filters for carried out
110
-     * actions.
111
-     *
112
-     * @since 4.6.x
113
-     * @var array.
114
-     */
115
-    protected $_default_route_query_args;
116
-
117
-    //set via request page and action args.
118
-    protected $_current_page;
108
+	/**
109
+	 * Used to hold default query args for list table routes to help preserve stickiness of filters for carried out
110
+	 * actions.
111
+	 *
112
+	 * @since 4.6.x
113
+	 * @var array.
114
+	 */
115
+	protected $_default_route_query_args;
116
+
117
+	//set via request page and action args.
118
+	protected $_current_page;
119 119
 
120
-    protected $_current_view;
120
+	protected $_current_view;
121 121
 
122
-    protected $_current_page_view_url;
122
+	protected $_current_page_view_url;
123 123
 
124
-    //sanitized request action (and nonce)
124
+	//sanitized request action (and nonce)
125 125
 
126
-    /**
127
-     * @var string $_req_action
128
-     */
129
-    protected $_req_action;
130
-
131
-    /**
132
-     * @var string $_req_nonce
133
-     */
134
-    protected $_req_nonce;
135
-
136
-    //search related
137
-    protected $_search_btn_label;
138
-
139
-    protected $_search_box_callback;
140
-
141
-    /**
142
-     * WP Current Screen object
143
-     *
144
-     * @var WP_Screen
145
-     */
146
-    protected $_current_screen;
147
-
148
-    //for holding EE_Admin_Hooks object when needed (set via set_hook_object())
149
-    protected $_hook_obj;
150
-
151
-    //for holding incoming request data
152
-    protected $_req_data;
153
-
154
-    // yes / no array for admin form fields
155
-    protected $_yes_no_values = array();
156
-
157
-    //some default things shared by all child classes
158
-    protected $_default_espresso_metaboxes;
159
-
160
-    /**
161
-     *    EE_Registry Object
162
-     *
163
-     * @var    EE_Registry
164
-     */
165
-    protected $EE = null;
166
-
167
-
168
-
169
-    /**
170
-     * This is just a property that flags whether the given route is a caffeinated route or not.
171
-     *
172
-     * @var boolean
173
-     */
174
-    protected $_is_caf = false;
175
-
176
-
177
-
178
-    /**
179
-     * @Constructor
180
-     * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
181
-     * @throws EE_Error
182
-     * @throws InvalidArgumentException
183
-     * @throws ReflectionException
184
-     * @throws InvalidDataTypeException
185
-     * @throws InvalidInterfaceException
186
-     */
187
-    public function __construct($routing = true)
188
-    {
189
-        if (strpos($this->_get_dir(), 'caffeinated') !== false) {
190
-            $this->_is_caf = true;
191
-        }
192
-        $this->_yes_no_values = array(
193
-            array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
194
-            array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
195
-        );
196
-        //set the _req_data property.
197
-        $this->_req_data = array_merge($_GET, $_POST);
198
-        //routing enabled?
199
-        $this->_routing = $routing;
200
-        //set initial page props (child method)
201
-        $this->_init_page_props();
202
-        //set global defaults
203
-        $this->_set_defaults();
204
-        //set early because incoming requests could be ajax related and we need to register those hooks.
205
-        $this->_global_ajax_hooks();
206
-        $this->_ajax_hooks();
207
-        //other_page_hooks have to be early too.
208
-        $this->_do_other_page_hooks();
209
-        //This just allows us to have extending classes do something specific
210
-        // before the parent constructor runs _page_setup().
211
-        if (method_exists($this, '_before_page_setup')) {
212
-            $this->_before_page_setup();
213
-        }
214
-        //set up page dependencies
215
-        $this->_page_setup();
216
-    }
217
-
218
-
219
-
220
-    /**
221
-     * _init_page_props
222
-     * Child classes use to set at least the following properties:
223
-     * $page_slug.
224
-     * $page_label.
225
-     *
226
-     * @abstract
227
-     * @return void
228
-     */
229
-    abstract protected function _init_page_props();
230
-
231
-
232
-
233
-    /**
234
-     * _ajax_hooks
235
-     * child classes put all their add_action('wp_ajax_{name_of_hook}') hooks in here.
236
-     * Note: within the ajax callback methods.
237
-     *
238
-     * @abstract
239
-     * @return void
240
-     */
241
-    abstract protected function _ajax_hooks();
242
-
243
-
244
-
245
-    /**
246
-     * _define_page_props
247
-     * child classes define page properties in here.  Must include at least:
248
-     * $_admin_base_url = base_url for all admin pages
249
-     * $_admin_page_title = default admin_page_title for admin pages
250
-     * $_labels = array of default labels for various automatically generated elements:
251
-     *    array(
252
-     *        'buttons' => array(
253
-     *            'add' => esc_html__('label for add new button'),
254
-     *            'edit' => esc_html__('label for edit button'),
255
-     *            'delete' => esc_html__('label for delete button')
256
-     *            )
257
-     *        )
258
-     *
259
-     * @abstract
260
-     * @return void
261
-     */
262
-    abstract protected function _define_page_props();
263
-
264
-
265
-
266
-    /**
267
-     * _set_page_routes
268
-     * child classes use this to define the page routes for all subpages handled by the class.  Page routes are
269
-     * assigned to a action => method pairs in an array and to the $_page_routes property.  Each page route must also
270
-     * have a 'default' route. Here's the format
271
-     * $this->_page_routes = array(
272
-     *        'default' => array(
273
-     *            'func' => '_default_method_handling_route',
274
-     *            'args' => array('array','of','args'),
275
-     *            'noheader' => true, //add this in if this page route is processed before any headers are loaded (i.e.
276
-     *            ajax request, backend processing)
277
-     *            'headers_sent_route'=>'headers_route_reference', //add this if noheader=>true, and you want to load a
278
-     *            headers route after.  The string you enter here should match the defined route reference for a
279
-     *            headers sent route.
280
-     *            'capability' => 'route_capability', //indicate a string for minimum capability required to access
281
-     *            this route.
282
-     *            'obj_id' => 10 // if this route has an object id, then this can include it (used for capability
283
-     *            checks).
284
-     *        ),
285
-     *        'insert_item' => '_method_for_handling_insert_item' //this can be used if all we need to have is a
286
-     *        handling method.
287
-     *        )
288
-     * )
289
-     *
290
-     * @abstract
291
-     * @return void
292
-     */
293
-    abstract protected function _set_page_routes();
294
-
295
-
296
-
297
-    /**
298
-     * _set_page_config
299
-     * child classes use this to define the _page_config array for all subpages handled by the class. Each key in the
300
-     * array corresponds to the page_route for the loaded page. Format:
301
-     * $this->_page_config = array(
302
-     *        'default' => array(
303
-     *            'labels' => array(
304
-     *                'buttons' => array(
305
-     *                    'add' => esc_html__('label for adding item'),
306
-     *                    'edit' => esc_html__('label for editing item'),
307
-     *                    'delete' => esc_html__('label for deleting item')
308
-     *                ),
309
-     *                'publishbox' => esc_html__('Localized Title for Publish metabox', 'event_espresso')
310
-     *            ), //optional an array of custom labels for various automatically generated elements to use on the
311
-     *            page. If this isn't present then the defaults will be used as set for the $this->_labels in
312
-     *            _define_page_props() method
313
-     *            'nav' => array(
314
-     *                'label' => esc_html__('Label for Tab', 'event_espresso').
315
-     *                'url' => 'http://someurl', //automatically generated UNLESS you define
316
-     *                'css_class' => 'css-class', //automatically generated UNLESS you define
317
-     *                'order' => 10, //required to indicate tab position.
318
-     *                'persistent' => false //if you want the nav tab to ONLY display when the specific route is
319
-     *                displayed then add this parameter.
320
-     *            'list_table' => 'name_of_list_table' //string for list table class to be loaded for this admin_page.
321
-     *            'metaboxes' => array('metabox1', 'metabox2'), //if present this key indicates we want to load
322
-     *            metaboxes set for eventespresso admin pages.
323
-     *            'has_metaboxes' => true, //this boolean flag can simply be used to indicate if the route will have
324
-     *            metaboxes.  Typically this is used if the 'metaboxes' index is not used because metaboxes are added
325
-     *            later.  We just use this flag to make sure the necessary js gets enqueued on page load.
326
-     *            'has_help_popups' => false //defaults(true) //this boolean flag can simply be used to indicate if the
327
-     *            given route has help popups setup and if it does then we need to make sure thickbox is enqueued.
328
-     *            'columns' => array(4, 2), //this key triggers the setup of a page that uses columns (metaboxes).  The
329
-     *            array indicates the max number of columns (4) and the default number of columns on page load (2).
330
-     *            There is an option in the "screen_options" dropdown that is setup so users can pick what columns they
331
-     *            want to display.
332
-     *            'help_tabs' => array( //this is used for adding help tabs to a page
333
-     *                'tab_id' => array(
334
-     *                    'title' => 'tab_title',
335
-     *                    'filename' => 'name_of_file_containing_content', //this is the primary method for setting
336
-     *                    help tab content.  The fallback if it isn't present is to try a the callback.  Filename
337
-     *                    should match a file in the admin folder's "help_tabs" dir (ie..
338
-     *                    events/help_tabs/name_of_file_containing_content.help_tab.php)
339
-     *                    'callback' => 'callback_method_for_content', //if 'filename' isn't present then system will
340
-     *                    attempt to use the callback which should match the name of a method in the class
341
-     *                    ),
342
-     *                'tab2_id' => array(
343
-     *                    'title' => 'tab2 title',
344
-     *                    'filename' => 'file_name_2'
345
-     *                    'callback' => 'callback_method_for_content',
346
-     *                 ),
347
-     *            'help_sidebar' => 'callback_for_sidebar_content', //this is used for setting up the sidebar in the
348
-     *            help tab area on an admin page. @link
349
-     *            http://make.wordpress.org/core/2011/12/06/help-and-screen-api-changes-in-3-3/
350
-     *            'help_tour' => array(
351
-     *                'name_of_help_tour_class', //all help tours shoudl be a child class of EE_Help_Tour and located
352
-     *                in a folder for this admin page named "help_tours", a file name matching the key given here
353
-     *                (name_of_help_tour_class.class.php), and class matching key given here (name_of_help_tour_class)
354
-     *            ),
355
-     *            'require_nonce' => TRUE //this is used if you want to set a route to NOT require a nonce (default is
356
-     *            true if it isn't present).  To remove the requirement for a nonce check when this route is visited
357
-     *            just set
358
-     *            'require_nonce' to FALSE
359
-     *            )
360
-     * )
361
-     *
362
-     * @abstract
363
-     * @return void
364
-     */
365
-    abstract protected function _set_page_config();
366
-
367
-
368
-
369
-
370
-
371
-    /** end sample help_tour methods **/
372
-    /**
373
-     * _add_screen_options
374
-     * Child classes can add any extra wp_screen_options within this method using built-in WP functions/methods for
375
-     * doing so. Note child classes can also define _add_screen_options_($this->_current_view) to limit screen options
376
-     * to a particular view.
377
-     *
378
-     * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
379
-     *         see also WP_Screen object documents...
380
-     * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
381
-     * @abstract
382
-     * @return void
383
-     */
384
-    abstract protected function _add_screen_options();
385
-
386
-
387
-
388
-    /**
389
-     * _add_feature_pointers
390
-     * Child classes should use this method for implementing any "feature pointers" (using built-in WP styling js).
391
-     * Note child classes can also define _add_feature_pointers_($this->_current_view) to limit screen options to a
392
-     * particular view. Note: this is just a placeholder for now.  Implementation will come down the road See:
393
-     * WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be
394
-     * extended) also see:
395
-     *
396
-     * @link   http://eamann.com/tech/wordpress-portland/
397
-     * @abstract
398
-     * @return void
399
-     */
400
-    abstract protected function _add_feature_pointers();
401
-
402
-
403
-
404
-    /**
405
-     * load_scripts_styles
406
-     * child classes put their wp_enqueue_script and wp_enqueue_style hooks in here for anything they need loaded for
407
-     * their pages/subpages.  Note this is for all pages/subpages of the system.  You can also load only specific
408
-     * scripts/styles per view by putting them in a dynamic function in this format
409
-     * (load_scripts_styles_{$this->_current_view}) which matches your page route (action request arg)
410
-     *
411
-     * @abstract
412
-     * @return void
413
-     */
414
-    abstract public function load_scripts_styles();
415
-
416
-
417
-
418
-    /**
419
-     * admin_init
420
-     * Anything that should be set/executed at 'admin_init' WP hook runtime should be put in here.  This will apply to
421
-     * all pages/views loaded by child class.
422
-     *
423
-     * @abstract
424
-     * @return void
425
-     */
426
-    abstract public function admin_init();
427
-
428
-
429
-
430
-    /**
431
-     * admin_notices
432
-     * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply to
433
-     * all pages/views loaded by child class.
434
-     *
435
-     * @abstract
436
-     * @return void
437
-     */
438
-    abstract public function admin_notices();
439
-
440
-
441
-
442
-    /**
443
-     * admin_footer_scripts
444
-     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
445
-     * will apply to all pages/views loaded by child class.
446
-     *
447
-     * @return void
448
-     */
449
-    abstract public function admin_footer_scripts();
450
-
451
-
452
-
453
-    /**
454
-     * admin_footer
455
-     * anything triggered by the 'admin_footer' WP action hook should be added to here. This particular method will
456
-     * apply to all pages/views loaded by child class.
457
-     *
458
-     * @return void
459
-     */
460
-    public function admin_footer()
461
-    {
462
-    }
463
-
464
-
465
-
466
-    /**
467
-     * _global_ajax_hooks
468
-     * all global add_action('wp_ajax_{name_of_hook}') hooks in here.
469
-     * Note: within the ajax callback methods.
470
-     *
471
-     * @abstract
472
-     * @return void
473
-     */
474
-    protected function _global_ajax_hooks()
475
-    {
476
-        //for lazy loading of metabox content
477
-        add_action('wp_ajax_espresso-ajax-content', array($this, 'ajax_metabox_content'), 10);
478
-    }
479
-
480
-
481
-
482
-    public function ajax_metabox_content()
483
-    {
484
-        $contentid = isset($this->_req_data['contentid']) ? $this->_req_data['contentid'] : '';
485
-        $url       = isset($this->_req_data['contenturl']) ? $this->_req_data['contenturl'] : '';
486
-        self::cached_rss_display($contentid, $url);
487
-        wp_die();
488
-    }
489
-
490
-
491
-
492
-    /**
493
-     * _page_setup
494
-     * Makes sure any things that need to be loaded early get handled.  We also escape early here if the page requested
495
-     * doesn't match the object.
496
-     *
497
-     * @final
498
-     * @return void
499
-     * @throws EE_Error
500
-     * @throws InvalidArgumentException
501
-     * @throws ReflectionException
502
-     * @throws InvalidDataTypeException
503
-     * @throws InvalidInterfaceException
504
-     */
505
-    final protected function _page_setup()
506
-    {
507
-        //requires?
508
-        //admin_init stuff - global - we're setting this REALLY early so if EE_Admin pages have to hook into other WP pages they can.  But keep in mind, not everything is available from the EE_Admin Page object at this point.
509
-        add_action('admin_init', array($this, 'admin_init_global'), 5);
510
-        //next verify if we need to load anything...
511
-        $this->_current_page = ! empty($_GET['page']) ? sanitize_key($_GET['page']) : '';
512
-        $this->page_folder   = strtolower(
513
-            str_replace(array('_Admin_Page', 'Extend_'), '', get_class($this))
514
-        );
515
-        global $ee_menu_slugs;
516
-        $ee_menu_slugs = (array)$ee_menu_slugs;
517
-        if (! defined('DOING_AJAX') && (! $this->_current_page || ! isset($ee_menu_slugs[$this->_current_page]))) {
518
-            return;
519
-        }
520
-        // becuz WP List tables have two duplicate select inputs for choosing bulk actions, we need to copy the action from the second to the first
521
-        if (isset($this->_req_data['action2']) && $this->_req_data['action'] === '-1') {
522
-            $this->_req_data['action'] = ! empty($this->_req_data['action2']) && $this->_req_data['action2'] !== '-1'
523
-                ? $this->_req_data['action2']
524
-                : $this->_req_data['action'];
525
-        }
526
-        // then set blank or -1 action values to 'default'
527
-        $this->_req_action = isset($this->_req_data['action'])
528
-                             && ! empty($this->_req_data['action'])
529
-                             && $this->_req_data['action'] !== '-1'
530
-            ? sanitize_key($this->_req_data['action'])
531
-            : 'default';
532
-        // if action is 'default' after the above BUT we have  'route' var set, then let's use the route as the action.
533
-        //  This covers cases where we're coming in from a list table that isn't on the default route.
534
-        $this->_req_action = $this->_req_action === 'default' && isset($this->_req_data['route'])
535
-            ? $this->_req_data['route'] : $this->_req_action;
536
-        //however if we are doing_ajax and we've got a 'route' set then that's what the req_action will be
537
-        $this->_req_action   = defined('DOING_AJAX') && isset($this->_req_data['route'])
538
-            ? $this->_req_data['route']
539
-            : $this->_req_action;
540
-        $this->_current_view = $this->_req_action;
541
-        $this->_req_nonce    = $this->_req_action . '_nonce';
542
-        $this->_define_page_props();
543
-        $this->_current_page_view_url = add_query_arg(
544
-            array('page' => $this->_current_page, 'action' => $this->_current_view),
545
-            $this->_admin_base_url
546
-        );
547
-        //default things
548
-        $this->_default_espresso_metaboxes = array(
549
-            '_espresso_news_post_box',
550
-            '_espresso_links_post_box',
551
-            '_espresso_ratings_request',
552
-            '_espresso_sponsors_post_box',
553
-        );
554
-        //set page configs
555
-        $this->_set_page_routes();
556
-        $this->_set_page_config();
557
-        //let's include any referrer data in our default_query_args for this route for "stickiness".
558
-        if (isset($this->_req_data['wp_referer'])) {
559
-            $this->_default_route_query_args['wp_referer'] = $this->_req_data['wp_referer'];
560
-        }
561
-        //for caffeinated and other extended functionality.
562
-        //  If there is a _extend_page_config method
563
-        // then let's run that to modify the all the various page configuration arrays
564
-        if (method_exists($this, '_extend_page_config')) {
565
-            $this->_extend_page_config();
566
-        }
567
-        //for CPT and other extended functionality.
568
-        // If there is an _extend_page_config_for_cpt
569
-        // then let's run that to modify all the various page configuration arrays.
570
-        if (method_exists($this, '_extend_page_config_for_cpt')) {
571
-            $this->_extend_page_config_for_cpt();
572
-        }
573
-        //filter routes and page_config so addons can add their stuff. Filtering done per class
574
-        $this->_page_routes = apply_filters(
575
-            'FHEE__' . get_class($this) . '__page_setup__page_routes',
576
-            $this->_page_routes,
577
-            $this
578
-        );
579
-        $this->_page_config = apply_filters(
580
-            'FHEE__' . get_class($this) . '__page_setup__page_config',
581
-            $this->_page_config,
582
-            $this
583
-        );
584
-        //if AHEE__EE_Admin_Page__route_admin_request_$this->_current_view method is present
585
-        // then we call it hooked into the AHEE__EE_Admin_Page__route_admin_request action
586
-        if (
587
-            method_exists($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view)
588
-        ) {
589
-            add_action(
590
-                'AHEE__EE_Admin_Page__route_admin_request',
591
-                array($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view),
592
-                10,
593
-                2
594
-            );
595
-        }
596
-        //next route only if routing enabled
597
-        if ($this->_routing && ! defined('DOING_AJAX')) {
598
-            $this->_verify_routes();
599
-            //next let's just check user_access and kill if no access
600
-            $this->check_user_access();
601
-            if ($this->_is_UI_request) {
602
-                //admin_init stuff - global, all views for this page class, specific view
603
-                add_action('admin_init', array($this, 'admin_init'), 10);
604
-                if (method_exists($this, 'admin_init_' . $this->_current_view)) {
605
-                    add_action('admin_init', array($this, 'admin_init_' . $this->_current_view), 15);
606
-                }
607
-            } else {
608
-                //hijack regular WP loading and route admin request immediately
609
-                @ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT));
610
-                $this->route_admin_request();
611
-            }
612
-        }
613
-    }
614
-
615
-
616
-
617
-    /**
618
-     * Provides a way for related child admin pages to load stuff on the loaded admin page.
619
-     *
620
-     * @return void
621
-     * @throws ReflectionException
622
-     * @throws EE_Error
623
-     */
624
-    private function _do_other_page_hooks()
625
-    {
626
-        $registered_pages = apply_filters('FHEE_do_other_page_hooks_' . $this->page_slug, array());
627
-        foreach ($registered_pages as $page) {
628
-            //now let's setup the file name and class that should be present
629
-            $classname = str_replace('.class.php', '', $page);
630
-            //autoloaders should take care of loading file
631
-            if (! class_exists($classname)) {
632
-                $error_msg[] = sprintf(
633
-                    esc_html__(
634
-                        'Something went wrong with loading the %s admin hooks page.',
635
-                        'event_espresso'
636
-                    ),
637
-                    $page
638
-                );
639
-                $error_msg[] = $error_msg[0]
640
-                               . "\r\n"
641
-                               . sprintf(
642
-                                   esc_html__(
643
-                                       'There is no class in place for the %1$s admin hooks page.%2$sMake sure you have %3$s defined. If this is a non-EE-core admin page then you also must have an autoloader in place for your class',
644
-                                       'event_espresso'
645
-                                   ),
646
-                                   $page,
647
-                                   '<br />',
648
-                                   '<strong>' . $classname . '</strong>'
649
-                               );
650
-                throw new EE_Error(implode('||', $error_msg));
651
-            }
652
-            $a = new ReflectionClass($classname);
653
-            //notice we are passing the instance of this class to the hook object.
654
-            $hookobj[] = $a->newInstance($this);
655
-        }
656
-    }
657
-
658
-
659
-
660
-    public function load_page_dependencies()
661
-    {
662
-        try {
663
-            $this->_load_page_dependencies();
664
-        } catch (EE_Error $e) {
665
-            $e->get_error();
666
-        }
667
-    }
668
-
669
-
670
-
671
-    /**
672
-     * load_page_dependencies
673
-     * loads things specific to this page class when its loaded.  Really helps with efficiency.
674
-     *
675
-     * @return void
676
-     * @throws DomainException
677
-     * @throws EE_Error
678
-     * @throws InvalidArgumentException
679
-     * @throws InvalidDataTypeException
680
-     * @throws InvalidInterfaceException
681
-     * @throws ReflectionException
682
-     */
683
-    protected function _load_page_dependencies()
684
-    {
685
-        //let's set the current_screen and screen options to override what WP set
686
-        $this->_current_screen = get_current_screen();
687
-        //load admin_notices - global, page class, and view specific
688
-        add_action('admin_notices', array($this, 'admin_notices_global'), 5);
689
-        add_action('admin_notices', array($this, 'admin_notices'), 10);
690
-        if (method_exists($this, 'admin_notices_' . $this->_current_view)) {
691
-            add_action('admin_notices', array($this, 'admin_notices_' . $this->_current_view), 15);
692
-        }
693
-        //load network admin_notices - global, page class, and view specific
694
-        add_action('network_admin_notices', array($this, 'network_admin_notices_global'), 5);
695
-        if (method_exists($this, 'network_admin_notices_' . $this->_current_view)) {
696
-            add_action('network_admin_notices', array($this, 'network_admin_notices_' . $this->_current_view));
697
-        }
698
-        //this will save any per_page screen options if they are present
699
-        $this->_set_per_page_screen_options();
700
-        //setup list table properties
701
-        $this->_set_list_table();
702
-        // child classes can "register" a metabox to be automatically handled via the _page_config array property.
703
-        // However in some cases the metaboxes will need to be added within a route handling callback.
704
-        $this->_add_registered_meta_boxes();
705
-        $this->_add_screen_columns();
706
-        //add screen options - global, page child class, and view specific
707
-        $this->_add_global_screen_options();
708
-        $this->_add_screen_options();
709
-        $add_screen_options  = "_add_screen_options_{$this->_current_view}";
710
-        if (method_exists($this, $add_screen_options )) {
711
-            $this->{$add_screen_options}();
712
-        }
713
-        //add help tab(s) and tours- set via page_config and qtips.
714
-        $this->_add_help_tour();
715
-        $this->_add_help_tabs();
716
-        $this->_add_qtips();
717
-        //add feature_pointers - global, page child class, and view specific
718
-        $this->_add_feature_pointers();
719
-        $this->_add_global_feature_pointers();
720
-        $add_feature_pointer = "_add_feature_pointer_{$this->_current_view}";
721
-        if (method_exists($this, $add_feature_pointer )) {
722
-            $this->{$add_feature_pointer}();
723
-        }
724
-        //enqueue scripts/styles - global, page class, and view specific
725
-        add_action('admin_enqueue_scripts', array($this, 'load_global_scripts_styles'), 5);
726
-        add_action('admin_enqueue_scripts', array($this, 'load_scripts_styles'), 10);
727
-        if (method_exists($this, "load_scripts_styles_{$this->_current_view}")) {
728
-            add_action('admin_enqueue_scripts', array($this, "load_scripts_styles_{$this->_current_view}"), 15);
729
-        }
730
-        add_action('admin_enqueue_scripts', array($this, 'admin_footer_scripts_eei18n_js_strings'), 100);
731
-        // admin_print_footer_scripts - global, page child class, and view specific.
732
-        // NOTE, despite the name, whenever possible, scripts should NOT be loaded using this.
733
-        // In most cases that's doing_it_wrong().  But adding hidden container elements etc.
734
-        // is a good use case. Notice the late priority we're giving these
735
-        add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts_global'), 99);
736
-        add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts'), 100);
737
-        if (method_exists($this, "admin_footer_scripts_{$this->_current_view}")) {
738
-            add_action('admin_print_footer_scripts', array($this, "admin_footer_scripts_{$this->_current_view}"), 101);
739
-        }
740
-        //admin footer scripts
741
-        add_action('admin_footer', array($this, 'admin_footer_global'), 99);
742
-        add_action('admin_footer', array($this, 'admin_footer'), 100);
743
-        if (method_exists($this, "admin_footer_{$this->_current_view}")) {
744
-            add_action('admin_footer', array($this, "admin_footer_{$this->_current_view}"), 101);
745
-        }
746
-        do_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', $this->page_slug);
747
-        //targeted hook
748
-        do_action(
749
-            "FHEE__EE_Admin_Page___load_page_dependencies__after_load__{$this->page_slug}__{$this->_req_action}"
750
-
751
-        );
752
-    }
753
-
754
-
755
-
756
-    /**
757
-     * _set_defaults
758
-     * This sets some global defaults for class properties.
759
-     */
760
-    private function _set_defaults()
761
-    {
762
-        $this->_current_screen = $this->_admin_page_title = $this->_req_action = $this->_req_nonce = null;
763
-        $this->_event = $this->_template_path = $this->_column_template_path = null;
764
-        $this->_nav_tabs = $this->_views = $this->_page_routes = array();
765
-        $this->_page_config = $this->_default_route_query_args = array();
766
-        $this->_default_nav_tab_name = 'overview';
767
-        //init template args
768
-        $this->_template_args = array(
769
-            'admin_page_header'  => '',
770
-            'admin_page_content' => '',
771
-            'post_body_content'  => '',
772
-            'before_list_table'  => '',
773
-            'after_list_table'   => '',
774
-        );
775
-    }
776
-
777
-
778
-
779
-    /**
780
-     * route_admin_request
781
-     *
782
-     * @see    _route_admin_request()
783
-     * @return exception|void error
784
-     * @throws InvalidArgumentException
785
-     * @throws InvalidInterfaceException
786
-     * @throws InvalidDataTypeException
787
-     * @throws EE_Error
788
-     * @throws ReflectionException
789
-     */
790
-    public function route_admin_request()
791
-    {
792
-        try {
793
-            $this->_route_admin_request();
794
-        } catch (EE_Error $e) {
795
-            $e->get_error();
796
-        }
797
-    }
798
-
799
-
800
-
801
-    public function set_wp_page_slug($wp_page_slug)
802
-    {
803
-        $this->_wp_page_slug = $wp_page_slug;
804
-        //if in network admin then we need to append "-network" to the page slug. Why? Because that's how WP rolls...
805
-        if (is_network_admin()) {
806
-            $this->_wp_page_slug .= '-network';
807
-        }
808
-    }
809
-
810
-
811
-
812
-    /**
813
-     * _verify_routes
814
-     * All this method does is verify the incoming request and make sure that routes exist for it.  We do this early so
815
-     * we know if we need to drop out.
816
-     *
817
-     * @return bool
818
-     * @throws EE_Error
819
-     */
820
-    protected function _verify_routes()
821
-    {
822
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
823
-        if (! $this->_current_page && ! defined('DOING_AJAX')) {
824
-            return false;
825
-        }
826
-        $this->_route = false;
827
-        // check that the page_routes array is not empty
828
-        if (empty($this->_page_routes)) {
829
-            // user error msg
830
-            $error_msg = sprintf(
831
-                esc_html__('No page routes have been set for the %s admin page.', 'event_espresso'),
832
-                $this->_admin_page_title
833
-            );
834
-            // developer error msg
835
-            $error_msg .= '||' . $error_msg . esc_html__(
836
-                ' Make sure the "set_page_routes()" method exists, and is setting the "_page_routes" array properly.',
837
-                'event_espresso'
838
-            );
839
-            throw new EE_Error($error_msg);
840
-        }
841
-        // and that the requested page route exists
842
-        if (array_key_exists($this->_req_action, $this->_page_routes)) {
843
-            $this->_route        = $this->_page_routes[$this->_req_action];
844
-            $this->_route_config = isset($this->_page_config[$this->_req_action])
845
-                ? $this->_page_config[$this->_req_action] : array();
846
-        } else {
847
-            // user error msg
848
-            $error_msg = sprintf(
849
-                esc_html__(
850
-                        'The requested page route does not exist for the %s admin page.',
851
-                        'event_espresso'
852
-                ),
853
-                $this->_admin_page_title
854
-            );
855
-            // developer error msg
856
-            $error_msg .= '||' . $error_msg . sprintf(
857
-                    esc_html__(
858
-                        ' Create a key in the "_page_routes" array named "%s" and set its value to the appropriate method.',
859
-                        'event_espresso'
860
-                    ),
861
-                    $this->_req_action
862
-                );
863
-            throw new EE_Error($error_msg);
864
-        }
865
-        // and that a default route exists
866
-        if (! array_key_exists('default', $this->_page_routes)) {
867
-            // user error msg
868
-            $error_msg = sprintf(
869
-                esc_html__(
870
-                        'A default page route has not been set for the % admin page.',
871
-                        'event_espresso'
872
-                ),
873
-                $this->_admin_page_title
874
-            );
875
-            // developer error msg
876
-            $error_msg .= '||' . $error_msg . esc_html__(
877
-                ' Create a key in the "_page_routes" array named "default" and set its value to your default page method.',
878
-                'event_espresso'
879
-            );
880
-            throw new EE_Error($error_msg);
881
-        }
882
-        //first lets' catch if the UI request has EVER been set.
883
-        if ($this->_is_UI_request === null) {
884
-            //lets set if this is a UI request or not.
885
-            $this->_is_UI_request = ! isset($this->_req_data['noheader']) || $this->_req_data['noheader'] !== true;
886
-            //wait a minute... we might have a noheader in the route array
887
-            $this->_is_UI_request = is_array($this->_route)
888
-                                    && isset($this->_route['noheader'])
889
-                                    && $this->_route['noheader'] ? false : $this->_is_UI_request;
890
-        }
891
-        $this->_set_current_labels();
892
-        return true;
893
-    }
894
-
895
-
896
-
897
-    /**
898
-     * this method simply verifies a given route and makes sure its an actual route available for the loaded page
899
-     *
900
-     * @param  string $route the route name we're verifying
901
-     * @return mixed (bool|Exception)      we'll throw an exception if this isn't a valid route.
902
-     * @throws EE_Error
903
-     */
904
-    protected function _verify_route($route)
905
-    {
906
-        if (array_key_exists($this->_req_action, $this->_page_routes)) {
907
-            return true;
908
-        }
909
-        // user error msg
910
-        $error_msg = sprintf(
911
-            esc_html__('The given page route does not exist for the %s admin page.', 'event_espresso'),
912
-            $this->_admin_page_title
913
-        );
914
-        // developer error msg
915
-        $error_msg .= '||' . $error_msg . sprintf(
916
-                esc_html__(
917
-                    ' Check the route you are using in your method (%s) and make sure it matches a route set in your "_page_routes" array property',
918
-                    'event_espresso'
919
-                ),
920
-                $route
921
-            );
922
-        throw new EE_Error($error_msg);
923
-    }
924
-
925
-
926
-
927
-    /**
928
-     * perform nonce verification
929
-     * This method has be encapsulated here so that any ajax requests that bypass normal routes can verify their nonces
930
-     * using this method (and save retyping!)
931
-     *
932
-     * @param  string $nonce     The nonce sent
933
-     * @param  string $nonce_ref The nonce reference string (name0)
934
-     * @return void
935
-     * @throws EE_Error
936
-     */
937
-    protected function _verify_nonce($nonce, $nonce_ref)
938
-    {
939
-        // verify nonce against expected value
940
-        if (! wp_verify_nonce($nonce, $nonce_ref)) {
941
-            // these are not the droids you are looking for !!!
942
-            $msg = sprintf(
943
-                esc_html__('%sNonce Fail.%s', 'event_espresso'),
944
-                '<a href="http://www.youtube.com/watch?v=56_S0WeTkzs">',
945
-                '</a>'
946
-            );
947
-            if (WP_DEBUG) {
948
-                $msg .= "\n  " . sprintf(
949
-                        esc_html__(
950
-                            'In order to dynamically generate nonces for your actions, use the %s::add_query_args_and_nonce() method. May the Nonce be with you!',
951
-                            'event_espresso'
952
-                        ),
953
-                        __CLASS__
954
-                    );
955
-            }
956
-            if (! defined('DOING_AJAX')) {
957
-                wp_die($msg);
958
-            } else {
959
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
960
-                $this->_return_json();
961
-            }
962
-        }
963
-    }
964
-
965
-
966
-
967
-    /**
968
-     * _route_admin_request()
969
-     * Meat and potatoes of the class.  Basically, this dude checks out what's being requested and sees if theres are
970
-     * some doodads to work the magic and handle the flingjangy. Translation:  Checks if the requested action is listed
971
-     * in the page routes and then will try to load the corresponding method.
972
-     *
973
-     * @return void
974
-     * @throws EE_Error
975
-     * @throws InvalidArgumentException
976
-     * @throws InvalidDataTypeException
977
-     * @throws InvalidInterfaceException
978
-     * @throws ReflectionException
979
-     */
980
-    protected function _route_admin_request()
981
-    {
982
-        if (! $this->_is_UI_request) {
983
-            $this->_verify_routes();
984
-        }
985
-        $nonce_check = isset($this->_route_config['require_nonce'])
986
-            ? $this->_route_config['require_nonce']
987
-            : true;
988
-        if ($this->_req_action !== 'default' && $nonce_check) {
989
-            // set nonce from post data
990
-            $nonce = isset($this->_req_data[$this->_req_nonce])
991
-                ? sanitize_text_field($this->_req_data[$this->_req_nonce])
992
-                : '';
993
-            $this->_verify_nonce($nonce, $this->_req_nonce);
994
-        }
995
-        //set the nav_tabs array but ONLY if this is  UI_request
996
-        if ($this->_is_UI_request) {
997
-            $this->_set_nav_tabs();
998
-        }
999
-        // grab callback function
1000
-        $func = is_array($this->_route) ? $this->_route['func'] : $this->_route;
1001
-        // check if callback has args
1002
-        $args      = is_array($this->_route) && isset($this->_route['args']) ? $this->_route['args'] : array();
1003
-        $error_msg = '';
1004
-        // action right before calling route
1005
-        // (hook is something like 'AHEE__Registrations_Admin_Page__route_admin_request')
1006
-        if (! did_action('AHEE__EE_Admin_Page__route_admin_request')) {
1007
-            do_action('AHEE__EE_Admin_Page__route_admin_request', $this->_current_view, $this);
1008
-        }
1009
-        // right before calling the route, let's remove _wp_http_referer from the
1010
-        // $_SERVER[REQUEST_URI] global (its now in _req_data for route processing).
1011
-        $_SERVER['REQUEST_URI'] = remove_query_arg(
1012
-                '_wp_http_referer',
1013
-                wp_unslash($_SERVER['REQUEST_URI'])
1014
-        );
1015
-        if (! empty($func)) {
1016
-            if (is_array($func)) {
1017
-                list($class, $method) = $func;
1018
-            } elseif (strpos($func, '::') !== false) {
1019
-                list($class, $method) = explode('::', $func);
1020
-            } else {
1021
-                $class  = $this;
1022
-                $method = $func;
1023
-            }
1024
-            if (! (is_object($class) && $class === $this)) {
1025
-                // send along this admin page object for access by addons.
1026
-                $args['admin_page_object'] = $this;
1027
-            }
1028
-            if (
1029
-                //is it a method on a class that doesn't work?
1030
-                (
1031
-                    (
1032
-                        method_exists($class, $method)
1033
-                        && call_user_func_array(array($class, $method), $args) === false
1034
-                    )
1035
-                    && (
1036
-                        //is it a standalone function that doesn't work?
1037
-                        function_exists($method)
1038
-                        && call_user_func_array(
1039
-                            $func,
1040
-                            array_merge(array('admin_page_object' => $this), $args)
1041
-                           ) === false
1042
-                    )
1043
-                )
1044
-                || (
1045
-                    //is it neither a class method NOR a standalone function?
1046
-                    ! method_exists($class, $method)
1047
-                    && ! function_exists($method)
1048
-                )
1049
-            ) {
1050
-                // user error msg
1051
-                $error_msg = esc_html__(
1052
-                    'An error occurred. The  requested page route could not be found.',
1053
-                    'event_espresso'
1054
-                );
1055
-                // developer error msg
1056
-                $error_msg .= '||';
1057
-                $error_msg .= sprintf(
1058
-                    esc_html__(
1059
-                        'Page route "%s" could not be called. Check that the spelling for method names and actions in the "_page_routes" array are all correct.',
1060
-                        'event_espresso'
1061
-                    ),
1062
-                    $method
1063
-                );
1064
-            }
1065
-            if (! empty($error_msg)) {
1066
-                throw new EE_Error($error_msg);
1067
-            }
1068
-        }
1069
-        // if we've routed and this route has a no headers route AND a sent_headers_route,
1070
-        // then we need to reset the routing properties to the new route.
1071
-        //now if UI request is FALSE and noheader is true AND we have a headers_sent_route in the route array then let's set UI_request to true because the no header route has a second func after headers have been sent.
1072
-        if ($this->_is_UI_request === false
1073
-            && is_array($this->_route)
1074
-            && ! empty($this->_route['headers_sent_route'])
1075
-        ) {
1076
-            $this->_reset_routing_properties($this->_route['headers_sent_route']);
1077
-        }
1078
-    }
1079
-
1080
-
1081
-
1082
-    /**
1083
-     * This method just allows the resetting of page properties in the case where a no headers
1084
-     * route redirects to a headers route in its route config.
1085
-     *
1086
-     * @since   4.3.0
1087
-     * @param  string $new_route New (non header) route to redirect to.
1088
-     * @return   void
1089
-     * @throws ReflectionException
1090
-     * @throws InvalidArgumentException
1091
-     * @throws InvalidInterfaceException
1092
-     * @throws InvalidDataTypeException
1093
-     * @throws EE_Error
1094
-     */
1095
-    protected function _reset_routing_properties($new_route)
1096
-    {
1097
-        $this->_is_UI_request = true;
1098
-        //now we set the current route to whatever the headers_sent_route is set at
1099
-        $this->_req_data['action'] = $new_route;
1100
-        //rerun page setup
1101
-        $this->_page_setup();
1102
-    }
1103
-
1104
-
1105
-
1106
-    /**
1107
-     * _add_query_arg
1108
-     * adds nonce to array of arguments then calls WP add_query_arg function
1109
-     *(internally just uses EEH_URL's function with the same name)
1110
-     *
1111
-     * @param array  $args
1112
-     * @param string $url
1113
-     * @param bool   $sticky                  if true, then the existing Request params will be appended to the
1114
-     *                                        generated url in an associative array indexed by the key 'wp_referer';
1115
-     *                                        Example usage: If the current page is:
1116
-     *                                        http://mydomain.com/wp-admin/admin.php?page=espresso_registrations
1117
-     *                                        &action=default&event_id=20&month_range=March%202015
1118
-     *                                        &_wpnonce=5467821
1119
-     *                                        and you call:
1120
-     *                                        EE_Admin_Page::add_query_args_and_nonce(
1121
-     *                                        array(
1122
-     *                                        'action' => 'resend_something',
1123
-     *                                        'page=>espresso_registrations'
1124
-     *                                        ),
1125
-     *                                        $some_url,
1126
-     *                                        true
1127
-     *                                        );
1128
-     *                                        It will produce a url in this structure:
1129
-     *                                        http://{$some_url}/?page=espresso_registrations&action=resend_something
1130
-     *                                        &wp_referer[action]=default&wp_referer[event_id]=20&wpreferer[
1131
-     *                                        month_range]=March%202015
1132
-     * @param   bool $exclude_nonce           If true, the the nonce will be excluded from the generated nonce.
1133
-     * @return string
1134
-     */
1135
-    public static function add_query_args_and_nonce(
1136
-        $args = array(),
1137
-        $url = false,
1138
-        $sticky = false,
1139
-        $exclude_nonce = false
1140
-    ) {
1141
-        //if there is a _wp_http_referer include the values from the request but only if sticky = true
1142
-        if ($sticky) {
1143
-            $request = $_REQUEST;
1144
-            unset($request['_wp_http_referer']);
1145
-            unset($request['wp_referer']);
1146
-            foreach ($request as $key => $value) {
1147
-                //do not add nonces
1148
-                if (strpos($key, 'nonce') !== false) {
1149
-                    continue;
1150
-                }
1151
-                $args['wp_referer[' . $key . ']'] = $value;
1152
-            }
1153
-        }
1154
-        return EEH_URL::add_query_args_and_nonce($args, $url, $exclude_nonce);
1155
-    }
1156
-
1157
-
1158
-
1159
-    /**
1160
-     * This returns a generated link that will load the related help tab.
1161
-     *
1162
-     * @param  string $help_tab_id the id for the connected help tab
1163
-     * @param  string $icon_style  (optional) include css class for the style you want to use for the help icon.
1164
-     * @param  string $help_text   (optional) send help text you want to use for the link if default not to be used
1165
-     * @uses EEH_Template::get_help_tab_link()
1166
-     * @return string              generated link
1167
-     */
1168
-    protected function _get_help_tab_link($help_tab_id, $icon_style = '', $help_text = '')
1169
-    {
1170
-        return EEH_Template::get_help_tab_link(
1171
-            $help_tab_id,
1172
-            $this->page_slug,
1173
-            $this->_req_action,
1174
-            $icon_style,
1175
-            $help_text
1176
-        );
1177
-    }
1178
-
1179
-
1180
-
1181
-    /**
1182
-     * _add_help_tabs
1183
-     * Note child classes define their help tabs within the page_config array.
1184
-     *
1185
-     * @link   http://codex.wordpress.org/Function_Reference/add_help_tab
1186
-     * @return void
1187
-     * @throws DomainException
1188
-     * @throws EE_Error
1189
-     */
1190
-    protected function _add_help_tabs()
1191
-    {
1192
-        $tour_buttons = '';
1193
-        if (isset($this->_page_config[$this->_req_action])) {
1194
-            $config = $this->_page_config[$this->_req_action];
1195
-            //is there a help tour for the current route?  if there is let's setup the tour buttons
1196
-            if (isset($this->_help_tour[$this->_req_action])) {
1197
-                $tb           = array();
1198
-                $tour_buttons = '<div class="ee-abs-container"><div class="ee-help-tour-restart-buttons">';
1199
-                foreach ($this->_help_tour['tours'] as $tour) {
1200
-                    //if this is the end tour then we don't need to setup a button
1201
-                    if ($tour instanceof EE_Help_Tour_final_stop || ! $tour instanceof EE_Help_Tour) {
1202
-                        continue;
1203
-                    }
1204
-                    $tb[] = '<button id="trigger-tour-'
1205
-                            . $tour->get_slug()
1206
-                            . '" class="button-primary trigger-ee-help-tour">'
1207
-                            . $tour->get_label()
1208
-                            . '</button>';
1209
-                }
1210
-                $tour_buttons .= implode('<br />', $tb);
1211
-                $tour_buttons .= '</div></div>';
1212
-            }
1213
-            // let's see if there is a help_sidebar set for the current route and we'll set that up for usage as well.
1214
-            if (is_array($config) && isset($config['help_sidebar'])) {
1215
-                //check that the callback given is valid
1216
-                if (! method_exists($this, $config['help_sidebar'])) {
1217
-                    throw new EE_Error(
1218
-                        sprintf(
1219
-                            esc_html__(
1220
-                                'The _page_config array has a callback set for the "help_sidebar" option.  However the callback given (%s) is not a valid callback.  Doublecheck the spelling and make sure this method exists for the class %s',
1221
-                                'event_espresso'
1222
-                            ),
1223
-                            $config['help_sidebar'],
1224
-                            get_class($this)
1225
-                        )
1226
-                    );
1227
-                }
1228
-                $content = apply_filters(
1229
-                    'FHEE__' . get_class($this) . '__add_help_tabs__help_sidebar',
1230
-                    $this->{$config['help_sidebar']}()
1231
-                );
1232
-                $content .= $tour_buttons; //add help tour buttons.
1233
-                //do we have any help tours setup?  Cause if we do we want to add the buttons
1234
-                $this->_current_screen->set_help_sidebar($content);
1235
-            }
1236
-            //if we DON'T have config help sidebar and there ARE tour buttons then we'll just add the tour buttons to the sidebar.
1237
-            if (! isset($config['help_sidebar']) && ! empty($tour_buttons)) {
1238
-                $this->_current_screen->set_help_sidebar($tour_buttons);
1239
-            }
1240
-            //handle if no help_tabs are set so the sidebar will still show for the help tour buttons
1241
-            if (! isset($config['help_tabs']) && ! empty($tour_buttons)) {
1242
-                $_ht['id']      = $this->page_slug;
1243
-                $_ht['title']   = esc_html__('Help Tours', 'event_espresso');
1244
-                $_ht['content'] = '<p>' . esc_html__(
1245
-                        'The buttons to the right allow you to start/restart any help tours available for this page',
1246
-                        'event_espresso'
1247
-                    ) . '</p>';
1248
-                $this->_current_screen->add_help_tab($_ht);
1249
-            }
1250
-            if (! isset($config['help_tabs'])) {
1251
-                return;
1252
-            } //no help tabs for this route
1253
-            foreach ((array)$config['help_tabs'] as $tab_id => $cfg) {
1254
-                //we're here so there ARE help tabs!
1255
-                //make sure we've got what we need
1256
-                if (! isset($cfg['title'])) {
1257
-                    throw new EE_Error(
1258
-                        esc_html__(
1259
-                            'The _page_config array is not set up properly for help tabs.  It is missing a title',
1260
-                            'event_espresso'
1261
-                        )
1262
-                    );
1263
-                }
1264
-                if (! isset($cfg['filename']) && ! isset($cfg['callback']) && ! isset($cfg['content'])) {
1265
-                    throw new EE_Error(
1266
-                        esc_html__(
1267
-                            'The _page_config array is not setup properly for help tabs. It is missing a either a filename reference, or a callback reference or a content reference so there is no way to know the content for the help tab',
1268
-                            'event_espresso'
1269
-                        )
1270
-                    );
1271
-                }
1272
-                //first priority goes to content.
1273
-                if (! empty($cfg['content'])) {
1274
-                    $content = ! empty($cfg['content']) ? $cfg['content'] : null;
1275
-                    //second priority goes to filename
1276
-                } elseif (! empty($cfg['filename'])) {
1277
-                    $file_path = $this->_get_dir() . '/help_tabs/' . $cfg['filename'] . '.help_tab.php';
1278
-                    //it's possible that the file is located on decaf route (and above sets up for caf route, if this is the case then lets check decaf route too)
1279
-                    $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES
1280
-                                                             . basename($this->_get_dir())
1281
-                                                             . '/help_tabs/'
1282
-                                                             . $cfg['filename']
1283
-                                                             . '.help_tab.php' : $file_path;
1284
-                    //if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1285
-                    if (! isset($cfg['callback']) && ! is_readable($file_path)) {
1286
-                        EE_Error::add_error(
1287
-                            sprintf(
1288
-                                esc_html__(
1289
-                                    'The filename given for the help tab %s is not a valid file and there is no other configuration for the tab content.  Please check that the string you set for the help tab on this route (%s) is the correct spelling.  The file should be in %s',
1290
-                                    'event_espresso'
1291
-                                ),
1292
-                                $tab_id,
1293
-                                key($config),
1294
-                                $file_path
1295
-                            ),
1296
-                            __FILE__,
1297
-                            __FUNCTION__,
1298
-                            __LINE__
1299
-                        );
1300
-                        return;
1301
-                    }
1302
-                    $template_args['admin_page_obj'] = $this;
1303
-                    $content = EEH_Template::display_template(
1304
-                        $file_path,
1305
-                        $template_args,
1306
-                        true
1307
-                    );
1308
-                } else {
1309
-                    $content = '';
1310
-                }
1311
-                //check if callback is valid
1312
-                if (
1313
-                    empty($content) && (
1314
-                        ! isset($cfg['callback']) || ! method_exists($this, $cfg['callback'])
1315
-                    )
1316
-                ) {
1317
-                    EE_Error::add_error(
1318
-                        sprintf(
1319
-                            esc_html__(
1320
-                                'The callback given for a %s help tab on this page does not content OR a corresponding method for generating the content.  Check the spelling or make sure the method is present.',
1321
-                                'event_espresso'
1322
-                            ),
1323
-                            $cfg['title']
1324
-                        ),
1325
-                        __FILE__,
1326
-                        __FUNCTION__,
1327
-                        __LINE__
1328
-                    );
1329
-                    return;
1330
-                }
1331
-                //setup config array for help tab method
1332
-                $id  = $this->page_slug . '-' . $this->_req_action . '-' . $tab_id;
1333
-                $_ht = array(
1334
-                    'id'       => $id,
1335
-                    'title'    => $cfg['title'],
1336
-                    'callback' => isset($cfg['callback']) && empty($content) ? array($this, $cfg['callback']) : null,
1337
-                    'content'  => $content,
1338
-                );
1339
-                $this->_current_screen->add_help_tab($_ht);
1340
-            }
1341
-        }
1342
-    }
1343
-
1344
-
1345
-
1346
-    /**
1347
-     * This basically checks loaded $_page_config property to see if there are any help_tours defined.  "help_tours" is
1348
-     * an array with properties for setting up usage of the joyride plugin
1349
-     *
1350
-     * @link   http://zurb.com/playground/jquery-joyride-feature-tour-plugin
1351
-     * @see    instructions regarding the format and construction of the "help_tour" array element is found in the
1352
-     *         _set_page_config() comments
1353
-     * @return void
1354
-     * @throws EE_Error
1355
-     * @throws InvalidArgumentException
1356
-     * @throws InvalidDataTypeException
1357
-     * @throws InvalidInterfaceException
1358
-     */
1359
-    protected function _add_help_tour()
1360
-    {
1361
-        $tours            = array();
1362
-        $this->_help_tour = array();
1363
-        //exit early if help tours are turned off globally
1364
-        if ((defined('EE_DISABLE_HELP_TOURS') && EE_DISABLE_HELP_TOURS)
1365
-            || ! EE_Registry::instance()->CFG->admin->help_tour_activation
1366
-        ) {
1367
-            return;
1368
-        }
1369
-        //loop through _page_config to find any help_tour defined
1370
-        foreach ($this->_page_config as $route => $config) {
1371
-            //we're only going to set things up for this route
1372
-            if ($route !== $this->_req_action) {
1373
-                continue;
1374
-            }
1375
-            if (isset($config['help_tour'])) {
1376
-                foreach ($config['help_tour'] as $tour) {
1377
-                    $file_path = $this->_get_dir() . '/help_tours/' . $tour . '.class.php';
1378
-                    // let's see if we can get that file...
1379
-                    // if not its possible this is a decaf route not set in caffeinated
1380
-                    // so lets try and get the caffeinated equivalent
1381
-                    $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES
1382
-                                                             . basename($this->_get_dir())
1383
-                                                             . '/help_tours/'
1384
-                                                             . $tour
1385
-                                                             . '.class.php' : $file_path;
1386
-                    //if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1387
-                    if (! is_readable($file_path)) {
1388
-                        EE_Error::add_error(
1389
-                            sprintf(
1390
-                                esc_html__(
1391
-                                    'The file path given for the help tour (%s) is not a valid path.  Please check that the string you set for the help tour on this route (%s) is the correct spelling',
1392
-                                    'event_espresso'
1393
-                                ),
1394
-                                $file_path,
1395
-                                $tour
1396
-                            ),
1397
-                            __FILE__,
1398
-                            __FUNCTION__,
1399
-                            __LINE__
1400
-                        );
1401
-                        return;
1402
-                    }
1403
-                    require_once $file_path;
1404
-                    if (! class_exists($tour)) {
1405
-                        $error_msg[] = sprintf(
1406
-                            esc_html__('Something went wrong with loading the %s Help Tour Class.', 'event_espresso'),
1407
-                            $tour
1408
-                        );
1409
-                        $error_msg[] = $error_msg[0] . "\r\n" . sprintf(
1410
-                                esc_html__(
1411
-                                    'There is no class in place for the %s help tour.%s Make sure you have <strong>%s</strong> defined in the "help_tour" array for the %s route of the % admin page.',
1412
-                                    'event_espresso'
1413
-                                ),
1414
-                                $tour,
1415
-                                '<br />',
1416
-                                $tour,
1417
-                                $this->_req_action,
1418
-                                get_class($this)
1419
-                            );
1420
-                        throw new EE_Error(implode('||', $error_msg));
1421
-                    }
1422
-                    $tour_obj                   = new $tour($this->_is_caf);
1423
-                    $tours[]                    = $tour_obj;
1424
-                    $this->_help_tour[$route][] = EEH_Template::help_tour_stops_generator($tour_obj);
1425
-                }
1426
-                //let's inject the end tour stop element common to all pages... this will only get seen once per machine.
1427
-                $end_stop_tour              = new EE_Help_Tour_final_stop($this->_is_caf);
1428
-                $tours[]                    = $end_stop_tour;
1429
-                $this->_help_tour[$route][] = EEH_Template::help_tour_stops_generator($end_stop_tour);
1430
-            }
1431
-        }
1432
-        if (! empty($tours)) {
1433
-            $this->_help_tour['tours'] = $tours;
1434
-        }
1435
-        // that's it!  Now that the $_help_tours property is set (or not)
1436
-        // the scripts and html should be taken care of automatically.
1437
-    }
1438
-
1439
-
1440
-
1441
-    /**
1442
-     * This simply sets up any qtips that have been defined in the page config
1443
-     *
1444
-     * @return void
1445
-     */
1446
-    protected function _add_qtips()
1447
-    {
1448
-        if (isset($this->_route_config['qtips'])) {
1449
-            $qtips = (array)$this->_route_config['qtips'];
1450
-            //load qtip loader
1451
-            $path = array(
1452
-                $this->_get_dir() . '/qtips/',
1453
-                EE_ADMIN_PAGES . basename($this->_get_dir()) . '/qtips/',
1454
-            );
1455
-            EEH_Qtip_Loader::instance()->register($qtips, $path);
1456
-        }
1457
-    }
1458
-
1459
-
1460
-
1461
-    /**
1462
-     * _set_nav_tabs
1463
-     * This sets up the nav tabs from the page_routes array.  This method can be overwritten by child classes if you
1464
-     * wish to add additional tabs or modify accordingly.
1465
-     *
1466
-     * @return void
1467
-     * @throws InvalidArgumentException
1468
-     * @throws InvalidInterfaceException
1469
-     * @throws InvalidDataTypeException
1470
-     */
1471
-    protected function _set_nav_tabs()
1472
-    {
1473
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1474
-        $i = 0;
1475
-        foreach ($this->_page_config as $slug => $config) {
1476
-            if (
1477
-                ! is_array($config)
1478
-                || (
1479
-                    is_array($config)
1480
-                    && (
1481
-                        (isset($config['nav']) && ! $config['nav'])
1482
-                        || ! isset($config['nav'])
1483
-                    )
1484
-                )
1485
-            ) {
1486
-                continue;
1487
-            }
1488
-            //no nav tab for this config
1489
-            //check for persistent flag
1490
-            if ($slug !== $this->_req_action && isset($config['nav']['persistent']) && ! $config['nav']['persistent']) {
1491
-                // nav tab is only to appear when route requested.
1492
-                continue;
1493
-            }
1494
-            if (! $this->check_user_access($slug, true)) {
1495
-                // no nav tab because current user does not have access.
1496
-                continue;
1497
-            }
1498
-            $css_class              = isset($config['css_class']) ? $config['css_class'] . ' ' : '';
1499
-            $this->_nav_tabs[$slug] = array(
1500
-                'url'       => isset($config['nav']['url'])
1501
-                    ? $config['nav']['url']
1502
-                    : self::add_query_args_and_nonce(
1503
-                        array('action' => $slug),
1504
-                        $this->_admin_base_url
1505
-                    ),
1506
-                'link_text' => isset($config['nav']['label'])
1507
-                    ? $config['nav']['label']
1508
-                    : ucwords(
1509
-                        str_replace('_', ' ', $slug)
1510
-                    ),
1511
-                'css_class' => $this->_req_action === $slug ? $css_class . 'nav-tab-active' : $css_class,
1512
-                'order'     => isset($config['nav']['order']) ? $config['nav']['order'] : $i,
1513
-            );
1514
-            $i++;
1515
-        }
1516
-        //if $this->_nav_tabs is empty then lets set the default
1517
-        if (empty($this->_nav_tabs)) {
1518
-            $this->_nav_tabs[$this->_default_nav_tab_name] = array(
1519
-                'url'       => $this->_admin_base_url,
1520
-                'link_text' => ucwords(str_replace('_', ' ', $this->_default_nav_tab_name)),
1521
-                'css_class' => 'nav-tab-active',
1522
-                'order'     => 10,
1523
-            );
1524
-        }
1525
-        //now let's sort the tabs according to order
1526
-        usort($this->_nav_tabs, array($this, '_sort_nav_tabs'));
1527
-    }
1528
-
1529
-
1530
-
1531
-    /**
1532
-     * _set_current_labels
1533
-     * This method modifies the _labels property with any optional specific labels indicated in the _page_routes
1534
-     * property array
1535
-     *
1536
-     * @return void
1537
-     */
1538
-    private function _set_current_labels()
1539
-    {
1540
-        if (is_array($this->_route_config) && isset($this->_route_config['labels'])) {
1541
-            foreach ($this->_route_config['labels'] as $label => $text) {
1542
-                if (is_array($text)) {
1543
-                    foreach ($text as $sublabel => $subtext) {
1544
-                        $this->_labels[$label][$sublabel] = $subtext;
1545
-                    }
1546
-                } else {
1547
-                    $this->_labels[$label] = $text;
1548
-                }
1549
-            }
1550
-        }
1551
-    }
1552
-
1553
-
1554
-
1555
-    /**
1556
-     *        verifies user access for this admin page
1557
-     *
1558
-     * @param string $route_to_check if present then the capability for the route matching this string is checked.
1559
-     * @param bool   $verify_only    Default is FALSE which means if user check fails then wp_die().  Otherwise just
1560
-     *                               return false if verify fail.
1561
-     * @return bool
1562
-     * @throws InvalidArgumentException
1563
-     * @throws InvalidDataTypeException
1564
-     * @throws InvalidInterfaceException
1565
-     */
1566
-    public function check_user_access($route_to_check = '', $verify_only = false)
1567
-    {
1568
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1569
-        $route_to_check = empty($route_to_check) ? $this->_req_action : $route_to_check;
1570
-        $capability     = ! empty($route_to_check) && isset($this->_page_routes[$route_to_check])
1571
-                          && is_array(
1572
-                              $this->_page_routes[$route_to_check]
1573
-                          )
1574
-                          && ! empty($this->_page_routes[$route_to_check]['capability'])
1575
-            ? $this->_page_routes[$route_to_check]['capability'] : null;
1576
-        if (empty($capability) && empty($route_to_check)) {
1577
-            $capability = is_array($this->_route) && empty($this->_route['capability']) ? 'manage_options'
1578
-                : $this->_route['capability'];
1579
-        } else {
1580
-            $capability = empty($capability) ? 'manage_options' : $capability;
1581
-        }
1582
-        $id = is_array($this->_route) && ! empty($this->_route['obj_id']) ? $this->_route['obj_id'] : 0;
1583
-        if (
1584
-            ! defined('DOING_AJAX')
1585
-            && (
1586
-                ! function_exists('is_admin')
1587
-                || ! EE_Registry::instance()->CAP->current_user_can(
1588
-                    $capability,
1589
-                    $this->page_slug
1590
-                    . '_'
1591
-                    . $route_to_check,
1592
-                    $id
1593
-                )
1594
-            )
1595
-        ) {
1596
-            if ($verify_only) {
1597
-                return false;
1598
-            }
1599
-            if (is_user_logged_in()) {
1600
-                wp_die(__('You do not have access to this route.', 'event_espresso'));
1601
-            } else {
1602
-                return false;
1603
-            }
1604
-        }
1605
-        return true;
1606
-    }
1607
-
1608
-
1609
-
1610
-    /**
1611
-     * admin_init_global
1612
-     * This runs all the code that we want executed within the WP admin_init hook.
1613
-     * This method executes for ALL EE Admin pages.
1614
-     *
1615
-     * @return void
1616
-     */
1617
-    public function admin_init_global()
1618
-    {
1619
-    }
1620
-
1621
-
1622
-
1623
-    /**
1624
-     * wp_loaded_global
1625
-     * This runs all the code that we want executed within the WP wp_loaded hook.  This method is optional for an
1626
-     * EE_Admin page and will execute on every EE Admin Page load
1627
-     *
1628
-     * @return void
1629
-     */
1630
-    public function wp_loaded()
1631
-    {
1632
-    }
1633
-
1634
-
1635
-
1636
-    /**
1637
-     * admin_notices
1638
-     * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply on
1639
-     * ALL EE_Admin pages.
1640
-     *
1641
-     * @return void
1642
-     */
1643
-    public function admin_notices_global()
1644
-    {
1645
-        $this->_display_no_javascript_warning();
1646
-        $this->_display_espresso_notices();
1647
-    }
1648
-
1649
-
1650
-
1651
-    public function network_admin_notices_global()
1652
-    {
1653
-        $this->_display_no_javascript_warning();
1654
-        $this->_display_espresso_notices();
1655
-    }
1656
-
1657
-
1658
-
1659
-    /**
1660
-     * admin_footer_scripts_global
1661
-     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
1662
-     * will apply on ALL EE_Admin pages.
1663
-     *
1664
-     * @return void
1665
-     */
1666
-    public function admin_footer_scripts_global()
1667
-    {
1668
-        $this->_add_admin_page_ajax_loading_img();
1669
-        $this->_add_admin_page_overlay();
1670
-        //if metaboxes are present we need to add the nonce field
1671
-        if (
1672
-             isset($this->_route_config['metaboxes'])
1673
-             || isset($this->_route_config['list_table'])
1674
-             || (isset($this->_route_config['has_metaboxes']) && $this->_route_config['has_metaboxes'])
1675
-        ) {
1676
-            wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
1677
-            wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
1678
-        }
1679
-    }
1680
-
1681
-
1682
-
1683
-    /**
1684
-     * admin_footer_global
1685
-     * Anything triggered by the wp 'admin_footer' wp hook should be put in here. This particular method will apply on
1686
-     * ALL EE_Admin Pages.
1687
-     *
1688
-     * @return void
1689
-     * @throws EE_Error
1690
-     */
1691
-    public function admin_footer_global()
1692
-    {
1693
-        //dialog container for dialog helper
1694
-        $d_cont = '<div class="ee-admin-dialog-container auto-hide hidden">' . "\n";
1695
-        $d_cont .= '<div class="ee-notices"></div>';
1696
-        $d_cont .= '<div class="ee-admin-dialog-container-inner-content"></div>';
1697
-        $d_cont .= '</div>';
1698
-        echo $d_cont;
1699
-        //help tour stuff?
1700
-        if (isset($this->_help_tour[$this->_req_action])) {
1701
-            echo implode('<br />', $this->_help_tour[$this->_req_action]);
1702
-        }
1703
-        //current set timezone for timezone js
1704
-        echo '<span id="current_timezone" class="hidden">' . EEH_DTT_Helper::get_timezone() . '</span>';
1705
-    }
1706
-
1707
-
1708
-
1709
-    /**
1710
-     * This function sees if there is a method for help popup content existing for the given route.  If there is then
1711
-     * we'll use the retrieved array to output the content using the template. For child classes: If you want to have
1712
-     * help popups then in your templates or your content you set "triggers" for the content using the
1713
-     * "_set_help_trigger('help_trigger_id')" where "help_trigger_id" is what you will use later in your custom method
1714
-     * for the help popup content on that page. Then in your Child_Admin_Page class you need to define a help popup
1715
-     * method for the content in the format "_help_popup_content_{route_name}()"  So if you are setting help content
1716
-     * for the
1717
-     * 'edit_event' route you should have a method named "_help_popup_content_edit_route". In your defined
1718
-     * "help_popup_content_..." method.  You must prepare and return an array in the following format array(
1719
-     *    'help_trigger_id' => array(
1720
-     *        'title' => esc_html__('localized title for popup', 'event_espresso'),
1721
-     *        'content' => esc_html__('localized content for popup', 'event_espresso')
1722
-     *    )
1723
-     * );
1724
-     * Then the EE_Admin_Parent will take care of making sure that is setup properly on the correct route.
1725
-     *
1726
-     * @param array $help_array
1727
-     * @param bool  $display
1728
-     * @return string content
1729
-     * @throws DomainException
1730
-     * @throws EE_Error
1731
-     */
1732
-    protected function _set_help_popup_content($help_array = array(), $display = false)
1733
-    {
1734
-        $content       = '';
1735
-        $help_array    = empty($help_array) ? $this->_get_help_content() : $help_array;
1736
-        //loop through the array and setup content
1737
-        foreach ($help_array as $trigger => $help) {
1738
-            //make sure the array is setup properly
1739
-            if (! isset($help['title']) || ! isset($help['content'])) {
1740
-                throw new EE_Error(
1741
-                    esc_html__(
1742
-                        'Does not look like the popup content array has been setup correctly.  Might want to double check that.  Read the comments for the _get_help_popup_content method found in "EE_Admin_Page" class',
1743
-                        'event_espresso'
1744
-                    )
1745
-                );
1746
-            }
1747
-            //we're good so let'd setup the template vars and then assign parsed template content to our content.
1748
-            $template_args = array(
1749
-                'help_popup_id'      => $trigger,
1750
-                'help_popup_title'   => $help['title'],
1751
-                'help_popup_content' => $help['content'],
1752
-            );
1753
-            $content       .= EEH_Template::display_template(
1754
-                EE_ADMIN_TEMPLATE . 'admin_help_popup.template.php',
1755
-                $template_args,
1756
-                true
1757
-            );
1758
-        }
1759
-        if ($display) {
1760
-            echo $content;
1761
-            return '';
1762
-        }
1763
-        return $content;
1764
-    }
1765
-
1766
-
1767
-
1768
-    /**
1769
-     * All this does is retrieve the help content array if set by the EE_Admin_Page child
1770
-     *
1771
-     * @return array properly formatted array for help popup content
1772
-     * @throws EE_Error
1773
-     */
1774
-    private function _get_help_content()
1775
-    {
1776
-        //what is the method we're looking for?
1777
-        $method_name = '_help_popup_content_' . $this->_req_action;
1778
-        //if method doesn't exist let's get out.
1779
-        if (! method_exists($this, $method_name)) {
1780
-            return array();
1781
-        }
1782
-        //k we're good to go let's retrieve the help array
1783
-        $help_array = call_user_func(array($this, $method_name));
1784
-        //make sure we've got an array!
1785
-        if (! is_array($help_array)) {
1786
-            throw new EE_Error(
1787
-                esc_html__(
1788
-                    'Something went wrong with help popup content generation. Expecting an array and well, this ain\'t no array bub.',
1789
-                    'event_espresso'
1790
-                )
1791
-            );
1792
-        }
1793
-        return $help_array;
1794
-    }
1795
-
1796
-
1797
-
1798
-    /**
1799
-     * EE Admin Pages can use this to set a properly formatted trigger for a help popup.
1800
-     * By default the trigger html is printed.  Otherwise it can be returned if the $display flag is set "false"
1801
-     * See comments made on the _set_help_content method for understanding other parts to the help popup tool.
1802
-     *
1803
-     * @param string  $trigger_id reference for retrieving the trigger content for the popup
1804
-     * @param boolean $display    if false then we return the trigger string
1805
-     * @param array   $dimensions an array of dimensions for the box (array(h,w))
1806
-     * @return string
1807
-     * @throws DomainException
1808
-     * @throws EE_Error
1809
-     */
1810
-    protected function _set_help_trigger($trigger_id, $display = true, $dimensions = array('400', '640'))
1811
-    {
1812
-        if (defined('DOING_AJAX')) {
1813
-            return '';
1814
-        }
1815
-        //let's check and see if there is any content set for this popup.  If there isn't then we'll include a default title and content so that developers know something needs to be corrected
1816
-        $help_array   = $this->_get_help_content();
1817
-        $help_content = '';
1818
-        if (empty($help_array) || ! isset($help_array[$trigger_id])) {
1819
-            $help_array[$trigger_id] = array(
1820
-                'title'   => esc_html__('Missing Content', 'event_espresso'),
1821
-                'content' => esc_html__(
1822
-                    'A trigger has been set that doesn\'t have any corresponding content. Make sure you have set the help content. (see the "_set_help_popup_content" method in the EE_Admin_Page for instructions.)',
1823
-                    'event_espresso'
1824
-                ),
1825
-            );
1826
-            $help_content            = $this->_set_help_popup_content($help_array, false);
1827
-        }
1828
-        //let's setup the trigger
1829
-        $content = '<a class="ee-dialog" href="?height='
1830
-                   . $dimensions[0]
1831
-                   . '&width='
1832
-                   . $dimensions[1]
1833
-                   . '&inlineId='
1834
-                   . $trigger_id
1835
-                   . '" target="_blank"><span class="question ee-help-popup-question"></span></a>';
1836
-        $content .= $help_content;
1837
-        if ($display) {
1838
-            echo $content;
1839
-            return  '';
1840
-        }
1841
-        return $content;
1842
-    }
1843
-
1844
-
1845
-
1846
-    /**
1847
-     * _add_global_screen_options
1848
-     * Add any extra wp_screen_options within this method using built-in WP functions/methods for doing so.
1849
-     * This particular method will add_screen_options on ALL EE_Admin Pages
1850
-     *
1851
-     * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
1852
-     *         see also WP_Screen object documents...
1853
-     * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
1854
-     * @abstract
1855
-     * @return void
1856
-     */
1857
-    private function _add_global_screen_options()
1858
-    {
1859
-    }
1860
-
1861
-
1862
-
1863
-    /**
1864
-     * _add_global_feature_pointers
1865
-     * This method is used for implementing any "feature pointers" (using built-in WP styling js).
1866
-     * This particular method will implement feature pointers for ALL EE_Admin pages.
1867
-     * Note: this is just a placeholder for now.  Implementation will come down the road
1868
-     *
1869
-     * @see    WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be
1870
-     *         extended) also see:
1871
-     * @link   http://eamann.com/tech/wordpress-portland/
1872
-     * @abstract
1873
-     * @return void
1874
-     */
1875
-    private function _add_global_feature_pointers()
1876
-    {
1877
-    }
1878
-
1879
-
1880
-
1881
-    /**
1882
-     * load_global_scripts_styles
1883
-     * The scripts and styles enqueued in here will be loaded on every EE Admin page
1884
-     *
1885
-     * @return void
1886
-     * @throws EE_Error
1887
-     */
1888
-    public function load_global_scripts_styles()
1889
-    {
1890
-        /** STYLES **/
1891
-        // add debugging styles
1892
-        if (WP_DEBUG) {
1893
-            add_action('admin_head', array($this, 'add_xdebug_style'));
1894
-        }
1895
-        // register all styles
1896
-        wp_register_style(
1897
-            'espresso-ui-theme',
1898
-            EE_GLOBAL_ASSETS_URL . 'css/espresso-ui-theme/jquery-ui-1.10.3.custom.min.css',
1899
-            array(),
1900
-            EVENT_ESPRESSO_VERSION
1901
-        );
1902
-        wp_register_style('ee-admin-css', EE_ADMIN_URL . 'assets/ee-admin-page.css', array(), EVENT_ESPRESSO_VERSION);
1903
-        //helpers styles
1904
-        wp_register_style(
1905
-            'ee-text-links',
1906
-            EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.css',
1907
-            array(),
1908
-            EVENT_ESPRESSO_VERSION
1909
-        );
1910
-        /** SCRIPTS **/
1911
-        //register all scripts
1912
-        wp_register_script(
1913
-            'ee-dialog',
1914
-            EE_ADMIN_URL . 'assets/ee-dialog-helper.js',
1915
-            array('jquery', 'jquery-ui-draggable'),
1916
-            EVENT_ESPRESSO_VERSION,
1917
-            true
1918
-        );
1919
-        wp_register_script(
1920
-            'ee_admin_js',
1921
-            EE_ADMIN_URL . 'assets/ee-admin-page.js',
1922
-            array('espresso_core', 'ee-parse-uri', 'ee-dialog'),
1923
-            EVENT_ESPRESSO_VERSION,
1924
-            true
1925
-        );
1926
-        wp_register_script(
1927
-            'jquery-ui-timepicker-addon',
1928
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery-ui-timepicker-addon.js',
1929
-            array('jquery-ui-datepicker', 'jquery-ui-slider'),
1930
-            EVENT_ESPRESSO_VERSION,
1931
-            true
1932
-        );
1933
-        add_filter('FHEE_load_joyride', '__return_true');
1934
-        //script for sorting tables
1935
-        wp_register_script(
1936
-            'espresso_ajax_table_sorting',
1937
-            EE_ADMIN_URL . 'assets/espresso_ajax_table_sorting.js',
1938
-            array('ee_admin_js', 'jquery-ui-sortable'),
1939
-            EVENT_ESPRESSO_VERSION,
1940
-            true
1941
-        );
1942
-        //script for parsing uri's
1943
-        wp_register_script(
1944
-            'ee-parse-uri',
1945
-            EE_GLOBAL_ASSETS_URL . 'scripts/parseuri.js',
1946
-            array(),
1947
-            EVENT_ESPRESSO_VERSION,
1948
-            true
1949
-        );
1950
-        //and parsing associative serialized form elements
1951
-        wp_register_script(
1952
-            'ee-serialize-full-array',
1953
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.serializefullarray.js',
1954
-            array('jquery'),
1955
-            EVENT_ESPRESSO_VERSION,
1956
-            true
1957
-        );
1958
-        //helpers scripts
1959
-        wp_register_script(
1960
-            'ee-text-links',
1961
-            EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.js',
1962
-            array('jquery'),
1963
-            EVENT_ESPRESSO_VERSION,
1964
-            true
1965
-        );
1966
-        wp_register_script(
1967
-            'ee-moment-core',
1968
-            EE_THIRD_PARTY_URL . 'moment/moment-with-locales.min.js',
1969
-            array(),
1970
-            EVENT_ESPRESSO_VERSION,
1971
-            true
1972
-        );
1973
-        wp_register_script(
1974
-            'ee-moment',
1975
-            EE_THIRD_PARTY_URL . 'moment/moment-timezone-with-data.min.js',
1976
-            array('ee-moment-core'),
1977
-            EVENT_ESPRESSO_VERSION,
1978
-            true
1979
-        );
1980
-        wp_register_script(
1981
-            'ee-datepicker',
1982
-            EE_ADMIN_URL . 'assets/ee-datepicker.js',
1983
-            array('jquery-ui-timepicker-addon', 'ee-moment'),
1984
-            EVENT_ESPRESSO_VERSION,
1985
-            true
1986
-        );
1987
-        //google charts
1988
-        wp_register_script(
1989
-            'google-charts',
1990
-            'https://www.gstatic.com/charts/loader.js',
1991
-            array(),
1992
-            EVENT_ESPRESSO_VERSION,
1993
-            false
1994
-        );
1995
-        // ENQUEUE ALL BASICS BY DEFAULT
1996
-        wp_enqueue_style('ee-admin-css');
1997
-        wp_enqueue_script('ee_admin_js');
1998
-        wp_enqueue_script('ee-accounting');
1999
-        wp_enqueue_script('jquery-validate');
2000
-        //taking care of metaboxes
2001
-        if (
2002
-            empty($this->_cpt_route)
2003
-            && (isset($this->_route_config['metaboxes']) || isset($this->_route_config['has_metaboxes']))
2004
-        ) {
2005
-            wp_enqueue_script('dashboard');
2006
-        }
2007
-        // LOCALIZED DATA
2008
-        //localize script for ajax lazy loading
2009
-        $lazy_loader_container_ids = apply_filters(
2010
-            'FHEE__EE_Admin_Page_Core__load_global_scripts_styles__loader_containers',
2011
-            array('espresso_news_post_box_content')
2012
-        );
2013
-        wp_localize_script('ee_admin_js', 'eeLazyLoadingContainers', $lazy_loader_container_ids);
2014
-        /**
2015
-         * help tour stuff
2016
-         */
2017
-        if (! empty($this->_help_tour)) {
2018
-            //register the js for kicking things off
2019
-            wp_enqueue_script(
2020
-                'ee-help-tour',
2021
-                EE_ADMIN_URL . 'assets/ee-help-tour.js',
2022
-                array('jquery-joyride'),
2023
-                EVENT_ESPRESSO_VERSION,
2024
-                true
2025
-            );
2026
-            $tours = array();
2027
-            //setup tours for the js tour object
2028
-            foreach ($this->_help_tour['tours'] as $tour) {
2029
-                if ($tour instanceof EE_Help_Tour) {
2030
-                    $tours[] = array(
2031
-                        'id'      => $tour->get_slug(),
2032
-                        'options' => $tour->get_options(),
2033
-                    );
2034
-                }
2035
-            }
2036
-            wp_localize_script('ee-help-tour', 'EE_HELP_TOUR', array('tours' => $tours));
2037
-            //admin_footer_global will take care of making sure our help_tour skeleton gets printed via the info stored in $this->_help_tour
2038
-        }
2039
-    }
2040
-
2041
-
2042
-
2043
-    /**
2044
-     *        admin_footer_scripts_eei18n_js_strings
2045
-     *
2046
-     * @return        void
2047
-     */
2048
-    public function admin_footer_scripts_eei18n_js_strings()
2049
-    {
2050
-        EE_Registry::$i18n_js_strings['ajax_url']       = WP_AJAX_URL;
2051
-        EE_Registry::$i18n_js_strings['confirm_delete'] = esc_html__(
2052
-            'Are you absolutely sure you want to delete this item?\nThis action will delete ALL DATA associated with this item!!!\nThis can NOT be undone!!!',
2053
-            'event_espresso'
2054
-        );
2055
-        EE_Registry::$i18n_js_strings['January']        = esc_html__('January', 'event_espresso');
2056
-        EE_Registry::$i18n_js_strings['February']       = esc_html__('February', 'event_espresso');
2057
-        EE_Registry::$i18n_js_strings['March']          = esc_html__('March', 'event_espresso');
2058
-        EE_Registry::$i18n_js_strings['April']          = esc_html__('April', 'event_espresso');
2059
-        EE_Registry::$i18n_js_strings['May']            = esc_html__('May', 'event_espresso');
2060
-        EE_Registry::$i18n_js_strings['June']           = esc_html__('June', 'event_espresso');
2061
-        EE_Registry::$i18n_js_strings['July']           = esc_html__('July', 'event_espresso');
2062
-        EE_Registry::$i18n_js_strings['August']         = esc_html__('August', 'event_espresso');
2063
-        EE_Registry::$i18n_js_strings['September']      = esc_html__('September', 'event_espresso');
2064
-        EE_Registry::$i18n_js_strings['October']        = esc_html__('October', 'event_espresso');
2065
-        EE_Registry::$i18n_js_strings['November']       = esc_html__('November', 'event_espresso');
2066
-        EE_Registry::$i18n_js_strings['December']       = esc_html__('December', 'event_espresso');
2067
-        EE_Registry::$i18n_js_strings['Jan']            = esc_html__('Jan', 'event_espresso');
2068
-        EE_Registry::$i18n_js_strings['Feb']            = esc_html__('Feb', 'event_espresso');
2069
-        EE_Registry::$i18n_js_strings['Mar']            = esc_html__('Mar', 'event_espresso');
2070
-        EE_Registry::$i18n_js_strings['Apr']            = esc_html__('Apr', 'event_espresso');
2071
-        EE_Registry::$i18n_js_strings['May']            = esc_html__('May', 'event_espresso');
2072
-        EE_Registry::$i18n_js_strings['Jun']            = esc_html__('Jun', 'event_espresso');
2073
-        EE_Registry::$i18n_js_strings['Jul']            = esc_html__('Jul', 'event_espresso');
2074
-        EE_Registry::$i18n_js_strings['Aug']            = esc_html__('Aug', 'event_espresso');
2075
-        EE_Registry::$i18n_js_strings['Sep']            = esc_html__('Sep', 'event_espresso');
2076
-        EE_Registry::$i18n_js_strings['Oct']            = esc_html__('Oct', 'event_espresso');
2077
-        EE_Registry::$i18n_js_strings['Nov']            = esc_html__('Nov', 'event_espresso');
2078
-        EE_Registry::$i18n_js_strings['Dec']            = esc_html__('Dec', 'event_espresso');
2079
-        EE_Registry::$i18n_js_strings['Sunday']         = esc_html__('Sunday', 'event_espresso');
2080
-        EE_Registry::$i18n_js_strings['Monday']         = esc_html__('Monday', 'event_espresso');
2081
-        EE_Registry::$i18n_js_strings['Tuesday']        = esc_html__('Tuesday', 'event_espresso');
2082
-        EE_Registry::$i18n_js_strings['Wednesday']      = esc_html__('Wednesday', 'event_espresso');
2083
-        EE_Registry::$i18n_js_strings['Thursday']       = esc_html__('Thursday', 'event_espresso');
2084
-        EE_Registry::$i18n_js_strings['Friday']         = esc_html__('Friday', 'event_espresso');
2085
-        EE_Registry::$i18n_js_strings['Saturday']       = esc_html__('Saturday', 'event_espresso');
2086
-        EE_Registry::$i18n_js_strings['Sun']            = esc_html__('Sun', 'event_espresso');
2087
-        EE_Registry::$i18n_js_strings['Mon']            = esc_html__('Mon', 'event_espresso');
2088
-        EE_Registry::$i18n_js_strings['Tue']            = esc_html__('Tue', 'event_espresso');
2089
-        EE_Registry::$i18n_js_strings['Wed']            = esc_html__('Wed', 'event_espresso');
2090
-        EE_Registry::$i18n_js_strings['Thu']            = esc_html__('Thu', 'event_espresso');
2091
-        EE_Registry::$i18n_js_strings['Fri']            = esc_html__('Fri', 'event_espresso');
2092
-        EE_Registry::$i18n_js_strings['Sat']            = esc_html__('Sat', 'event_espresso');
2093
-    }
2094
-
2095
-
2096
-
2097
-    /**
2098
-     *        load enhanced xdebug styles for ppl with failing eyesight
2099
-     *
2100
-     * @return        void
2101
-     */
2102
-    public function add_xdebug_style()
2103
-    {
2104
-        echo '<style>.xdebug-error { font-size:1.5em; }</style>';
2105
-    }
2106
-
2107
-
2108
-    /************************/
2109
-    /** LIST TABLE METHODS **/
2110
-    /************************/
2111
-    /**
2112
-     * this sets up the list table if the current view requires it.
2113
-     *
2114
-     * @return void
2115
-     * @throws EE_Error
2116
-     */
2117
-    protected function _set_list_table()
2118
-    {
2119
-        //first is this a list_table view?
2120
-        if (! isset($this->_route_config['list_table'])) {
2121
-            return;
2122
-        } //not a list_table view so get out.
2123
-        // list table functions are per view specific (because some admin pages might have more than one list table!)
2124
-        $list_table_view = '_set_list_table_views_' . $this->_req_action;
2125
-        if (! method_exists($this, $list_table_view) || $this->{$list_table_view}() === false) {
2126
-            //user error msg
2127
-            $error_msg = esc_html__(
2128
-                'An error occurred. The requested list table views could not be found.',
2129
-                'event_espresso'
2130
-            );
2131
-            //developer error msg
2132
-            $error_msg .= '||' . sprintf(
2133
-                    esc_html__(
2134
-                        'List table views for "%s" route could not be setup. Check that you have the corresponding method, "%s" set up for defining list_table_views for this route.',
2135
-                        'event_espresso'
2136
-                    ),
2137
-                    $this->_req_action,
2138
-                    $list_table_view
2139
-                );
2140
-            throw new EE_Error($error_msg);
2141
-        }
2142
-        //let's provide the ability to filter the views per PAGE AND ROUTE, per PAGE, and globally
2143
-        $this->_views = apply_filters(
2144
-            'FHEE_list_table_views_' . $this->page_slug . '_' . $this->_req_action,
2145
-            $this->_views
2146
-        );
2147
-        $this->_views = apply_filters('FHEE_list_table_views_' . $this->page_slug, $this->_views);
2148
-        $this->_views = apply_filters('FHEE_list_table_views', $this->_views);
2149
-        $this->_set_list_table_view();
2150
-        $this->_set_list_table_object();
2151
-    }
2152
-
2153
-
2154
-
2155
-    /**
2156
-     * set current view for List Table
2157
-     *
2158
-     * @return void
2159
-     */
2160
-    protected function _set_list_table_view()
2161
-    {
2162
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2163
-        // looking at active items or dumpster diving ?
2164
-        if (! isset($this->_req_data['status']) || ! array_key_exists($this->_req_data['status'], $this->_views)) {
2165
-            $this->_view = isset($this->_views['in_use']) ? 'in_use' : 'all';
2166
-        } else {
2167
-            $this->_view = sanitize_key($this->_req_data['status']);
2168
-        }
2169
-    }
2170
-
2171
-
2172
-    /**
2173
-     * _set_list_table_object
2174
-     * WP_List_Table objects need to be loaded fairly early so automatic stuff WP does is taken care of.
2175
-     *
2176
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2177
-     * @throws \InvalidArgumentException
2178
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2179
-     * @throws EE_Error
2180
-     * @throws InvalidInterfaceException
2181
-     */
2182
-    protected function _set_list_table_object()
2183
-    {
2184
-        if (isset($this->_route_config['list_table'])) {
2185
-            if (! class_exists($this->_route_config['list_table'])) {
2186
-                throw new EE_Error(
2187
-                    sprintf(
2188
-                        esc_html__(
2189
-                            'The %s class defined for the list table does not exist.  Please check the spelling of the class ref in the $_page_config property on %s.',
2190
-                            'event_espresso'
2191
-                        ),
2192
-                        $this->_route_config['list_table'],
2193
-                        get_class($this)
2194
-                    )
2195
-                );
2196
-            }
2197
-            $this->_list_table_object = LoaderFactory::getLoader()->getShared(
2198
-                $this->_route_config['list_table'],
2199
-                array($this)
2200
-            );
2201
-        }
2202
-    }
2203
-
2204
-
2205
-
2206
-    /**
2207
-     * get_list_table_view_RLs - get it? View RL ?? VU-RL???  URL ??
2208
-     *
2209
-     * @param array $extra_query_args                     Optional. An array of extra query args to add to the generated
2210
-     *                                                    urls.  The array should be indexed by the view it is being
2211
-     *                                                    added to.
2212
-     * @return array
2213
-     */
2214
-    public function get_list_table_view_RLs($extra_query_args = array())
2215
-    {
2216
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2217
-        if (empty($this->_views)) {
2218
-            $this->_views = array();
2219
-        }
2220
-        // cycle thru views
2221
-        foreach ($this->_views as $key => $view) {
2222
-            $query_args = array();
2223
-            // check for current view
2224
-            $this->_views[$key]['class']               = $this->_view === $view['slug'] ? 'current' : '';
2225
-            $query_args['action']                      = $this->_req_action;
2226
-            $query_args[$this->_req_action . '_nonce'] = wp_create_nonce($query_args['action'] . '_nonce');
2227
-            $query_args['status']                      = $view['slug'];
2228
-            //merge any other arguments sent in.
2229
-            if (isset($extra_query_args[$view['slug']])) {
2230
-                $query_args = array_merge($query_args, $extra_query_args[$view['slug']]);
2231
-            }
2232
-            $this->_views[$key]['url'] = EE_Admin_Page::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2233
-        }
2234
-        return $this->_views;
2235
-    }
2236
-
2237
-
2238
-
2239
-    /**
2240
-     * _entries_per_page_dropdown
2241
-     * generates a drop down box for selecting the number of visible rows in an admin page list table
2242
-     *
2243
-     * @todo   : Note: ideally this should be added to the screen options dropdown as that would be consistent with how
2244
-     *         WP does it.
2245
-     * @param int $max_entries total number of rows in the table
2246
-     * @return string
2247
-     */
2248
-    protected function _entries_per_page_dropdown($max_entries = 0)
2249
-    {
2250
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2251
-        $values   = array(10, 25, 50, 100);
2252
-        $per_page = (! empty($this->_req_data['per_page'])) ? absint($this->_req_data['per_page']) : 10;
2253
-        if ($max_entries) {
2254
-            $values[] = $max_entries;
2255
-            sort($values);
2256
-        }
2257
-        $entries_per_page_dropdown = '
126
+	/**
127
+	 * @var string $_req_action
128
+	 */
129
+	protected $_req_action;
130
+
131
+	/**
132
+	 * @var string $_req_nonce
133
+	 */
134
+	protected $_req_nonce;
135
+
136
+	//search related
137
+	protected $_search_btn_label;
138
+
139
+	protected $_search_box_callback;
140
+
141
+	/**
142
+	 * WP Current Screen object
143
+	 *
144
+	 * @var WP_Screen
145
+	 */
146
+	protected $_current_screen;
147
+
148
+	//for holding EE_Admin_Hooks object when needed (set via set_hook_object())
149
+	protected $_hook_obj;
150
+
151
+	//for holding incoming request data
152
+	protected $_req_data;
153
+
154
+	// yes / no array for admin form fields
155
+	protected $_yes_no_values = array();
156
+
157
+	//some default things shared by all child classes
158
+	protected $_default_espresso_metaboxes;
159
+
160
+	/**
161
+	 *    EE_Registry Object
162
+	 *
163
+	 * @var    EE_Registry
164
+	 */
165
+	protected $EE = null;
166
+
167
+
168
+
169
+	/**
170
+	 * This is just a property that flags whether the given route is a caffeinated route or not.
171
+	 *
172
+	 * @var boolean
173
+	 */
174
+	protected $_is_caf = false;
175
+
176
+
177
+
178
+	/**
179
+	 * @Constructor
180
+	 * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
181
+	 * @throws EE_Error
182
+	 * @throws InvalidArgumentException
183
+	 * @throws ReflectionException
184
+	 * @throws InvalidDataTypeException
185
+	 * @throws InvalidInterfaceException
186
+	 */
187
+	public function __construct($routing = true)
188
+	{
189
+		if (strpos($this->_get_dir(), 'caffeinated') !== false) {
190
+			$this->_is_caf = true;
191
+		}
192
+		$this->_yes_no_values = array(
193
+			array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
194
+			array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
195
+		);
196
+		//set the _req_data property.
197
+		$this->_req_data = array_merge($_GET, $_POST);
198
+		//routing enabled?
199
+		$this->_routing = $routing;
200
+		//set initial page props (child method)
201
+		$this->_init_page_props();
202
+		//set global defaults
203
+		$this->_set_defaults();
204
+		//set early because incoming requests could be ajax related and we need to register those hooks.
205
+		$this->_global_ajax_hooks();
206
+		$this->_ajax_hooks();
207
+		//other_page_hooks have to be early too.
208
+		$this->_do_other_page_hooks();
209
+		//This just allows us to have extending classes do something specific
210
+		// before the parent constructor runs _page_setup().
211
+		if (method_exists($this, '_before_page_setup')) {
212
+			$this->_before_page_setup();
213
+		}
214
+		//set up page dependencies
215
+		$this->_page_setup();
216
+	}
217
+
218
+
219
+
220
+	/**
221
+	 * _init_page_props
222
+	 * Child classes use to set at least the following properties:
223
+	 * $page_slug.
224
+	 * $page_label.
225
+	 *
226
+	 * @abstract
227
+	 * @return void
228
+	 */
229
+	abstract protected function _init_page_props();
230
+
231
+
232
+
233
+	/**
234
+	 * _ajax_hooks
235
+	 * child classes put all their add_action('wp_ajax_{name_of_hook}') hooks in here.
236
+	 * Note: within the ajax callback methods.
237
+	 *
238
+	 * @abstract
239
+	 * @return void
240
+	 */
241
+	abstract protected function _ajax_hooks();
242
+
243
+
244
+
245
+	/**
246
+	 * _define_page_props
247
+	 * child classes define page properties in here.  Must include at least:
248
+	 * $_admin_base_url = base_url for all admin pages
249
+	 * $_admin_page_title = default admin_page_title for admin pages
250
+	 * $_labels = array of default labels for various automatically generated elements:
251
+	 *    array(
252
+	 *        'buttons' => array(
253
+	 *            'add' => esc_html__('label for add new button'),
254
+	 *            'edit' => esc_html__('label for edit button'),
255
+	 *            'delete' => esc_html__('label for delete button')
256
+	 *            )
257
+	 *        )
258
+	 *
259
+	 * @abstract
260
+	 * @return void
261
+	 */
262
+	abstract protected function _define_page_props();
263
+
264
+
265
+
266
+	/**
267
+	 * _set_page_routes
268
+	 * child classes use this to define the page routes for all subpages handled by the class.  Page routes are
269
+	 * assigned to a action => method pairs in an array and to the $_page_routes property.  Each page route must also
270
+	 * have a 'default' route. Here's the format
271
+	 * $this->_page_routes = array(
272
+	 *        'default' => array(
273
+	 *            'func' => '_default_method_handling_route',
274
+	 *            'args' => array('array','of','args'),
275
+	 *            'noheader' => true, //add this in if this page route is processed before any headers are loaded (i.e.
276
+	 *            ajax request, backend processing)
277
+	 *            'headers_sent_route'=>'headers_route_reference', //add this if noheader=>true, and you want to load a
278
+	 *            headers route after.  The string you enter here should match the defined route reference for a
279
+	 *            headers sent route.
280
+	 *            'capability' => 'route_capability', //indicate a string for minimum capability required to access
281
+	 *            this route.
282
+	 *            'obj_id' => 10 // if this route has an object id, then this can include it (used for capability
283
+	 *            checks).
284
+	 *        ),
285
+	 *        'insert_item' => '_method_for_handling_insert_item' //this can be used if all we need to have is a
286
+	 *        handling method.
287
+	 *        )
288
+	 * )
289
+	 *
290
+	 * @abstract
291
+	 * @return void
292
+	 */
293
+	abstract protected function _set_page_routes();
294
+
295
+
296
+
297
+	/**
298
+	 * _set_page_config
299
+	 * child classes use this to define the _page_config array for all subpages handled by the class. Each key in the
300
+	 * array corresponds to the page_route for the loaded page. Format:
301
+	 * $this->_page_config = array(
302
+	 *        'default' => array(
303
+	 *            'labels' => array(
304
+	 *                'buttons' => array(
305
+	 *                    'add' => esc_html__('label for adding item'),
306
+	 *                    'edit' => esc_html__('label for editing item'),
307
+	 *                    'delete' => esc_html__('label for deleting item')
308
+	 *                ),
309
+	 *                'publishbox' => esc_html__('Localized Title for Publish metabox', 'event_espresso')
310
+	 *            ), //optional an array of custom labels for various automatically generated elements to use on the
311
+	 *            page. If this isn't present then the defaults will be used as set for the $this->_labels in
312
+	 *            _define_page_props() method
313
+	 *            'nav' => array(
314
+	 *                'label' => esc_html__('Label for Tab', 'event_espresso').
315
+	 *                'url' => 'http://someurl', //automatically generated UNLESS you define
316
+	 *                'css_class' => 'css-class', //automatically generated UNLESS you define
317
+	 *                'order' => 10, //required to indicate tab position.
318
+	 *                'persistent' => false //if you want the nav tab to ONLY display when the specific route is
319
+	 *                displayed then add this parameter.
320
+	 *            'list_table' => 'name_of_list_table' //string for list table class to be loaded for this admin_page.
321
+	 *            'metaboxes' => array('metabox1', 'metabox2'), //if present this key indicates we want to load
322
+	 *            metaboxes set for eventespresso admin pages.
323
+	 *            'has_metaboxes' => true, //this boolean flag can simply be used to indicate if the route will have
324
+	 *            metaboxes.  Typically this is used if the 'metaboxes' index is not used because metaboxes are added
325
+	 *            later.  We just use this flag to make sure the necessary js gets enqueued on page load.
326
+	 *            'has_help_popups' => false //defaults(true) //this boolean flag can simply be used to indicate if the
327
+	 *            given route has help popups setup and if it does then we need to make sure thickbox is enqueued.
328
+	 *            'columns' => array(4, 2), //this key triggers the setup of a page that uses columns (metaboxes).  The
329
+	 *            array indicates the max number of columns (4) and the default number of columns on page load (2).
330
+	 *            There is an option in the "screen_options" dropdown that is setup so users can pick what columns they
331
+	 *            want to display.
332
+	 *            'help_tabs' => array( //this is used for adding help tabs to a page
333
+	 *                'tab_id' => array(
334
+	 *                    'title' => 'tab_title',
335
+	 *                    'filename' => 'name_of_file_containing_content', //this is the primary method for setting
336
+	 *                    help tab content.  The fallback if it isn't present is to try a the callback.  Filename
337
+	 *                    should match a file in the admin folder's "help_tabs" dir (ie..
338
+	 *                    events/help_tabs/name_of_file_containing_content.help_tab.php)
339
+	 *                    'callback' => 'callback_method_for_content', //if 'filename' isn't present then system will
340
+	 *                    attempt to use the callback which should match the name of a method in the class
341
+	 *                    ),
342
+	 *                'tab2_id' => array(
343
+	 *                    'title' => 'tab2 title',
344
+	 *                    'filename' => 'file_name_2'
345
+	 *                    'callback' => 'callback_method_for_content',
346
+	 *                 ),
347
+	 *            'help_sidebar' => 'callback_for_sidebar_content', //this is used for setting up the sidebar in the
348
+	 *            help tab area on an admin page. @link
349
+	 *            http://make.wordpress.org/core/2011/12/06/help-and-screen-api-changes-in-3-3/
350
+	 *            'help_tour' => array(
351
+	 *                'name_of_help_tour_class', //all help tours shoudl be a child class of EE_Help_Tour and located
352
+	 *                in a folder for this admin page named "help_tours", a file name matching the key given here
353
+	 *                (name_of_help_tour_class.class.php), and class matching key given here (name_of_help_tour_class)
354
+	 *            ),
355
+	 *            'require_nonce' => TRUE //this is used if you want to set a route to NOT require a nonce (default is
356
+	 *            true if it isn't present).  To remove the requirement for a nonce check when this route is visited
357
+	 *            just set
358
+	 *            'require_nonce' to FALSE
359
+	 *            )
360
+	 * )
361
+	 *
362
+	 * @abstract
363
+	 * @return void
364
+	 */
365
+	abstract protected function _set_page_config();
366
+
367
+
368
+
369
+
370
+
371
+	/** end sample help_tour methods **/
372
+	/**
373
+	 * _add_screen_options
374
+	 * Child classes can add any extra wp_screen_options within this method using built-in WP functions/methods for
375
+	 * doing so. Note child classes can also define _add_screen_options_($this->_current_view) to limit screen options
376
+	 * to a particular view.
377
+	 *
378
+	 * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
379
+	 *         see also WP_Screen object documents...
380
+	 * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
381
+	 * @abstract
382
+	 * @return void
383
+	 */
384
+	abstract protected function _add_screen_options();
385
+
386
+
387
+
388
+	/**
389
+	 * _add_feature_pointers
390
+	 * Child classes should use this method for implementing any "feature pointers" (using built-in WP styling js).
391
+	 * Note child classes can also define _add_feature_pointers_($this->_current_view) to limit screen options to a
392
+	 * particular view. Note: this is just a placeholder for now.  Implementation will come down the road See:
393
+	 * WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be
394
+	 * extended) also see:
395
+	 *
396
+	 * @link   http://eamann.com/tech/wordpress-portland/
397
+	 * @abstract
398
+	 * @return void
399
+	 */
400
+	abstract protected function _add_feature_pointers();
401
+
402
+
403
+
404
+	/**
405
+	 * load_scripts_styles
406
+	 * child classes put their wp_enqueue_script and wp_enqueue_style hooks in here for anything they need loaded for
407
+	 * their pages/subpages.  Note this is for all pages/subpages of the system.  You can also load only specific
408
+	 * scripts/styles per view by putting them in a dynamic function in this format
409
+	 * (load_scripts_styles_{$this->_current_view}) which matches your page route (action request arg)
410
+	 *
411
+	 * @abstract
412
+	 * @return void
413
+	 */
414
+	abstract public function load_scripts_styles();
415
+
416
+
417
+
418
+	/**
419
+	 * admin_init
420
+	 * Anything that should be set/executed at 'admin_init' WP hook runtime should be put in here.  This will apply to
421
+	 * all pages/views loaded by child class.
422
+	 *
423
+	 * @abstract
424
+	 * @return void
425
+	 */
426
+	abstract public function admin_init();
427
+
428
+
429
+
430
+	/**
431
+	 * admin_notices
432
+	 * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply to
433
+	 * all pages/views loaded by child class.
434
+	 *
435
+	 * @abstract
436
+	 * @return void
437
+	 */
438
+	abstract public function admin_notices();
439
+
440
+
441
+
442
+	/**
443
+	 * admin_footer_scripts
444
+	 * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
445
+	 * will apply to all pages/views loaded by child class.
446
+	 *
447
+	 * @return void
448
+	 */
449
+	abstract public function admin_footer_scripts();
450
+
451
+
452
+
453
+	/**
454
+	 * admin_footer
455
+	 * anything triggered by the 'admin_footer' WP action hook should be added to here. This particular method will
456
+	 * apply to all pages/views loaded by child class.
457
+	 *
458
+	 * @return void
459
+	 */
460
+	public function admin_footer()
461
+	{
462
+	}
463
+
464
+
465
+
466
+	/**
467
+	 * _global_ajax_hooks
468
+	 * all global add_action('wp_ajax_{name_of_hook}') hooks in here.
469
+	 * Note: within the ajax callback methods.
470
+	 *
471
+	 * @abstract
472
+	 * @return void
473
+	 */
474
+	protected function _global_ajax_hooks()
475
+	{
476
+		//for lazy loading of metabox content
477
+		add_action('wp_ajax_espresso-ajax-content', array($this, 'ajax_metabox_content'), 10);
478
+	}
479
+
480
+
481
+
482
+	public function ajax_metabox_content()
483
+	{
484
+		$contentid = isset($this->_req_data['contentid']) ? $this->_req_data['contentid'] : '';
485
+		$url       = isset($this->_req_data['contenturl']) ? $this->_req_data['contenturl'] : '';
486
+		self::cached_rss_display($contentid, $url);
487
+		wp_die();
488
+	}
489
+
490
+
491
+
492
+	/**
493
+	 * _page_setup
494
+	 * Makes sure any things that need to be loaded early get handled.  We also escape early here if the page requested
495
+	 * doesn't match the object.
496
+	 *
497
+	 * @final
498
+	 * @return void
499
+	 * @throws EE_Error
500
+	 * @throws InvalidArgumentException
501
+	 * @throws ReflectionException
502
+	 * @throws InvalidDataTypeException
503
+	 * @throws InvalidInterfaceException
504
+	 */
505
+	final protected function _page_setup()
506
+	{
507
+		//requires?
508
+		//admin_init stuff - global - we're setting this REALLY early so if EE_Admin pages have to hook into other WP pages they can.  But keep in mind, not everything is available from the EE_Admin Page object at this point.
509
+		add_action('admin_init', array($this, 'admin_init_global'), 5);
510
+		//next verify if we need to load anything...
511
+		$this->_current_page = ! empty($_GET['page']) ? sanitize_key($_GET['page']) : '';
512
+		$this->page_folder   = strtolower(
513
+			str_replace(array('_Admin_Page', 'Extend_'), '', get_class($this))
514
+		);
515
+		global $ee_menu_slugs;
516
+		$ee_menu_slugs = (array)$ee_menu_slugs;
517
+		if (! defined('DOING_AJAX') && (! $this->_current_page || ! isset($ee_menu_slugs[$this->_current_page]))) {
518
+			return;
519
+		}
520
+		// becuz WP List tables have two duplicate select inputs for choosing bulk actions, we need to copy the action from the second to the first
521
+		if (isset($this->_req_data['action2']) && $this->_req_data['action'] === '-1') {
522
+			$this->_req_data['action'] = ! empty($this->_req_data['action2']) && $this->_req_data['action2'] !== '-1'
523
+				? $this->_req_data['action2']
524
+				: $this->_req_data['action'];
525
+		}
526
+		// then set blank or -1 action values to 'default'
527
+		$this->_req_action = isset($this->_req_data['action'])
528
+							 && ! empty($this->_req_data['action'])
529
+							 && $this->_req_data['action'] !== '-1'
530
+			? sanitize_key($this->_req_data['action'])
531
+			: 'default';
532
+		// if action is 'default' after the above BUT we have  'route' var set, then let's use the route as the action.
533
+		//  This covers cases where we're coming in from a list table that isn't on the default route.
534
+		$this->_req_action = $this->_req_action === 'default' && isset($this->_req_data['route'])
535
+			? $this->_req_data['route'] : $this->_req_action;
536
+		//however if we are doing_ajax and we've got a 'route' set then that's what the req_action will be
537
+		$this->_req_action   = defined('DOING_AJAX') && isset($this->_req_data['route'])
538
+			? $this->_req_data['route']
539
+			: $this->_req_action;
540
+		$this->_current_view = $this->_req_action;
541
+		$this->_req_nonce    = $this->_req_action . '_nonce';
542
+		$this->_define_page_props();
543
+		$this->_current_page_view_url = add_query_arg(
544
+			array('page' => $this->_current_page, 'action' => $this->_current_view),
545
+			$this->_admin_base_url
546
+		);
547
+		//default things
548
+		$this->_default_espresso_metaboxes = array(
549
+			'_espresso_news_post_box',
550
+			'_espresso_links_post_box',
551
+			'_espresso_ratings_request',
552
+			'_espresso_sponsors_post_box',
553
+		);
554
+		//set page configs
555
+		$this->_set_page_routes();
556
+		$this->_set_page_config();
557
+		//let's include any referrer data in our default_query_args for this route for "stickiness".
558
+		if (isset($this->_req_data['wp_referer'])) {
559
+			$this->_default_route_query_args['wp_referer'] = $this->_req_data['wp_referer'];
560
+		}
561
+		//for caffeinated and other extended functionality.
562
+		//  If there is a _extend_page_config method
563
+		// then let's run that to modify the all the various page configuration arrays
564
+		if (method_exists($this, '_extend_page_config')) {
565
+			$this->_extend_page_config();
566
+		}
567
+		//for CPT and other extended functionality.
568
+		// If there is an _extend_page_config_for_cpt
569
+		// then let's run that to modify all the various page configuration arrays.
570
+		if (method_exists($this, '_extend_page_config_for_cpt')) {
571
+			$this->_extend_page_config_for_cpt();
572
+		}
573
+		//filter routes and page_config so addons can add their stuff. Filtering done per class
574
+		$this->_page_routes = apply_filters(
575
+			'FHEE__' . get_class($this) . '__page_setup__page_routes',
576
+			$this->_page_routes,
577
+			$this
578
+		);
579
+		$this->_page_config = apply_filters(
580
+			'FHEE__' . get_class($this) . '__page_setup__page_config',
581
+			$this->_page_config,
582
+			$this
583
+		);
584
+		//if AHEE__EE_Admin_Page__route_admin_request_$this->_current_view method is present
585
+		// then we call it hooked into the AHEE__EE_Admin_Page__route_admin_request action
586
+		if (
587
+			method_exists($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view)
588
+		) {
589
+			add_action(
590
+				'AHEE__EE_Admin_Page__route_admin_request',
591
+				array($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view),
592
+				10,
593
+				2
594
+			);
595
+		}
596
+		//next route only if routing enabled
597
+		if ($this->_routing && ! defined('DOING_AJAX')) {
598
+			$this->_verify_routes();
599
+			//next let's just check user_access and kill if no access
600
+			$this->check_user_access();
601
+			if ($this->_is_UI_request) {
602
+				//admin_init stuff - global, all views for this page class, specific view
603
+				add_action('admin_init', array($this, 'admin_init'), 10);
604
+				if (method_exists($this, 'admin_init_' . $this->_current_view)) {
605
+					add_action('admin_init', array($this, 'admin_init_' . $this->_current_view), 15);
606
+				}
607
+			} else {
608
+				//hijack regular WP loading and route admin request immediately
609
+				@ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT));
610
+				$this->route_admin_request();
611
+			}
612
+		}
613
+	}
614
+
615
+
616
+
617
+	/**
618
+	 * Provides a way for related child admin pages to load stuff on the loaded admin page.
619
+	 *
620
+	 * @return void
621
+	 * @throws ReflectionException
622
+	 * @throws EE_Error
623
+	 */
624
+	private function _do_other_page_hooks()
625
+	{
626
+		$registered_pages = apply_filters('FHEE_do_other_page_hooks_' . $this->page_slug, array());
627
+		foreach ($registered_pages as $page) {
628
+			//now let's setup the file name and class that should be present
629
+			$classname = str_replace('.class.php', '', $page);
630
+			//autoloaders should take care of loading file
631
+			if (! class_exists($classname)) {
632
+				$error_msg[] = sprintf(
633
+					esc_html__(
634
+						'Something went wrong with loading the %s admin hooks page.',
635
+						'event_espresso'
636
+					),
637
+					$page
638
+				);
639
+				$error_msg[] = $error_msg[0]
640
+							   . "\r\n"
641
+							   . sprintf(
642
+								   esc_html__(
643
+									   'There is no class in place for the %1$s admin hooks page.%2$sMake sure you have %3$s defined. If this is a non-EE-core admin page then you also must have an autoloader in place for your class',
644
+									   'event_espresso'
645
+								   ),
646
+								   $page,
647
+								   '<br />',
648
+								   '<strong>' . $classname . '</strong>'
649
+							   );
650
+				throw new EE_Error(implode('||', $error_msg));
651
+			}
652
+			$a = new ReflectionClass($classname);
653
+			//notice we are passing the instance of this class to the hook object.
654
+			$hookobj[] = $a->newInstance($this);
655
+		}
656
+	}
657
+
658
+
659
+
660
+	public function load_page_dependencies()
661
+	{
662
+		try {
663
+			$this->_load_page_dependencies();
664
+		} catch (EE_Error $e) {
665
+			$e->get_error();
666
+		}
667
+	}
668
+
669
+
670
+
671
+	/**
672
+	 * load_page_dependencies
673
+	 * loads things specific to this page class when its loaded.  Really helps with efficiency.
674
+	 *
675
+	 * @return void
676
+	 * @throws DomainException
677
+	 * @throws EE_Error
678
+	 * @throws InvalidArgumentException
679
+	 * @throws InvalidDataTypeException
680
+	 * @throws InvalidInterfaceException
681
+	 * @throws ReflectionException
682
+	 */
683
+	protected function _load_page_dependencies()
684
+	{
685
+		//let's set the current_screen and screen options to override what WP set
686
+		$this->_current_screen = get_current_screen();
687
+		//load admin_notices - global, page class, and view specific
688
+		add_action('admin_notices', array($this, 'admin_notices_global'), 5);
689
+		add_action('admin_notices', array($this, 'admin_notices'), 10);
690
+		if (method_exists($this, 'admin_notices_' . $this->_current_view)) {
691
+			add_action('admin_notices', array($this, 'admin_notices_' . $this->_current_view), 15);
692
+		}
693
+		//load network admin_notices - global, page class, and view specific
694
+		add_action('network_admin_notices', array($this, 'network_admin_notices_global'), 5);
695
+		if (method_exists($this, 'network_admin_notices_' . $this->_current_view)) {
696
+			add_action('network_admin_notices', array($this, 'network_admin_notices_' . $this->_current_view));
697
+		}
698
+		//this will save any per_page screen options if they are present
699
+		$this->_set_per_page_screen_options();
700
+		//setup list table properties
701
+		$this->_set_list_table();
702
+		// child classes can "register" a metabox to be automatically handled via the _page_config array property.
703
+		// However in some cases the metaboxes will need to be added within a route handling callback.
704
+		$this->_add_registered_meta_boxes();
705
+		$this->_add_screen_columns();
706
+		//add screen options - global, page child class, and view specific
707
+		$this->_add_global_screen_options();
708
+		$this->_add_screen_options();
709
+		$add_screen_options  = "_add_screen_options_{$this->_current_view}";
710
+		if (method_exists($this, $add_screen_options )) {
711
+			$this->{$add_screen_options}();
712
+		}
713
+		//add help tab(s) and tours- set via page_config and qtips.
714
+		$this->_add_help_tour();
715
+		$this->_add_help_tabs();
716
+		$this->_add_qtips();
717
+		//add feature_pointers - global, page child class, and view specific
718
+		$this->_add_feature_pointers();
719
+		$this->_add_global_feature_pointers();
720
+		$add_feature_pointer = "_add_feature_pointer_{$this->_current_view}";
721
+		if (method_exists($this, $add_feature_pointer )) {
722
+			$this->{$add_feature_pointer}();
723
+		}
724
+		//enqueue scripts/styles - global, page class, and view specific
725
+		add_action('admin_enqueue_scripts', array($this, 'load_global_scripts_styles'), 5);
726
+		add_action('admin_enqueue_scripts', array($this, 'load_scripts_styles'), 10);
727
+		if (method_exists($this, "load_scripts_styles_{$this->_current_view}")) {
728
+			add_action('admin_enqueue_scripts', array($this, "load_scripts_styles_{$this->_current_view}"), 15);
729
+		}
730
+		add_action('admin_enqueue_scripts', array($this, 'admin_footer_scripts_eei18n_js_strings'), 100);
731
+		// admin_print_footer_scripts - global, page child class, and view specific.
732
+		// NOTE, despite the name, whenever possible, scripts should NOT be loaded using this.
733
+		// In most cases that's doing_it_wrong().  But adding hidden container elements etc.
734
+		// is a good use case. Notice the late priority we're giving these
735
+		add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts_global'), 99);
736
+		add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts'), 100);
737
+		if (method_exists($this, "admin_footer_scripts_{$this->_current_view}")) {
738
+			add_action('admin_print_footer_scripts', array($this, "admin_footer_scripts_{$this->_current_view}"), 101);
739
+		}
740
+		//admin footer scripts
741
+		add_action('admin_footer', array($this, 'admin_footer_global'), 99);
742
+		add_action('admin_footer', array($this, 'admin_footer'), 100);
743
+		if (method_exists($this, "admin_footer_{$this->_current_view}")) {
744
+			add_action('admin_footer', array($this, "admin_footer_{$this->_current_view}"), 101);
745
+		}
746
+		do_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', $this->page_slug);
747
+		//targeted hook
748
+		do_action(
749
+			"FHEE__EE_Admin_Page___load_page_dependencies__after_load__{$this->page_slug}__{$this->_req_action}"
750
+
751
+		);
752
+	}
753
+
754
+
755
+
756
+	/**
757
+	 * _set_defaults
758
+	 * This sets some global defaults for class properties.
759
+	 */
760
+	private function _set_defaults()
761
+	{
762
+		$this->_current_screen = $this->_admin_page_title = $this->_req_action = $this->_req_nonce = null;
763
+		$this->_event = $this->_template_path = $this->_column_template_path = null;
764
+		$this->_nav_tabs = $this->_views = $this->_page_routes = array();
765
+		$this->_page_config = $this->_default_route_query_args = array();
766
+		$this->_default_nav_tab_name = 'overview';
767
+		//init template args
768
+		$this->_template_args = array(
769
+			'admin_page_header'  => '',
770
+			'admin_page_content' => '',
771
+			'post_body_content'  => '',
772
+			'before_list_table'  => '',
773
+			'after_list_table'   => '',
774
+		);
775
+	}
776
+
777
+
778
+
779
+	/**
780
+	 * route_admin_request
781
+	 *
782
+	 * @see    _route_admin_request()
783
+	 * @return exception|void error
784
+	 * @throws InvalidArgumentException
785
+	 * @throws InvalidInterfaceException
786
+	 * @throws InvalidDataTypeException
787
+	 * @throws EE_Error
788
+	 * @throws ReflectionException
789
+	 */
790
+	public function route_admin_request()
791
+	{
792
+		try {
793
+			$this->_route_admin_request();
794
+		} catch (EE_Error $e) {
795
+			$e->get_error();
796
+		}
797
+	}
798
+
799
+
800
+
801
+	public function set_wp_page_slug($wp_page_slug)
802
+	{
803
+		$this->_wp_page_slug = $wp_page_slug;
804
+		//if in network admin then we need to append "-network" to the page slug. Why? Because that's how WP rolls...
805
+		if (is_network_admin()) {
806
+			$this->_wp_page_slug .= '-network';
807
+		}
808
+	}
809
+
810
+
811
+
812
+	/**
813
+	 * _verify_routes
814
+	 * All this method does is verify the incoming request and make sure that routes exist for it.  We do this early so
815
+	 * we know if we need to drop out.
816
+	 *
817
+	 * @return bool
818
+	 * @throws EE_Error
819
+	 */
820
+	protected function _verify_routes()
821
+	{
822
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
823
+		if (! $this->_current_page && ! defined('DOING_AJAX')) {
824
+			return false;
825
+		}
826
+		$this->_route = false;
827
+		// check that the page_routes array is not empty
828
+		if (empty($this->_page_routes)) {
829
+			// user error msg
830
+			$error_msg = sprintf(
831
+				esc_html__('No page routes have been set for the %s admin page.', 'event_espresso'),
832
+				$this->_admin_page_title
833
+			);
834
+			// developer error msg
835
+			$error_msg .= '||' . $error_msg . esc_html__(
836
+				' Make sure the "set_page_routes()" method exists, and is setting the "_page_routes" array properly.',
837
+				'event_espresso'
838
+			);
839
+			throw new EE_Error($error_msg);
840
+		}
841
+		// and that the requested page route exists
842
+		if (array_key_exists($this->_req_action, $this->_page_routes)) {
843
+			$this->_route        = $this->_page_routes[$this->_req_action];
844
+			$this->_route_config = isset($this->_page_config[$this->_req_action])
845
+				? $this->_page_config[$this->_req_action] : array();
846
+		} else {
847
+			// user error msg
848
+			$error_msg = sprintf(
849
+				esc_html__(
850
+						'The requested page route does not exist for the %s admin page.',
851
+						'event_espresso'
852
+				),
853
+				$this->_admin_page_title
854
+			);
855
+			// developer error msg
856
+			$error_msg .= '||' . $error_msg . sprintf(
857
+					esc_html__(
858
+						' Create a key in the "_page_routes" array named "%s" and set its value to the appropriate method.',
859
+						'event_espresso'
860
+					),
861
+					$this->_req_action
862
+				);
863
+			throw new EE_Error($error_msg);
864
+		}
865
+		// and that a default route exists
866
+		if (! array_key_exists('default', $this->_page_routes)) {
867
+			// user error msg
868
+			$error_msg = sprintf(
869
+				esc_html__(
870
+						'A default page route has not been set for the % admin page.',
871
+						'event_espresso'
872
+				),
873
+				$this->_admin_page_title
874
+			);
875
+			// developer error msg
876
+			$error_msg .= '||' . $error_msg . esc_html__(
877
+				' Create a key in the "_page_routes" array named "default" and set its value to your default page method.',
878
+				'event_espresso'
879
+			);
880
+			throw new EE_Error($error_msg);
881
+		}
882
+		//first lets' catch if the UI request has EVER been set.
883
+		if ($this->_is_UI_request === null) {
884
+			//lets set if this is a UI request or not.
885
+			$this->_is_UI_request = ! isset($this->_req_data['noheader']) || $this->_req_data['noheader'] !== true;
886
+			//wait a minute... we might have a noheader in the route array
887
+			$this->_is_UI_request = is_array($this->_route)
888
+									&& isset($this->_route['noheader'])
889
+									&& $this->_route['noheader'] ? false : $this->_is_UI_request;
890
+		}
891
+		$this->_set_current_labels();
892
+		return true;
893
+	}
894
+
895
+
896
+
897
+	/**
898
+	 * this method simply verifies a given route and makes sure its an actual route available for the loaded page
899
+	 *
900
+	 * @param  string $route the route name we're verifying
901
+	 * @return mixed (bool|Exception)      we'll throw an exception if this isn't a valid route.
902
+	 * @throws EE_Error
903
+	 */
904
+	protected function _verify_route($route)
905
+	{
906
+		if (array_key_exists($this->_req_action, $this->_page_routes)) {
907
+			return true;
908
+		}
909
+		// user error msg
910
+		$error_msg = sprintf(
911
+			esc_html__('The given page route does not exist for the %s admin page.', 'event_espresso'),
912
+			$this->_admin_page_title
913
+		);
914
+		// developer error msg
915
+		$error_msg .= '||' . $error_msg . sprintf(
916
+				esc_html__(
917
+					' Check the route you are using in your method (%s) and make sure it matches a route set in your "_page_routes" array property',
918
+					'event_espresso'
919
+				),
920
+				$route
921
+			);
922
+		throw new EE_Error($error_msg);
923
+	}
924
+
925
+
926
+
927
+	/**
928
+	 * perform nonce verification
929
+	 * This method has be encapsulated here so that any ajax requests that bypass normal routes can verify their nonces
930
+	 * using this method (and save retyping!)
931
+	 *
932
+	 * @param  string $nonce     The nonce sent
933
+	 * @param  string $nonce_ref The nonce reference string (name0)
934
+	 * @return void
935
+	 * @throws EE_Error
936
+	 */
937
+	protected function _verify_nonce($nonce, $nonce_ref)
938
+	{
939
+		// verify nonce against expected value
940
+		if (! wp_verify_nonce($nonce, $nonce_ref)) {
941
+			// these are not the droids you are looking for !!!
942
+			$msg = sprintf(
943
+				esc_html__('%sNonce Fail.%s', 'event_espresso'),
944
+				'<a href="http://www.youtube.com/watch?v=56_S0WeTkzs">',
945
+				'</a>'
946
+			);
947
+			if (WP_DEBUG) {
948
+				$msg .= "\n  " . sprintf(
949
+						esc_html__(
950
+							'In order to dynamically generate nonces for your actions, use the %s::add_query_args_and_nonce() method. May the Nonce be with you!',
951
+							'event_espresso'
952
+						),
953
+						__CLASS__
954
+					);
955
+			}
956
+			if (! defined('DOING_AJAX')) {
957
+				wp_die($msg);
958
+			} else {
959
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
960
+				$this->_return_json();
961
+			}
962
+		}
963
+	}
964
+
965
+
966
+
967
+	/**
968
+	 * _route_admin_request()
969
+	 * Meat and potatoes of the class.  Basically, this dude checks out what's being requested and sees if theres are
970
+	 * some doodads to work the magic and handle the flingjangy. Translation:  Checks if the requested action is listed
971
+	 * in the page routes and then will try to load the corresponding method.
972
+	 *
973
+	 * @return void
974
+	 * @throws EE_Error
975
+	 * @throws InvalidArgumentException
976
+	 * @throws InvalidDataTypeException
977
+	 * @throws InvalidInterfaceException
978
+	 * @throws ReflectionException
979
+	 */
980
+	protected function _route_admin_request()
981
+	{
982
+		if (! $this->_is_UI_request) {
983
+			$this->_verify_routes();
984
+		}
985
+		$nonce_check = isset($this->_route_config['require_nonce'])
986
+			? $this->_route_config['require_nonce']
987
+			: true;
988
+		if ($this->_req_action !== 'default' && $nonce_check) {
989
+			// set nonce from post data
990
+			$nonce = isset($this->_req_data[$this->_req_nonce])
991
+				? sanitize_text_field($this->_req_data[$this->_req_nonce])
992
+				: '';
993
+			$this->_verify_nonce($nonce, $this->_req_nonce);
994
+		}
995
+		//set the nav_tabs array but ONLY if this is  UI_request
996
+		if ($this->_is_UI_request) {
997
+			$this->_set_nav_tabs();
998
+		}
999
+		// grab callback function
1000
+		$func = is_array($this->_route) ? $this->_route['func'] : $this->_route;
1001
+		// check if callback has args
1002
+		$args      = is_array($this->_route) && isset($this->_route['args']) ? $this->_route['args'] : array();
1003
+		$error_msg = '';
1004
+		// action right before calling route
1005
+		// (hook is something like 'AHEE__Registrations_Admin_Page__route_admin_request')
1006
+		if (! did_action('AHEE__EE_Admin_Page__route_admin_request')) {
1007
+			do_action('AHEE__EE_Admin_Page__route_admin_request', $this->_current_view, $this);
1008
+		}
1009
+		// right before calling the route, let's remove _wp_http_referer from the
1010
+		// $_SERVER[REQUEST_URI] global (its now in _req_data for route processing).
1011
+		$_SERVER['REQUEST_URI'] = remove_query_arg(
1012
+				'_wp_http_referer',
1013
+				wp_unslash($_SERVER['REQUEST_URI'])
1014
+		);
1015
+		if (! empty($func)) {
1016
+			if (is_array($func)) {
1017
+				list($class, $method) = $func;
1018
+			} elseif (strpos($func, '::') !== false) {
1019
+				list($class, $method) = explode('::', $func);
1020
+			} else {
1021
+				$class  = $this;
1022
+				$method = $func;
1023
+			}
1024
+			if (! (is_object($class) && $class === $this)) {
1025
+				// send along this admin page object for access by addons.
1026
+				$args['admin_page_object'] = $this;
1027
+			}
1028
+			if (
1029
+				//is it a method on a class that doesn't work?
1030
+				(
1031
+					(
1032
+						method_exists($class, $method)
1033
+						&& call_user_func_array(array($class, $method), $args) === false
1034
+					)
1035
+					&& (
1036
+						//is it a standalone function that doesn't work?
1037
+						function_exists($method)
1038
+						&& call_user_func_array(
1039
+							$func,
1040
+							array_merge(array('admin_page_object' => $this), $args)
1041
+						   ) === false
1042
+					)
1043
+				)
1044
+				|| (
1045
+					//is it neither a class method NOR a standalone function?
1046
+					! method_exists($class, $method)
1047
+					&& ! function_exists($method)
1048
+				)
1049
+			) {
1050
+				// user error msg
1051
+				$error_msg = esc_html__(
1052
+					'An error occurred. The  requested page route could not be found.',
1053
+					'event_espresso'
1054
+				);
1055
+				// developer error msg
1056
+				$error_msg .= '||';
1057
+				$error_msg .= sprintf(
1058
+					esc_html__(
1059
+						'Page route "%s" could not be called. Check that the spelling for method names and actions in the "_page_routes" array are all correct.',
1060
+						'event_espresso'
1061
+					),
1062
+					$method
1063
+				);
1064
+			}
1065
+			if (! empty($error_msg)) {
1066
+				throw new EE_Error($error_msg);
1067
+			}
1068
+		}
1069
+		// if we've routed and this route has a no headers route AND a sent_headers_route,
1070
+		// then we need to reset the routing properties to the new route.
1071
+		//now if UI request is FALSE and noheader is true AND we have a headers_sent_route in the route array then let's set UI_request to true because the no header route has a second func after headers have been sent.
1072
+		if ($this->_is_UI_request === false
1073
+			&& is_array($this->_route)
1074
+			&& ! empty($this->_route['headers_sent_route'])
1075
+		) {
1076
+			$this->_reset_routing_properties($this->_route['headers_sent_route']);
1077
+		}
1078
+	}
1079
+
1080
+
1081
+
1082
+	/**
1083
+	 * This method just allows the resetting of page properties in the case where a no headers
1084
+	 * route redirects to a headers route in its route config.
1085
+	 *
1086
+	 * @since   4.3.0
1087
+	 * @param  string $new_route New (non header) route to redirect to.
1088
+	 * @return   void
1089
+	 * @throws ReflectionException
1090
+	 * @throws InvalidArgumentException
1091
+	 * @throws InvalidInterfaceException
1092
+	 * @throws InvalidDataTypeException
1093
+	 * @throws EE_Error
1094
+	 */
1095
+	protected function _reset_routing_properties($new_route)
1096
+	{
1097
+		$this->_is_UI_request = true;
1098
+		//now we set the current route to whatever the headers_sent_route is set at
1099
+		$this->_req_data['action'] = $new_route;
1100
+		//rerun page setup
1101
+		$this->_page_setup();
1102
+	}
1103
+
1104
+
1105
+
1106
+	/**
1107
+	 * _add_query_arg
1108
+	 * adds nonce to array of arguments then calls WP add_query_arg function
1109
+	 *(internally just uses EEH_URL's function with the same name)
1110
+	 *
1111
+	 * @param array  $args
1112
+	 * @param string $url
1113
+	 * @param bool   $sticky                  if true, then the existing Request params will be appended to the
1114
+	 *                                        generated url in an associative array indexed by the key 'wp_referer';
1115
+	 *                                        Example usage: If the current page is:
1116
+	 *                                        http://mydomain.com/wp-admin/admin.php?page=espresso_registrations
1117
+	 *                                        &action=default&event_id=20&month_range=March%202015
1118
+	 *                                        &_wpnonce=5467821
1119
+	 *                                        and you call:
1120
+	 *                                        EE_Admin_Page::add_query_args_and_nonce(
1121
+	 *                                        array(
1122
+	 *                                        'action' => 'resend_something',
1123
+	 *                                        'page=>espresso_registrations'
1124
+	 *                                        ),
1125
+	 *                                        $some_url,
1126
+	 *                                        true
1127
+	 *                                        );
1128
+	 *                                        It will produce a url in this structure:
1129
+	 *                                        http://{$some_url}/?page=espresso_registrations&action=resend_something
1130
+	 *                                        &wp_referer[action]=default&wp_referer[event_id]=20&wpreferer[
1131
+	 *                                        month_range]=March%202015
1132
+	 * @param   bool $exclude_nonce           If true, the the nonce will be excluded from the generated nonce.
1133
+	 * @return string
1134
+	 */
1135
+	public static function add_query_args_and_nonce(
1136
+		$args = array(),
1137
+		$url = false,
1138
+		$sticky = false,
1139
+		$exclude_nonce = false
1140
+	) {
1141
+		//if there is a _wp_http_referer include the values from the request but only if sticky = true
1142
+		if ($sticky) {
1143
+			$request = $_REQUEST;
1144
+			unset($request['_wp_http_referer']);
1145
+			unset($request['wp_referer']);
1146
+			foreach ($request as $key => $value) {
1147
+				//do not add nonces
1148
+				if (strpos($key, 'nonce') !== false) {
1149
+					continue;
1150
+				}
1151
+				$args['wp_referer[' . $key . ']'] = $value;
1152
+			}
1153
+		}
1154
+		return EEH_URL::add_query_args_and_nonce($args, $url, $exclude_nonce);
1155
+	}
1156
+
1157
+
1158
+
1159
+	/**
1160
+	 * This returns a generated link that will load the related help tab.
1161
+	 *
1162
+	 * @param  string $help_tab_id the id for the connected help tab
1163
+	 * @param  string $icon_style  (optional) include css class for the style you want to use for the help icon.
1164
+	 * @param  string $help_text   (optional) send help text you want to use for the link if default not to be used
1165
+	 * @uses EEH_Template::get_help_tab_link()
1166
+	 * @return string              generated link
1167
+	 */
1168
+	protected function _get_help_tab_link($help_tab_id, $icon_style = '', $help_text = '')
1169
+	{
1170
+		return EEH_Template::get_help_tab_link(
1171
+			$help_tab_id,
1172
+			$this->page_slug,
1173
+			$this->_req_action,
1174
+			$icon_style,
1175
+			$help_text
1176
+		);
1177
+	}
1178
+
1179
+
1180
+
1181
+	/**
1182
+	 * _add_help_tabs
1183
+	 * Note child classes define their help tabs within the page_config array.
1184
+	 *
1185
+	 * @link   http://codex.wordpress.org/Function_Reference/add_help_tab
1186
+	 * @return void
1187
+	 * @throws DomainException
1188
+	 * @throws EE_Error
1189
+	 */
1190
+	protected function _add_help_tabs()
1191
+	{
1192
+		$tour_buttons = '';
1193
+		if (isset($this->_page_config[$this->_req_action])) {
1194
+			$config = $this->_page_config[$this->_req_action];
1195
+			//is there a help tour for the current route?  if there is let's setup the tour buttons
1196
+			if (isset($this->_help_tour[$this->_req_action])) {
1197
+				$tb           = array();
1198
+				$tour_buttons = '<div class="ee-abs-container"><div class="ee-help-tour-restart-buttons">';
1199
+				foreach ($this->_help_tour['tours'] as $tour) {
1200
+					//if this is the end tour then we don't need to setup a button
1201
+					if ($tour instanceof EE_Help_Tour_final_stop || ! $tour instanceof EE_Help_Tour) {
1202
+						continue;
1203
+					}
1204
+					$tb[] = '<button id="trigger-tour-'
1205
+							. $tour->get_slug()
1206
+							. '" class="button-primary trigger-ee-help-tour">'
1207
+							. $tour->get_label()
1208
+							. '</button>';
1209
+				}
1210
+				$tour_buttons .= implode('<br />', $tb);
1211
+				$tour_buttons .= '</div></div>';
1212
+			}
1213
+			// let's see if there is a help_sidebar set for the current route and we'll set that up for usage as well.
1214
+			if (is_array($config) && isset($config['help_sidebar'])) {
1215
+				//check that the callback given is valid
1216
+				if (! method_exists($this, $config['help_sidebar'])) {
1217
+					throw new EE_Error(
1218
+						sprintf(
1219
+							esc_html__(
1220
+								'The _page_config array has a callback set for the "help_sidebar" option.  However the callback given (%s) is not a valid callback.  Doublecheck the spelling and make sure this method exists for the class %s',
1221
+								'event_espresso'
1222
+							),
1223
+							$config['help_sidebar'],
1224
+							get_class($this)
1225
+						)
1226
+					);
1227
+				}
1228
+				$content = apply_filters(
1229
+					'FHEE__' . get_class($this) . '__add_help_tabs__help_sidebar',
1230
+					$this->{$config['help_sidebar']}()
1231
+				);
1232
+				$content .= $tour_buttons; //add help tour buttons.
1233
+				//do we have any help tours setup?  Cause if we do we want to add the buttons
1234
+				$this->_current_screen->set_help_sidebar($content);
1235
+			}
1236
+			//if we DON'T have config help sidebar and there ARE tour buttons then we'll just add the tour buttons to the sidebar.
1237
+			if (! isset($config['help_sidebar']) && ! empty($tour_buttons)) {
1238
+				$this->_current_screen->set_help_sidebar($tour_buttons);
1239
+			}
1240
+			//handle if no help_tabs are set so the sidebar will still show for the help tour buttons
1241
+			if (! isset($config['help_tabs']) && ! empty($tour_buttons)) {
1242
+				$_ht['id']      = $this->page_slug;
1243
+				$_ht['title']   = esc_html__('Help Tours', 'event_espresso');
1244
+				$_ht['content'] = '<p>' . esc_html__(
1245
+						'The buttons to the right allow you to start/restart any help tours available for this page',
1246
+						'event_espresso'
1247
+					) . '</p>';
1248
+				$this->_current_screen->add_help_tab($_ht);
1249
+			}
1250
+			if (! isset($config['help_tabs'])) {
1251
+				return;
1252
+			} //no help tabs for this route
1253
+			foreach ((array)$config['help_tabs'] as $tab_id => $cfg) {
1254
+				//we're here so there ARE help tabs!
1255
+				//make sure we've got what we need
1256
+				if (! isset($cfg['title'])) {
1257
+					throw new EE_Error(
1258
+						esc_html__(
1259
+							'The _page_config array is not set up properly for help tabs.  It is missing a title',
1260
+							'event_espresso'
1261
+						)
1262
+					);
1263
+				}
1264
+				if (! isset($cfg['filename']) && ! isset($cfg['callback']) && ! isset($cfg['content'])) {
1265
+					throw new EE_Error(
1266
+						esc_html__(
1267
+							'The _page_config array is not setup properly for help tabs. It is missing a either a filename reference, or a callback reference or a content reference so there is no way to know the content for the help tab',
1268
+							'event_espresso'
1269
+						)
1270
+					);
1271
+				}
1272
+				//first priority goes to content.
1273
+				if (! empty($cfg['content'])) {
1274
+					$content = ! empty($cfg['content']) ? $cfg['content'] : null;
1275
+					//second priority goes to filename
1276
+				} elseif (! empty($cfg['filename'])) {
1277
+					$file_path = $this->_get_dir() . '/help_tabs/' . $cfg['filename'] . '.help_tab.php';
1278
+					//it's possible that the file is located on decaf route (and above sets up for caf route, if this is the case then lets check decaf route too)
1279
+					$file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES
1280
+															 . basename($this->_get_dir())
1281
+															 . '/help_tabs/'
1282
+															 . $cfg['filename']
1283
+															 . '.help_tab.php' : $file_path;
1284
+					//if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1285
+					if (! isset($cfg['callback']) && ! is_readable($file_path)) {
1286
+						EE_Error::add_error(
1287
+							sprintf(
1288
+								esc_html__(
1289
+									'The filename given for the help tab %s is not a valid file and there is no other configuration for the tab content.  Please check that the string you set for the help tab on this route (%s) is the correct spelling.  The file should be in %s',
1290
+									'event_espresso'
1291
+								),
1292
+								$tab_id,
1293
+								key($config),
1294
+								$file_path
1295
+							),
1296
+							__FILE__,
1297
+							__FUNCTION__,
1298
+							__LINE__
1299
+						);
1300
+						return;
1301
+					}
1302
+					$template_args['admin_page_obj'] = $this;
1303
+					$content = EEH_Template::display_template(
1304
+						$file_path,
1305
+						$template_args,
1306
+						true
1307
+					);
1308
+				} else {
1309
+					$content = '';
1310
+				}
1311
+				//check if callback is valid
1312
+				if (
1313
+					empty($content) && (
1314
+						! isset($cfg['callback']) || ! method_exists($this, $cfg['callback'])
1315
+					)
1316
+				) {
1317
+					EE_Error::add_error(
1318
+						sprintf(
1319
+							esc_html__(
1320
+								'The callback given for a %s help tab on this page does not content OR a corresponding method for generating the content.  Check the spelling or make sure the method is present.',
1321
+								'event_espresso'
1322
+							),
1323
+							$cfg['title']
1324
+						),
1325
+						__FILE__,
1326
+						__FUNCTION__,
1327
+						__LINE__
1328
+					);
1329
+					return;
1330
+				}
1331
+				//setup config array for help tab method
1332
+				$id  = $this->page_slug . '-' . $this->_req_action . '-' . $tab_id;
1333
+				$_ht = array(
1334
+					'id'       => $id,
1335
+					'title'    => $cfg['title'],
1336
+					'callback' => isset($cfg['callback']) && empty($content) ? array($this, $cfg['callback']) : null,
1337
+					'content'  => $content,
1338
+				);
1339
+				$this->_current_screen->add_help_tab($_ht);
1340
+			}
1341
+		}
1342
+	}
1343
+
1344
+
1345
+
1346
+	/**
1347
+	 * This basically checks loaded $_page_config property to see if there are any help_tours defined.  "help_tours" is
1348
+	 * an array with properties for setting up usage of the joyride plugin
1349
+	 *
1350
+	 * @link   http://zurb.com/playground/jquery-joyride-feature-tour-plugin
1351
+	 * @see    instructions regarding the format and construction of the "help_tour" array element is found in the
1352
+	 *         _set_page_config() comments
1353
+	 * @return void
1354
+	 * @throws EE_Error
1355
+	 * @throws InvalidArgumentException
1356
+	 * @throws InvalidDataTypeException
1357
+	 * @throws InvalidInterfaceException
1358
+	 */
1359
+	protected function _add_help_tour()
1360
+	{
1361
+		$tours            = array();
1362
+		$this->_help_tour = array();
1363
+		//exit early if help tours are turned off globally
1364
+		if ((defined('EE_DISABLE_HELP_TOURS') && EE_DISABLE_HELP_TOURS)
1365
+			|| ! EE_Registry::instance()->CFG->admin->help_tour_activation
1366
+		) {
1367
+			return;
1368
+		}
1369
+		//loop through _page_config to find any help_tour defined
1370
+		foreach ($this->_page_config as $route => $config) {
1371
+			//we're only going to set things up for this route
1372
+			if ($route !== $this->_req_action) {
1373
+				continue;
1374
+			}
1375
+			if (isset($config['help_tour'])) {
1376
+				foreach ($config['help_tour'] as $tour) {
1377
+					$file_path = $this->_get_dir() . '/help_tours/' . $tour . '.class.php';
1378
+					// let's see if we can get that file...
1379
+					// if not its possible this is a decaf route not set in caffeinated
1380
+					// so lets try and get the caffeinated equivalent
1381
+					$file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES
1382
+															 . basename($this->_get_dir())
1383
+															 . '/help_tours/'
1384
+															 . $tour
1385
+															 . '.class.php' : $file_path;
1386
+					//if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1387
+					if (! is_readable($file_path)) {
1388
+						EE_Error::add_error(
1389
+							sprintf(
1390
+								esc_html__(
1391
+									'The file path given for the help tour (%s) is not a valid path.  Please check that the string you set for the help tour on this route (%s) is the correct spelling',
1392
+									'event_espresso'
1393
+								),
1394
+								$file_path,
1395
+								$tour
1396
+							),
1397
+							__FILE__,
1398
+							__FUNCTION__,
1399
+							__LINE__
1400
+						);
1401
+						return;
1402
+					}
1403
+					require_once $file_path;
1404
+					if (! class_exists($tour)) {
1405
+						$error_msg[] = sprintf(
1406
+							esc_html__('Something went wrong with loading the %s Help Tour Class.', 'event_espresso'),
1407
+							$tour
1408
+						);
1409
+						$error_msg[] = $error_msg[0] . "\r\n" . sprintf(
1410
+								esc_html__(
1411
+									'There is no class in place for the %s help tour.%s Make sure you have <strong>%s</strong> defined in the "help_tour" array for the %s route of the % admin page.',
1412
+									'event_espresso'
1413
+								),
1414
+								$tour,
1415
+								'<br />',
1416
+								$tour,
1417
+								$this->_req_action,
1418
+								get_class($this)
1419
+							);
1420
+						throw new EE_Error(implode('||', $error_msg));
1421
+					}
1422
+					$tour_obj                   = new $tour($this->_is_caf);
1423
+					$tours[]                    = $tour_obj;
1424
+					$this->_help_tour[$route][] = EEH_Template::help_tour_stops_generator($tour_obj);
1425
+				}
1426
+				//let's inject the end tour stop element common to all pages... this will only get seen once per machine.
1427
+				$end_stop_tour              = new EE_Help_Tour_final_stop($this->_is_caf);
1428
+				$tours[]                    = $end_stop_tour;
1429
+				$this->_help_tour[$route][] = EEH_Template::help_tour_stops_generator($end_stop_tour);
1430
+			}
1431
+		}
1432
+		if (! empty($tours)) {
1433
+			$this->_help_tour['tours'] = $tours;
1434
+		}
1435
+		// that's it!  Now that the $_help_tours property is set (or not)
1436
+		// the scripts and html should be taken care of automatically.
1437
+	}
1438
+
1439
+
1440
+
1441
+	/**
1442
+	 * This simply sets up any qtips that have been defined in the page config
1443
+	 *
1444
+	 * @return void
1445
+	 */
1446
+	protected function _add_qtips()
1447
+	{
1448
+		if (isset($this->_route_config['qtips'])) {
1449
+			$qtips = (array)$this->_route_config['qtips'];
1450
+			//load qtip loader
1451
+			$path = array(
1452
+				$this->_get_dir() . '/qtips/',
1453
+				EE_ADMIN_PAGES . basename($this->_get_dir()) . '/qtips/',
1454
+			);
1455
+			EEH_Qtip_Loader::instance()->register($qtips, $path);
1456
+		}
1457
+	}
1458
+
1459
+
1460
+
1461
+	/**
1462
+	 * _set_nav_tabs
1463
+	 * This sets up the nav tabs from the page_routes array.  This method can be overwritten by child classes if you
1464
+	 * wish to add additional tabs or modify accordingly.
1465
+	 *
1466
+	 * @return void
1467
+	 * @throws InvalidArgumentException
1468
+	 * @throws InvalidInterfaceException
1469
+	 * @throws InvalidDataTypeException
1470
+	 */
1471
+	protected function _set_nav_tabs()
1472
+	{
1473
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1474
+		$i = 0;
1475
+		foreach ($this->_page_config as $slug => $config) {
1476
+			if (
1477
+				! is_array($config)
1478
+				|| (
1479
+					is_array($config)
1480
+					&& (
1481
+						(isset($config['nav']) && ! $config['nav'])
1482
+						|| ! isset($config['nav'])
1483
+					)
1484
+				)
1485
+			) {
1486
+				continue;
1487
+			}
1488
+			//no nav tab for this config
1489
+			//check for persistent flag
1490
+			if ($slug !== $this->_req_action && isset($config['nav']['persistent']) && ! $config['nav']['persistent']) {
1491
+				// nav tab is only to appear when route requested.
1492
+				continue;
1493
+			}
1494
+			if (! $this->check_user_access($slug, true)) {
1495
+				// no nav tab because current user does not have access.
1496
+				continue;
1497
+			}
1498
+			$css_class              = isset($config['css_class']) ? $config['css_class'] . ' ' : '';
1499
+			$this->_nav_tabs[$slug] = array(
1500
+				'url'       => isset($config['nav']['url'])
1501
+					? $config['nav']['url']
1502
+					: self::add_query_args_and_nonce(
1503
+						array('action' => $slug),
1504
+						$this->_admin_base_url
1505
+					),
1506
+				'link_text' => isset($config['nav']['label'])
1507
+					? $config['nav']['label']
1508
+					: ucwords(
1509
+						str_replace('_', ' ', $slug)
1510
+					),
1511
+				'css_class' => $this->_req_action === $slug ? $css_class . 'nav-tab-active' : $css_class,
1512
+				'order'     => isset($config['nav']['order']) ? $config['nav']['order'] : $i,
1513
+			);
1514
+			$i++;
1515
+		}
1516
+		//if $this->_nav_tabs is empty then lets set the default
1517
+		if (empty($this->_nav_tabs)) {
1518
+			$this->_nav_tabs[$this->_default_nav_tab_name] = array(
1519
+				'url'       => $this->_admin_base_url,
1520
+				'link_text' => ucwords(str_replace('_', ' ', $this->_default_nav_tab_name)),
1521
+				'css_class' => 'nav-tab-active',
1522
+				'order'     => 10,
1523
+			);
1524
+		}
1525
+		//now let's sort the tabs according to order
1526
+		usort($this->_nav_tabs, array($this, '_sort_nav_tabs'));
1527
+	}
1528
+
1529
+
1530
+
1531
+	/**
1532
+	 * _set_current_labels
1533
+	 * This method modifies the _labels property with any optional specific labels indicated in the _page_routes
1534
+	 * property array
1535
+	 *
1536
+	 * @return void
1537
+	 */
1538
+	private function _set_current_labels()
1539
+	{
1540
+		if (is_array($this->_route_config) && isset($this->_route_config['labels'])) {
1541
+			foreach ($this->_route_config['labels'] as $label => $text) {
1542
+				if (is_array($text)) {
1543
+					foreach ($text as $sublabel => $subtext) {
1544
+						$this->_labels[$label][$sublabel] = $subtext;
1545
+					}
1546
+				} else {
1547
+					$this->_labels[$label] = $text;
1548
+				}
1549
+			}
1550
+		}
1551
+	}
1552
+
1553
+
1554
+
1555
+	/**
1556
+	 *        verifies user access for this admin page
1557
+	 *
1558
+	 * @param string $route_to_check if present then the capability for the route matching this string is checked.
1559
+	 * @param bool   $verify_only    Default is FALSE which means if user check fails then wp_die().  Otherwise just
1560
+	 *                               return false if verify fail.
1561
+	 * @return bool
1562
+	 * @throws InvalidArgumentException
1563
+	 * @throws InvalidDataTypeException
1564
+	 * @throws InvalidInterfaceException
1565
+	 */
1566
+	public function check_user_access($route_to_check = '', $verify_only = false)
1567
+	{
1568
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1569
+		$route_to_check = empty($route_to_check) ? $this->_req_action : $route_to_check;
1570
+		$capability     = ! empty($route_to_check) && isset($this->_page_routes[$route_to_check])
1571
+						  && is_array(
1572
+							  $this->_page_routes[$route_to_check]
1573
+						  )
1574
+						  && ! empty($this->_page_routes[$route_to_check]['capability'])
1575
+			? $this->_page_routes[$route_to_check]['capability'] : null;
1576
+		if (empty($capability) && empty($route_to_check)) {
1577
+			$capability = is_array($this->_route) && empty($this->_route['capability']) ? 'manage_options'
1578
+				: $this->_route['capability'];
1579
+		} else {
1580
+			$capability = empty($capability) ? 'manage_options' : $capability;
1581
+		}
1582
+		$id = is_array($this->_route) && ! empty($this->_route['obj_id']) ? $this->_route['obj_id'] : 0;
1583
+		if (
1584
+			! defined('DOING_AJAX')
1585
+			&& (
1586
+				! function_exists('is_admin')
1587
+				|| ! EE_Registry::instance()->CAP->current_user_can(
1588
+					$capability,
1589
+					$this->page_slug
1590
+					. '_'
1591
+					. $route_to_check,
1592
+					$id
1593
+				)
1594
+			)
1595
+		) {
1596
+			if ($verify_only) {
1597
+				return false;
1598
+			}
1599
+			if (is_user_logged_in()) {
1600
+				wp_die(__('You do not have access to this route.', 'event_espresso'));
1601
+			} else {
1602
+				return false;
1603
+			}
1604
+		}
1605
+		return true;
1606
+	}
1607
+
1608
+
1609
+
1610
+	/**
1611
+	 * admin_init_global
1612
+	 * This runs all the code that we want executed within the WP admin_init hook.
1613
+	 * This method executes for ALL EE Admin pages.
1614
+	 *
1615
+	 * @return void
1616
+	 */
1617
+	public function admin_init_global()
1618
+	{
1619
+	}
1620
+
1621
+
1622
+
1623
+	/**
1624
+	 * wp_loaded_global
1625
+	 * This runs all the code that we want executed within the WP wp_loaded hook.  This method is optional for an
1626
+	 * EE_Admin page and will execute on every EE Admin Page load
1627
+	 *
1628
+	 * @return void
1629
+	 */
1630
+	public function wp_loaded()
1631
+	{
1632
+	}
1633
+
1634
+
1635
+
1636
+	/**
1637
+	 * admin_notices
1638
+	 * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply on
1639
+	 * ALL EE_Admin pages.
1640
+	 *
1641
+	 * @return void
1642
+	 */
1643
+	public function admin_notices_global()
1644
+	{
1645
+		$this->_display_no_javascript_warning();
1646
+		$this->_display_espresso_notices();
1647
+	}
1648
+
1649
+
1650
+
1651
+	public function network_admin_notices_global()
1652
+	{
1653
+		$this->_display_no_javascript_warning();
1654
+		$this->_display_espresso_notices();
1655
+	}
1656
+
1657
+
1658
+
1659
+	/**
1660
+	 * admin_footer_scripts_global
1661
+	 * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
1662
+	 * will apply on ALL EE_Admin pages.
1663
+	 *
1664
+	 * @return void
1665
+	 */
1666
+	public function admin_footer_scripts_global()
1667
+	{
1668
+		$this->_add_admin_page_ajax_loading_img();
1669
+		$this->_add_admin_page_overlay();
1670
+		//if metaboxes are present we need to add the nonce field
1671
+		if (
1672
+			 isset($this->_route_config['metaboxes'])
1673
+			 || isset($this->_route_config['list_table'])
1674
+			 || (isset($this->_route_config['has_metaboxes']) && $this->_route_config['has_metaboxes'])
1675
+		) {
1676
+			wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
1677
+			wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
1678
+		}
1679
+	}
1680
+
1681
+
1682
+
1683
+	/**
1684
+	 * admin_footer_global
1685
+	 * Anything triggered by the wp 'admin_footer' wp hook should be put in here. This particular method will apply on
1686
+	 * ALL EE_Admin Pages.
1687
+	 *
1688
+	 * @return void
1689
+	 * @throws EE_Error
1690
+	 */
1691
+	public function admin_footer_global()
1692
+	{
1693
+		//dialog container for dialog helper
1694
+		$d_cont = '<div class="ee-admin-dialog-container auto-hide hidden">' . "\n";
1695
+		$d_cont .= '<div class="ee-notices"></div>';
1696
+		$d_cont .= '<div class="ee-admin-dialog-container-inner-content"></div>';
1697
+		$d_cont .= '</div>';
1698
+		echo $d_cont;
1699
+		//help tour stuff?
1700
+		if (isset($this->_help_tour[$this->_req_action])) {
1701
+			echo implode('<br />', $this->_help_tour[$this->_req_action]);
1702
+		}
1703
+		//current set timezone for timezone js
1704
+		echo '<span id="current_timezone" class="hidden">' . EEH_DTT_Helper::get_timezone() . '</span>';
1705
+	}
1706
+
1707
+
1708
+
1709
+	/**
1710
+	 * This function sees if there is a method for help popup content existing for the given route.  If there is then
1711
+	 * we'll use the retrieved array to output the content using the template. For child classes: If you want to have
1712
+	 * help popups then in your templates or your content you set "triggers" for the content using the
1713
+	 * "_set_help_trigger('help_trigger_id')" where "help_trigger_id" is what you will use later in your custom method
1714
+	 * for the help popup content on that page. Then in your Child_Admin_Page class you need to define a help popup
1715
+	 * method for the content in the format "_help_popup_content_{route_name}()"  So if you are setting help content
1716
+	 * for the
1717
+	 * 'edit_event' route you should have a method named "_help_popup_content_edit_route". In your defined
1718
+	 * "help_popup_content_..." method.  You must prepare and return an array in the following format array(
1719
+	 *    'help_trigger_id' => array(
1720
+	 *        'title' => esc_html__('localized title for popup', 'event_espresso'),
1721
+	 *        'content' => esc_html__('localized content for popup', 'event_espresso')
1722
+	 *    )
1723
+	 * );
1724
+	 * Then the EE_Admin_Parent will take care of making sure that is setup properly on the correct route.
1725
+	 *
1726
+	 * @param array $help_array
1727
+	 * @param bool  $display
1728
+	 * @return string content
1729
+	 * @throws DomainException
1730
+	 * @throws EE_Error
1731
+	 */
1732
+	protected function _set_help_popup_content($help_array = array(), $display = false)
1733
+	{
1734
+		$content       = '';
1735
+		$help_array    = empty($help_array) ? $this->_get_help_content() : $help_array;
1736
+		//loop through the array and setup content
1737
+		foreach ($help_array as $trigger => $help) {
1738
+			//make sure the array is setup properly
1739
+			if (! isset($help['title']) || ! isset($help['content'])) {
1740
+				throw new EE_Error(
1741
+					esc_html__(
1742
+						'Does not look like the popup content array has been setup correctly.  Might want to double check that.  Read the comments for the _get_help_popup_content method found in "EE_Admin_Page" class',
1743
+						'event_espresso'
1744
+					)
1745
+				);
1746
+			}
1747
+			//we're good so let'd setup the template vars and then assign parsed template content to our content.
1748
+			$template_args = array(
1749
+				'help_popup_id'      => $trigger,
1750
+				'help_popup_title'   => $help['title'],
1751
+				'help_popup_content' => $help['content'],
1752
+			);
1753
+			$content       .= EEH_Template::display_template(
1754
+				EE_ADMIN_TEMPLATE . 'admin_help_popup.template.php',
1755
+				$template_args,
1756
+				true
1757
+			);
1758
+		}
1759
+		if ($display) {
1760
+			echo $content;
1761
+			return '';
1762
+		}
1763
+		return $content;
1764
+	}
1765
+
1766
+
1767
+
1768
+	/**
1769
+	 * All this does is retrieve the help content array if set by the EE_Admin_Page child
1770
+	 *
1771
+	 * @return array properly formatted array for help popup content
1772
+	 * @throws EE_Error
1773
+	 */
1774
+	private function _get_help_content()
1775
+	{
1776
+		//what is the method we're looking for?
1777
+		$method_name = '_help_popup_content_' . $this->_req_action;
1778
+		//if method doesn't exist let's get out.
1779
+		if (! method_exists($this, $method_name)) {
1780
+			return array();
1781
+		}
1782
+		//k we're good to go let's retrieve the help array
1783
+		$help_array = call_user_func(array($this, $method_name));
1784
+		//make sure we've got an array!
1785
+		if (! is_array($help_array)) {
1786
+			throw new EE_Error(
1787
+				esc_html__(
1788
+					'Something went wrong with help popup content generation. Expecting an array and well, this ain\'t no array bub.',
1789
+					'event_espresso'
1790
+				)
1791
+			);
1792
+		}
1793
+		return $help_array;
1794
+	}
1795
+
1796
+
1797
+
1798
+	/**
1799
+	 * EE Admin Pages can use this to set a properly formatted trigger for a help popup.
1800
+	 * By default the trigger html is printed.  Otherwise it can be returned if the $display flag is set "false"
1801
+	 * See comments made on the _set_help_content method for understanding other parts to the help popup tool.
1802
+	 *
1803
+	 * @param string  $trigger_id reference for retrieving the trigger content for the popup
1804
+	 * @param boolean $display    if false then we return the trigger string
1805
+	 * @param array   $dimensions an array of dimensions for the box (array(h,w))
1806
+	 * @return string
1807
+	 * @throws DomainException
1808
+	 * @throws EE_Error
1809
+	 */
1810
+	protected function _set_help_trigger($trigger_id, $display = true, $dimensions = array('400', '640'))
1811
+	{
1812
+		if (defined('DOING_AJAX')) {
1813
+			return '';
1814
+		}
1815
+		//let's check and see if there is any content set for this popup.  If there isn't then we'll include a default title and content so that developers know something needs to be corrected
1816
+		$help_array   = $this->_get_help_content();
1817
+		$help_content = '';
1818
+		if (empty($help_array) || ! isset($help_array[$trigger_id])) {
1819
+			$help_array[$trigger_id] = array(
1820
+				'title'   => esc_html__('Missing Content', 'event_espresso'),
1821
+				'content' => esc_html__(
1822
+					'A trigger has been set that doesn\'t have any corresponding content. Make sure you have set the help content. (see the "_set_help_popup_content" method in the EE_Admin_Page for instructions.)',
1823
+					'event_espresso'
1824
+				),
1825
+			);
1826
+			$help_content            = $this->_set_help_popup_content($help_array, false);
1827
+		}
1828
+		//let's setup the trigger
1829
+		$content = '<a class="ee-dialog" href="?height='
1830
+				   . $dimensions[0]
1831
+				   . '&width='
1832
+				   . $dimensions[1]
1833
+				   . '&inlineId='
1834
+				   . $trigger_id
1835
+				   . '" target="_blank"><span class="question ee-help-popup-question"></span></a>';
1836
+		$content .= $help_content;
1837
+		if ($display) {
1838
+			echo $content;
1839
+			return  '';
1840
+		}
1841
+		return $content;
1842
+	}
1843
+
1844
+
1845
+
1846
+	/**
1847
+	 * _add_global_screen_options
1848
+	 * Add any extra wp_screen_options within this method using built-in WP functions/methods for doing so.
1849
+	 * This particular method will add_screen_options on ALL EE_Admin Pages
1850
+	 *
1851
+	 * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
1852
+	 *         see also WP_Screen object documents...
1853
+	 * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
1854
+	 * @abstract
1855
+	 * @return void
1856
+	 */
1857
+	private function _add_global_screen_options()
1858
+	{
1859
+	}
1860
+
1861
+
1862
+
1863
+	/**
1864
+	 * _add_global_feature_pointers
1865
+	 * This method is used for implementing any "feature pointers" (using built-in WP styling js).
1866
+	 * This particular method will implement feature pointers for ALL EE_Admin pages.
1867
+	 * Note: this is just a placeholder for now.  Implementation will come down the road
1868
+	 *
1869
+	 * @see    WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be
1870
+	 *         extended) also see:
1871
+	 * @link   http://eamann.com/tech/wordpress-portland/
1872
+	 * @abstract
1873
+	 * @return void
1874
+	 */
1875
+	private function _add_global_feature_pointers()
1876
+	{
1877
+	}
1878
+
1879
+
1880
+
1881
+	/**
1882
+	 * load_global_scripts_styles
1883
+	 * The scripts and styles enqueued in here will be loaded on every EE Admin page
1884
+	 *
1885
+	 * @return void
1886
+	 * @throws EE_Error
1887
+	 */
1888
+	public function load_global_scripts_styles()
1889
+	{
1890
+		/** STYLES **/
1891
+		// add debugging styles
1892
+		if (WP_DEBUG) {
1893
+			add_action('admin_head', array($this, 'add_xdebug_style'));
1894
+		}
1895
+		// register all styles
1896
+		wp_register_style(
1897
+			'espresso-ui-theme',
1898
+			EE_GLOBAL_ASSETS_URL . 'css/espresso-ui-theme/jquery-ui-1.10.3.custom.min.css',
1899
+			array(),
1900
+			EVENT_ESPRESSO_VERSION
1901
+		);
1902
+		wp_register_style('ee-admin-css', EE_ADMIN_URL . 'assets/ee-admin-page.css', array(), EVENT_ESPRESSO_VERSION);
1903
+		//helpers styles
1904
+		wp_register_style(
1905
+			'ee-text-links',
1906
+			EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.css',
1907
+			array(),
1908
+			EVENT_ESPRESSO_VERSION
1909
+		);
1910
+		/** SCRIPTS **/
1911
+		//register all scripts
1912
+		wp_register_script(
1913
+			'ee-dialog',
1914
+			EE_ADMIN_URL . 'assets/ee-dialog-helper.js',
1915
+			array('jquery', 'jquery-ui-draggable'),
1916
+			EVENT_ESPRESSO_VERSION,
1917
+			true
1918
+		);
1919
+		wp_register_script(
1920
+			'ee_admin_js',
1921
+			EE_ADMIN_URL . 'assets/ee-admin-page.js',
1922
+			array('espresso_core', 'ee-parse-uri', 'ee-dialog'),
1923
+			EVENT_ESPRESSO_VERSION,
1924
+			true
1925
+		);
1926
+		wp_register_script(
1927
+			'jquery-ui-timepicker-addon',
1928
+			EE_GLOBAL_ASSETS_URL . 'scripts/jquery-ui-timepicker-addon.js',
1929
+			array('jquery-ui-datepicker', 'jquery-ui-slider'),
1930
+			EVENT_ESPRESSO_VERSION,
1931
+			true
1932
+		);
1933
+		add_filter('FHEE_load_joyride', '__return_true');
1934
+		//script for sorting tables
1935
+		wp_register_script(
1936
+			'espresso_ajax_table_sorting',
1937
+			EE_ADMIN_URL . 'assets/espresso_ajax_table_sorting.js',
1938
+			array('ee_admin_js', 'jquery-ui-sortable'),
1939
+			EVENT_ESPRESSO_VERSION,
1940
+			true
1941
+		);
1942
+		//script for parsing uri's
1943
+		wp_register_script(
1944
+			'ee-parse-uri',
1945
+			EE_GLOBAL_ASSETS_URL . 'scripts/parseuri.js',
1946
+			array(),
1947
+			EVENT_ESPRESSO_VERSION,
1948
+			true
1949
+		);
1950
+		//and parsing associative serialized form elements
1951
+		wp_register_script(
1952
+			'ee-serialize-full-array',
1953
+			EE_GLOBAL_ASSETS_URL . 'scripts/jquery.serializefullarray.js',
1954
+			array('jquery'),
1955
+			EVENT_ESPRESSO_VERSION,
1956
+			true
1957
+		);
1958
+		//helpers scripts
1959
+		wp_register_script(
1960
+			'ee-text-links',
1961
+			EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.js',
1962
+			array('jquery'),
1963
+			EVENT_ESPRESSO_VERSION,
1964
+			true
1965
+		);
1966
+		wp_register_script(
1967
+			'ee-moment-core',
1968
+			EE_THIRD_PARTY_URL . 'moment/moment-with-locales.min.js',
1969
+			array(),
1970
+			EVENT_ESPRESSO_VERSION,
1971
+			true
1972
+		);
1973
+		wp_register_script(
1974
+			'ee-moment',
1975
+			EE_THIRD_PARTY_URL . 'moment/moment-timezone-with-data.min.js',
1976
+			array('ee-moment-core'),
1977
+			EVENT_ESPRESSO_VERSION,
1978
+			true
1979
+		);
1980
+		wp_register_script(
1981
+			'ee-datepicker',
1982
+			EE_ADMIN_URL . 'assets/ee-datepicker.js',
1983
+			array('jquery-ui-timepicker-addon', 'ee-moment'),
1984
+			EVENT_ESPRESSO_VERSION,
1985
+			true
1986
+		);
1987
+		//google charts
1988
+		wp_register_script(
1989
+			'google-charts',
1990
+			'https://www.gstatic.com/charts/loader.js',
1991
+			array(),
1992
+			EVENT_ESPRESSO_VERSION,
1993
+			false
1994
+		);
1995
+		// ENQUEUE ALL BASICS BY DEFAULT
1996
+		wp_enqueue_style('ee-admin-css');
1997
+		wp_enqueue_script('ee_admin_js');
1998
+		wp_enqueue_script('ee-accounting');
1999
+		wp_enqueue_script('jquery-validate');
2000
+		//taking care of metaboxes
2001
+		if (
2002
+			empty($this->_cpt_route)
2003
+			&& (isset($this->_route_config['metaboxes']) || isset($this->_route_config['has_metaboxes']))
2004
+		) {
2005
+			wp_enqueue_script('dashboard');
2006
+		}
2007
+		// LOCALIZED DATA
2008
+		//localize script for ajax lazy loading
2009
+		$lazy_loader_container_ids = apply_filters(
2010
+			'FHEE__EE_Admin_Page_Core__load_global_scripts_styles__loader_containers',
2011
+			array('espresso_news_post_box_content')
2012
+		);
2013
+		wp_localize_script('ee_admin_js', 'eeLazyLoadingContainers', $lazy_loader_container_ids);
2014
+		/**
2015
+		 * help tour stuff
2016
+		 */
2017
+		if (! empty($this->_help_tour)) {
2018
+			//register the js for kicking things off
2019
+			wp_enqueue_script(
2020
+				'ee-help-tour',
2021
+				EE_ADMIN_URL . 'assets/ee-help-tour.js',
2022
+				array('jquery-joyride'),
2023
+				EVENT_ESPRESSO_VERSION,
2024
+				true
2025
+			);
2026
+			$tours = array();
2027
+			//setup tours for the js tour object
2028
+			foreach ($this->_help_tour['tours'] as $tour) {
2029
+				if ($tour instanceof EE_Help_Tour) {
2030
+					$tours[] = array(
2031
+						'id'      => $tour->get_slug(),
2032
+						'options' => $tour->get_options(),
2033
+					);
2034
+				}
2035
+			}
2036
+			wp_localize_script('ee-help-tour', 'EE_HELP_TOUR', array('tours' => $tours));
2037
+			//admin_footer_global will take care of making sure our help_tour skeleton gets printed via the info stored in $this->_help_tour
2038
+		}
2039
+	}
2040
+
2041
+
2042
+
2043
+	/**
2044
+	 *        admin_footer_scripts_eei18n_js_strings
2045
+	 *
2046
+	 * @return        void
2047
+	 */
2048
+	public function admin_footer_scripts_eei18n_js_strings()
2049
+	{
2050
+		EE_Registry::$i18n_js_strings['ajax_url']       = WP_AJAX_URL;
2051
+		EE_Registry::$i18n_js_strings['confirm_delete'] = esc_html__(
2052
+			'Are you absolutely sure you want to delete this item?\nThis action will delete ALL DATA associated with this item!!!\nThis can NOT be undone!!!',
2053
+			'event_espresso'
2054
+		);
2055
+		EE_Registry::$i18n_js_strings['January']        = esc_html__('January', 'event_espresso');
2056
+		EE_Registry::$i18n_js_strings['February']       = esc_html__('February', 'event_espresso');
2057
+		EE_Registry::$i18n_js_strings['March']          = esc_html__('March', 'event_espresso');
2058
+		EE_Registry::$i18n_js_strings['April']          = esc_html__('April', 'event_espresso');
2059
+		EE_Registry::$i18n_js_strings['May']            = esc_html__('May', 'event_espresso');
2060
+		EE_Registry::$i18n_js_strings['June']           = esc_html__('June', 'event_espresso');
2061
+		EE_Registry::$i18n_js_strings['July']           = esc_html__('July', 'event_espresso');
2062
+		EE_Registry::$i18n_js_strings['August']         = esc_html__('August', 'event_espresso');
2063
+		EE_Registry::$i18n_js_strings['September']      = esc_html__('September', 'event_espresso');
2064
+		EE_Registry::$i18n_js_strings['October']        = esc_html__('October', 'event_espresso');
2065
+		EE_Registry::$i18n_js_strings['November']       = esc_html__('November', 'event_espresso');
2066
+		EE_Registry::$i18n_js_strings['December']       = esc_html__('December', 'event_espresso');
2067
+		EE_Registry::$i18n_js_strings['Jan']            = esc_html__('Jan', 'event_espresso');
2068
+		EE_Registry::$i18n_js_strings['Feb']            = esc_html__('Feb', 'event_espresso');
2069
+		EE_Registry::$i18n_js_strings['Mar']            = esc_html__('Mar', 'event_espresso');
2070
+		EE_Registry::$i18n_js_strings['Apr']            = esc_html__('Apr', 'event_espresso');
2071
+		EE_Registry::$i18n_js_strings['May']            = esc_html__('May', 'event_espresso');
2072
+		EE_Registry::$i18n_js_strings['Jun']            = esc_html__('Jun', 'event_espresso');
2073
+		EE_Registry::$i18n_js_strings['Jul']            = esc_html__('Jul', 'event_espresso');
2074
+		EE_Registry::$i18n_js_strings['Aug']            = esc_html__('Aug', 'event_espresso');
2075
+		EE_Registry::$i18n_js_strings['Sep']            = esc_html__('Sep', 'event_espresso');
2076
+		EE_Registry::$i18n_js_strings['Oct']            = esc_html__('Oct', 'event_espresso');
2077
+		EE_Registry::$i18n_js_strings['Nov']            = esc_html__('Nov', 'event_espresso');
2078
+		EE_Registry::$i18n_js_strings['Dec']            = esc_html__('Dec', 'event_espresso');
2079
+		EE_Registry::$i18n_js_strings['Sunday']         = esc_html__('Sunday', 'event_espresso');
2080
+		EE_Registry::$i18n_js_strings['Monday']         = esc_html__('Monday', 'event_espresso');
2081
+		EE_Registry::$i18n_js_strings['Tuesday']        = esc_html__('Tuesday', 'event_espresso');
2082
+		EE_Registry::$i18n_js_strings['Wednesday']      = esc_html__('Wednesday', 'event_espresso');
2083
+		EE_Registry::$i18n_js_strings['Thursday']       = esc_html__('Thursday', 'event_espresso');
2084
+		EE_Registry::$i18n_js_strings['Friday']         = esc_html__('Friday', 'event_espresso');
2085
+		EE_Registry::$i18n_js_strings['Saturday']       = esc_html__('Saturday', 'event_espresso');
2086
+		EE_Registry::$i18n_js_strings['Sun']            = esc_html__('Sun', 'event_espresso');
2087
+		EE_Registry::$i18n_js_strings['Mon']            = esc_html__('Mon', 'event_espresso');
2088
+		EE_Registry::$i18n_js_strings['Tue']            = esc_html__('Tue', 'event_espresso');
2089
+		EE_Registry::$i18n_js_strings['Wed']            = esc_html__('Wed', 'event_espresso');
2090
+		EE_Registry::$i18n_js_strings['Thu']            = esc_html__('Thu', 'event_espresso');
2091
+		EE_Registry::$i18n_js_strings['Fri']            = esc_html__('Fri', 'event_espresso');
2092
+		EE_Registry::$i18n_js_strings['Sat']            = esc_html__('Sat', 'event_espresso');
2093
+	}
2094
+
2095
+
2096
+
2097
+	/**
2098
+	 *        load enhanced xdebug styles for ppl with failing eyesight
2099
+	 *
2100
+	 * @return        void
2101
+	 */
2102
+	public function add_xdebug_style()
2103
+	{
2104
+		echo '<style>.xdebug-error { font-size:1.5em; }</style>';
2105
+	}
2106
+
2107
+
2108
+	/************************/
2109
+	/** LIST TABLE METHODS **/
2110
+	/************************/
2111
+	/**
2112
+	 * this sets up the list table if the current view requires it.
2113
+	 *
2114
+	 * @return void
2115
+	 * @throws EE_Error
2116
+	 */
2117
+	protected function _set_list_table()
2118
+	{
2119
+		//first is this a list_table view?
2120
+		if (! isset($this->_route_config['list_table'])) {
2121
+			return;
2122
+		} //not a list_table view so get out.
2123
+		// list table functions are per view specific (because some admin pages might have more than one list table!)
2124
+		$list_table_view = '_set_list_table_views_' . $this->_req_action;
2125
+		if (! method_exists($this, $list_table_view) || $this->{$list_table_view}() === false) {
2126
+			//user error msg
2127
+			$error_msg = esc_html__(
2128
+				'An error occurred. The requested list table views could not be found.',
2129
+				'event_espresso'
2130
+			);
2131
+			//developer error msg
2132
+			$error_msg .= '||' . sprintf(
2133
+					esc_html__(
2134
+						'List table views for "%s" route could not be setup. Check that you have the corresponding method, "%s" set up for defining list_table_views for this route.',
2135
+						'event_espresso'
2136
+					),
2137
+					$this->_req_action,
2138
+					$list_table_view
2139
+				);
2140
+			throw new EE_Error($error_msg);
2141
+		}
2142
+		//let's provide the ability to filter the views per PAGE AND ROUTE, per PAGE, and globally
2143
+		$this->_views = apply_filters(
2144
+			'FHEE_list_table_views_' . $this->page_slug . '_' . $this->_req_action,
2145
+			$this->_views
2146
+		);
2147
+		$this->_views = apply_filters('FHEE_list_table_views_' . $this->page_slug, $this->_views);
2148
+		$this->_views = apply_filters('FHEE_list_table_views', $this->_views);
2149
+		$this->_set_list_table_view();
2150
+		$this->_set_list_table_object();
2151
+	}
2152
+
2153
+
2154
+
2155
+	/**
2156
+	 * set current view for List Table
2157
+	 *
2158
+	 * @return void
2159
+	 */
2160
+	protected function _set_list_table_view()
2161
+	{
2162
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2163
+		// looking at active items or dumpster diving ?
2164
+		if (! isset($this->_req_data['status']) || ! array_key_exists($this->_req_data['status'], $this->_views)) {
2165
+			$this->_view = isset($this->_views['in_use']) ? 'in_use' : 'all';
2166
+		} else {
2167
+			$this->_view = sanitize_key($this->_req_data['status']);
2168
+		}
2169
+	}
2170
+
2171
+
2172
+	/**
2173
+	 * _set_list_table_object
2174
+	 * WP_List_Table objects need to be loaded fairly early so automatic stuff WP does is taken care of.
2175
+	 *
2176
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
2177
+	 * @throws \InvalidArgumentException
2178
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
2179
+	 * @throws EE_Error
2180
+	 * @throws InvalidInterfaceException
2181
+	 */
2182
+	protected function _set_list_table_object()
2183
+	{
2184
+		if (isset($this->_route_config['list_table'])) {
2185
+			if (! class_exists($this->_route_config['list_table'])) {
2186
+				throw new EE_Error(
2187
+					sprintf(
2188
+						esc_html__(
2189
+							'The %s class defined for the list table does not exist.  Please check the spelling of the class ref in the $_page_config property on %s.',
2190
+							'event_espresso'
2191
+						),
2192
+						$this->_route_config['list_table'],
2193
+						get_class($this)
2194
+					)
2195
+				);
2196
+			}
2197
+			$this->_list_table_object = LoaderFactory::getLoader()->getShared(
2198
+				$this->_route_config['list_table'],
2199
+				array($this)
2200
+			);
2201
+		}
2202
+	}
2203
+
2204
+
2205
+
2206
+	/**
2207
+	 * get_list_table_view_RLs - get it? View RL ?? VU-RL???  URL ??
2208
+	 *
2209
+	 * @param array $extra_query_args                     Optional. An array of extra query args to add to the generated
2210
+	 *                                                    urls.  The array should be indexed by the view it is being
2211
+	 *                                                    added to.
2212
+	 * @return array
2213
+	 */
2214
+	public function get_list_table_view_RLs($extra_query_args = array())
2215
+	{
2216
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2217
+		if (empty($this->_views)) {
2218
+			$this->_views = array();
2219
+		}
2220
+		// cycle thru views
2221
+		foreach ($this->_views as $key => $view) {
2222
+			$query_args = array();
2223
+			// check for current view
2224
+			$this->_views[$key]['class']               = $this->_view === $view['slug'] ? 'current' : '';
2225
+			$query_args['action']                      = $this->_req_action;
2226
+			$query_args[$this->_req_action . '_nonce'] = wp_create_nonce($query_args['action'] . '_nonce');
2227
+			$query_args['status']                      = $view['slug'];
2228
+			//merge any other arguments sent in.
2229
+			if (isset($extra_query_args[$view['slug']])) {
2230
+				$query_args = array_merge($query_args, $extra_query_args[$view['slug']]);
2231
+			}
2232
+			$this->_views[$key]['url'] = EE_Admin_Page::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2233
+		}
2234
+		return $this->_views;
2235
+	}
2236
+
2237
+
2238
+
2239
+	/**
2240
+	 * _entries_per_page_dropdown
2241
+	 * generates a drop down box for selecting the number of visible rows in an admin page list table
2242
+	 *
2243
+	 * @todo   : Note: ideally this should be added to the screen options dropdown as that would be consistent with how
2244
+	 *         WP does it.
2245
+	 * @param int $max_entries total number of rows in the table
2246
+	 * @return string
2247
+	 */
2248
+	protected function _entries_per_page_dropdown($max_entries = 0)
2249
+	{
2250
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2251
+		$values   = array(10, 25, 50, 100);
2252
+		$per_page = (! empty($this->_req_data['per_page'])) ? absint($this->_req_data['per_page']) : 10;
2253
+		if ($max_entries) {
2254
+			$values[] = $max_entries;
2255
+			sort($values);
2256
+		}
2257
+		$entries_per_page_dropdown = '
2258 2258
 			<div id="entries-per-page-dv" class="alignleft actions">
2259 2259
 				<label class="hide-if-no-js">
2260 2260
 					Show
2261 2261
 					<select id="entries-per-page-slct" name="entries-per-page-slct">';
2262
-        foreach ($values as $value) {
2263
-            if ($value < $max_entries) {
2264
-                $selected                  = $value === $per_page ? ' selected="' . $per_page . '"' : '';
2265
-                $entries_per_page_dropdown .= '
2262
+		foreach ($values as $value) {
2263
+			if ($value < $max_entries) {
2264
+				$selected                  = $value === $per_page ? ' selected="' . $per_page . '"' : '';
2265
+				$entries_per_page_dropdown .= '
2266 2266
 						<option value="' . $value . '"' . $selected . '>' . $value . '&nbsp;&nbsp;</option>';
2267
-            }
2268
-        }
2269
-        $selected                  = $max_entries === $per_page ? ' selected="' . $per_page . '"' : '';
2270
-        $entries_per_page_dropdown .= '
2267
+			}
2268
+		}
2269
+		$selected                  = $max_entries === $per_page ? ' selected="' . $per_page . '"' : '';
2270
+		$entries_per_page_dropdown .= '
2271 2271
 						<option value="' . $max_entries . '"' . $selected . '>All&nbsp;&nbsp;</option>';
2272
-        $entries_per_page_dropdown .= '
2272
+		$entries_per_page_dropdown .= '
2273 2273
 					</select>
2274 2274
 					entries
2275 2275
 				</label>
2276 2276
 				<input id="entries-per-page-btn" class="button-secondary" type="submit" value="Go" >
2277 2277
 			</div>
2278 2278
 		';
2279
-        return $entries_per_page_dropdown;
2280
-    }
2281
-
2282
-
2283
-
2284
-    /**
2285
-     *        _set_search_attributes
2286
-     *
2287
-     * @return        void
2288
-     */
2289
-    public function _set_search_attributes()
2290
-    {
2291
-        $this->_template_args['search']['btn_label'] = sprintf(
2292
-            esc_html__('Search %s', 'event_espresso'),
2293
-            empty($this->_search_btn_label) ? $this->page_label
2294
-                : $this->_search_btn_label
2295
-        );
2296
-        $this->_template_args['search']['callback']  = 'search_' . $this->page_slug;
2297
-    }
2298
-
2299
-
2300
-
2301
-    /*** END LIST TABLE METHODS **/
2302
-
2303
-
2304
-
2305
-    /**
2306
-     * _add_registered_metaboxes
2307
-     *  this loads any registered metaboxes via the 'metaboxes' index in the _page_config property array.
2308
-     *
2309
-     * @link   http://codex.wordpress.org/Function_Reference/add_meta_box
2310
-     * @return void
2311
-     * @throws EE_Error
2312
-     */
2313
-    private function _add_registered_meta_boxes()
2314
-    {
2315
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2316
-        //we only add meta boxes if the page_route calls for it
2317
-        if (is_array($this->_route_config) && isset($this->_route_config['metaboxes'])
2318
-            && is_array(
2319
-                $this->_route_config['metaboxes']
2320
-            )
2321
-        ) {
2322
-            // this simply loops through the callbacks provided
2323
-            // and checks if there is a corresponding callback registered by the child
2324
-            // if there is then we go ahead and process the metabox loader.
2325
-            foreach ($this->_route_config['metaboxes'] as $metabox_callback) {
2326
-                // first check for Closures
2327
-                if ($metabox_callback instanceof Closure) {
2328
-                    $result = $metabox_callback();
2329
-                } elseif (is_array($metabox_callback) && isset($metabox_callback[0], $metabox_callback[1])) {
2330
-                    $result = call_user_func(array($metabox_callback[0], $metabox_callback[1]));
2331
-                } else {
2332
-                    $result = call_user_func(array($this, &$metabox_callback));
2333
-                }
2334
-                if ($result === false) {
2335
-                    // user error msg
2336
-                    $error_msg = esc_html__(
2337
-                            'An error occurred. The  requested metabox could not be found.',
2338
-                            'event_espresso'
2339
-                    );
2340
-                    // developer error msg
2341
-                    $error_msg .= '||' . sprintf(
2342
-                            esc_html__(
2343
-                                'The metabox with the string "%s" could not be called. Check that the spelling for method names and actions in the "_page_config[\'metaboxes\']" array are all correct.',
2344
-                                'event_espresso'
2345
-                            ),
2346
-                            $metabox_callback
2347
-                        );
2348
-                    throw new EE_Error($error_msg);
2349
-                }
2350
-            }
2351
-        }
2352
-    }
2353
-
2354
-
2355
-
2356
-    /**
2357
-     * _add_screen_columns
2358
-     * This will check the _page_config array and if there is "columns" key index indicated, we'll set the template as
2359
-     * the dynamic column template and we'll setup the column options for the page.
2360
-     *
2361
-     * @return void
2362
-     */
2363
-    private function _add_screen_columns()
2364
-    {
2365
-        if (
2366
-            is_array($this->_route_config)
2367
-            && isset($this->_route_config['columns'])
2368
-            && is_array($this->_route_config['columns'])
2369
-            && count($this->_route_config['columns']) === 2
2370
-        ) {
2371
-            add_screen_option(
2372
-                'layout_columns',
2373
-                array(
2374
-                    'max'     => (int)$this->_route_config['columns'][0],
2375
-                    'default' => (int)$this->_route_config['columns'][1],
2376
-                )
2377
-            );
2378
-            $this->_template_args['num_columns']                 = $this->_route_config['columns'][0];
2379
-            $screen_id                                           = $this->_current_screen->id;
2380
-            $screen_columns                                      = (int)get_user_option("screen_layout_{$screen_id}");
2381
-            $total_columns                                       = ! empty($screen_columns)
2382
-                ? $screen_columns
2383
-                : $this->_route_config['columns'][1];
2384
-            $this->_template_args['current_screen_widget_class'] = 'columns-' . $total_columns;
2385
-            $this->_template_args['current_page']                = $this->_wp_page_slug;
2386
-            $this->_template_args['screen']                      = $this->_current_screen;
2387
-            $this->_column_template_path                         = EE_ADMIN_TEMPLATE
2388
-                                                                   . 'admin_details_metabox_column_wrapper.template.php';
2389
-            // finally if we don't have has_metaboxes set in the route config
2390
-            // let's make sure it IS set other wise the necessary hidden fields for this won't be loaded.
2391
-            $this->_route_config['has_metaboxes'] = true;
2392
-        }
2393
-    }
2394
-
2395
-
2396
-
2397
-    /** GLOBALLY AVAILABLE METABOXES **/
2398
-
2399
-
2400
-    /**
2401
-     * In this section we put any globally available EE metaboxes for all EE Admin pages.  They are called by simply
2402
-     * referencing the callback in the _page_config array property.  This way you can be very specific about what pages
2403
-     * these get loaded on.
2404
-     */
2405
-    private function _espresso_news_post_box()
2406
-    {
2407
-        $news_box_title = apply_filters(
2408
-            'FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title',
2409
-            esc_html__('New @ Event Espresso', 'event_espresso')
2410
-        );
2411
-        add_meta_box(
2412
-            'espresso_news_post_box',
2413
-            $news_box_title,
2414
-            array(
2415
-                $this,
2416
-                'espresso_news_post_box',
2417
-            ),
2418
-            $this->_wp_page_slug,
2419
-            'side'
2420
-        );
2421
-    }
2422
-
2423
-
2424
-
2425
-    /**
2426
-     * Code for setting up espresso ratings request metabox.
2427
-     */
2428
-    protected function _espresso_ratings_request()
2429
-    {
2430
-        if (! apply_filters('FHEE_show_ratings_request_meta_box', true)) {
2431
-            return;
2432
-        }
2433
-        $ratings_box_title = apply_filters(
2434
-            'FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title',
2435
-            esc_html__('Keep Event Espresso Decaf Free', 'event_espresso')
2436
-        );
2437
-        add_meta_box(
2438
-            'espresso_ratings_request',
2439
-            $ratings_box_title,
2440
-            array(
2441
-                $this,
2442
-                'espresso_ratings_request',
2443
-            ),
2444
-            $this->_wp_page_slug,
2445
-            'side'
2446
-        );
2447
-    }
2448
-
2449
-
2450
-
2451
-    /**
2452
-     * Code for setting up espresso ratings request metabox content.
2453
-     *
2454
-     * @throws DomainException
2455
-     */
2456
-    public function espresso_ratings_request()
2457
-    {
2458
-        EEH_Template::display_template(
2459
-            EE_ADMIN_TEMPLATE . 'espresso_ratings_request_content.template.php',
2460
-                array()
2461
-        );
2462
-    }
2463
-
2464
-
2465
-
2466
-    public static function cached_rss_display($rss_id, $url)
2467
-    {
2468
-        $loading    = '<p class="widget-loading hide-if-no-js">'
2469
-                      . __('Loading&#8230;')
2470
-                      . '</p><p class="hide-if-js">'
2471
-                      . esc_html__('This widget requires JavaScript.')
2472
-                      . '</p>';
2473
-        $pre        = '<div class="espresso-rss-display">' . "\n\t";
2474
-        $pre        .= '<span id="' . $rss_id . '_url" class="hidden">' . $url . '</span>';
2475
-        $post       = '</div>' . "\n";
2476
-        $cache_key  = 'ee_rss_' . md5($rss_id);
2477
-        $output = get_transient($cache_key);
2478
-        if ($output !== false) {
2479
-            echo $pre . $output . $post;
2480
-            return true;
2481
-        }
2482
-        if (! (defined('DOING_AJAX') && DOING_AJAX)) {
2483
-            echo $pre . $loading . $post;
2484
-            return false;
2485
-        }
2486
-        ob_start();
2487
-        wp_widget_rss_output($url, array('show_date' => 0, 'items' => 5));
2488
-        set_transient($cache_key, ob_get_flush(), 12 * HOUR_IN_SECONDS);
2489
-        return true;
2490
-    }
2491
-
2492
-
2493
-
2494
-    public function espresso_news_post_box()
2495
-    {
2496
-        ?>
2279
+		return $entries_per_page_dropdown;
2280
+	}
2281
+
2282
+
2283
+
2284
+	/**
2285
+	 *        _set_search_attributes
2286
+	 *
2287
+	 * @return        void
2288
+	 */
2289
+	public function _set_search_attributes()
2290
+	{
2291
+		$this->_template_args['search']['btn_label'] = sprintf(
2292
+			esc_html__('Search %s', 'event_espresso'),
2293
+			empty($this->_search_btn_label) ? $this->page_label
2294
+				: $this->_search_btn_label
2295
+		);
2296
+		$this->_template_args['search']['callback']  = 'search_' . $this->page_slug;
2297
+	}
2298
+
2299
+
2300
+
2301
+	/*** END LIST TABLE METHODS **/
2302
+
2303
+
2304
+
2305
+	/**
2306
+	 * _add_registered_metaboxes
2307
+	 *  this loads any registered metaboxes via the 'metaboxes' index in the _page_config property array.
2308
+	 *
2309
+	 * @link   http://codex.wordpress.org/Function_Reference/add_meta_box
2310
+	 * @return void
2311
+	 * @throws EE_Error
2312
+	 */
2313
+	private function _add_registered_meta_boxes()
2314
+	{
2315
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2316
+		//we only add meta boxes if the page_route calls for it
2317
+		if (is_array($this->_route_config) && isset($this->_route_config['metaboxes'])
2318
+			&& is_array(
2319
+				$this->_route_config['metaboxes']
2320
+			)
2321
+		) {
2322
+			// this simply loops through the callbacks provided
2323
+			// and checks if there is a corresponding callback registered by the child
2324
+			// if there is then we go ahead and process the metabox loader.
2325
+			foreach ($this->_route_config['metaboxes'] as $metabox_callback) {
2326
+				// first check for Closures
2327
+				if ($metabox_callback instanceof Closure) {
2328
+					$result = $metabox_callback();
2329
+				} elseif (is_array($metabox_callback) && isset($metabox_callback[0], $metabox_callback[1])) {
2330
+					$result = call_user_func(array($metabox_callback[0], $metabox_callback[1]));
2331
+				} else {
2332
+					$result = call_user_func(array($this, &$metabox_callback));
2333
+				}
2334
+				if ($result === false) {
2335
+					// user error msg
2336
+					$error_msg = esc_html__(
2337
+							'An error occurred. The  requested metabox could not be found.',
2338
+							'event_espresso'
2339
+					);
2340
+					// developer error msg
2341
+					$error_msg .= '||' . sprintf(
2342
+							esc_html__(
2343
+								'The metabox with the string "%s" could not be called. Check that the spelling for method names and actions in the "_page_config[\'metaboxes\']" array are all correct.',
2344
+								'event_espresso'
2345
+							),
2346
+							$metabox_callback
2347
+						);
2348
+					throw new EE_Error($error_msg);
2349
+				}
2350
+			}
2351
+		}
2352
+	}
2353
+
2354
+
2355
+
2356
+	/**
2357
+	 * _add_screen_columns
2358
+	 * This will check the _page_config array and if there is "columns" key index indicated, we'll set the template as
2359
+	 * the dynamic column template and we'll setup the column options for the page.
2360
+	 *
2361
+	 * @return void
2362
+	 */
2363
+	private function _add_screen_columns()
2364
+	{
2365
+		if (
2366
+			is_array($this->_route_config)
2367
+			&& isset($this->_route_config['columns'])
2368
+			&& is_array($this->_route_config['columns'])
2369
+			&& count($this->_route_config['columns']) === 2
2370
+		) {
2371
+			add_screen_option(
2372
+				'layout_columns',
2373
+				array(
2374
+					'max'     => (int)$this->_route_config['columns'][0],
2375
+					'default' => (int)$this->_route_config['columns'][1],
2376
+				)
2377
+			);
2378
+			$this->_template_args['num_columns']                 = $this->_route_config['columns'][0];
2379
+			$screen_id                                           = $this->_current_screen->id;
2380
+			$screen_columns                                      = (int)get_user_option("screen_layout_{$screen_id}");
2381
+			$total_columns                                       = ! empty($screen_columns)
2382
+				? $screen_columns
2383
+				: $this->_route_config['columns'][1];
2384
+			$this->_template_args['current_screen_widget_class'] = 'columns-' . $total_columns;
2385
+			$this->_template_args['current_page']                = $this->_wp_page_slug;
2386
+			$this->_template_args['screen']                      = $this->_current_screen;
2387
+			$this->_column_template_path                         = EE_ADMIN_TEMPLATE
2388
+																   . 'admin_details_metabox_column_wrapper.template.php';
2389
+			// finally if we don't have has_metaboxes set in the route config
2390
+			// let's make sure it IS set other wise the necessary hidden fields for this won't be loaded.
2391
+			$this->_route_config['has_metaboxes'] = true;
2392
+		}
2393
+	}
2394
+
2395
+
2396
+
2397
+	/** GLOBALLY AVAILABLE METABOXES **/
2398
+
2399
+
2400
+	/**
2401
+	 * In this section we put any globally available EE metaboxes for all EE Admin pages.  They are called by simply
2402
+	 * referencing the callback in the _page_config array property.  This way you can be very specific about what pages
2403
+	 * these get loaded on.
2404
+	 */
2405
+	private function _espresso_news_post_box()
2406
+	{
2407
+		$news_box_title = apply_filters(
2408
+			'FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title',
2409
+			esc_html__('New @ Event Espresso', 'event_espresso')
2410
+		);
2411
+		add_meta_box(
2412
+			'espresso_news_post_box',
2413
+			$news_box_title,
2414
+			array(
2415
+				$this,
2416
+				'espresso_news_post_box',
2417
+			),
2418
+			$this->_wp_page_slug,
2419
+			'side'
2420
+		);
2421
+	}
2422
+
2423
+
2424
+
2425
+	/**
2426
+	 * Code for setting up espresso ratings request metabox.
2427
+	 */
2428
+	protected function _espresso_ratings_request()
2429
+	{
2430
+		if (! apply_filters('FHEE_show_ratings_request_meta_box', true)) {
2431
+			return;
2432
+		}
2433
+		$ratings_box_title = apply_filters(
2434
+			'FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title',
2435
+			esc_html__('Keep Event Espresso Decaf Free', 'event_espresso')
2436
+		);
2437
+		add_meta_box(
2438
+			'espresso_ratings_request',
2439
+			$ratings_box_title,
2440
+			array(
2441
+				$this,
2442
+				'espresso_ratings_request',
2443
+			),
2444
+			$this->_wp_page_slug,
2445
+			'side'
2446
+		);
2447
+	}
2448
+
2449
+
2450
+
2451
+	/**
2452
+	 * Code for setting up espresso ratings request metabox content.
2453
+	 *
2454
+	 * @throws DomainException
2455
+	 */
2456
+	public function espresso_ratings_request()
2457
+	{
2458
+		EEH_Template::display_template(
2459
+			EE_ADMIN_TEMPLATE . 'espresso_ratings_request_content.template.php',
2460
+				array()
2461
+		);
2462
+	}
2463
+
2464
+
2465
+
2466
+	public static function cached_rss_display($rss_id, $url)
2467
+	{
2468
+		$loading    = '<p class="widget-loading hide-if-no-js">'
2469
+					  . __('Loading&#8230;')
2470
+					  . '</p><p class="hide-if-js">'
2471
+					  . esc_html__('This widget requires JavaScript.')
2472
+					  . '</p>';
2473
+		$pre        = '<div class="espresso-rss-display">' . "\n\t";
2474
+		$pre        .= '<span id="' . $rss_id . '_url" class="hidden">' . $url . '</span>';
2475
+		$post       = '</div>' . "\n";
2476
+		$cache_key  = 'ee_rss_' . md5($rss_id);
2477
+		$output = get_transient($cache_key);
2478
+		if ($output !== false) {
2479
+			echo $pre . $output . $post;
2480
+			return true;
2481
+		}
2482
+		if (! (defined('DOING_AJAX') && DOING_AJAX)) {
2483
+			echo $pre . $loading . $post;
2484
+			return false;
2485
+		}
2486
+		ob_start();
2487
+		wp_widget_rss_output($url, array('show_date' => 0, 'items' => 5));
2488
+		set_transient($cache_key, ob_get_flush(), 12 * HOUR_IN_SECONDS);
2489
+		return true;
2490
+	}
2491
+
2492
+
2493
+
2494
+	public function espresso_news_post_box()
2495
+	{
2496
+		?>
2497 2497
         <div class="padding">
2498 2498
             <div id="espresso_news_post_box_content" class="infolinks">
2499 2499
                 <?php
2500
-                // Get RSS Feed(s)
2501
-                self::cached_rss_display(
2502
-                    'espresso_news_post_box_content',
2503
-                    urlencode(
2504
-                        apply_filters(
2505
-                            'FHEE__EE_Admin_Page__espresso_news_post_box__feed_url',
2506
-                            'http://eventespresso.com/feed/'
2507
-                        )
2508
-                    )
2509
-                );
2510
-                ?>
2500
+				// Get RSS Feed(s)
2501
+				self::cached_rss_display(
2502
+					'espresso_news_post_box_content',
2503
+					urlencode(
2504
+						apply_filters(
2505
+							'FHEE__EE_Admin_Page__espresso_news_post_box__feed_url',
2506
+							'http://eventespresso.com/feed/'
2507
+						)
2508
+					)
2509
+				);
2510
+				?>
2511 2511
             </div>
2512 2512
             <?php do_action('AHEE__EE_Admin_Page__espresso_news_post_box__after_content'); ?>
2513 2513
         </div>
2514 2514
         <?php
2515
-    }
2516
-
2517
-
2518
-
2519
-    private function _espresso_links_post_box()
2520
-    {
2521
-        //Hiding until we actually have content to put in here...
2522
-        //add_meta_box('espresso_links_post_box', esc_html__('Helpful Plugin Links', 'event_espresso'), array( $this, 'espresso_links_post_box'), $this->_wp_page_slug, 'side');
2523
-    }
2524
-
2525
-
2526
-
2527
-    public function espresso_links_post_box()
2528
-    {
2529
-        //Hiding until we actually have content to put in here...
2530
-        // EEH_Template::display_template(
2531
-        //     EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_links.template.php'
2532
-        // );
2533
-    }
2534
-
2535
-
2536
-
2537
-    protected function _espresso_sponsors_post_box()
2538
-    {
2539
-        if (apply_filters('FHEE_show_sponsors_meta_box', true)) {
2540
-            add_meta_box(
2541
-                'espresso_sponsors_post_box',
2542
-                esc_html__('Event Espresso Highlights', 'event_espresso'),
2543
-                array($this, 'espresso_sponsors_post_box'),
2544
-                $this->_wp_page_slug,
2545
-                'side'
2546
-            );
2547
-        }
2548
-    }
2549
-
2550
-
2551
-
2552
-    public function espresso_sponsors_post_box()
2553
-    {
2554
-        EEH_Template::display_template(
2555
-            EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_sponsors.template.php'
2556
-        );
2557
-    }
2558
-
2559
-
2560
-
2561
-    private function _publish_post_box()
2562
-    {
2563
-        $meta_box_ref = 'espresso_' . $this->page_slug . '_editor_overview';
2564
-        // if there is a array('label' => array('publishbox' => 'some title') ) present in the _page_config array
2565
-        // then we'll use that for the metabox label.
2566
-        // Otherwise we'll just use publish (publishbox itself could be an array of labels indexed by routes)
2567
-        if (! empty($this->_labels['publishbox'])) {
2568
-            $box_label = is_array($this->_labels['publishbox']) ? $this->_labels['publishbox'][$this->_req_action]
2569
-                : $this->_labels['publishbox'];
2570
-        } else {
2571
-            $box_label = esc_html__('Publish', 'event_espresso');
2572
-        }
2573
-        $box_label = apply_filters(
2574
-            'FHEE__EE_Admin_Page___publish_post_box__box_label',
2575
-            $box_label,
2576
-            $this->_req_action,
2577
-            $this
2578
-        );
2579
-        add_meta_box(
2580
-            $meta_box_ref,
2581
-            $box_label,
2582
-            array($this, 'editor_overview'),
2583
-            $this->_current_screen->id,
2584
-            'side',
2585
-            'high'
2586
-        );
2587
-    }
2588
-
2589
-
2590
-
2591
-    public function editor_overview()
2592
-    {
2593
-        //if we have extra content set let's add it in if not make sure its empty
2594
-        $this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content'])
2595
-            ? $this->_template_args['publish_box_extra_content']
2596
-            : '';
2597
-        echo EEH_Template::display_template(
2598
-            EE_ADMIN_TEMPLATE . 'admin_details_publish_metabox.template.php',
2599
-            $this->_template_args,
2600
-            true
2601
-        );
2602
-    }
2603
-
2604
-
2605
-    /** end of globally available metaboxes section **/
2606
-
2607
-
2608
-
2609
-    /**
2610
-     * Public wrapper for the protected method.  Allows plugins/addons to externally call the
2611
-     * protected method.
2612
-     *
2613
-     * @see   $this->_set_publish_post_box_vars for param details
2614
-     * @since 4.6.0
2615
-     * @param string $name
2616
-     * @param int    $id
2617
-     * @param bool   $delete
2618
-     * @param string $save_close_redirect_URL
2619
-     * @param bool   $both_btns
2620
-     * @throws EE_Error
2621
-     * @throws InvalidArgumentException
2622
-     * @throws InvalidDataTypeException
2623
-     * @throws InvalidInterfaceException
2624
-     */
2625
-    public function set_publish_post_box_vars(
2626
-        $name = '',
2627
-        $id = 0,
2628
-        $delete = false,
2629
-        $save_close_redirect_URL = '',
2630
-        $both_btns = true
2631
-    ) {
2632
-        $this->_set_publish_post_box_vars(
2633
-            $name,
2634
-            $id,
2635
-            $delete,
2636
-            $save_close_redirect_URL,
2637
-            $both_btns
2638
-        );
2639
-    }
2640
-
2641
-
2642
-
2643
-    /**
2644
-     * Sets the _template_args arguments used by the _publish_post_box shortcut
2645
-     * Note: currently there is no validation for this.  However if you want the delete button, the
2646
-     * save, and save and close buttons to work properly, then you will want to include a
2647
-     * values for the name and id arguments.
2648
-     *
2649
-     * @todo  Add in validation for name/id arguments.
2650
-     * @param    string  $name                    key used for the action ID (i.e. event_id)
2651
-     * @param    int     $id                      id attached to the item published
2652
-     * @param    string  $delete                  page route callback for the delete action
2653
-     * @param    string  $save_close_redirect_URL custom URL to redirect to after Save & Close has been completed
2654
-     * @param    boolean $both_btns               whether to display BOTH the "Save & Close" and "Save" buttons or just
2655
-     *                                            the Save button
2656
-     * @throws EE_Error
2657
-     * @throws InvalidArgumentException
2658
-     * @throws InvalidDataTypeException
2659
-     * @throws InvalidInterfaceException
2660
-     */
2661
-    protected function _set_publish_post_box_vars(
2662
-        $name = '',
2663
-        $id = 0,
2664
-        $delete = '',
2665
-        $save_close_redirect_URL = '',
2666
-        $both_btns = true
2667
-    ) {
2668
-        // if Save & Close, use a custom redirect URL or default to the main page?
2669
-        $save_close_redirect_URL = ! empty($save_close_redirect_URL)
2670
-            ? $save_close_redirect_URL
2671
-            : $this->_admin_base_url;
2672
-        // create the Save & Close and Save buttons
2673
-        $this->_set_save_buttons($both_btns, array(), array(), $save_close_redirect_URL);
2674
-        //if we have extra content set let's add it in if not make sure its empty
2675
-        $this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content'])
2676
-            ? $this->_template_args['publish_box_extra_content']
2677
-            : '';
2678
-        if ($delete && ! empty($id)) {
2679
-            //make sure we have a default if just true is sent.
2680
-            $delete           = ! empty($delete) ? $delete : 'delete';
2681
-            $delete_link_args = array($name => $id);
2682
-            $delete           = $this->get_action_link_or_button(
2683
-                $delete,
2684
-                $delete,
2685
-                $delete_link_args,
2686
-                'submitdelete deletion',
2687
-                '',
2688
-                false
2689
-            );
2690
-        }
2691
-        $this->_template_args['publish_delete_link'] = ! empty($id) ? $delete : '';
2692
-        if (! empty($name) && ! empty($id)) {
2693
-            $hidden_field_arr[$name] = array(
2694
-                'type'  => 'hidden',
2695
-                'value' => $id,
2696
-            );
2697
-            $hf                      = $this->_generate_admin_form_fields($hidden_field_arr, 'array');
2698
-        } else {
2699
-            $hf = '';
2700
-        }
2701
-        // add hidden field
2702
-        $this->_template_args['publish_hidden_fields'] = is_array($hf) && ! empty($name)
2703
-            ? $hf[$name]['field']
2704
-            : $hf;
2705
-    }
2706
-
2707
-
2708
-
2709
-    /**
2710
-     * displays an error message to ppl who have javascript disabled
2711
-     *
2712
-     * @return void
2713
-     */
2714
-    private function _display_no_javascript_warning()
2715
-    {
2716
-        ?>
2515
+	}
2516
+
2517
+
2518
+
2519
+	private function _espresso_links_post_box()
2520
+	{
2521
+		//Hiding until we actually have content to put in here...
2522
+		//add_meta_box('espresso_links_post_box', esc_html__('Helpful Plugin Links', 'event_espresso'), array( $this, 'espresso_links_post_box'), $this->_wp_page_slug, 'side');
2523
+	}
2524
+
2525
+
2526
+
2527
+	public function espresso_links_post_box()
2528
+	{
2529
+		//Hiding until we actually have content to put in here...
2530
+		// EEH_Template::display_template(
2531
+		//     EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_links.template.php'
2532
+		// );
2533
+	}
2534
+
2535
+
2536
+
2537
+	protected function _espresso_sponsors_post_box()
2538
+	{
2539
+		if (apply_filters('FHEE_show_sponsors_meta_box', true)) {
2540
+			add_meta_box(
2541
+				'espresso_sponsors_post_box',
2542
+				esc_html__('Event Espresso Highlights', 'event_espresso'),
2543
+				array($this, 'espresso_sponsors_post_box'),
2544
+				$this->_wp_page_slug,
2545
+				'side'
2546
+			);
2547
+		}
2548
+	}
2549
+
2550
+
2551
+
2552
+	public function espresso_sponsors_post_box()
2553
+	{
2554
+		EEH_Template::display_template(
2555
+			EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_sponsors.template.php'
2556
+		);
2557
+	}
2558
+
2559
+
2560
+
2561
+	private function _publish_post_box()
2562
+	{
2563
+		$meta_box_ref = 'espresso_' . $this->page_slug . '_editor_overview';
2564
+		// if there is a array('label' => array('publishbox' => 'some title') ) present in the _page_config array
2565
+		// then we'll use that for the metabox label.
2566
+		// Otherwise we'll just use publish (publishbox itself could be an array of labels indexed by routes)
2567
+		if (! empty($this->_labels['publishbox'])) {
2568
+			$box_label = is_array($this->_labels['publishbox']) ? $this->_labels['publishbox'][$this->_req_action]
2569
+				: $this->_labels['publishbox'];
2570
+		} else {
2571
+			$box_label = esc_html__('Publish', 'event_espresso');
2572
+		}
2573
+		$box_label = apply_filters(
2574
+			'FHEE__EE_Admin_Page___publish_post_box__box_label',
2575
+			$box_label,
2576
+			$this->_req_action,
2577
+			$this
2578
+		);
2579
+		add_meta_box(
2580
+			$meta_box_ref,
2581
+			$box_label,
2582
+			array($this, 'editor_overview'),
2583
+			$this->_current_screen->id,
2584
+			'side',
2585
+			'high'
2586
+		);
2587
+	}
2588
+
2589
+
2590
+
2591
+	public function editor_overview()
2592
+	{
2593
+		//if we have extra content set let's add it in if not make sure its empty
2594
+		$this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content'])
2595
+			? $this->_template_args['publish_box_extra_content']
2596
+			: '';
2597
+		echo EEH_Template::display_template(
2598
+			EE_ADMIN_TEMPLATE . 'admin_details_publish_metabox.template.php',
2599
+			$this->_template_args,
2600
+			true
2601
+		);
2602
+	}
2603
+
2604
+
2605
+	/** end of globally available metaboxes section **/
2606
+
2607
+
2608
+
2609
+	/**
2610
+	 * Public wrapper for the protected method.  Allows plugins/addons to externally call the
2611
+	 * protected method.
2612
+	 *
2613
+	 * @see   $this->_set_publish_post_box_vars for param details
2614
+	 * @since 4.6.0
2615
+	 * @param string $name
2616
+	 * @param int    $id
2617
+	 * @param bool   $delete
2618
+	 * @param string $save_close_redirect_URL
2619
+	 * @param bool   $both_btns
2620
+	 * @throws EE_Error
2621
+	 * @throws InvalidArgumentException
2622
+	 * @throws InvalidDataTypeException
2623
+	 * @throws InvalidInterfaceException
2624
+	 */
2625
+	public function set_publish_post_box_vars(
2626
+		$name = '',
2627
+		$id = 0,
2628
+		$delete = false,
2629
+		$save_close_redirect_URL = '',
2630
+		$both_btns = true
2631
+	) {
2632
+		$this->_set_publish_post_box_vars(
2633
+			$name,
2634
+			$id,
2635
+			$delete,
2636
+			$save_close_redirect_URL,
2637
+			$both_btns
2638
+		);
2639
+	}
2640
+
2641
+
2642
+
2643
+	/**
2644
+	 * Sets the _template_args arguments used by the _publish_post_box shortcut
2645
+	 * Note: currently there is no validation for this.  However if you want the delete button, the
2646
+	 * save, and save and close buttons to work properly, then you will want to include a
2647
+	 * values for the name and id arguments.
2648
+	 *
2649
+	 * @todo  Add in validation for name/id arguments.
2650
+	 * @param    string  $name                    key used for the action ID (i.e. event_id)
2651
+	 * @param    int     $id                      id attached to the item published
2652
+	 * @param    string  $delete                  page route callback for the delete action
2653
+	 * @param    string  $save_close_redirect_URL custom URL to redirect to after Save & Close has been completed
2654
+	 * @param    boolean $both_btns               whether to display BOTH the "Save & Close" and "Save" buttons or just
2655
+	 *                                            the Save button
2656
+	 * @throws EE_Error
2657
+	 * @throws InvalidArgumentException
2658
+	 * @throws InvalidDataTypeException
2659
+	 * @throws InvalidInterfaceException
2660
+	 */
2661
+	protected function _set_publish_post_box_vars(
2662
+		$name = '',
2663
+		$id = 0,
2664
+		$delete = '',
2665
+		$save_close_redirect_URL = '',
2666
+		$both_btns = true
2667
+	) {
2668
+		// if Save & Close, use a custom redirect URL or default to the main page?
2669
+		$save_close_redirect_URL = ! empty($save_close_redirect_URL)
2670
+			? $save_close_redirect_URL
2671
+			: $this->_admin_base_url;
2672
+		// create the Save & Close and Save buttons
2673
+		$this->_set_save_buttons($both_btns, array(), array(), $save_close_redirect_URL);
2674
+		//if we have extra content set let's add it in if not make sure its empty
2675
+		$this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content'])
2676
+			? $this->_template_args['publish_box_extra_content']
2677
+			: '';
2678
+		if ($delete && ! empty($id)) {
2679
+			//make sure we have a default if just true is sent.
2680
+			$delete           = ! empty($delete) ? $delete : 'delete';
2681
+			$delete_link_args = array($name => $id);
2682
+			$delete           = $this->get_action_link_or_button(
2683
+				$delete,
2684
+				$delete,
2685
+				$delete_link_args,
2686
+				'submitdelete deletion',
2687
+				'',
2688
+				false
2689
+			);
2690
+		}
2691
+		$this->_template_args['publish_delete_link'] = ! empty($id) ? $delete : '';
2692
+		if (! empty($name) && ! empty($id)) {
2693
+			$hidden_field_arr[$name] = array(
2694
+				'type'  => 'hidden',
2695
+				'value' => $id,
2696
+			);
2697
+			$hf                      = $this->_generate_admin_form_fields($hidden_field_arr, 'array');
2698
+		} else {
2699
+			$hf = '';
2700
+		}
2701
+		// add hidden field
2702
+		$this->_template_args['publish_hidden_fields'] = is_array($hf) && ! empty($name)
2703
+			? $hf[$name]['field']
2704
+			: $hf;
2705
+	}
2706
+
2707
+
2708
+
2709
+	/**
2710
+	 * displays an error message to ppl who have javascript disabled
2711
+	 *
2712
+	 * @return void
2713
+	 */
2714
+	private function _display_no_javascript_warning()
2715
+	{
2716
+		?>
2717 2717
         <noscript>
2718 2718
             <div id="no-js-message" class="error">
2719 2719
                 <p style="font-size:1.3em;">
2720 2720
                     <span style="color:red;"><?php esc_html_e('Warning!', 'event_espresso'); ?></span>
2721 2721
                     <?php esc_html_e(
2722
-                        'Javascript is currently turned off for your browser. Javascript must be enabled in order for all of the features on this page to function properly. Please turn your javascript back on.',
2723
-                        'event_espresso'
2724
-                    ); ?>
2722
+						'Javascript is currently turned off for your browser. Javascript must be enabled in order for all of the features on this page to function properly. Please turn your javascript back on.',
2723
+						'event_espresso'
2724
+					); ?>
2725 2725
                 </p>
2726 2726
             </div>
2727 2727
         </noscript>
2728 2728
         <?php
2729
-    }
2729
+	}
2730 2730
 
2731 2731
 
2732 2732
 
2733
-    /**
2734
-     * displays espresso success and/or error notices
2735
-     *
2736
-     * @return void
2737
-     */
2738
-    private function _display_espresso_notices()
2739
-    {
2740
-        $notices = $this->_get_transient(true);
2741
-        echo stripslashes($notices);
2742
-    }
2733
+	/**
2734
+	 * displays espresso success and/or error notices
2735
+	 *
2736
+	 * @return void
2737
+	 */
2738
+	private function _display_espresso_notices()
2739
+	{
2740
+		$notices = $this->_get_transient(true);
2741
+		echo stripslashes($notices);
2742
+	}
2743 2743
 
2744 2744
 
2745 2745
 
2746
-    /**
2747
-     * spinny things pacify the masses
2748
-     *
2749
-     * @return void
2750
-     */
2751
-    protected function _add_admin_page_ajax_loading_img()
2752
-    {
2753
-        ?>
2746
+	/**
2747
+	 * spinny things pacify the masses
2748
+	 *
2749
+	 * @return void
2750
+	 */
2751
+	protected function _add_admin_page_ajax_loading_img()
2752
+	{
2753
+		?>
2754 2754
         <div id="espresso-ajax-loading" class="ajax-loading-grey">
2755 2755
             <span class="ee-spinner ee-spin"></span><span class="hidden"><?php esc_html_e(
2756
-                    'loading...',
2757
-                    'event_espresso'
2758
-                ); ?></span>
2756
+					'loading...',
2757
+					'event_espresso'
2758
+				); ?></span>
2759 2759
         </div>
2760 2760
         <?php
2761
-    }
2761
+	}
2762 2762
 
2763 2763
 
2764 2764
 
2765
-    /**
2766
-     * add admin page overlay for modal boxes
2767
-     *
2768
-     * @return void
2769
-     */
2770
-    protected function _add_admin_page_overlay()
2771
-    {
2772
-        ?>
2765
+	/**
2766
+	 * add admin page overlay for modal boxes
2767
+	 *
2768
+	 * @return void
2769
+	 */
2770
+	protected function _add_admin_page_overlay()
2771
+	{
2772
+		?>
2773 2773
         <div id="espresso-admin-page-overlay-dv" class=""></div>
2774 2774
         <?php
2775
-    }
2776
-
2777
-
2778
-
2779
-    /**
2780
-     * facade for add_meta_box
2781
-     *
2782
-     * @param string  $action        where the metabox get's displayed
2783
-     * @param string  $title         Title of Metabox (output in metabox header)
2784
-     * @param string  $callback      If not empty and $create_fun is set to false then we'll use a custom callback
2785
-     *                               instead of the one created in here.
2786
-     * @param array   $callback_args an array of args supplied for the metabox
2787
-     * @param string  $column        what metabox column
2788
-     * @param string  $priority      give this metabox a priority (using accepted priorities for wp meta boxes)
2789
-     * @param boolean $create_func   default is true.  Basically we can say we don't WANT to have the runtime function
2790
-     *                               created but just set our own callback for wp's add_meta_box.
2791
-     * @throws \DomainException
2792
-     */
2793
-    public function _add_admin_page_meta_box(
2794
-        $action,
2795
-        $title,
2796
-        $callback,
2797
-        $callback_args,
2798
-        $column = 'normal',
2799
-        $priority = 'high',
2800
-        $create_func = true
2801
-    ) {
2802
-        do_action('AHEE_log', __FILE__, __FUNCTION__, $callback);
2803
-        //if we have empty callback args and we want to automatically create the metabox callback then we need to make sure the callback args are generated.
2804
-        if (empty($callback_args) && $create_func) {
2805
-            $callback_args = array(
2806
-                'template_path' => $this->_template_path,
2807
-                'template_args' => $this->_template_args,
2808
-            );
2809
-        }
2810
-        //if $create_func is true (default) then we automatically create the function for displaying the actual meta box.  If false then we take the $callback reference passed through and use it instead (so callers can define their own callback function/method if they wish)
2811
-        $call_back_func = $create_func
2812
-            ? function ($post, $metabox)
2813
-            {
2814
-                do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2815
-                echo EEH_Template::display_template(
2816
-                    $metabox['args']['template_path'],
2817
-                    $metabox['args']['template_args'],
2818
-                    true
2819
-                );
2820
-            }
2821
-            : $callback;
2822
-        add_meta_box(
2823
-            str_replace('_', '-', $action) . '-mbox',
2824
-            $title,
2825
-            $call_back_func,
2826
-            $this->_wp_page_slug,
2827
-            $column,
2828
-            $priority,
2829
-            $callback_args
2830
-        );
2831
-    }
2832
-
2833
-
2834
-
2835
-    /**
2836
-     * generates HTML wrapper for and admin details page that contains metaboxes in columns
2837
-     *
2838
-     * @throws DomainException
2839
-     * @throws EE_Error
2840
-     */
2841
-    public function display_admin_page_with_metabox_columns()
2842
-    {
2843
-        $this->_template_args['post_body_content']  = $this->_template_args['admin_page_content'];
2844
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
2845
-            $this->_column_template_path,
2846
-            $this->_template_args,
2847
-            true
2848
-        );
2849
-        //the final wrapper
2850
-        $this->admin_page_wrapper();
2851
-    }
2852
-
2853
-
2854
-
2855
-    /**
2856
-     * generates  HTML wrapper for an admin details page
2857
-     *
2858
-     * @return void
2859
-     * @throws EE_Error
2860
-     * @throws DomainException
2861
-     */
2862
-    public function display_admin_page_with_sidebar()
2863
-    {
2864
-        $this->_display_admin_page(true);
2865
-    }
2866
-
2867
-
2868
-
2869
-    /**
2870
-     * generates  HTML wrapper for an admin details page (except no sidebar)
2871
-     *
2872
-     * @return void
2873
-     * @throws EE_Error
2874
-     * @throws DomainException
2875
-     */
2876
-    public function display_admin_page_with_no_sidebar()
2877
-    {
2878
-        $this->_display_admin_page();
2879
-    }
2880
-
2881
-
2882
-
2883
-    /**
2884
-     * generates HTML wrapper for an EE about admin page (no sidebar)
2885
-     *
2886
-     * @return void
2887
-     * @throws EE_Error
2888
-     * @throws DomainException
2889
-     */
2890
-    public function display_about_admin_page()
2891
-    {
2892
-        $this->_display_admin_page(false, true);
2893
-    }
2894
-
2895
-
2896
-
2897
-    /**
2898
-     * display_admin_page
2899
-     * contains the code for actually displaying an admin page
2900
-     *
2901
-     * @param  boolean $sidebar true with sidebar, false without
2902
-     * @param  boolean $about   use the about admin wrapper instead of the default.
2903
-     * @return void
2904
-     * @throws DomainException
2905
-     * @throws EE_Error
2906
-     */
2907
-    private function _display_admin_page($sidebar = false, $about = false)
2908
-    {
2909
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2910
-        //custom remove metaboxes hook to add or remove any metaboxes to/from Admin pages.
2911
-        do_action('AHEE__EE_Admin_Page___display_admin_page__modify_metaboxes');
2912
-        // set current wp page slug - looks like: event-espresso_page_event_categories
2913
-        // keep in mind "event-espresso" COULD be something else if the top level menu label has been translated.
2914
-        $this->_template_args['current_page']              = $this->_wp_page_slug;
2915
-        $this->_template_args['admin_page_wrapper_div_id'] = $this->_cpt_route
2916
-            ? 'poststuff'
2917
-            : 'espresso-default-admin';
2918
-        $template_path                                     = $sidebar
2919
-            ? EE_ADMIN_TEMPLATE . 'admin_details_wrapper.template.php'
2920
-            : EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar.template.php';
2921
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2922
-            $template_path = EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar_ajax.template.php';
2923
-        }
2924
-        $template_path                                     = ! empty($this->_column_template_path)
2925
-            ? $this->_column_template_path : $template_path;
2926
-        $this->_template_args['post_body_content']         = isset($this->_template_args['admin_page_content'])
2927
-            ? $this->_template_args['admin_page_content']
2928
-            : '';
2929
-        $this->_template_args['before_admin_page_content'] = isset($this->_template_args['before_admin_page_content'])
2930
-            ? $this->_template_args['before_admin_page_content']
2931
-            : '';
2932
-        $this->_template_args['after_admin_page_content']  = isset($this->_template_args['after_admin_page_content'])
2933
-            ? $this->_template_args['after_admin_page_content']
2934
-            : '';
2935
-        $this->_template_args['admin_page_content']        = EEH_Template::display_template(
2936
-            $template_path,
2937
-            $this->_template_args,
2938
-            true
2939
-        );
2940
-        // the final template wrapper
2941
-        $this->admin_page_wrapper($about);
2942
-    }
2943
-
2944
-
2945
-
2946
-    /**
2947
-     * This is used to display caf preview pages.
2948
-     *
2949
-     * @since 4.3.2
2950
-     * @param string $utm_campaign_source what is the key used for google analytics link
2951
-     * @param bool   $display_sidebar     whether to use the sidebar template or the full template for the page.  TRUE
2952
-     *                                    = SHOW sidebar, FALSE = no sidebar. Default no sidebar.
2953
-     * @return void
2954
-     * @throws DomainException
2955
-     * @throws EE_Error
2956
-     * @throws InvalidArgumentException
2957
-     * @throws InvalidDataTypeException
2958
-     * @throws InvalidInterfaceException
2959
-     */
2960
-    public function display_admin_caf_preview_page($utm_campaign_source = '', $display_sidebar = true)
2961
-    {
2962
-        //let's generate a default preview action button if there isn't one already present.
2963
-        $this->_labels['buttons']['buy_now']           = esc_html__(
2964
-            'Upgrade to Event Espresso 4 Right Now',
2965
-            'event_espresso'
2966
-        );
2967
-        $buy_now_url                                   = add_query_arg(
2968
-            array(
2969
-                'ee_ver'       => 'ee4',
2970
-                'utm_source'   => 'ee4_plugin_admin',
2971
-                'utm_medium'   => 'link',
2972
-                'utm_campaign' => $utm_campaign_source,
2973
-                'utm_content'  => 'buy_now_button',
2974
-            ),
2975
-            'http://eventespresso.com/pricing/'
2976
-        );
2977
-        $this->_template_args['preview_action_button'] = ! isset($this->_template_args['preview_action_button'])
2978
-            ? $this->get_action_link_or_button(
2979
-                '',
2980
-                'buy_now',
2981
-                array(),
2982
-                'button-primary button-large',
2983
-                $buy_now_url,
2984
-                true
2985
-            )
2986
-            : $this->_template_args['preview_action_button'];
2987
-        $this->_template_args['admin_page_content']    = EEH_Template::display_template(
2988
-            EE_ADMIN_TEMPLATE . 'admin_caf_full_page_preview.template.php',
2989
-            $this->_template_args,
2990
-            true
2991
-        );
2992
-        $this->_display_admin_page($display_sidebar);
2993
-    }
2994
-
2995
-
2996
-
2997
-    /**
2998
-     * display_admin_list_table_page_with_sidebar
2999
-     * generates HTML wrapper for an admin_page with list_table
3000
-     *
3001
-     * @return void
3002
-     * @throws EE_Error
3003
-     * @throws DomainException
3004
-     */
3005
-    public function display_admin_list_table_page_with_sidebar()
3006
-    {
3007
-        $this->_display_admin_list_table_page(true);
3008
-    }
3009
-
3010
-
3011
-
3012
-    /**
3013
-     * display_admin_list_table_page_with_no_sidebar
3014
-     * generates HTML wrapper for an admin_page with list_table (but with no sidebar)
3015
-     *
3016
-     * @return void
3017
-     * @throws EE_Error
3018
-     * @throws DomainException
3019
-     */
3020
-    public function display_admin_list_table_page_with_no_sidebar()
3021
-    {
3022
-        $this->_display_admin_list_table_page();
3023
-    }
3024
-
3025
-
3026
-
3027
-    /**
3028
-     * generates html wrapper for an admin_list_table page
3029
-     *
3030
-     * @param boolean $sidebar whether to display with sidebar or not.
3031
-     * @return void
3032
-     * @throws DomainException
3033
-     * @throws EE_Error
3034
-     */
3035
-    private function _display_admin_list_table_page($sidebar = false)
3036
-    {
3037
-        //setup search attributes
3038
-        $this->_set_search_attributes();
3039
-        $this->_template_args['current_page']     = $this->_wp_page_slug;
3040
-        $template_path                            = EE_ADMIN_TEMPLATE . 'admin_list_wrapper.template.php';
3041
-        $this->_template_args['table_url']        = defined('DOING_AJAX')
3042
-            ? add_query_arg(array('noheader' => 'true', 'route' => $this->_req_action), $this->_admin_base_url)
3043
-            : add_query_arg(array('route' => $this->_req_action), $this->_admin_base_url);
3044
-        $this->_template_args['list_table']       = $this->_list_table_object;
3045
-        $this->_template_args['current_route']    = $this->_req_action;
3046
-        $this->_template_args['list_table_class'] = get_class($this->_list_table_object);
3047
-        $ajax_sorting_callback                    = $this->_list_table_object->get_ajax_sorting_callback();
3048
-        if (! empty($ajax_sorting_callback)) {
3049
-            $sortable_list_table_form_fields = wp_nonce_field(
3050
-                $ajax_sorting_callback . '_nonce',
3051
-                $ajax_sorting_callback . '_nonce',
3052
-                false,
3053
-                false
3054
-            );
3055
-            //			$reorder_action = 'espresso_' . $ajax_sorting_callback . '_nonce';
3056
-            //			$sortable_list_table_form_fields = wp_nonce_field( $reorder_action, 'ajax_table_sort_nonce', FALSE, FALSE );
3057
-            $sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_page" name="ajax_table_sort_page" value="'
3058
-                                                . $this->page_slug
3059
-                                                . '" />';
3060
-            $sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_action" name="ajax_table_sort_action" value="'
3061
-                                                . $ajax_sorting_callback
3062
-                                                . '" />';
3063
-        } else {
3064
-            $sortable_list_table_form_fields = '';
3065
-        }
3066
-        $this->_template_args['sortable_list_table_form_fields'] = $sortable_list_table_form_fields;
3067
-        $hidden_form_fields                                      = isset($this->_template_args['list_table_hidden_fields'])
3068
-            ? $this->_template_args['list_table_hidden_fields']
3069
-            : '';
3070
-        $nonce_ref                                               = $this->_req_action . '_nonce';
3071
-        $hidden_form_fields                                      .= '<input type="hidden" name="'
3072
-                                                                    . $nonce_ref
3073
-                                                                    . '" value="'
3074
-                                                                    . wp_create_nonce($nonce_ref)
3075
-                                                                    . '">';
3076
-        $this->_template_args['list_table_hidden_fields']        = $hidden_form_fields;
3077
-        //display message about search results?
3078
-        $this->_template_args['before_list_table'] .= ! empty($this->_req_data['s'])
3079
-            ? '<p class="ee-search-results">' . sprintf(
3080
-                esc_html__('Displaying search results for the search string: %1$s', 'event_espresso'),
3081
-                trim($this->_req_data['s'], '%')
3082
-            ) . '</p>'
3083
-            : '';
3084
-        // filter before_list_table template arg
3085
-        $this->_template_args['before_list_table'] = apply_filters(
3086
-            'FHEE__EE_Admin_Page___display_admin_list_table_page__before_list_table__template_arg',
3087
-            $this->_template_args['before_list_table'],
3088
-            $this->page_slug,
3089
-            $this->_req_data,
3090
-            $this->_req_action
3091
-        );
3092
-        // convert to array and filter again
3093
-        // arrays are easier to inject new items in a specific location,
3094
-        // but would not be backwards compatible, so we have to add a new filter
3095
-        $this->_template_args['before_list_table'] = implode(
3096
-            " \n",
3097
-            (array)apply_filters(
3098
-                'FHEE__EE_Admin_Page___display_admin_list_table_page__before_list_table__template_args_array',
3099
-                (array)$this->_template_args['before_list_table'],
3100
-                $this->page_slug,
3101
-                $this->_req_data,
3102
-                $this->_req_action
3103
-            )
3104
-        );
3105
-        // filter after_list_table template arg
3106
-        $this->_template_args['after_list_table'] = apply_filters(
3107
-            'FHEE__EE_Admin_Page___display_admin_list_table_page__after_list_table__template_arg',
3108
-            $this->_template_args['after_list_table'],
3109
-            $this->page_slug,
3110
-            $this->_req_data,
3111
-            $this->_req_action
3112
-        );
3113
-        // convert to array and filter again
3114
-        // arrays are easier to inject new items in a specific location,
3115
-        // but would not be backwards compatible, so we have to add a new filter
3116
-        $this->_template_args['after_list_table']   = implode(
3117
-            " \n",
3118
-            (array)apply_filters(
3119
-                'FHEE__EE_Admin_Page___display_admin_list_table_page__after_list_table__template_args_array',
3120
-                (array)$this->_template_args['after_list_table'],
3121
-                $this->page_slug,
3122
-                $this->_req_data,
3123
-                $this->_req_action
3124
-            )
3125
-        );
3126
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
3127
-            $template_path,
3128
-            $this->_template_args,
3129
-            true
3130
-        );
3131
-        // the final template wrapper
3132
-        if ($sidebar) {
3133
-            $this->display_admin_page_with_sidebar();
3134
-        } else {
3135
-            $this->display_admin_page_with_no_sidebar();
3136
-        }
3137
-    }
3138
-
3139
-
3140
-
3141
-    /**
3142
-     * This just prepares a legend using the given items and the admin_details_legend.template.php file and returns the
3143
-     * html string for the legend.
3144
-     * $items are expected in an array in the following format:
3145
-     * $legend_items = array(
3146
-     *        'item_id' => array(
3147
-     *            'icon' => 'http://url_to_icon_being_described.png',
3148
-     *            'desc' => esc_html__('localized description of item');
3149
-     *        )
3150
-     * );
3151
-     *
3152
-     * @param  array $items see above for format of array
3153
-     * @return string html string of legend
3154
-     * @throws DomainException
3155
-     */
3156
-    protected function _display_legend($items)
3157
-    {
3158
-        $this->_template_args['items'] = apply_filters(
3159
-            'FHEE__EE_Admin_Page___display_legend__items',
3160
-            (array)$items,
3161
-            $this
3162
-        );
3163
-        return EEH_Template::display_template(
3164
-            EE_ADMIN_TEMPLATE . 'admin_details_legend.template.php',
3165
-            $this->_template_args,
3166
-            true
3167
-        );
3168
-    }
3169
-
3170
-
3171
-    /**
3172
-     * This is used whenever we're DOING_AJAX to return a formatted json array that our calling javascript can expect
3173
-     * The returned json object is created from an array in the following format:
3174
-     * array(
3175
-     *  'error' => FALSE, //(default FALSE), contains any errors and/or exceptions (exceptions return json early),
3176
-     *  'success' => FALSE, //(default FALSE) - contains any special success message.
3177
-     *  'notices' => '', // - contains any EE_Error formatted notices
3178
-     *  'content' => 'string can be html', //this is a string of formatted content (can be html)
3179
-     *  'data' => array() //this can be any key/value pairs that a method returns for later json parsing by the js.
3180
-     *  We're also going to include the template args with every package (so js can pick out any specific template args
3181
-     *  that might be included in here)
3182
-     * )
3183
-     * The json object is populated by whatever is set in the $_template_args property.
3184
-     *
3185
-     * @param bool  $sticky_notices    Used to indicate whether you want to ensure notices are added to a transient
3186
-     *                                 instead of displayed.
3187
-     * @param array $notices_arguments Use this to pass any additional args on to the _process_notices.
3188
-     * @return void
3189
-     * @throws EE_Error
3190
-     */
3191
-    protected function _return_json($sticky_notices = false, $notices_arguments = array())
3192
-    {
3193
-        //make sure any EE_Error notices have been handled.
3194
-        $this->_process_notices($notices_arguments, true, $sticky_notices);
3195
-        $data = isset($this->_template_args['data']) ? $this->_template_args['data'] : array();
3196
-        unset($this->_template_args['data']);
3197
-        $json = array(
3198
-            'error'     => isset($this->_template_args['error']) ? $this->_template_args['error'] : false,
3199
-            'success'   => isset($this->_template_args['success']) ? $this->_template_args['success'] : false,
3200
-            'errors'    => isset($this->_template_args['errors']) ? $this->_template_args['errors'] : false,
3201
-            'attention' => isset($this->_template_args['attention']) ? $this->_template_args['attention'] : false,
3202
-            'notices'   => EE_Error::get_notices(),
3203
-            'content'   => isset($this->_template_args['admin_page_content'])
3204
-                ? $this->_template_args['admin_page_content'] : '',
3205
-            'data'      => array_merge($data, array('template_args' => $this->_template_args)),
3206
-            'isEEajax'  => true
3207
-            //special flag so any ajax.Success methods in js can identify this return package as a EEajax package.
3208
-        );
3209
-        // make sure there are no php errors or headers_sent.  Then we can set correct json header.
3210
-        if (null === error_get_last() || ! headers_sent()) {
3211
-            header('Content-Type: application/json; charset=UTF-8');
3212
-        }
3213
-        echo wp_json_encode($json);
3214
-        exit();
3215
-    }
3216
-
3217
-
3218
-
3219
-    /**
3220
-     * Simply a wrapper for the protected method so we can call this outside the class (ONLY when doing ajax)
3221
-     *
3222
-     * @return void
3223
-     * @throws EE_Error
3224
-     */
3225
-    public function return_json()
3226
-    {
3227
-        if (defined('DOING_AJAX') && DOING_AJAX) {
3228
-            $this->_return_json();
3229
-        } else {
3230
-            throw new EE_Error(
3231
-                sprintf(
3232
-                    esc_html__('The public %s method can only be called when DOING_AJAX = TRUE', 'event_espresso'),
3233
-                    __FUNCTION__
3234
-                )
3235
-            );
3236
-        }
3237
-    }
3238
-
3239
-
3240
-
3241
-    /**
3242
-     * This provides a way for child hook classes to send along themselves by reference so methods/properties within
3243
-     * them can be accessed by EE_Admin_child pages. This is assigned to the $_hook_obj property.
3244
-     *
3245
-     * @param EE_Admin_Hooks $hook_obj This will be the object for the EE_Admin_Hooks child
3246
-     */
3247
-    public function set_hook_object(EE_Admin_Hooks $hook_obj)
3248
-    {
3249
-        $this->_hook_obj = $hook_obj;
3250
-    }
3251
-
3252
-
3253
-
3254
-    /**
3255
-     *        generates  HTML wrapper with Tabbed nav for an admin page
3256
-     *
3257
-     * @param  boolean $about whether to use the special about page wrapper or default.
3258
-     * @return void
3259
-     * @throws DomainException
3260
-     * @throws EE_Error
3261
-     */
3262
-    public function admin_page_wrapper($about = false)
3263
-    {
3264
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3265
-        $this->_nav_tabs                                   = $this->_get_main_nav_tabs();
3266
-        $this->_template_args['nav_tabs']                  = $this->_nav_tabs;
3267
-        $this->_template_args['admin_page_title']          = $this->_admin_page_title;
3268
-        $this->_template_args['before_admin_page_content'] = apply_filters(
3269
-            "FHEE_before_admin_page_content{$this->_current_page}{$this->_current_view}",
3270
-            isset($this->_template_args['before_admin_page_content'])
3271
-                ? $this->_template_args['before_admin_page_content']
3272
-                : ''
3273
-        );
3274
-        $this->_template_args['after_admin_page_content']  = apply_filters(
3275
-            "FHEE_after_admin_page_content{$this->_current_page}{$this->_current_view}",
3276
-            isset($this->_template_args['after_admin_page_content'])
3277
-                ? $this->_template_args['after_admin_page_content']
3278
-                : ''
3279
-        );
3280
-        $this->_template_args['after_admin_page_content']  .= $this->_set_help_popup_content();
3281
-        // load settings page wrapper template
3282
-        $template_path = ! defined('DOING_AJAX')
3283
-            ? EE_ADMIN_TEMPLATE . 'admin_wrapper.template.php'
3284
-            : EE_ADMIN_TEMPLATE
3285
-              . 'admin_wrapper_ajax.template.php';
3286
-        //about page?
3287
-        $template_path = $about
3288
-            ? EE_ADMIN_TEMPLATE . 'about_admin_wrapper.template.php'
3289
-            : $template_path;
3290
-        if (defined('DOING_AJAX')) {
3291
-            $this->_template_args['admin_page_content'] = EEH_Template::display_template(
3292
-                $template_path,
3293
-                $this->_template_args,
3294
-                true
3295
-            );
3296
-            $this->_return_json();
3297
-        } else {
3298
-            EEH_Template::display_template($template_path, $this->_template_args);
3299
-        }
3300
-    }
3301
-
3302
-
3303
-
3304
-    /**
3305
-     * This returns the admin_nav tabs html using the configuration in the _nav_tabs property
3306
-     *
3307
-     * @return string html
3308
-     * @throws EE_Error
3309
-     */
3310
-    protected function _get_main_nav_tabs()
3311
-    {
3312
-        // let's generate the html using the EEH_Tabbed_Content helper.
3313
-        // We do this here so that it's possible for child classes to add in nav tabs dynamically at the last minute
3314
-        // (rather than setting in the page_routes array)
3315
-        return EEH_Tabbed_Content::display_admin_nav_tabs($this->_nav_tabs);
3316
-    }
3317
-
3318
-
3319
-
3320
-    /**
3321
-     *        sort nav tabs
3322
-     *
3323
-     * @param $a
3324
-     * @param $b
3325
-     * @return int
3326
-     */
3327
-    private function _sort_nav_tabs($a, $b)
3328
-    {
3329
-        if ($a['order'] === $b['order']) {
3330
-            return 0;
3331
-        }
3332
-        return ($a['order'] < $b['order']) ? -1 : 1;
3333
-    }
3334
-
3335
-
3336
-
3337
-    /**
3338
-     *    generates HTML for the forms used on admin pages
3339
-     *
3340
-     * @param    array $input_vars - array of input field details
3341
-     * @param string   $generator  (options are 'string' or 'array', basically use this to indicate which generator to
3342
-     *                             use)
3343
-     * @param bool     $id
3344
-     * @return string
3345
-     * @uses   EEH_Form_Fields::get_form_fields (/helper/EEH_Form_Fields.helper.php)
3346
-     * @uses   EEH_Form_Fields::get_form_fields_array (/helper/EEH_Form_Fields.helper.php)
3347
-     */
3348
-    protected function _generate_admin_form_fields($input_vars = array(), $generator = 'string', $id = false)
3349
-    {
3350
-        $content = $generator === 'string'
3351
-            ? EEH_Form_Fields::get_form_fields($input_vars, $id)
3352
-            : EEH_Form_Fields::get_form_fields_array($input_vars);
3353
-        return $content;
3354
-    }
3355
-
3356
-
3357
-
3358
-    /**
3359
-     * generates the "Save" and "Save & Close" buttons for edit forms
3360
-     *
3361
-     * @param bool             $both     if true then both buttons will be generated.  If false then just the "Save &
3362
-     *                                   Close" button.
3363
-     * @param array            $text     if included, generator will use the given text for the buttons ( array([0] =>
3364
-     *                                   'Save', [1] => 'save & close')
3365
-     * @param array            $actions  if included allows us to set the actions that each button will carry out (i.e.
3366
-     *                                   via the "name" value in the button).  We can also use this to just dump
3367
-     *                                   default actions by submitting some other value.
3368
-     * @param bool|string|null $referrer if false then we just do the default action on save and close.  Other wise it
3369
-     *                                   will use the $referrer string. IF null, then we don't do ANYTHING on save and
3370
-     *                                   close (normal form handling).
3371
-     */
3372
-    protected function _set_save_buttons($both = true, $text = array(), $actions = array(), $referrer = null)
3373
-    {
3374
-        //make sure $text and $actions are in an array
3375
-        $text          = (array)$text;
3376
-        $actions       = (array)$actions;
3377
-        $referrer_url  = empty($referrer)
3378
-            ? '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="'
3379
-              . $_SERVER['REQUEST_URI']
3380
-              . '" />'
3381
-            : '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="'
3382
-              . $referrer
3383
-              . '" />';
3384
-        $button_text   = ! empty($text)
3385
-            ? $text
3386
-            : array(
3387
-                esc_html__('Save', 'event_espresso'),
3388
-                esc_html__('Save and Close', 'event_espresso'),
3389
-            );
3390
-        $default_names = array('save', 'save_and_close');
3391
-        //add in a hidden index for the current page (so save and close redirects properly)
3392
-        $this->_template_args['save_buttons'] = $referrer_url;
3393
-        foreach ($button_text as $key => $button) {
3394
-            $ref                                  = $default_names[$key];
3395
-            $this->_template_args['save_buttons'] .= '<input type="submit" class="button-primary '
3396
-                                                     . $ref
3397
-                                                     . '" value="'
3398
-                                                     . $button
3399
-                                                     . '" name="'
3400
-                                                     . (! empty($actions) ? $actions[$key] : $ref)
3401
-                                                     . '" id="'
3402
-                                                     . $this->_current_view . '_' . $ref
3403
-                                                     . '" />';
3404
-            if (! $both) {
3405
-                break;
3406
-            }
3407
-        }
3408
-    }
3409
-
3410
-
3411
-
3412
-    /**
3413
-     * Wrapper for the protected function.  Allows plugins/addons to call this to set the form tags.
3414
-     *
3415
-     * @see   $this->_set_add_edit_form_tags() for details on params
3416
-     * @since 4.6.0
3417
-     * @param string $route
3418
-     * @param array  $additional_hidden_fields
3419
-     */
3420
-    public function set_add_edit_form_tags($route = '', $additional_hidden_fields = array())
3421
-    {
3422
-        $this->_set_add_edit_form_tags($route, $additional_hidden_fields);
3423
-    }
3424
-
3425
-
3426
-
3427
-    /**
3428
-     * set form open and close tags on add/edit pages.
3429
-     *
3430
-     * @param string $route                    the route you want the form to direct to
3431
-     * @param array  $additional_hidden_fields any additional hidden fields required in the form header
3432
-     * @return void
3433
-     */
3434
-    protected function _set_add_edit_form_tags($route = '', $additional_hidden_fields = array())
3435
-    {
3436
-        if (empty($route)) {
3437
-            $user_msg = esc_html__(
3438
-                'An error occurred. No action was set for this page\'s form.',
3439
-                'event_espresso'
3440
-            );
3441
-            $dev_msg  = $user_msg . "\n" . sprintf(
3442
-                    esc_html__('The $route argument is required for the %s->%s method.', 'event_espresso'),
3443
-                    __FUNCTION__,
3444
-                    __CLASS__
3445
-                );
3446
-            EE_Error::add_error($user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
3447
-        }
3448
-        // open form
3449
-        $this->_template_args['before_admin_page_content'] = '<form name="form" method="post" action="'
3450
-                                                             . $this->_admin_base_url
3451
-                                                             . '" id="'
3452
-                                                             . $route
3453
-                                                             . '_event_form" >';
3454
-        // add nonce
3455
-        $nonce = wp_nonce_field($route . '_nonce', $route . '_nonce', false, false);
3456
-        //		$nonce = wp_nonce_field( $route . '_nonce', '_wpnonce', FALSE, FALSE );
3457
-        $this->_template_args['before_admin_page_content'] .= "\n\t" . $nonce;
3458
-        // add REQUIRED form action
3459
-        $hidden_fields = array(
3460
-            'action' => array('type' => 'hidden', 'value' => $route),
3461
-        );
3462
-        // merge arrays
3463
-        $hidden_fields = is_array($additional_hidden_fields)
3464
-            ? array_merge($hidden_fields, $additional_hidden_fields)
3465
-            : $hidden_fields;
3466
-        // generate form fields
3467
-        $form_fields = $this->_generate_admin_form_fields($hidden_fields, 'array');
3468
-        // add fields to form
3469
-        foreach ((array)$form_fields as $field_name => $form_field) {
3470
-            $this->_template_args['before_admin_page_content'] .= "\n\t" . $form_field['field'];
3471
-        }
3472
-        // close form
3473
-        $this->_template_args['after_admin_page_content'] = '</form>';
3474
-    }
3475
-
3476
-
3477
-
3478
-    /**
3479
-     * Public Wrapper for _redirect_after_action() method since its
3480
-     * discovered it would be useful for external code to have access.
3481
-     *
3482
-     * @see   EE_Admin_Page::_redirect_after_action() for params.
3483
-     * @since 4.5.0
3484
-     * @param bool   $success
3485
-     * @param string $what
3486
-     * @param string $action_desc
3487
-     * @param array  $query_args
3488
-     * @param bool   $override_overwrite
3489
-     * @throws EE_Error
3490
-     */
3491
-    public function redirect_after_action(
3492
-        $success = false,
3493
-        $what = 'item',
3494
-        $action_desc = 'processed',
3495
-        $query_args = array(),
3496
-        $override_overwrite = false
3497
-    ) {
3498
-        $this->_redirect_after_action(
3499
-            $success,
3500
-            $what,
3501
-            $action_desc,
3502
-            $query_args,
3503
-            $override_overwrite
3504
-        );
3505
-    }
3506
-
3507
-
3508
-
3509
-    /**
3510
-     *    _redirect_after_action
3511
-     *
3512
-     * @param int    $success            - whether success was for two or more records, or just one, or none
3513
-     * @param string $what               - what the action was performed on
3514
-     * @param string $action_desc        - what was done ie: updated, deleted, etc
3515
-     * @param array  $query_args         - an array of query_args to be added to the URL to redirect to after the admin
3516
-     *                                   action is completed
3517
-     * @param BOOL   $override_overwrite by default all EE_Error::success messages are overwritten, this allows you to
3518
-     *                                   override this so that they show.
3519
-     * @return void
3520
-     * @throws EE_Error
3521
-     */
3522
-    protected function _redirect_after_action(
3523
-        $success = 0,
3524
-        $what = 'item',
3525
-        $action_desc = 'processed',
3526
-        $query_args = array(),
3527
-        $override_overwrite = false
3528
-    ) {
3529
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3530
-        //class name for actions/filters.
3531
-        $classname = get_class($this);
3532
-        // set redirect url.
3533
-        // Note if there is a "page" index in the $query_args then we go with vanilla admin.php route,
3534
-        // otherwise we go with whatever is set as the _admin_base_url
3535
-        $redirect_url = isset($query_args['page']) ? admin_url('admin.php') : $this->_admin_base_url;
3536
-        $notices      = EE_Error::get_notices(false);
3537
-        // overwrite default success messages //BUT ONLY if overwrite not overridden
3538
-        if (! $override_overwrite || ! empty($notices['errors'])) {
3539
-            EE_Error::overwrite_success();
3540
-        }
3541
-        if (! empty($what) && ! empty($action_desc)  && empty($notices['errors'])) {
3542
-            // how many records affected ? more than one record ? or just one ?
3543
-            if ($success > 1) {
3544
-                // set plural msg
3545
-                EE_Error::add_success(
3546
-                    sprintf(
3547
-                        esc_html__('The "%s" have been successfully %s.', 'event_espresso'),
3548
-                        $what,
3549
-                        $action_desc
3550
-                    ),
3551
-                    __FILE__,
3552
-                    __FUNCTION__,
3553
-                    __LINE__
3554
-                );
3555
-            } elseif ($success === 1) {
3556
-                // set singular msg
3557
-                EE_Error::add_success(
3558
-                    sprintf(
3559
-                        esc_html__('The "%s" has been successfully %s.', 'event_espresso'),
3560
-                        $what,
3561
-                        $action_desc
3562
-                    ),
3563
-                    __FILE__,
3564
-                    __FUNCTION__,
3565
-                    __LINE__
3566
-                );
3567
-            }
3568
-        }
3569
-        // check that $query_args isn't something crazy
3570
-        if (! is_array($query_args)) {
3571
-            $query_args = array();
3572
-        }
3573
-        /**
3574
-         * Allow injecting actions before the query_args are modified for possible different
3575
-         * redirections on save and close actions
3576
-         *
3577
-         * @since 4.2.0
3578
-         * @param array $query_args       The original query_args array coming into the
3579
-         *                                method.
3580
-         */
3581
-        do_action(
3582
-            "AHEE__{$classname}___redirect_after_action__before_redirect_modification_{$this->_req_action}",
3583
-            $query_args
3584
-        );
3585
-        //calculate where we're going (if we have a "save and close" button pushed)
3586
-        if (isset($this->_req_data['save_and_close'], $this->_req_data['save_and_close_referrer'])) {
3587
-            // even though we have the save_and_close referrer, we need to parse the url for the action in order to generate a nonce
3588
-            $parsed_url = parse_url($this->_req_data['save_and_close_referrer']);
3589
-            // regenerate query args array from referrer URL
3590
-            parse_str($parsed_url['query'], $query_args);
3591
-            // correct page and action will be in the query args now
3592
-            $redirect_url = admin_url('admin.php');
3593
-        }
3594
-        //merge any default query_args set in _default_route_query_args property
3595
-        if (! empty($this->_default_route_query_args) && ! $this->_is_UI_request) {
3596
-            $args_to_merge = array();
3597
-            foreach ($this->_default_route_query_args as $query_param => $query_value) {
3598
-                //is there a wp_referer array in our _default_route_query_args property?
3599
-                if ($query_param === 'wp_referer') {
3600
-                    $query_value = (array)$query_value;
3601
-                    foreach ($query_value as $reference => $value) {
3602
-                        if (strpos($reference, 'nonce') !== false) {
3603
-                            continue;
3604
-                        }
3605
-                        //finally we will override any arguments in the referer with
3606
-                        //what might be set on the _default_route_query_args array.
3607
-                        if (isset($this->_default_route_query_args[$reference])) {
3608
-                            $args_to_merge[$reference] = urlencode($this->_default_route_query_args[$reference]);
3609
-                        } else {
3610
-                            $args_to_merge[$reference] = urlencode($value);
3611
-                        }
3612
-                    }
3613
-                    continue;
3614
-                }
3615
-                $args_to_merge[$query_param] = $query_value;
3616
-            }
3617
-            //now let's merge these arguments but override with what was specifically sent in to the
3618
-            //redirect.
3619
-            $query_args = array_merge($args_to_merge, $query_args);
3620
-        }
3621
-        $this->_process_notices($query_args);
3622
-        // generate redirect url
3623
-        // if redirecting to anything other than the main page, add a nonce
3624
-        if (isset($query_args['action'])) {
3625
-            // manually generate wp_nonce and merge that with the query vars
3626
-            // becuz the wp_nonce_url function wrecks havoc on some vars
3627
-            $query_args['_wpnonce'] = wp_create_nonce($query_args['action'] . '_nonce');
3628
-        }
3629
-        // we're adding some hooks and filters in here for processing any things just before redirects
3630
-        // (example: an admin page has done an insert or update and we want to run something after that).
3631
-        do_action('AHEE_redirect_' . $classname . $this->_req_action, $query_args);
3632
-        $redirect_url = apply_filters(
3633
-            'FHEE_redirect_' . $classname . $this->_req_action,
3634
-            self::add_query_args_and_nonce($query_args, $redirect_url),
3635
-            $query_args
3636
-        );
3637
-        // check if we're doing ajax.  If we are then lets just return the results and js can handle how it wants.
3638
-        if (defined('DOING_AJAX')) {
3639
-            $default_data                    = array(
3640
-                'close'        => true,
3641
-                'redirect_url' => $redirect_url,
3642
-                'where'        => 'main',
3643
-                'what'         => 'append',
3644
-            );
3645
-            $this->_template_args['success'] = $success;
3646
-            $this->_template_args['data']    = ! empty($this->_template_args['data']) ? array_merge(
3647
-                $default_data,
3648
-                $this->_template_args['data']
3649
-            ) : $default_data;
3650
-            $this->_return_json();
3651
-        }
3652
-        wp_safe_redirect($redirect_url);
3653
-        exit();
3654
-    }
3655
-
3656
-
3657
-
3658
-    /**
3659
-     * process any notices before redirecting (or returning ajax request)
3660
-     * This method sets the $this->_template_args['notices'] attribute;
3661
-     *
3662
-     * @param  array $query_args        any query args that need to be used for notice transient ('action')
3663
-     * @param bool   $skip_route_verify This is typically used when we are processing notices REALLY early and
3664
-     *                                  page_routes haven't been defined yet.
3665
-     * @param bool   $sticky_notices    This is used to flag that regardless of whether this is doing_ajax or not, we
3666
-     *                                  still save a transient for the notice.
3667
-     * @return void
3668
-     * @throws EE_Error
3669
-     */
3670
-    protected function _process_notices($query_args = array(), $skip_route_verify = false, $sticky_notices = true)
3671
-    {
3672
-        //first let's set individual error properties if doing_ajax and the properties aren't already set.
3673
-        if (defined('DOING_AJAX') && DOING_AJAX) {
3674
-            $notices = EE_Error::get_notices(false);
3675
-            if (empty($this->_template_args['success'])) {
3676
-                $this->_template_args['success'] = isset($notices['success']) ? $notices['success'] : false;
3677
-            }
3678
-            if (empty($this->_template_args['errors'])) {
3679
-                $this->_template_args['errors'] = isset($notices['errors']) ? $notices['errors'] : false;
3680
-            }
3681
-            if (empty($this->_template_args['attention'])) {
3682
-                $this->_template_args['attention'] = isset($notices['attention']) ? $notices['attention'] : false;
3683
-            }
3684
-        }
3685
-        $this->_template_args['notices'] = EE_Error::get_notices();
3686
-        //IF this isn't ajax we need to create a transient for the notices using the route (however, overridden if $sticky_notices == true)
3687
-        if (! defined('DOING_AJAX') || $sticky_notices) {
3688
-            $route = isset($query_args['action']) ? $query_args['action'] : 'default';
3689
-            $this->_add_transient(
3690
-                $route,
3691
-                $this->_template_args['notices'],
3692
-                true,
3693
-                $skip_route_verify
3694
-            );
3695
-        }
3696
-    }
3697
-
3698
-
3699
-
3700
-    /**
3701
-     * get_action_link_or_button
3702
-     * returns the button html for adding, editing, or deleting an item (depending on given type)
3703
-     *
3704
-     * @param string $action        use this to indicate which action the url is generated with.
3705
-     * @param string $type          accepted strings must be defined in the $_labels['button'] array(as the key)
3706
-     *                              property.
3707
-     * @param array  $extra_request if the button requires extra params you can include them in $key=>$value pairs.
3708
-     * @param string $class         Use this to give the class for the button. Defaults to 'button-primary'
3709
-     * @param string $base_url      If this is not provided
3710
-     *                              the _admin_base_url will be used as the default for the button base_url.
3711
-     *                              Otherwise this value will be used.
3712
-     * @param bool   $exclude_nonce If true then no nonce will be in the generated button link.
3713
-     * @return string
3714
-     * @throws InvalidArgumentException
3715
-     * @throws InvalidInterfaceException
3716
-     * @throws InvalidDataTypeException
3717
-     * @throws EE_Error
3718
-     */
3719
-    public function get_action_link_or_button(
3720
-        $action,
3721
-        $type = 'add',
3722
-        $extra_request = array(),
3723
-        $class = 'button-primary',
3724
-        $base_url = '',
3725
-        $exclude_nonce = false
3726
-    ) {
3727
-        //first let's validate the action (if $base_url is FALSE otherwise validation will happen further along)
3728
-        if (empty($base_url) && ! isset($this->_page_routes[$action])) {
3729
-            throw new EE_Error(
3730
-                sprintf(
3731
-                    esc_html__(
3732
-                        'There is no page route for given action for the button.  This action was given: %s',
3733
-                        'event_espresso'
3734
-                    ),
3735
-                    $action
3736
-                )
3737
-            );
3738
-        }
3739
-        if (! isset($this->_labels['buttons'][$type])) {
3740
-            throw new EE_Error(
3741
-                sprintf(
3742
-                    __(
3743
-                        'There is no label for the given button type (%s). Labels are set in the <code>_page_config</code> property.',
3744
-                        'event_espresso'
3745
-                    ),
3746
-                    $type
3747
-                )
3748
-            );
3749
-        }
3750
-        //finally check user access for this button.
3751
-        $has_access = $this->check_user_access($action, true);
3752
-        if (! $has_access) {
3753
-            return '';
3754
-        }
3755
-        $_base_url  = ! $base_url ? $this->_admin_base_url : $base_url;
3756
-        $query_args = array(
3757
-            'action' => $action,
3758
-        );
3759
-        //merge extra_request args but make sure our original action takes precedence and doesn't get overwritten.
3760
-        if (! empty($extra_request)) {
3761
-            $query_args = array_merge($extra_request, $query_args);
3762
-        }
3763
-        $url = self::add_query_args_and_nonce($query_args, $_base_url, false, $exclude_nonce);
3764
-        return EEH_Template::get_button_or_link($url, $this->_labels['buttons'][$type], $class);
3765
-    }
3766
-
3767
-
3768
-
3769
-    /**
3770
-     * _per_page_screen_option
3771
-     * Utility function for adding in a per_page_option in the screen_options_dropdown.
3772
-     *
3773
-     * @return void
3774
-     * @throws InvalidArgumentException
3775
-     * @throws InvalidInterfaceException
3776
-     * @throws InvalidDataTypeException
3777
-     */
3778
-    protected function _per_page_screen_option()
3779
-    {
3780
-        $option = 'per_page';
3781
-        $args   = array(
3782
-            'label'   => esc_html__(
3783
-                    apply_filters(
3784
-                        'FHEE__EE_Admin_Page___per_page_screen_options___label',
3785
-                        $this->_admin_page_title,
3786
-                        $this
3787
-                    )
3788
-            ),
3789
-            'default' => (int) apply_filters(
3790
-                    'FHEE__EE_Admin_Page___per_page_screen_options__default',
3791
-                    10
3792
-            ),
3793
-            'option'  => $this->_current_page . '_' . $this->_current_view . '_per_page',
3794
-        );
3795
-        //ONLY add the screen option if the user has access to it.
3796
-        if ($this->check_user_access($this->_current_view, true)) {
3797
-            add_screen_option($option, $args);
3798
-        }
3799
-    }
3800
-
3801
-
3802
-
3803
-    /**
3804
-     * set_per_page_screen_option
3805
-     * All this does is make sure that WordPress saves any per_page screen options (if set) for the current page.
3806
-     * we have to do this rather than running inside the 'set-screen-options' hook because it runs earlier than
3807
-     * admin_menu.
3808
-     *
3809
-     * @return void
3810
-     */
3811
-    private function _set_per_page_screen_options()
3812
-    {
3813
-        if (isset($_POST['wp_screen_options']) && is_array($_POST['wp_screen_options'])) {
3814
-            check_admin_referer('screen-options-nonce', 'screenoptionnonce');
3815
-            if (! $user = wp_get_current_user()) {
3816
-                return;
3817
-            }
3818
-            $option = $_POST['wp_screen_options']['option'];
3819
-            $value  = $_POST['wp_screen_options']['value'];
3820
-            if ($option != sanitize_key($option)) {
3821
-                return;
3822
-            }
3823
-            $map_option = $option;
3824
-            $option     = str_replace('-', '_', $option);
3825
-            switch ($map_option) {
3826
-                case $this->_current_page . '_' . $this->_current_view . '_per_page':
3827
-                    $value = (int)$value;
3828
-                    $max_value = apply_filters(
3829
-                        'FHEE__EE_Admin_Page___set_per_page_screen_options__max_value',
3830
-                        999,
3831
-                        $this->_current_page,
3832
-                        $this->_current_view
3833
-                    );
3834
-                    if ($value < 1) {
3835
-                        return;
3836
-                    }
3837
-                    $value = min($value, $max_value);
3838
-                    break;
3839
-                default:
3840
-                    $value = apply_filters(
3841
-                        'FHEE__EE_Admin_Page___set_per_page_screen_options__value',
3842
-                        false,
3843
-                        $option,
3844
-                        $value
3845
-                    );
3846
-                    if (false === $value) {
3847
-                        return;
3848
-                    }
3849
-                    break;
3850
-            }
3851
-            update_user_meta($user->ID, $option, $value);
3852
-            wp_safe_redirect(remove_query_arg(array('pagenum', 'apage', 'paged'), wp_get_referer()));
3853
-            exit;
3854
-        }
3855
-    }
3856
-
3857
-
3858
-
3859
-    /**
3860
-     * This just allows for setting the $_template_args property if it needs to be set outside the object
3861
-     *
3862
-     * @param array $data array that will be assigned to template args.
3863
-     */
3864
-    public function set_template_args($data)
3865
-    {
3866
-        $this->_template_args = array_merge($this->_template_args, (array)$data);
3867
-    }
3868
-
3869
-
3870
-
3871
-    /**
3872
-     * This makes available the WP transient system for temporarily moving data between routes
3873
-     *
3874
-     * @param string $route             the route that should receive the transient
3875
-     * @param array  $data              the data that gets sent
3876
-     * @param bool   $notices           If this is for notices then we use this to indicate so, otherwise its just a
3877
-     *                                  normal route transient.
3878
-     * @param bool   $skip_route_verify Used to indicate we want to skip route verification.  This is usually ONLY used
3879
-     *                                  when we are adding a transient before page_routes have been defined.
3880
-     * @return void
3881
-     * @throws EE_Error
3882
-     */
3883
-    protected function _add_transient($route, $data, $notices = false, $skip_route_verify = false)
3884
-    {
3885
-        $user_id = get_current_user_id();
3886
-        if (! $skip_route_verify) {
3887
-            $this->_verify_route($route);
3888
-        }
3889
-        //now let's set the string for what kind of transient we're setting
3890
-        $transient = $notices
3891
-            ? 'ee_rte_n_tx_' . $route . '_' . $user_id
3892
-            : 'rte_tx_' . $route . '_' . $user_id;
3893
-        $data      = $notices ? array('notices' => $data) : $data;
3894
-        //is there already a transient for this route?  If there is then let's ADD to that transient
3895
-        $existing = is_multisite() && is_network_admin()
3896
-            ? get_site_transient($transient)
3897
-            : get_transient($transient);
3898
-        if ($existing) {
3899
-            $data = array_merge((array)$data, (array)$existing);
3900
-        }
3901
-        if (is_multisite() && is_network_admin()) {
3902
-            set_site_transient($transient, $data, 8);
3903
-        } else {
3904
-            set_transient($transient, $data, 8);
3905
-        }
3906
-    }
3907
-
3908
-
3909
-
3910
-    /**
3911
-     * this retrieves the temporary transient that has been set for moving data between routes.
3912
-     *
3913
-     * @param bool   $notices true we get notices transient. False we just return normal route transient
3914
-     * @param string $route
3915
-     * @return mixed data
3916
-     */
3917
-    protected function _get_transient($notices = false, $route = '')
3918
-    {
3919
-        $user_id   = get_current_user_id();
3920
-        $route     = ! $route ? $this->_req_action : $route;
3921
-        $transient = $notices
3922
-            ? 'ee_rte_n_tx_' . $route . '_' . $user_id
3923
-            : 'rte_tx_' . $route . '_' . $user_id;
3924
-        $data      = is_multisite() && is_network_admin()
3925
-            ? get_site_transient($transient)
3926
-            : get_transient($transient);
3927
-        //delete transient after retrieval (just in case it hasn't expired);
3928
-        if (is_multisite() && is_network_admin()) {
3929
-            delete_site_transient($transient);
3930
-        } else {
3931
-            delete_transient($transient);
3932
-        }
3933
-        return $notices && isset($data['notices']) ? $data['notices'] : $data;
3934
-    }
3935
-
3936
-
3937
-
3938
-    /**
3939
-     * The purpose of this method is just to run garbage collection on any EE transients that might have expired but
3940
-     * would not be called later. This will be assigned to run on a specific EE Admin page. (place the method in the
3941
-     * default route callback on the EE_Admin page you want it run.)
3942
-     *
3943
-     * @return void
3944
-     */
3945
-    protected function _transient_garbage_collection()
3946
-    {
3947
-        global $wpdb;
3948
-        //retrieve all existing transients
3949
-        $query = "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '%rte_tx_%' OR option_name LIKE '%rte_n_tx_%'";
3950
-        if ($results = $wpdb->get_results($query)) {
3951
-            foreach ($results as $result) {
3952
-                $transient = str_replace('_transient_', '', $result->option_name);
3953
-                get_transient($transient);
3954
-                if (is_multisite() && is_network_admin()) {
3955
-                    get_site_transient($transient);
3956
-                }
3957
-            }
3958
-        }
3959
-    }
3960
-
3961
-
3962
-
3963
-    /**
3964
-     * get_view
3965
-     *
3966
-     * @return string content of _view property
3967
-     */
3968
-    public function get_view()
3969
-    {
3970
-        return $this->_view;
3971
-    }
3972
-
3973
-
3974
-
3975
-    /**
3976
-     * getter for the protected $_views property
3977
-     *
3978
-     * @return array
3979
-     */
3980
-    public function get_views()
3981
-    {
3982
-        return $this->_views;
3983
-    }
3984
-
3985
-
3986
-
3987
-    /**
3988
-     * get_current_page
3989
-     *
3990
-     * @return string _current_page property value
3991
-     */
3992
-    public function get_current_page()
3993
-    {
3994
-        return $this->_current_page;
3995
-    }
3996
-
3997
-
3998
-
3999
-    /**
4000
-     * get_current_view
4001
-     *
4002
-     * @return string _current_view property value
4003
-     */
4004
-    public function get_current_view()
4005
-    {
4006
-        return $this->_current_view;
4007
-    }
4008
-
4009
-
4010
-
4011
-    /**
4012
-     * get_current_screen
4013
-     *
4014
-     * @return object The current WP_Screen object
4015
-     */
4016
-    public function get_current_screen()
4017
-    {
4018
-        return $this->_current_screen;
4019
-    }
4020
-
4021
-
4022
-
4023
-    /**
4024
-     * get_current_page_view_url
4025
-     *
4026
-     * @return string This returns the url for the current_page_view.
4027
-     */
4028
-    public function get_current_page_view_url()
4029
-    {
4030
-        return $this->_current_page_view_url;
4031
-    }
4032
-
4033
-
4034
-
4035
-    /**
4036
-     * just returns the _req_data property
4037
-     *
4038
-     * @return array
4039
-     */
4040
-    public function get_request_data()
4041
-    {
4042
-        return $this->_req_data;
4043
-    }
4044
-
4045
-
4046
-
4047
-    /**
4048
-     * returns the _req_data protected property
4049
-     *
4050
-     * @return string
4051
-     */
4052
-    public function get_req_action()
4053
-    {
4054
-        return $this->_req_action;
4055
-    }
4056
-
4057
-
4058
-
4059
-    /**
4060
-     * @return bool  value of $_is_caf property
4061
-     */
4062
-    public function is_caf()
4063
-    {
4064
-        return $this->_is_caf;
4065
-    }
4066
-
4067
-
4068
-
4069
-    /**
4070
-     * @return mixed
4071
-     */
4072
-    public function default_espresso_metaboxes()
4073
-    {
4074
-        return $this->_default_espresso_metaboxes;
4075
-    }
4076
-
4077
-
4078
-
4079
-    /**
4080
-     * @return mixed
4081
-     */
4082
-    public function admin_base_url()
4083
-    {
4084
-        return $this->_admin_base_url;
4085
-    }
2775
+	}
2776
+
2777
+
2778
+
2779
+	/**
2780
+	 * facade for add_meta_box
2781
+	 *
2782
+	 * @param string  $action        where the metabox get's displayed
2783
+	 * @param string  $title         Title of Metabox (output in metabox header)
2784
+	 * @param string  $callback      If not empty and $create_fun is set to false then we'll use a custom callback
2785
+	 *                               instead of the one created in here.
2786
+	 * @param array   $callback_args an array of args supplied for the metabox
2787
+	 * @param string  $column        what metabox column
2788
+	 * @param string  $priority      give this metabox a priority (using accepted priorities for wp meta boxes)
2789
+	 * @param boolean $create_func   default is true.  Basically we can say we don't WANT to have the runtime function
2790
+	 *                               created but just set our own callback for wp's add_meta_box.
2791
+	 * @throws \DomainException
2792
+	 */
2793
+	public function _add_admin_page_meta_box(
2794
+		$action,
2795
+		$title,
2796
+		$callback,
2797
+		$callback_args,
2798
+		$column = 'normal',
2799
+		$priority = 'high',
2800
+		$create_func = true
2801
+	) {
2802
+		do_action('AHEE_log', __FILE__, __FUNCTION__, $callback);
2803
+		//if we have empty callback args and we want to automatically create the metabox callback then we need to make sure the callback args are generated.
2804
+		if (empty($callback_args) && $create_func) {
2805
+			$callback_args = array(
2806
+				'template_path' => $this->_template_path,
2807
+				'template_args' => $this->_template_args,
2808
+			);
2809
+		}
2810
+		//if $create_func is true (default) then we automatically create the function for displaying the actual meta box.  If false then we take the $callback reference passed through and use it instead (so callers can define their own callback function/method if they wish)
2811
+		$call_back_func = $create_func
2812
+			? function ($post, $metabox)
2813
+			{
2814
+				do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2815
+				echo EEH_Template::display_template(
2816
+					$metabox['args']['template_path'],
2817
+					$metabox['args']['template_args'],
2818
+					true
2819
+				);
2820
+			}
2821
+			: $callback;
2822
+		add_meta_box(
2823
+			str_replace('_', '-', $action) . '-mbox',
2824
+			$title,
2825
+			$call_back_func,
2826
+			$this->_wp_page_slug,
2827
+			$column,
2828
+			$priority,
2829
+			$callback_args
2830
+		);
2831
+	}
2832
+
2833
+
2834
+
2835
+	/**
2836
+	 * generates HTML wrapper for and admin details page that contains metaboxes in columns
2837
+	 *
2838
+	 * @throws DomainException
2839
+	 * @throws EE_Error
2840
+	 */
2841
+	public function display_admin_page_with_metabox_columns()
2842
+	{
2843
+		$this->_template_args['post_body_content']  = $this->_template_args['admin_page_content'];
2844
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
2845
+			$this->_column_template_path,
2846
+			$this->_template_args,
2847
+			true
2848
+		);
2849
+		//the final wrapper
2850
+		$this->admin_page_wrapper();
2851
+	}
2852
+
2853
+
2854
+
2855
+	/**
2856
+	 * generates  HTML wrapper for an admin details page
2857
+	 *
2858
+	 * @return void
2859
+	 * @throws EE_Error
2860
+	 * @throws DomainException
2861
+	 */
2862
+	public function display_admin_page_with_sidebar()
2863
+	{
2864
+		$this->_display_admin_page(true);
2865
+	}
2866
+
2867
+
2868
+
2869
+	/**
2870
+	 * generates  HTML wrapper for an admin details page (except no sidebar)
2871
+	 *
2872
+	 * @return void
2873
+	 * @throws EE_Error
2874
+	 * @throws DomainException
2875
+	 */
2876
+	public function display_admin_page_with_no_sidebar()
2877
+	{
2878
+		$this->_display_admin_page();
2879
+	}
2880
+
2881
+
2882
+
2883
+	/**
2884
+	 * generates HTML wrapper for an EE about admin page (no sidebar)
2885
+	 *
2886
+	 * @return void
2887
+	 * @throws EE_Error
2888
+	 * @throws DomainException
2889
+	 */
2890
+	public function display_about_admin_page()
2891
+	{
2892
+		$this->_display_admin_page(false, true);
2893
+	}
2894
+
2895
+
2896
+
2897
+	/**
2898
+	 * display_admin_page
2899
+	 * contains the code for actually displaying an admin page
2900
+	 *
2901
+	 * @param  boolean $sidebar true with sidebar, false without
2902
+	 * @param  boolean $about   use the about admin wrapper instead of the default.
2903
+	 * @return void
2904
+	 * @throws DomainException
2905
+	 * @throws EE_Error
2906
+	 */
2907
+	private function _display_admin_page($sidebar = false, $about = false)
2908
+	{
2909
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2910
+		//custom remove metaboxes hook to add or remove any metaboxes to/from Admin pages.
2911
+		do_action('AHEE__EE_Admin_Page___display_admin_page__modify_metaboxes');
2912
+		// set current wp page slug - looks like: event-espresso_page_event_categories
2913
+		// keep in mind "event-espresso" COULD be something else if the top level menu label has been translated.
2914
+		$this->_template_args['current_page']              = $this->_wp_page_slug;
2915
+		$this->_template_args['admin_page_wrapper_div_id'] = $this->_cpt_route
2916
+			? 'poststuff'
2917
+			: 'espresso-default-admin';
2918
+		$template_path                                     = $sidebar
2919
+			? EE_ADMIN_TEMPLATE . 'admin_details_wrapper.template.php'
2920
+			: EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar.template.php';
2921
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2922
+			$template_path = EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar_ajax.template.php';
2923
+		}
2924
+		$template_path                                     = ! empty($this->_column_template_path)
2925
+			? $this->_column_template_path : $template_path;
2926
+		$this->_template_args['post_body_content']         = isset($this->_template_args['admin_page_content'])
2927
+			? $this->_template_args['admin_page_content']
2928
+			: '';
2929
+		$this->_template_args['before_admin_page_content'] = isset($this->_template_args['before_admin_page_content'])
2930
+			? $this->_template_args['before_admin_page_content']
2931
+			: '';
2932
+		$this->_template_args['after_admin_page_content']  = isset($this->_template_args['after_admin_page_content'])
2933
+			? $this->_template_args['after_admin_page_content']
2934
+			: '';
2935
+		$this->_template_args['admin_page_content']        = EEH_Template::display_template(
2936
+			$template_path,
2937
+			$this->_template_args,
2938
+			true
2939
+		);
2940
+		// the final template wrapper
2941
+		$this->admin_page_wrapper($about);
2942
+	}
2943
+
2944
+
2945
+
2946
+	/**
2947
+	 * This is used to display caf preview pages.
2948
+	 *
2949
+	 * @since 4.3.2
2950
+	 * @param string $utm_campaign_source what is the key used for google analytics link
2951
+	 * @param bool   $display_sidebar     whether to use the sidebar template or the full template for the page.  TRUE
2952
+	 *                                    = SHOW sidebar, FALSE = no sidebar. Default no sidebar.
2953
+	 * @return void
2954
+	 * @throws DomainException
2955
+	 * @throws EE_Error
2956
+	 * @throws InvalidArgumentException
2957
+	 * @throws InvalidDataTypeException
2958
+	 * @throws InvalidInterfaceException
2959
+	 */
2960
+	public function display_admin_caf_preview_page($utm_campaign_source = '', $display_sidebar = true)
2961
+	{
2962
+		//let's generate a default preview action button if there isn't one already present.
2963
+		$this->_labels['buttons']['buy_now']           = esc_html__(
2964
+			'Upgrade to Event Espresso 4 Right Now',
2965
+			'event_espresso'
2966
+		);
2967
+		$buy_now_url                                   = add_query_arg(
2968
+			array(
2969
+				'ee_ver'       => 'ee4',
2970
+				'utm_source'   => 'ee4_plugin_admin',
2971
+				'utm_medium'   => 'link',
2972
+				'utm_campaign' => $utm_campaign_source,
2973
+				'utm_content'  => 'buy_now_button',
2974
+			),
2975
+			'http://eventespresso.com/pricing/'
2976
+		);
2977
+		$this->_template_args['preview_action_button'] = ! isset($this->_template_args['preview_action_button'])
2978
+			? $this->get_action_link_or_button(
2979
+				'',
2980
+				'buy_now',
2981
+				array(),
2982
+				'button-primary button-large',
2983
+				$buy_now_url,
2984
+				true
2985
+			)
2986
+			: $this->_template_args['preview_action_button'];
2987
+		$this->_template_args['admin_page_content']    = EEH_Template::display_template(
2988
+			EE_ADMIN_TEMPLATE . 'admin_caf_full_page_preview.template.php',
2989
+			$this->_template_args,
2990
+			true
2991
+		);
2992
+		$this->_display_admin_page($display_sidebar);
2993
+	}
2994
+
2995
+
2996
+
2997
+	/**
2998
+	 * display_admin_list_table_page_with_sidebar
2999
+	 * generates HTML wrapper for an admin_page with list_table
3000
+	 *
3001
+	 * @return void
3002
+	 * @throws EE_Error
3003
+	 * @throws DomainException
3004
+	 */
3005
+	public function display_admin_list_table_page_with_sidebar()
3006
+	{
3007
+		$this->_display_admin_list_table_page(true);
3008
+	}
3009
+
3010
+
3011
+
3012
+	/**
3013
+	 * display_admin_list_table_page_with_no_sidebar
3014
+	 * generates HTML wrapper for an admin_page with list_table (but with no sidebar)
3015
+	 *
3016
+	 * @return void
3017
+	 * @throws EE_Error
3018
+	 * @throws DomainException
3019
+	 */
3020
+	public function display_admin_list_table_page_with_no_sidebar()
3021
+	{
3022
+		$this->_display_admin_list_table_page();
3023
+	}
3024
+
3025
+
3026
+
3027
+	/**
3028
+	 * generates html wrapper for an admin_list_table page
3029
+	 *
3030
+	 * @param boolean $sidebar whether to display with sidebar or not.
3031
+	 * @return void
3032
+	 * @throws DomainException
3033
+	 * @throws EE_Error
3034
+	 */
3035
+	private function _display_admin_list_table_page($sidebar = false)
3036
+	{
3037
+		//setup search attributes
3038
+		$this->_set_search_attributes();
3039
+		$this->_template_args['current_page']     = $this->_wp_page_slug;
3040
+		$template_path                            = EE_ADMIN_TEMPLATE . 'admin_list_wrapper.template.php';
3041
+		$this->_template_args['table_url']        = defined('DOING_AJAX')
3042
+			? add_query_arg(array('noheader' => 'true', 'route' => $this->_req_action), $this->_admin_base_url)
3043
+			: add_query_arg(array('route' => $this->_req_action), $this->_admin_base_url);
3044
+		$this->_template_args['list_table']       = $this->_list_table_object;
3045
+		$this->_template_args['current_route']    = $this->_req_action;
3046
+		$this->_template_args['list_table_class'] = get_class($this->_list_table_object);
3047
+		$ajax_sorting_callback                    = $this->_list_table_object->get_ajax_sorting_callback();
3048
+		if (! empty($ajax_sorting_callback)) {
3049
+			$sortable_list_table_form_fields = wp_nonce_field(
3050
+				$ajax_sorting_callback . '_nonce',
3051
+				$ajax_sorting_callback . '_nonce',
3052
+				false,
3053
+				false
3054
+			);
3055
+			//			$reorder_action = 'espresso_' . $ajax_sorting_callback . '_nonce';
3056
+			//			$sortable_list_table_form_fields = wp_nonce_field( $reorder_action, 'ajax_table_sort_nonce', FALSE, FALSE );
3057
+			$sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_page" name="ajax_table_sort_page" value="'
3058
+												. $this->page_slug
3059
+												. '" />';
3060
+			$sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_action" name="ajax_table_sort_action" value="'
3061
+												. $ajax_sorting_callback
3062
+												. '" />';
3063
+		} else {
3064
+			$sortable_list_table_form_fields = '';
3065
+		}
3066
+		$this->_template_args['sortable_list_table_form_fields'] = $sortable_list_table_form_fields;
3067
+		$hidden_form_fields                                      = isset($this->_template_args['list_table_hidden_fields'])
3068
+			? $this->_template_args['list_table_hidden_fields']
3069
+			: '';
3070
+		$nonce_ref                                               = $this->_req_action . '_nonce';
3071
+		$hidden_form_fields                                      .= '<input type="hidden" name="'
3072
+																	. $nonce_ref
3073
+																	. '" value="'
3074
+																	. wp_create_nonce($nonce_ref)
3075
+																	. '">';
3076
+		$this->_template_args['list_table_hidden_fields']        = $hidden_form_fields;
3077
+		//display message about search results?
3078
+		$this->_template_args['before_list_table'] .= ! empty($this->_req_data['s'])
3079
+			? '<p class="ee-search-results">' . sprintf(
3080
+				esc_html__('Displaying search results for the search string: %1$s', 'event_espresso'),
3081
+				trim($this->_req_data['s'], '%')
3082
+			) . '</p>'
3083
+			: '';
3084
+		// filter before_list_table template arg
3085
+		$this->_template_args['before_list_table'] = apply_filters(
3086
+			'FHEE__EE_Admin_Page___display_admin_list_table_page__before_list_table__template_arg',
3087
+			$this->_template_args['before_list_table'],
3088
+			$this->page_slug,
3089
+			$this->_req_data,
3090
+			$this->_req_action
3091
+		);
3092
+		// convert to array and filter again
3093
+		// arrays are easier to inject new items in a specific location,
3094
+		// but would not be backwards compatible, so we have to add a new filter
3095
+		$this->_template_args['before_list_table'] = implode(
3096
+			" \n",
3097
+			(array)apply_filters(
3098
+				'FHEE__EE_Admin_Page___display_admin_list_table_page__before_list_table__template_args_array',
3099
+				(array)$this->_template_args['before_list_table'],
3100
+				$this->page_slug,
3101
+				$this->_req_data,
3102
+				$this->_req_action
3103
+			)
3104
+		);
3105
+		// filter after_list_table template arg
3106
+		$this->_template_args['after_list_table'] = apply_filters(
3107
+			'FHEE__EE_Admin_Page___display_admin_list_table_page__after_list_table__template_arg',
3108
+			$this->_template_args['after_list_table'],
3109
+			$this->page_slug,
3110
+			$this->_req_data,
3111
+			$this->_req_action
3112
+		);
3113
+		// convert to array and filter again
3114
+		// arrays are easier to inject new items in a specific location,
3115
+		// but would not be backwards compatible, so we have to add a new filter
3116
+		$this->_template_args['after_list_table']   = implode(
3117
+			" \n",
3118
+			(array)apply_filters(
3119
+				'FHEE__EE_Admin_Page___display_admin_list_table_page__after_list_table__template_args_array',
3120
+				(array)$this->_template_args['after_list_table'],
3121
+				$this->page_slug,
3122
+				$this->_req_data,
3123
+				$this->_req_action
3124
+			)
3125
+		);
3126
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
3127
+			$template_path,
3128
+			$this->_template_args,
3129
+			true
3130
+		);
3131
+		// the final template wrapper
3132
+		if ($sidebar) {
3133
+			$this->display_admin_page_with_sidebar();
3134
+		} else {
3135
+			$this->display_admin_page_with_no_sidebar();
3136
+		}
3137
+	}
3138
+
3139
+
3140
+
3141
+	/**
3142
+	 * This just prepares a legend using the given items and the admin_details_legend.template.php file and returns the
3143
+	 * html string for the legend.
3144
+	 * $items are expected in an array in the following format:
3145
+	 * $legend_items = array(
3146
+	 *        'item_id' => array(
3147
+	 *            'icon' => 'http://url_to_icon_being_described.png',
3148
+	 *            'desc' => esc_html__('localized description of item');
3149
+	 *        )
3150
+	 * );
3151
+	 *
3152
+	 * @param  array $items see above for format of array
3153
+	 * @return string html string of legend
3154
+	 * @throws DomainException
3155
+	 */
3156
+	protected function _display_legend($items)
3157
+	{
3158
+		$this->_template_args['items'] = apply_filters(
3159
+			'FHEE__EE_Admin_Page___display_legend__items',
3160
+			(array)$items,
3161
+			$this
3162
+		);
3163
+		return EEH_Template::display_template(
3164
+			EE_ADMIN_TEMPLATE . 'admin_details_legend.template.php',
3165
+			$this->_template_args,
3166
+			true
3167
+		);
3168
+	}
3169
+
3170
+
3171
+	/**
3172
+	 * This is used whenever we're DOING_AJAX to return a formatted json array that our calling javascript can expect
3173
+	 * The returned json object is created from an array in the following format:
3174
+	 * array(
3175
+	 *  'error' => FALSE, //(default FALSE), contains any errors and/or exceptions (exceptions return json early),
3176
+	 *  'success' => FALSE, //(default FALSE) - contains any special success message.
3177
+	 *  'notices' => '', // - contains any EE_Error formatted notices
3178
+	 *  'content' => 'string can be html', //this is a string of formatted content (can be html)
3179
+	 *  'data' => array() //this can be any key/value pairs that a method returns for later json parsing by the js.
3180
+	 *  We're also going to include the template args with every package (so js can pick out any specific template args
3181
+	 *  that might be included in here)
3182
+	 * )
3183
+	 * The json object is populated by whatever is set in the $_template_args property.
3184
+	 *
3185
+	 * @param bool  $sticky_notices    Used to indicate whether you want to ensure notices are added to a transient
3186
+	 *                                 instead of displayed.
3187
+	 * @param array $notices_arguments Use this to pass any additional args on to the _process_notices.
3188
+	 * @return void
3189
+	 * @throws EE_Error
3190
+	 */
3191
+	protected function _return_json($sticky_notices = false, $notices_arguments = array())
3192
+	{
3193
+		//make sure any EE_Error notices have been handled.
3194
+		$this->_process_notices($notices_arguments, true, $sticky_notices);
3195
+		$data = isset($this->_template_args['data']) ? $this->_template_args['data'] : array();
3196
+		unset($this->_template_args['data']);
3197
+		$json = array(
3198
+			'error'     => isset($this->_template_args['error']) ? $this->_template_args['error'] : false,
3199
+			'success'   => isset($this->_template_args['success']) ? $this->_template_args['success'] : false,
3200
+			'errors'    => isset($this->_template_args['errors']) ? $this->_template_args['errors'] : false,
3201
+			'attention' => isset($this->_template_args['attention']) ? $this->_template_args['attention'] : false,
3202
+			'notices'   => EE_Error::get_notices(),
3203
+			'content'   => isset($this->_template_args['admin_page_content'])
3204
+				? $this->_template_args['admin_page_content'] : '',
3205
+			'data'      => array_merge($data, array('template_args' => $this->_template_args)),
3206
+			'isEEajax'  => true
3207
+			//special flag so any ajax.Success methods in js can identify this return package as a EEajax package.
3208
+		);
3209
+		// make sure there are no php errors or headers_sent.  Then we can set correct json header.
3210
+		if (null === error_get_last() || ! headers_sent()) {
3211
+			header('Content-Type: application/json; charset=UTF-8');
3212
+		}
3213
+		echo wp_json_encode($json);
3214
+		exit();
3215
+	}
3216
+
3217
+
3218
+
3219
+	/**
3220
+	 * Simply a wrapper for the protected method so we can call this outside the class (ONLY when doing ajax)
3221
+	 *
3222
+	 * @return void
3223
+	 * @throws EE_Error
3224
+	 */
3225
+	public function return_json()
3226
+	{
3227
+		if (defined('DOING_AJAX') && DOING_AJAX) {
3228
+			$this->_return_json();
3229
+		} else {
3230
+			throw new EE_Error(
3231
+				sprintf(
3232
+					esc_html__('The public %s method can only be called when DOING_AJAX = TRUE', 'event_espresso'),
3233
+					__FUNCTION__
3234
+				)
3235
+			);
3236
+		}
3237
+	}
3238
+
3239
+
3240
+
3241
+	/**
3242
+	 * This provides a way for child hook classes to send along themselves by reference so methods/properties within
3243
+	 * them can be accessed by EE_Admin_child pages. This is assigned to the $_hook_obj property.
3244
+	 *
3245
+	 * @param EE_Admin_Hooks $hook_obj This will be the object for the EE_Admin_Hooks child
3246
+	 */
3247
+	public function set_hook_object(EE_Admin_Hooks $hook_obj)
3248
+	{
3249
+		$this->_hook_obj = $hook_obj;
3250
+	}
3251
+
3252
+
3253
+
3254
+	/**
3255
+	 *        generates  HTML wrapper with Tabbed nav for an admin page
3256
+	 *
3257
+	 * @param  boolean $about whether to use the special about page wrapper or default.
3258
+	 * @return void
3259
+	 * @throws DomainException
3260
+	 * @throws EE_Error
3261
+	 */
3262
+	public function admin_page_wrapper($about = false)
3263
+	{
3264
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3265
+		$this->_nav_tabs                                   = $this->_get_main_nav_tabs();
3266
+		$this->_template_args['nav_tabs']                  = $this->_nav_tabs;
3267
+		$this->_template_args['admin_page_title']          = $this->_admin_page_title;
3268
+		$this->_template_args['before_admin_page_content'] = apply_filters(
3269
+			"FHEE_before_admin_page_content{$this->_current_page}{$this->_current_view}",
3270
+			isset($this->_template_args['before_admin_page_content'])
3271
+				? $this->_template_args['before_admin_page_content']
3272
+				: ''
3273
+		);
3274
+		$this->_template_args['after_admin_page_content']  = apply_filters(
3275
+			"FHEE_after_admin_page_content{$this->_current_page}{$this->_current_view}",
3276
+			isset($this->_template_args['after_admin_page_content'])
3277
+				? $this->_template_args['after_admin_page_content']
3278
+				: ''
3279
+		);
3280
+		$this->_template_args['after_admin_page_content']  .= $this->_set_help_popup_content();
3281
+		// load settings page wrapper template
3282
+		$template_path = ! defined('DOING_AJAX')
3283
+			? EE_ADMIN_TEMPLATE . 'admin_wrapper.template.php'
3284
+			: EE_ADMIN_TEMPLATE
3285
+			  . 'admin_wrapper_ajax.template.php';
3286
+		//about page?
3287
+		$template_path = $about
3288
+			? EE_ADMIN_TEMPLATE . 'about_admin_wrapper.template.php'
3289
+			: $template_path;
3290
+		if (defined('DOING_AJAX')) {
3291
+			$this->_template_args['admin_page_content'] = EEH_Template::display_template(
3292
+				$template_path,
3293
+				$this->_template_args,
3294
+				true
3295
+			);
3296
+			$this->_return_json();
3297
+		} else {
3298
+			EEH_Template::display_template($template_path, $this->_template_args);
3299
+		}
3300
+	}
3301
+
3302
+
3303
+
3304
+	/**
3305
+	 * This returns the admin_nav tabs html using the configuration in the _nav_tabs property
3306
+	 *
3307
+	 * @return string html
3308
+	 * @throws EE_Error
3309
+	 */
3310
+	protected function _get_main_nav_tabs()
3311
+	{
3312
+		// let's generate the html using the EEH_Tabbed_Content helper.
3313
+		// We do this here so that it's possible for child classes to add in nav tabs dynamically at the last minute
3314
+		// (rather than setting in the page_routes array)
3315
+		return EEH_Tabbed_Content::display_admin_nav_tabs($this->_nav_tabs);
3316
+	}
3317
+
3318
+
3319
+
3320
+	/**
3321
+	 *        sort nav tabs
3322
+	 *
3323
+	 * @param $a
3324
+	 * @param $b
3325
+	 * @return int
3326
+	 */
3327
+	private function _sort_nav_tabs($a, $b)
3328
+	{
3329
+		if ($a['order'] === $b['order']) {
3330
+			return 0;
3331
+		}
3332
+		return ($a['order'] < $b['order']) ? -1 : 1;
3333
+	}
3334
+
3335
+
3336
+
3337
+	/**
3338
+	 *    generates HTML for the forms used on admin pages
3339
+	 *
3340
+	 * @param    array $input_vars - array of input field details
3341
+	 * @param string   $generator  (options are 'string' or 'array', basically use this to indicate which generator to
3342
+	 *                             use)
3343
+	 * @param bool     $id
3344
+	 * @return string
3345
+	 * @uses   EEH_Form_Fields::get_form_fields (/helper/EEH_Form_Fields.helper.php)
3346
+	 * @uses   EEH_Form_Fields::get_form_fields_array (/helper/EEH_Form_Fields.helper.php)
3347
+	 */
3348
+	protected function _generate_admin_form_fields($input_vars = array(), $generator = 'string', $id = false)
3349
+	{
3350
+		$content = $generator === 'string'
3351
+			? EEH_Form_Fields::get_form_fields($input_vars, $id)
3352
+			: EEH_Form_Fields::get_form_fields_array($input_vars);
3353
+		return $content;
3354
+	}
3355
+
3356
+
3357
+
3358
+	/**
3359
+	 * generates the "Save" and "Save & Close" buttons for edit forms
3360
+	 *
3361
+	 * @param bool             $both     if true then both buttons will be generated.  If false then just the "Save &
3362
+	 *                                   Close" button.
3363
+	 * @param array            $text     if included, generator will use the given text for the buttons ( array([0] =>
3364
+	 *                                   'Save', [1] => 'save & close')
3365
+	 * @param array            $actions  if included allows us to set the actions that each button will carry out (i.e.
3366
+	 *                                   via the "name" value in the button).  We can also use this to just dump
3367
+	 *                                   default actions by submitting some other value.
3368
+	 * @param bool|string|null $referrer if false then we just do the default action on save and close.  Other wise it
3369
+	 *                                   will use the $referrer string. IF null, then we don't do ANYTHING on save and
3370
+	 *                                   close (normal form handling).
3371
+	 */
3372
+	protected function _set_save_buttons($both = true, $text = array(), $actions = array(), $referrer = null)
3373
+	{
3374
+		//make sure $text and $actions are in an array
3375
+		$text          = (array)$text;
3376
+		$actions       = (array)$actions;
3377
+		$referrer_url  = empty($referrer)
3378
+			? '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="'
3379
+			  . $_SERVER['REQUEST_URI']
3380
+			  . '" />'
3381
+			: '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="'
3382
+			  . $referrer
3383
+			  . '" />';
3384
+		$button_text   = ! empty($text)
3385
+			? $text
3386
+			: array(
3387
+				esc_html__('Save', 'event_espresso'),
3388
+				esc_html__('Save and Close', 'event_espresso'),
3389
+			);
3390
+		$default_names = array('save', 'save_and_close');
3391
+		//add in a hidden index for the current page (so save and close redirects properly)
3392
+		$this->_template_args['save_buttons'] = $referrer_url;
3393
+		foreach ($button_text as $key => $button) {
3394
+			$ref                                  = $default_names[$key];
3395
+			$this->_template_args['save_buttons'] .= '<input type="submit" class="button-primary '
3396
+													 . $ref
3397
+													 . '" value="'
3398
+													 . $button
3399
+													 . '" name="'
3400
+													 . (! empty($actions) ? $actions[$key] : $ref)
3401
+													 . '" id="'
3402
+													 . $this->_current_view . '_' . $ref
3403
+													 . '" />';
3404
+			if (! $both) {
3405
+				break;
3406
+			}
3407
+		}
3408
+	}
3409
+
3410
+
3411
+
3412
+	/**
3413
+	 * Wrapper for the protected function.  Allows plugins/addons to call this to set the form tags.
3414
+	 *
3415
+	 * @see   $this->_set_add_edit_form_tags() for details on params
3416
+	 * @since 4.6.0
3417
+	 * @param string $route
3418
+	 * @param array  $additional_hidden_fields
3419
+	 */
3420
+	public function set_add_edit_form_tags($route = '', $additional_hidden_fields = array())
3421
+	{
3422
+		$this->_set_add_edit_form_tags($route, $additional_hidden_fields);
3423
+	}
3424
+
3425
+
3426
+
3427
+	/**
3428
+	 * set form open and close tags on add/edit pages.
3429
+	 *
3430
+	 * @param string $route                    the route you want the form to direct to
3431
+	 * @param array  $additional_hidden_fields any additional hidden fields required in the form header
3432
+	 * @return void
3433
+	 */
3434
+	protected function _set_add_edit_form_tags($route = '', $additional_hidden_fields = array())
3435
+	{
3436
+		if (empty($route)) {
3437
+			$user_msg = esc_html__(
3438
+				'An error occurred. No action was set for this page\'s form.',
3439
+				'event_espresso'
3440
+			);
3441
+			$dev_msg  = $user_msg . "\n" . sprintf(
3442
+					esc_html__('The $route argument is required for the %s->%s method.', 'event_espresso'),
3443
+					__FUNCTION__,
3444
+					__CLASS__
3445
+				);
3446
+			EE_Error::add_error($user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
3447
+		}
3448
+		// open form
3449
+		$this->_template_args['before_admin_page_content'] = '<form name="form" method="post" action="'
3450
+															 . $this->_admin_base_url
3451
+															 . '" id="'
3452
+															 . $route
3453
+															 . '_event_form" >';
3454
+		// add nonce
3455
+		$nonce = wp_nonce_field($route . '_nonce', $route . '_nonce', false, false);
3456
+		//		$nonce = wp_nonce_field( $route . '_nonce', '_wpnonce', FALSE, FALSE );
3457
+		$this->_template_args['before_admin_page_content'] .= "\n\t" . $nonce;
3458
+		// add REQUIRED form action
3459
+		$hidden_fields = array(
3460
+			'action' => array('type' => 'hidden', 'value' => $route),
3461
+		);
3462
+		// merge arrays
3463
+		$hidden_fields = is_array($additional_hidden_fields)
3464
+			? array_merge($hidden_fields, $additional_hidden_fields)
3465
+			: $hidden_fields;
3466
+		// generate form fields
3467
+		$form_fields = $this->_generate_admin_form_fields($hidden_fields, 'array');
3468
+		// add fields to form
3469
+		foreach ((array)$form_fields as $field_name => $form_field) {
3470
+			$this->_template_args['before_admin_page_content'] .= "\n\t" . $form_field['field'];
3471
+		}
3472
+		// close form
3473
+		$this->_template_args['after_admin_page_content'] = '</form>';
3474
+	}
3475
+
3476
+
3477
+
3478
+	/**
3479
+	 * Public Wrapper for _redirect_after_action() method since its
3480
+	 * discovered it would be useful for external code to have access.
3481
+	 *
3482
+	 * @see   EE_Admin_Page::_redirect_after_action() for params.
3483
+	 * @since 4.5.0
3484
+	 * @param bool   $success
3485
+	 * @param string $what
3486
+	 * @param string $action_desc
3487
+	 * @param array  $query_args
3488
+	 * @param bool   $override_overwrite
3489
+	 * @throws EE_Error
3490
+	 */
3491
+	public function redirect_after_action(
3492
+		$success = false,
3493
+		$what = 'item',
3494
+		$action_desc = 'processed',
3495
+		$query_args = array(),
3496
+		$override_overwrite = false
3497
+	) {
3498
+		$this->_redirect_after_action(
3499
+			$success,
3500
+			$what,
3501
+			$action_desc,
3502
+			$query_args,
3503
+			$override_overwrite
3504
+		);
3505
+	}
3506
+
3507
+
3508
+
3509
+	/**
3510
+	 *    _redirect_after_action
3511
+	 *
3512
+	 * @param int    $success            - whether success was for two or more records, or just one, or none
3513
+	 * @param string $what               - what the action was performed on
3514
+	 * @param string $action_desc        - what was done ie: updated, deleted, etc
3515
+	 * @param array  $query_args         - an array of query_args to be added to the URL to redirect to after the admin
3516
+	 *                                   action is completed
3517
+	 * @param BOOL   $override_overwrite by default all EE_Error::success messages are overwritten, this allows you to
3518
+	 *                                   override this so that they show.
3519
+	 * @return void
3520
+	 * @throws EE_Error
3521
+	 */
3522
+	protected function _redirect_after_action(
3523
+		$success = 0,
3524
+		$what = 'item',
3525
+		$action_desc = 'processed',
3526
+		$query_args = array(),
3527
+		$override_overwrite = false
3528
+	) {
3529
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3530
+		//class name for actions/filters.
3531
+		$classname = get_class($this);
3532
+		// set redirect url.
3533
+		// Note if there is a "page" index in the $query_args then we go with vanilla admin.php route,
3534
+		// otherwise we go with whatever is set as the _admin_base_url
3535
+		$redirect_url = isset($query_args['page']) ? admin_url('admin.php') : $this->_admin_base_url;
3536
+		$notices      = EE_Error::get_notices(false);
3537
+		// overwrite default success messages //BUT ONLY if overwrite not overridden
3538
+		if (! $override_overwrite || ! empty($notices['errors'])) {
3539
+			EE_Error::overwrite_success();
3540
+		}
3541
+		if (! empty($what) && ! empty($action_desc)  && empty($notices['errors'])) {
3542
+			// how many records affected ? more than one record ? or just one ?
3543
+			if ($success > 1) {
3544
+				// set plural msg
3545
+				EE_Error::add_success(
3546
+					sprintf(
3547
+						esc_html__('The "%s" have been successfully %s.', 'event_espresso'),
3548
+						$what,
3549
+						$action_desc
3550
+					),
3551
+					__FILE__,
3552
+					__FUNCTION__,
3553
+					__LINE__
3554
+				);
3555
+			} elseif ($success === 1) {
3556
+				// set singular msg
3557
+				EE_Error::add_success(
3558
+					sprintf(
3559
+						esc_html__('The "%s" has been successfully %s.', 'event_espresso'),
3560
+						$what,
3561
+						$action_desc
3562
+					),
3563
+					__FILE__,
3564
+					__FUNCTION__,
3565
+					__LINE__
3566
+				);
3567
+			}
3568
+		}
3569
+		// check that $query_args isn't something crazy
3570
+		if (! is_array($query_args)) {
3571
+			$query_args = array();
3572
+		}
3573
+		/**
3574
+		 * Allow injecting actions before the query_args are modified for possible different
3575
+		 * redirections on save and close actions
3576
+		 *
3577
+		 * @since 4.2.0
3578
+		 * @param array $query_args       The original query_args array coming into the
3579
+		 *                                method.
3580
+		 */
3581
+		do_action(
3582
+			"AHEE__{$classname}___redirect_after_action__before_redirect_modification_{$this->_req_action}",
3583
+			$query_args
3584
+		);
3585
+		//calculate where we're going (if we have a "save and close" button pushed)
3586
+		if (isset($this->_req_data['save_and_close'], $this->_req_data['save_and_close_referrer'])) {
3587
+			// even though we have the save_and_close referrer, we need to parse the url for the action in order to generate a nonce
3588
+			$parsed_url = parse_url($this->_req_data['save_and_close_referrer']);
3589
+			// regenerate query args array from referrer URL
3590
+			parse_str($parsed_url['query'], $query_args);
3591
+			// correct page and action will be in the query args now
3592
+			$redirect_url = admin_url('admin.php');
3593
+		}
3594
+		//merge any default query_args set in _default_route_query_args property
3595
+		if (! empty($this->_default_route_query_args) && ! $this->_is_UI_request) {
3596
+			$args_to_merge = array();
3597
+			foreach ($this->_default_route_query_args as $query_param => $query_value) {
3598
+				//is there a wp_referer array in our _default_route_query_args property?
3599
+				if ($query_param === 'wp_referer') {
3600
+					$query_value = (array)$query_value;
3601
+					foreach ($query_value as $reference => $value) {
3602
+						if (strpos($reference, 'nonce') !== false) {
3603
+							continue;
3604
+						}
3605
+						//finally we will override any arguments in the referer with
3606
+						//what might be set on the _default_route_query_args array.
3607
+						if (isset($this->_default_route_query_args[$reference])) {
3608
+							$args_to_merge[$reference] = urlencode($this->_default_route_query_args[$reference]);
3609
+						} else {
3610
+							$args_to_merge[$reference] = urlencode($value);
3611
+						}
3612
+					}
3613
+					continue;
3614
+				}
3615
+				$args_to_merge[$query_param] = $query_value;
3616
+			}
3617
+			//now let's merge these arguments but override with what was specifically sent in to the
3618
+			//redirect.
3619
+			$query_args = array_merge($args_to_merge, $query_args);
3620
+		}
3621
+		$this->_process_notices($query_args);
3622
+		// generate redirect url
3623
+		// if redirecting to anything other than the main page, add a nonce
3624
+		if (isset($query_args['action'])) {
3625
+			// manually generate wp_nonce and merge that with the query vars
3626
+			// becuz the wp_nonce_url function wrecks havoc on some vars
3627
+			$query_args['_wpnonce'] = wp_create_nonce($query_args['action'] . '_nonce');
3628
+		}
3629
+		// we're adding some hooks and filters in here for processing any things just before redirects
3630
+		// (example: an admin page has done an insert or update and we want to run something after that).
3631
+		do_action('AHEE_redirect_' . $classname . $this->_req_action, $query_args);
3632
+		$redirect_url = apply_filters(
3633
+			'FHEE_redirect_' . $classname . $this->_req_action,
3634
+			self::add_query_args_and_nonce($query_args, $redirect_url),
3635
+			$query_args
3636
+		);
3637
+		// check if we're doing ajax.  If we are then lets just return the results and js can handle how it wants.
3638
+		if (defined('DOING_AJAX')) {
3639
+			$default_data                    = array(
3640
+				'close'        => true,
3641
+				'redirect_url' => $redirect_url,
3642
+				'where'        => 'main',
3643
+				'what'         => 'append',
3644
+			);
3645
+			$this->_template_args['success'] = $success;
3646
+			$this->_template_args['data']    = ! empty($this->_template_args['data']) ? array_merge(
3647
+				$default_data,
3648
+				$this->_template_args['data']
3649
+			) : $default_data;
3650
+			$this->_return_json();
3651
+		}
3652
+		wp_safe_redirect($redirect_url);
3653
+		exit();
3654
+	}
3655
+
3656
+
3657
+
3658
+	/**
3659
+	 * process any notices before redirecting (or returning ajax request)
3660
+	 * This method sets the $this->_template_args['notices'] attribute;
3661
+	 *
3662
+	 * @param  array $query_args        any query args that need to be used for notice transient ('action')
3663
+	 * @param bool   $skip_route_verify This is typically used when we are processing notices REALLY early and
3664
+	 *                                  page_routes haven't been defined yet.
3665
+	 * @param bool   $sticky_notices    This is used to flag that regardless of whether this is doing_ajax or not, we
3666
+	 *                                  still save a transient for the notice.
3667
+	 * @return void
3668
+	 * @throws EE_Error
3669
+	 */
3670
+	protected function _process_notices($query_args = array(), $skip_route_verify = false, $sticky_notices = true)
3671
+	{
3672
+		//first let's set individual error properties if doing_ajax and the properties aren't already set.
3673
+		if (defined('DOING_AJAX') && DOING_AJAX) {
3674
+			$notices = EE_Error::get_notices(false);
3675
+			if (empty($this->_template_args['success'])) {
3676
+				$this->_template_args['success'] = isset($notices['success']) ? $notices['success'] : false;
3677
+			}
3678
+			if (empty($this->_template_args['errors'])) {
3679
+				$this->_template_args['errors'] = isset($notices['errors']) ? $notices['errors'] : false;
3680
+			}
3681
+			if (empty($this->_template_args['attention'])) {
3682
+				$this->_template_args['attention'] = isset($notices['attention']) ? $notices['attention'] : false;
3683
+			}
3684
+		}
3685
+		$this->_template_args['notices'] = EE_Error::get_notices();
3686
+		//IF this isn't ajax we need to create a transient for the notices using the route (however, overridden if $sticky_notices == true)
3687
+		if (! defined('DOING_AJAX') || $sticky_notices) {
3688
+			$route = isset($query_args['action']) ? $query_args['action'] : 'default';
3689
+			$this->_add_transient(
3690
+				$route,
3691
+				$this->_template_args['notices'],
3692
+				true,
3693
+				$skip_route_verify
3694
+			);
3695
+		}
3696
+	}
3697
+
3698
+
3699
+
3700
+	/**
3701
+	 * get_action_link_or_button
3702
+	 * returns the button html for adding, editing, or deleting an item (depending on given type)
3703
+	 *
3704
+	 * @param string $action        use this to indicate which action the url is generated with.
3705
+	 * @param string $type          accepted strings must be defined in the $_labels['button'] array(as the key)
3706
+	 *                              property.
3707
+	 * @param array  $extra_request if the button requires extra params you can include them in $key=>$value pairs.
3708
+	 * @param string $class         Use this to give the class for the button. Defaults to 'button-primary'
3709
+	 * @param string $base_url      If this is not provided
3710
+	 *                              the _admin_base_url will be used as the default for the button base_url.
3711
+	 *                              Otherwise this value will be used.
3712
+	 * @param bool   $exclude_nonce If true then no nonce will be in the generated button link.
3713
+	 * @return string
3714
+	 * @throws InvalidArgumentException
3715
+	 * @throws InvalidInterfaceException
3716
+	 * @throws InvalidDataTypeException
3717
+	 * @throws EE_Error
3718
+	 */
3719
+	public function get_action_link_or_button(
3720
+		$action,
3721
+		$type = 'add',
3722
+		$extra_request = array(),
3723
+		$class = 'button-primary',
3724
+		$base_url = '',
3725
+		$exclude_nonce = false
3726
+	) {
3727
+		//first let's validate the action (if $base_url is FALSE otherwise validation will happen further along)
3728
+		if (empty($base_url) && ! isset($this->_page_routes[$action])) {
3729
+			throw new EE_Error(
3730
+				sprintf(
3731
+					esc_html__(
3732
+						'There is no page route for given action for the button.  This action was given: %s',
3733
+						'event_espresso'
3734
+					),
3735
+					$action
3736
+				)
3737
+			);
3738
+		}
3739
+		if (! isset($this->_labels['buttons'][$type])) {
3740
+			throw new EE_Error(
3741
+				sprintf(
3742
+					__(
3743
+						'There is no label for the given button type (%s). Labels are set in the <code>_page_config</code> property.',
3744
+						'event_espresso'
3745
+					),
3746
+					$type
3747
+				)
3748
+			);
3749
+		}
3750
+		//finally check user access for this button.
3751
+		$has_access = $this->check_user_access($action, true);
3752
+		if (! $has_access) {
3753
+			return '';
3754
+		}
3755
+		$_base_url  = ! $base_url ? $this->_admin_base_url : $base_url;
3756
+		$query_args = array(
3757
+			'action' => $action,
3758
+		);
3759
+		//merge extra_request args but make sure our original action takes precedence and doesn't get overwritten.
3760
+		if (! empty($extra_request)) {
3761
+			$query_args = array_merge($extra_request, $query_args);
3762
+		}
3763
+		$url = self::add_query_args_and_nonce($query_args, $_base_url, false, $exclude_nonce);
3764
+		return EEH_Template::get_button_or_link($url, $this->_labels['buttons'][$type], $class);
3765
+	}
3766
+
3767
+
3768
+
3769
+	/**
3770
+	 * _per_page_screen_option
3771
+	 * Utility function for adding in a per_page_option in the screen_options_dropdown.
3772
+	 *
3773
+	 * @return void
3774
+	 * @throws InvalidArgumentException
3775
+	 * @throws InvalidInterfaceException
3776
+	 * @throws InvalidDataTypeException
3777
+	 */
3778
+	protected function _per_page_screen_option()
3779
+	{
3780
+		$option = 'per_page';
3781
+		$args   = array(
3782
+			'label'   => esc_html__(
3783
+					apply_filters(
3784
+						'FHEE__EE_Admin_Page___per_page_screen_options___label',
3785
+						$this->_admin_page_title,
3786
+						$this
3787
+					)
3788
+			),
3789
+			'default' => (int) apply_filters(
3790
+					'FHEE__EE_Admin_Page___per_page_screen_options__default',
3791
+					10
3792
+			),
3793
+			'option'  => $this->_current_page . '_' . $this->_current_view . '_per_page',
3794
+		);
3795
+		//ONLY add the screen option if the user has access to it.
3796
+		if ($this->check_user_access($this->_current_view, true)) {
3797
+			add_screen_option($option, $args);
3798
+		}
3799
+	}
3800
+
3801
+
3802
+
3803
+	/**
3804
+	 * set_per_page_screen_option
3805
+	 * All this does is make sure that WordPress saves any per_page screen options (if set) for the current page.
3806
+	 * we have to do this rather than running inside the 'set-screen-options' hook because it runs earlier than
3807
+	 * admin_menu.
3808
+	 *
3809
+	 * @return void
3810
+	 */
3811
+	private function _set_per_page_screen_options()
3812
+	{
3813
+		if (isset($_POST['wp_screen_options']) && is_array($_POST['wp_screen_options'])) {
3814
+			check_admin_referer('screen-options-nonce', 'screenoptionnonce');
3815
+			if (! $user = wp_get_current_user()) {
3816
+				return;
3817
+			}
3818
+			$option = $_POST['wp_screen_options']['option'];
3819
+			$value  = $_POST['wp_screen_options']['value'];
3820
+			if ($option != sanitize_key($option)) {
3821
+				return;
3822
+			}
3823
+			$map_option = $option;
3824
+			$option     = str_replace('-', '_', $option);
3825
+			switch ($map_option) {
3826
+				case $this->_current_page . '_' . $this->_current_view . '_per_page':
3827
+					$value = (int)$value;
3828
+					$max_value = apply_filters(
3829
+						'FHEE__EE_Admin_Page___set_per_page_screen_options__max_value',
3830
+						999,
3831
+						$this->_current_page,
3832
+						$this->_current_view
3833
+					);
3834
+					if ($value < 1) {
3835
+						return;
3836
+					}
3837
+					$value = min($value, $max_value);
3838
+					break;
3839
+				default:
3840
+					$value = apply_filters(
3841
+						'FHEE__EE_Admin_Page___set_per_page_screen_options__value',
3842
+						false,
3843
+						$option,
3844
+						$value
3845
+					);
3846
+					if (false === $value) {
3847
+						return;
3848
+					}
3849
+					break;
3850
+			}
3851
+			update_user_meta($user->ID, $option, $value);
3852
+			wp_safe_redirect(remove_query_arg(array('pagenum', 'apage', 'paged'), wp_get_referer()));
3853
+			exit;
3854
+		}
3855
+	}
3856
+
3857
+
3858
+
3859
+	/**
3860
+	 * This just allows for setting the $_template_args property if it needs to be set outside the object
3861
+	 *
3862
+	 * @param array $data array that will be assigned to template args.
3863
+	 */
3864
+	public function set_template_args($data)
3865
+	{
3866
+		$this->_template_args = array_merge($this->_template_args, (array)$data);
3867
+	}
3868
+
3869
+
3870
+
3871
+	/**
3872
+	 * This makes available the WP transient system for temporarily moving data between routes
3873
+	 *
3874
+	 * @param string $route             the route that should receive the transient
3875
+	 * @param array  $data              the data that gets sent
3876
+	 * @param bool   $notices           If this is for notices then we use this to indicate so, otherwise its just a
3877
+	 *                                  normal route transient.
3878
+	 * @param bool   $skip_route_verify Used to indicate we want to skip route verification.  This is usually ONLY used
3879
+	 *                                  when we are adding a transient before page_routes have been defined.
3880
+	 * @return void
3881
+	 * @throws EE_Error
3882
+	 */
3883
+	protected function _add_transient($route, $data, $notices = false, $skip_route_verify = false)
3884
+	{
3885
+		$user_id = get_current_user_id();
3886
+		if (! $skip_route_verify) {
3887
+			$this->_verify_route($route);
3888
+		}
3889
+		//now let's set the string for what kind of transient we're setting
3890
+		$transient = $notices
3891
+			? 'ee_rte_n_tx_' . $route . '_' . $user_id
3892
+			: 'rte_tx_' . $route . '_' . $user_id;
3893
+		$data      = $notices ? array('notices' => $data) : $data;
3894
+		//is there already a transient for this route?  If there is then let's ADD to that transient
3895
+		$existing = is_multisite() && is_network_admin()
3896
+			? get_site_transient($transient)
3897
+			: get_transient($transient);
3898
+		if ($existing) {
3899
+			$data = array_merge((array)$data, (array)$existing);
3900
+		}
3901
+		if (is_multisite() && is_network_admin()) {
3902
+			set_site_transient($transient, $data, 8);
3903
+		} else {
3904
+			set_transient($transient, $data, 8);
3905
+		}
3906
+	}
3907
+
3908
+
3909
+
3910
+	/**
3911
+	 * this retrieves the temporary transient that has been set for moving data between routes.
3912
+	 *
3913
+	 * @param bool   $notices true we get notices transient. False we just return normal route transient
3914
+	 * @param string $route
3915
+	 * @return mixed data
3916
+	 */
3917
+	protected function _get_transient($notices = false, $route = '')
3918
+	{
3919
+		$user_id   = get_current_user_id();
3920
+		$route     = ! $route ? $this->_req_action : $route;
3921
+		$transient = $notices
3922
+			? 'ee_rte_n_tx_' . $route . '_' . $user_id
3923
+			: 'rte_tx_' . $route . '_' . $user_id;
3924
+		$data      = is_multisite() && is_network_admin()
3925
+			? get_site_transient($transient)
3926
+			: get_transient($transient);
3927
+		//delete transient after retrieval (just in case it hasn't expired);
3928
+		if (is_multisite() && is_network_admin()) {
3929
+			delete_site_transient($transient);
3930
+		} else {
3931
+			delete_transient($transient);
3932
+		}
3933
+		return $notices && isset($data['notices']) ? $data['notices'] : $data;
3934
+	}
3935
+
3936
+
3937
+
3938
+	/**
3939
+	 * The purpose of this method is just to run garbage collection on any EE transients that might have expired but
3940
+	 * would not be called later. This will be assigned to run on a specific EE Admin page. (place the method in the
3941
+	 * default route callback on the EE_Admin page you want it run.)
3942
+	 *
3943
+	 * @return void
3944
+	 */
3945
+	protected function _transient_garbage_collection()
3946
+	{
3947
+		global $wpdb;
3948
+		//retrieve all existing transients
3949
+		$query = "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '%rte_tx_%' OR option_name LIKE '%rte_n_tx_%'";
3950
+		if ($results = $wpdb->get_results($query)) {
3951
+			foreach ($results as $result) {
3952
+				$transient = str_replace('_transient_', '', $result->option_name);
3953
+				get_transient($transient);
3954
+				if (is_multisite() && is_network_admin()) {
3955
+					get_site_transient($transient);
3956
+				}
3957
+			}
3958
+		}
3959
+	}
3960
+
3961
+
3962
+
3963
+	/**
3964
+	 * get_view
3965
+	 *
3966
+	 * @return string content of _view property
3967
+	 */
3968
+	public function get_view()
3969
+	{
3970
+		return $this->_view;
3971
+	}
3972
+
3973
+
3974
+
3975
+	/**
3976
+	 * getter for the protected $_views property
3977
+	 *
3978
+	 * @return array
3979
+	 */
3980
+	public function get_views()
3981
+	{
3982
+		return $this->_views;
3983
+	}
3984
+
3985
+
3986
+
3987
+	/**
3988
+	 * get_current_page
3989
+	 *
3990
+	 * @return string _current_page property value
3991
+	 */
3992
+	public function get_current_page()
3993
+	{
3994
+		return $this->_current_page;
3995
+	}
3996
+
3997
+
3998
+
3999
+	/**
4000
+	 * get_current_view
4001
+	 *
4002
+	 * @return string _current_view property value
4003
+	 */
4004
+	public function get_current_view()
4005
+	{
4006
+		return $this->_current_view;
4007
+	}
4008
+
4009
+
4010
+
4011
+	/**
4012
+	 * get_current_screen
4013
+	 *
4014
+	 * @return object The current WP_Screen object
4015
+	 */
4016
+	public function get_current_screen()
4017
+	{
4018
+		return $this->_current_screen;
4019
+	}
4020
+
4021
+
4022
+
4023
+	/**
4024
+	 * get_current_page_view_url
4025
+	 *
4026
+	 * @return string This returns the url for the current_page_view.
4027
+	 */
4028
+	public function get_current_page_view_url()
4029
+	{
4030
+		return $this->_current_page_view_url;
4031
+	}
4032
+
4033
+
4034
+
4035
+	/**
4036
+	 * just returns the _req_data property
4037
+	 *
4038
+	 * @return array
4039
+	 */
4040
+	public function get_request_data()
4041
+	{
4042
+		return $this->_req_data;
4043
+	}
4044
+
4045
+
4046
+
4047
+	/**
4048
+	 * returns the _req_data protected property
4049
+	 *
4050
+	 * @return string
4051
+	 */
4052
+	public function get_req_action()
4053
+	{
4054
+		return $this->_req_action;
4055
+	}
4056
+
4057
+
4058
+
4059
+	/**
4060
+	 * @return bool  value of $_is_caf property
4061
+	 */
4062
+	public function is_caf()
4063
+	{
4064
+		return $this->_is_caf;
4065
+	}
4066
+
4067
+
4068
+
4069
+	/**
4070
+	 * @return mixed
4071
+	 */
4072
+	public function default_espresso_metaboxes()
4073
+	{
4074
+		return $this->_default_espresso_metaboxes;
4075
+	}
4076
+
4077
+
4078
+
4079
+	/**
4080
+	 * @return mixed
4081
+	 */
4082
+	public function admin_base_url()
4083
+	{
4084
+		return $this->_admin_base_url;
4085
+	}
4086 4086
 
4087 4087
 
4088 4088
 
4089
-    /**
4090
-     * @return mixed
4091
-     */
4092
-    public function wp_page_slug()
4093
-    {
4094
-        return $this->_wp_page_slug;
4095
-    }
4089
+	/**
4090
+	 * @return mixed
4091
+	 */
4092
+	public function wp_page_slug()
4093
+	{
4094
+		return $this->_wp_page_slug;
4095
+	}
4096 4096
 
4097 4097
 
4098
-
4099
-    /**
4100
-     * updates  espresso configuration settings
4101
-     *
4102
-     * @param string                   $tab
4103
-     * @param EE_Config_Base|EE_Config $config
4104
-     * @param string                   $file file where error occurred
4105
-     * @param string                   $func function  where error occurred
4106
-     * @param string                   $line line no where error occurred
4107
-     * @return boolean
4108
-     */
4109
-    protected function _update_espresso_configuration($tab, $config, $file = '', $func = '', $line = '')
4110
-    {
4111
-        //remove any options that are NOT going to be saved with the config settings.
4112
-        if (isset($config->core->ee_ueip_optin)) {
4113
-            $config->core->ee_ueip_has_notified = true;
4114
-            // TODO: remove the following two lines and make sure values are migrated from 3.1
4115
-            update_option('ee_ueip_optin', $config->core->ee_ueip_optin);
4116
-            update_option('ee_ueip_has_notified', true);
4117
-        }
4118
-        // and save it (note we're also doing the network save here)
4119
-        $net_saved    = is_main_site() ? EE_Network_Config::instance()->update_config(false, false) : true;
4120
-        $config_saved = EE_Config::instance()->update_espresso_config(false, false);
4121
-        if ($config_saved && $net_saved) {
4122
-            EE_Error::add_success(sprintf(__('"%s" have been successfully updated.', 'event_espresso'), $tab));
4123
-            return true;
4124
-        }
4125
-        EE_Error::add_error(sprintf(__('The "%s" were not updated.', 'event_espresso'), $tab), $file, $func, $line);
4126
-        return false;
4127
-    }
4128
-
4129
-
4130
-
4131
-    /**
4132
-     * Returns an array to be used for EE_FOrm_Fields.helper.php's select_input as the $values argument.
4133
-     *
4134
-     * @return array
4135
-     */
4136
-    public function get_yes_no_values()
4137
-    {
4138
-        return $this->_yes_no_values;
4139
-    }
4140
-
4141
-
4142
-
4143
-    protected function _get_dir()
4144
-    {
4145
-        $reflector = new ReflectionClass(get_class($this));
4146
-        return dirname($reflector->getFileName());
4147
-    }
4148
-
4149
-
4150
-
4151
-    /**
4152
-     * A helper for getting a "next link".
4153
-     *
4154
-     * @param string $url   The url to link to
4155
-     * @param string $class The class to use.
4156
-     * @return string
4157
-     */
4158
-    protected function _next_link($url, $class = 'dashicons dashicons-arrow-right')
4159
-    {
4160
-        return '<a class="' . $class . '" href="' . $url . '"></a>';
4161
-    }
4162
-
4163
-
4164
-
4165
-    /**
4166
-     * A helper for getting a "previous link".
4167
-     *
4168
-     * @param string $url   The url to link to
4169
-     * @param string $class The class to use.
4170
-     * @return string
4171
-     */
4172
-    protected function _previous_link($url, $class = 'dashicons dashicons-arrow-left')
4173
-    {
4174
-        return '<a class="' . $class . '" href="' . $url . '"></a>';
4175
-    }
4176
-
4177
-
4178
-
4179
-
4180
-
4181
-
4182
-
4183
-    //below are some messages related methods that should be available across the EE_Admin system.  Note, these methods are NOT page specific
4184
-
4185
-
4186
-    /**
4187
-     * This processes an request to resend a registration and assumes we have a _REG_ID for doing so. So if the caller
4188
-     * knows that the _REG_ID isn't in the req_data array but CAN obtain it, the caller should ADD the _REG_ID to the
4189
-     * _req_data array.
4190
-     *
4191
-     * @return bool success/fail
4192
-     * @throws EE_Error
4193
-     * @throws InvalidArgumentException
4194
-     * @throws ReflectionException
4195
-     * @throws InvalidDataTypeException
4196
-     * @throws InvalidInterfaceException
4197
-     */
4198
-    protected function _process_resend_registration()
4199
-    {
4200
-        $this->_template_args['success'] = EED_Messages::process_resend($this->_req_data);
4201
-        do_action(
4202
-            'AHEE__EE_Admin_Page___process_resend_registration',
4203
-            $this->_template_args['success'],
4204
-            $this->_req_data
4205
-        );
4206
-        return $this->_template_args['success'];
4207
-    }
4208
-
4209
-
4210
-
4211
-    /**
4212
-     * This automatically processes any payment message notifications when manual payment has been applied.
4213
-     *
4214
-     * @param \EE_Payment $payment
4215
-     * @return bool success/fail
4216
-     */
4217
-    protected function _process_payment_notification(EE_Payment $payment)
4218
-    {
4219
-        add_filter('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', '__return_true');
4220
-        do_action('AHEE__EE_Admin_Page___process_admin_payment_notification', $payment);
4221
-        $this->_template_args['success'] = apply_filters(
4222
-            'FHEE__EE_Admin_Page___process_admin_payment_notification__success',
4223
-            false,
4224
-            $payment
4225
-        );
4226
-        return $this->_template_args['success'];
4227
-    }
4098
+
4099
+	/**
4100
+	 * updates  espresso configuration settings
4101
+	 *
4102
+	 * @param string                   $tab
4103
+	 * @param EE_Config_Base|EE_Config $config
4104
+	 * @param string                   $file file where error occurred
4105
+	 * @param string                   $func function  where error occurred
4106
+	 * @param string                   $line line no where error occurred
4107
+	 * @return boolean
4108
+	 */
4109
+	protected function _update_espresso_configuration($tab, $config, $file = '', $func = '', $line = '')
4110
+	{
4111
+		//remove any options that are NOT going to be saved with the config settings.
4112
+		if (isset($config->core->ee_ueip_optin)) {
4113
+			$config->core->ee_ueip_has_notified = true;
4114
+			// TODO: remove the following two lines and make sure values are migrated from 3.1
4115
+			update_option('ee_ueip_optin', $config->core->ee_ueip_optin);
4116
+			update_option('ee_ueip_has_notified', true);
4117
+		}
4118
+		// and save it (note we're also doing the network save here)
4119
+		$net_saved    = is_main_site() ? EE_Network_Config::instance()->update_config(false, false) : true;
4120
+		$config_saved = EE_Config::instance()->update_espresso_config(false, false);
4121
+		if ($config_saved && $net_saved) {
4122
+			EE_Error::add_success(sprintf(__('"%s" have been successfully updated.', 'event_espresso'), $tab));
4123
+			return true;
4124
+		}
4125
+		EE_Error::add_error(sprintf(__('The "%s" were not updated.', 'event_espresso'), $tab), $file, $func, $line);
4126
+		return false;
4127
+	}
4128
+
4129
+
4130
+
4131
+	/**
4132
+	 * Returns an array to be used for EE_FOrm_Fields.helper.php's select_input as the $values argument.
4133
+	 *
4134
+	 * @return array
4135
+	 */
4136
+	public function get_yes_no_values()
4137
+	{
4138
+		return $this->_yes_no_values;
4139
+	}
4140
+
4141
+
4142
+
4143
+	protected function _get_dir()
4144
+	{
4145
+		$reflector = new ReflectionClass(get_class($this));
4146
+		return dirname($reflector->getFileName());
4147
+	}
4148
+
4149
+
4150
+
4151
+	/**
4152
+	 * A helper for getting a "next link".
4153
+	 *
4154
+	 * @param string $url   The url to link to
4155
+	 * @param string $class The class to use.
4156
+	 * @return string
4157
+	 */
4158
+	protected function _next_link($url, $class = 'dashicons dashicons-arrow-right')
4159
+	{
4160
+		return '<a class="' . $class . '" href="' . $url . '"></a>';
4161
+	}
4162
+
4163
+
4164
+
4165
+	/**
4166
+	 * A helper for getting a "previous link".
4167
+	 *
4168
+	 * @param string $url   The url to link to
4169
+	 * @param string $class The class to use.
4170
+	 * @return string
4171
+	 */
4172
+	protected function _previous_link($url, $class = 'dashicons dashicons-arrow-left')
4173
+	{
4174
+		return '<a class="' . $class . '" href="' . $url . '"></a>';
4175
+	}
4176
+
4177
+
4178
+
4179
+
4180
+
4181
+
4182
+
4183
+	//below are some messages related methods that should be available across the EE_Admin system.  Note, these methods are NOT page specific
4184
+
4185
+
4186
+	/**
4187
+	 * This processes an request to resend a registration and assumes we have a _REG_ID for doing so. So if the caller
4188
+	 * knows that the _REG_ID isn't in the req_data array but CAN obtain it, the caller should ADD the _REG_ID to the
4189
+	 * _req_data array.
4190
+	 *
4191
+	 * @return bool success/fail
4192
+	 * @throws EE_Error
4193
+	 * @throws InvalidArgumentException
4194
+	 * @throws ReflectionException
4195
+	 * @throws InvalidDataTypeException
4196
+	 * @throws InvalidInterfaceException
4197
+	 */
4198
+	protected function _process_resend_registration()
4199
+	{
4200
+		$this->_template_args['success'] = EED_Messages::process_resend($this->_req_data);
4201
+		do_action(
4202
+			'AHEE__EE_Admin_Page___process_resend_registration',
4203
+			$this->_template_args['success'],
4204
+			$this->_req_data
4205
+		);
4206
+		return $this->_template_args['success'];
4207
+	}
4208
+
4209
+
4210
+
4211
+	/**
4212
+	 * This automatically processes any payment message notifications when manual payment has been applied.
4213
+	 *
4214
+	 * @param \EE_Payment $payment
4215
+	 * @return bool success/fail
4216
+	 */
4217
+	protected function _process_payment_notification(EE_Payment $payment)
4218
+	{
4219
+		add_filter('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', '__return_true');
4220
+		do_action('AHEE__EE_Admin_Page___process_admin_payment_notification', $payment);
4221
+		$this->_template_args['success'] = apply_filters(
4222
+			'FHEE__EE_Admin_Page___process_admin_payment_notification__success',
4223
+			false,
4224
+			$payment
4225
+		);
4226
+		return $this->_template_args['success'];
4227
+	}
4228 4228
 
4229 4229
 
4230 4230
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Transaction.model.php 1 patch
Indentation   +405 added lines, -405 removed lines patch added patch discarded remove patch
@@ -5,7 +5,7 @@  discard block
 block discarded – undo
5 5
 use EventEspresso\core\services\loaders\LoaderFactory;
6 6
 
7 7
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
8
-    exit('No direct script access allowed');
8
+	exit('No direct script access allowed');
9 9
 }
10 10
 require_once(EE_MODELS . 'EEM_Base.model.php');
11 11
 
@@ -21,193 +21,193 @@  discard block
 block discarded – undo
21 21
 class EEM_Transaction extends EEM_Base
22 22
 {
23 23
 
24
-    // private instance of the Transaction object
25
-    protected static $_instance;
26
-
27
-    /**
28
-     * Status ID(STS_ID on esp_status table) to indicate the transaction is complete,
29
-     * but payment is pending. This is the state for transactions where payment is promised
30
-     * from an offline gateway.
31
-     */
32
-    //	const open_status_code = 'TPN';
33
-
34
-    /**
35
-     * Status ID(STS_ID on esp_status table) to indicate the transaction failed,
36
-     * either due to a technical reason (server or computer crash during registration),
37
-     *  or some other reason that prevent the collection of any useful contact information from any of the registrants
38
-     */
39
-    const failed_status_code = 'TFL';
40
-
41
-    /**
42
-     * Status ID(STS_ID on esp_status table) to indicate the transaction was abandoned,
43
-     * either due to a technical reason (server or computer crash during registration),
44
-     * or due to an abandoned cart after registrant chose not to complete the registration process
45
-     * HOWEVER...
46
-     * an abandoned TXN differs from a failed TXN in that it was able to capture contact information for at least one
47
-     * registrant
48
-     */
49
-    const abandoned_status_code = 'TAB';
50
-
51
-    /**
52
-     * Status ID(STS_ID on esp_status table) to indicate an incomplete transaction,
53
-     * meaning that monies are still owing: TXN_paid < TXN_total
54
-     */
55
-    const incomplete_status_code = 'TIN';
56
-
57
-    /**
58
-     * Status ID (STS_ID on esp_status table) to indicate a complete transaction.
59
-     * meaning that NO monies are owing: TXN_paid == TXN_total
60
-     */
61
-    const complete_status_code = 'TCM';
62
-
63
-    /**
64
-     *  Status ID(STS_ID on esp_status table) to indicate the transaction is overpaid.
65
-     *  This is the same as complete, but site admins actually owe clients the moneys!  TXN_paid > TXN_total
66
-     */
67
-    const overpaid_status_code = 'TOP';
68
-
69
-
70
-    /**
71
-     *    private constructor to prevent direct creation
72
-     *
73
-     * @Constructor
74
-     * @access protected
75
-     *
76
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
77
-     *                         incoming timezone data that gets saved). Note this just sends the timezone info to the
78
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
79
-     *                         timezone in the 'timezone_string' wp option)
80
-     *
81
-     * @return EEM_Transaction
82
-     * @throws \EE_Error
83
-     */
84
-    protected function __construct($timezone)
85
-    {
86
-        $this->singular_item = __('Transaction', 'event_espresso');
87
-        $this->plural_item   = __('Transactions', 'event_espresso');
88
-
89
-        $this->_tables                 = array(
90
-            'TransactionTable' => new EE_Primary_Table('esp_transaction', 'TXN_ID')
91
-        );
92
-        $this->_fields                 = array(
93
-            'TransactionTable' => array(
94
-                'TXN_ID'           => new EE_Primary_Key_Int_Field('TXN_ID', __('Transaction ID', 'event_espresso')),
95
-                'TXN_timestamp'    => new EE_Datetime_Field('TXN_timestamp',
96
-                    __('date when transaction was created', 'event_espresso'), false, EE_Datetime_Field::now,
97
-                    $timezone),
98
-                'TXN_total'        => new EE_Money_Field('TXN_total',
99
-                    __('Total value of Transaction', 'event_espresso'), false, 0),
100
-                'TXN_paid'         => new EE_Money_Field('TXN_paid',
101
-                    __('Amount paid towards transaction to date', 'event_espresso'), false, 0),
102
-                'STS_ID'           => new EE_Foreign_Key_String_Field('STS_ID', __('Status ID', 'event_espresso'),
103
-                    false, EEM_Transaction::failed_status_code, 'Status'),
104
-                'TXN_session_data' => new EE_Serialized_Text_Field('TXN_session_data',
105
-                    __('Serialized session data', 'event_espresso'), true, ''),
106
-                'TXN_hash_salt'    => new EE_Plain_Text_Field('TXN_hash_salt',
107
-                    __('Transaction Hash Salt', 'event_espresso'), true, ''),
108
-                'PMD_ID'           => new EE_Foreign_Key_Int_Field('PMD_ID',
109
-                    __("Last Used Payment Method", 'event_espresso'), true, null, 'Payment_Method'),
110
-                'TXN_reg_steps'    => new EE_Serialized_Text_Field('TXN_reg_steps',
111
-                    __('Registration Steps', 'event_espresso'), false, array()),
112
-            )
113
-        );
114
-        $this->_model_relations        = array(
115
-            'Registration'   => new EE_Has_Many_Relation(),
116
-            'Payment'        => new EE_Has_Many_Relation(),
117
-            'Status'         => new EE_Belongs_To_Relation(),
118
-            'Line_Item'      => new EE_Has_Many_Relation(false),
119
-            //you can delete a transaction without needing to delete its line items
120
-            'Payment_Method' => new EE_Belongs_To_Relation(),
121
-            'Message'        => new EE_Has_Many_Relation()
122
-        );
123
-        $this->_model_chain_to_wp_user = 'Registration.Event';
124
-        parent::__construct($timezone);
125
-
126
-    }
127
-
128
-
129
-    /**
130
-     *    txn_status_array
131
-     * get list of transaction statuses
132
-     *
133
-     * @access public
134
-     * @return array
135
-     */
136
-    public static function txn_status_array()
137
-    {
138
-        return apply_filters(
139
-            'FHEE__EEM_Transaction__txn_status_array',
140
-            array(
141
-                EEM_Transaction::overpaid_status_code,
142
-                EEM_Transaction::complete_status_code,
143
-                EEM_Transaction::incomplete_status_code,
144
-                EEM_Transaction::abandoned_status_code,
145
-                EEM_Transaction::failed_status_code,
146
-            )
147
-        );
148
-    }
149
-
150
-    /**
151
-     *        get the revenue per day  for the Transaction Admin page Reports Tab
152
-     *
153
-     * @access        public
154
-     *
155
-     * @param string $period
156
-     *
157
-     * @return \stdClass[]
158
-     */
159
-    public function get_revenue_per_day_report($period = '-1 month')
160
-    {
161
-        $sql_date = $this->convert_datetime_for_query('TXN_timestamp', date('Y-m-d H:i:s', strtotime($period)),
162
-            'Y-m-d H:i:s', 'UTC');
163
-
164
-        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'TXN_timestamp');
165
-
166
-        return $this->_get_all_wpdb_results(
167
-            array(
168
-                array(
169
-                    'TXN_timestamp' => array('>=', $sql_date)
170
-                ),
171
-                'group_by' => 'txnDate',
172
-                'order_by' => array('TXN_timestamp' => 'ASC')
173
-            ),
174
-            OBJECT,
175
-            array(
176
-                'txnDate' => array('DATE(' . $query_interval . ')', '%s'),
177
-                'revenue' => array('SUM(TransactionTable.TXN_paid)', '%d')
178
-            )
179
-        );
180
-    }
181
-
182
-
183
-    /**
184
-     *        get the revenue per event  for the Transaction Admin page Reports Tab
185
-     *
186
-     * @access        public
187
-     *
188
-     * @param string $period
189
-     *
190
-     * @throws \EE_Error
191
-     * @return mixed
192
-     */
193
-    public function get_revenue_per_event_report($period = '-1 month')
194
-    {
195
-        global $wpdb;
196
-        $transaction_table          = $wpdb->prefix . 'esp_transaction';
197
-        $registration_table         = $wpdb->prefix . 'esp_registration';
198
-        $registration_payment_table = $wpdb->prefix . 'esp_registration_payment';
199
-        $event_table                = $wpdb->posts;
200
-        $payment_table              = $wpdb->prefix . 'esp_payment';
201
-        $sql_date                   = date('Y-m-d H:i:s', strtotime($period));
202
-        $approved_payment_status    = EEM_Payment::status_id_approved;
203
-        $extra_event_on_join        = '';
204
-        //exclude events not authored by user if permissions in effect
205
-        if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
206
-            $extra_event_on_join = ' AND Event.post_author = ' . get_current_user_id();
207
-        }
208
-
209
-        return $wpdb->get_results(
210
-            "SELECT
24
+	// private instance of the Transaction object
25
+	protected static $_instance;
26
+
27
+	/**
28
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction is complete,
29
+	 * but payment is pending. This is the state for transactions where payment is promised
30
+	 * from an offline gateway.
31
+	 */
32
+	//	const open_status_code = 'TPN';
33
+
34
+	/**
35
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction failed,
36
+	 * either due to a technical reason (server or computer crash during registration),
37
+	 *  or some other reason that prevent the collection of any useful contact information from any of the registrants
38
+	 */
39
+	const failed_status_code = 'TFL';
40
+
41
+	/**
42
+	 * Status ID(STS_ID on esp_status table) to indicate the transaction was abandoned,
43
+	 * either due to a technical reason (server or computer crash during registration),
44
+	 * or due to an abandoned cart after registrant chose not to complete the registration process
45
+	 * HOWEVER...
46
+	 * an abandoned TXN differs from a failed TXN in that it was able to capture contact information for at least one
47
+	 * registrant
48
+	 */
49
+	const abandoned_status_code = 'TAB';
50
+
51
+	/**
52
+	 * Status ID(STS_ID on esp_status table) to indicate an incomplete transaction,
53
+	 * meaning that monies are still owing: TXN_paid < TXN_total
54
+	 */
55
+	const incomplete_status_code = 'TIN';
56
+
57
+	/**
58
+	 * Status ID (STS_ID on esp_status table) to indicate a complete transaction.
59
+	 * meaning that NO monies are owing: TXN_paid == TXN_total
60
+	 */
61
+	const complete_status_code = 'TCM';
62
+
63
+	/**
64
+	 *  Status ID(STS_ID on esp_status table) to indicate the transaction is overpaid.
65
+	 *  This is the same as complete, but site admins actually owe clients the moneys!  TXN_paid > TXN_total
66
+	 */
67
+	const overpaid_status_code = 'TOP';
68
+
69
+
70
+	/**
71
+	 *    private constructor to prevent direct creation
72
+	 *
73
+	 * @Constructor
74
+	 * @access protected
75
+	 *
76
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
77
+	 *                         incoming timezone data that gets saved). Note this just sends the timezone info to the
78
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
79
+	 *                         timezone in the 'timezone_string' wp option)
80
+	 *
81
+	 * @return EEM_Transaction
82
+	 * @throws \EE_Error
83
+	 */
84
+	protected function __construct($timezone)
85
+	{
86
+		$this->singular_item = __('Transaction', 'event_espresso');
87
+		$this->plural_item   = __('Transactions', 'event_espresso');
88
+
89
+		$this->_tables                 = array(
90
+			'TransactionTable' => new EE_Primary_Table('esp_transaction', 'TXN_ID')
91
+		);
92
+		$this->_fields                 = array(
93
+			'TransactionTable' => array(
94
+				'TXN_ID'           => new EE_Primary_Key_Int_Field('TXN_ID', __('Transaction ID', 'event_espresso')),
95
+				'TXN_timestamp'    => new EE_Datetime_Field('TXN_timestamp',
96
+					__('date when transaction was created', 'event_espresso'), false, EE_Datetime_Field::now,
97
+					$timezone),
98
+				'TXN_total'        => new EE_Money_Field('TXN_total',
99
+					__('Total value of Transaction', 'event_espresso'), false, 0),
100
+				'TXN_paid'         => new EE_Money_Field('TXN_paid',
101
+					__('Amount paid towards transaction to date', 'event_espresso'), false, 0),
102
+				'STS_ID'           => new EE_Foreign_Key_String_Field('STS_ID', __('Status ID', 'event_espresso'),
103
+					false, EEM_Transaction::failed_status_code, 'Status'),
104
+				'TXN_session_data' => new EE_Serialized_Text_Field('TXN_session_data',
105
+					__('Serialized session data', 'event_espresso'), true, ''),
106
+				'TXN_hash_salt'    => new EE_Plain_Text_Field('TXN_hash_salt',
107
+					__('Transaction Hash Salt', 'event_espresso'), true, ''),
108
+				'PMD_ID'           => new EE_Foreign_Key_Int_Field('PMD_ID',
109
+					__("Last Used Payment Method", 'event_espresso'), true, null, 'Payment_Method'),
110
+				'TXN_reg_steps'    => new EE_Serialized_Text_Field('TXN_reg_steps',
111
+					__('Registration Steps', 'event_espresso'), false, array()),
112
+			)
113
+		);
114
+		$this->_model_relations        = array(
115
+			'Registration'   => new EE_Has_Many_Relation(),
116
+			'Payment'        => new EE_Has_Many_Relation(),
117
+			'Status'         => new EE_Belongs_To_Relation(),
118
+			'Line_Item'      => new EE_Has_Many_Relation(false),
119
+			//you can delete a transaction without needing to delete its line items
120
+			'Payment_Method' => new EE_Belongs_To_Relation(),
121
+			'Message'        => new EE_Has_Many_Relation()
122
+		);
123
+		$this->_model_chain_to_wp_user = 'Registration.Event';
124
+		parent::__construct($timezone);
125
+
126
+	}
127
+
128
+
129
+	/**
130
+	 *    txn_status_array
131
+	 * get list of transaction statuses
132
+	 *
133
+	 * @access public
134
+	 * @return array
135
+	 */
136
+	public static function txn_status_array()
137
+	{
138
+		return apply_filters(
139
+			'FHEE__EEM_Transaction__txn_status_array',
140
+			array(
141
+				EEM_Transaction::overpaid_status_code,
142
+				EEM_Transaction::complete_status_code,
143
+				EEM_Transaction::incomplete_status_code,
144
+				EEM_Transaction::abandoned_status_code,
145
+				EEM_Transaction::failed_status_code,
146
+			)
147
+		);
148
+	}
149
+
150
+	/**
151
+	 *        get the revenue per day  for the Transaction Admin page Reports Tab
152
+	 *
153
+	 * @access        public
154
+	 *
155
+	 * @param string $period
156
+	 *
157
+	 * @return \stdClass[]
158
+	 */
159
+	public function get_revenue_per_day_report($period = '-1 month')
160
+	{
161
+		$sql_date = $this->convert_datetime_for_query('TXN_timestamp', date('Y-m-d H:i:s', strtotime($period)),
162
+			'Y-m-d H:i:s', 'UTC');
163
+
164
+		$query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset($this->get_timezone(), 'TXN_timestamp');
165
+
166
+		return $this->_get_all_wpdb_results(
167
+			array(
168
+				array(
169
+					'TXN_timestamp' => array('>=', $sql_date)
170
+				),
171
+				'group_by' => 'txnDate',
172
+				'order_by' => array('TXN_timestamp' => 'ASC')
173
+			),
174
+			OBJECT,
175
+			array(
176
+				'txnDate' => array('DATE(' . $query_interval . ')', '%s'),
177
+				'revenue' => array('SUM(TransactionTable.TXN_paid)', '%d')
178
+			)
179
+		);
180
+	}
181
+
182
+
183
+	/**
184
+	 *        get the revenue per event  for the Transaction Admin page Reports Tab
185
+	 *
186
+	 * @access        public
187
+	 *
188
+	 * @param string $period
189
+	 *
190
+	 * @throws \EE_Error
191
+	 * @return mixed
192
+	 */
193
+	public function get_revenue_per_event_report($period = '-1 month')
194
+	{
195
+		global $wpdb;
196
+		$transaction_table          = $wpdb->prefix . 'esp_transaction';
197
+		$registration_table         = $wpdb->prefix . 'esp_registration';
198
+		$registration_payment_table = $wpdb->prefix . 'esp_registration_payment';
199
+		$event_table                = $wpdb->posts;
200
+		$payment_table              = $wpdb->prefix . 'esp_payment';
201
+		$sql_date                   = date('Y-m-d H:i:s', strtotime($period));
202
+		$approved_payment_status    = EEM_Payment::status_id_approved;
203
+		$extra_event_on_join        = '';
204
+		//exclude events not authored by user if permissions in effect
205
+		if ( ! EE_Registry::instance()->CAP->current_user_can('ee_read_others_registrations', 'reg_per_event_report')) {
206
+			$extra_event_on_join = ' AND Event.post_author = ' . get_current_user_id();
207
+		}
208
+
209
+		return $wpdb->get_results(
210
+			"SELECT
211 211
 			Transaction_Event.event_name AS event_name,
212 212
 			SUM(Transaction_Event.paid) AS revenue
213 213
 			FROM
@@ -235,227 +235,227 @@  discard block
 block discarded – undo
235 235
 					$extra_event_on_join
236 236
 				) AS Transaction_Event
237 237
 			GROUP BY event_name",
238
-            OBJECT
239
-        );
240
-    }
241
-
242
-
243
-    /**
244
-     * Gets the current transaction given the reg_url_link, or assumes the reg_url_link is in the
245
-     * $_REQUEST global variable. Either way, tries to find the current transaction (through
246
-     * the registration pointed to by reg_url_link), if not returns null
247
-     *
248
-     * @param string $reg_url_link
249
-     *
250
-     * @return EE_Transaction
251
-     */
252
-    public function get_transaction_from_reg_url_link($reg_url_link = '')
253
-    {
254
-        return $this->get_one(array(
255
-            array(
256
-                'Registration.REG_url_link' => ! empty($reg_url_link) ? $reg_url_link : EE_Registry::instance()->REQ->get('e_reg_url_link',
257
-                    '')
258
-            )
259
-        ));
260
-    }
261
-
262
-
263
-    /**
264
-     * Updates the provided EE_Transaction with all the applicable payments
265
-     * (or fetch the EE_Transaction from its ID)
266
-     *
267
-     * @deprecated
268
-     *
269
-     * @param EE_Transaction|int $transaction_obj_or_id
270
-     * @param boolean            $save_txn whether or not to save the transaction during this function call
271
-     *
272
-     * @return boolean
273
-     * @throws \EE_Error
274
-     */
275
-    public function update_based_on_payments($transaction_obj_or_id, $save_txn = true)
276
-    {
277
-        EE_Error::doing_it_wrong(
278
-            __CLASS__ . '::' . __FUNCTION__,
279
-            sprintf(__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
280
-                'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'),
281
-            '4.6.0'
282
-        );
283
-        /** @type EE_Transaction_Processor $transaction_processor */
284
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
285
-
286
-        return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
287
-            $this->ensure_is_obj($transaction_obj_or_id)
288
-        );
289
-    }
290
-
291
-    /**
292
-     * Deletes "junk" transactions that were probably added by bots. There might be TONS
293
-     * of these, so we are very careful to NOT select (which the models do even when deleting),
294
-     * and so we only use wpdb directly and only do minimal joins.
295
-     * Transactions are considered "junk" if they're failed for longer than a week.
296
-     * Also, there is an extra check for payments related to the transaction, because if a transaction has a payment on
297
-     * it, it's probably not junk (regardless of what status it has).
298
-     * The downside to this approach is that is addons are listening for object deletions
299
-     * on EEM_Base::delete() they won't be notified of this.  However, there is an action that plugins can hook into
300
-     * to catch these types of deletions.
301
-     *
302
-     * @global WPDB $wpdb
303
-     * @return mixed
304
-     */
305
-    public function delete_junk_transactions()
306
-    {
307
-        /** @type WPDB $wpdb */
308
-        global $wpdb;
309
-        $deleted             = false;
310
-        $time_to_leave_alone = apply_filters(
311
-            'FHEE__EEM_Transaction__delete_junk_transactions__time_to_leave_alone'
312
-            , WEEK_IN_SECONDS
313
-        );
314
-
315
-
316
-        /**
317
-         * This allows code to filter the query arguments used for retrieving the transaction IDs to delete.
318
-         * Useful for plugins that want to exclude transactions matching certain query parameters.
319
-         * The query parameters should be in the format accepted by the EEM_Base model queries.
320
-         */
321
-        $ids_query = apply_filters(
322
-            'FHEE__EEM_Transaction__delete_junk_transactions__initial_query_args',
323
-            array(
324
-                0 => array(
325
-                    'STS_ID'        => EEM_Transaction::failed_status_code,
326
-                    'Payment.PAY_ID' => array( 'IS NULL' ),
327
-                    'TXN_timestamp' => array('<', time() - $time_to_leave_alone)
328
-                )
329
-            ),
330
-            $time_to_leave_alone
331
-        );
332
-
333
-
334
-        /**
335
-         * This filter is for when code needs to filter the list of transaction ids that represent transactions
336
-         * about to be deleted based on some other criteria that isn't easily done via the query args filter.
337
-         */
338
-        $txn_ids = apply_filters(
339
-            'FHEE__EEM_Transaction__delete_junk_transactions__transaction_ids_to_delete',
340
-            EEM_Transaction::instance()->get_col($ids_query, 'TXN_ID'),
341
-            $time_to_leave_alone
342
-        );
343
-        //now that we have the ids to delete
344
-        if (! empty($txn_ids) && is_array($txn_ids)) {
345
-            // first, make sure these TXN's are removed the "ee_locked_transactions" array
346
-            EEM_Transaction::unset_locked_transactions($txn_ids);
347
-            // let's get deletin'...
348
-            // Why no wpdb->prepare?  Because the data is trusted.
349
-            // We got the ids from the original query to get them FROM
350
-            // the db (which is sanitized) so no need to prepare them again.
351
-            $query   = '
238
+			OBJECT
239
+		);
240
+	}
241
+
242
+
243
+	/**
244
+	 * Gets the current transaction given the reg_url_link, or assumes the reg_url_link is in the
245
+	 * $_REQUEST global variable. Either way, tries to find the current transaction (through
246
+	 * the registration pointed to by reg_url_link), if not returns null
247
+	 *
248
+	 * @param string $reg_url_link
249
+	 *
250
+	 * @return EE_Transaction
251
+	 */
252
+	public function get_transaction_from_reg_url_link($reg_url_link = '')
253
+	{
254
+		return $this->get_one(array(
255
+			array(
256
+				'Registration.REG_url_link' => ! empty($reg_url_link) ? $reg_url_link : EE_Registry::instance()->REQ->get('e_reg_url_link',
257
+					'')
258
+			)
259
+		));
260
+	}
261
+
262
+
263
+	/**
264
+	 * Updates the provided EE_Transaction with all the applicable payments
265
+	 * (or fetch the EE_Transaction from its ID)
266
+	 *
267
+	 * @deprecated
268
+	 *
269
+	 * @param EE_Transaction|int $transaction_obj_or_id
270
+	 * @param boolean            $save_txn whether or not to save the transaction during this function call
271
+	 *
272
+	 * @return boolean
273
+	 * @throws \EE_Error
274
+	 */
275
+	public function update_based_on_payments($transaction_obj_or_id, $save_txn = true)
276
+	{
277
+		EE_Error::doing_it_wrong(
278
+			__CLASS__ . '::' . __FUNCTION__,
279
+			sprintf(__('This method is deprecated. Please use "%s" instead', 'event_espresso'),
280
+				'EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()'),
281
+			'4.6.0'
282
+		);
283
+		/** @type EE_Transaction_Processor $transaction_processor */
284
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
285
+
286
+		return $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
287
+			$this->ensure_is_obj($transaction_obj_or_id)
288
+		);
289
+	}
290
+
291
+	/**
292
+	 * Deletes "junk" transactions that were probably added by bots. There might be TONS
293
+	 * of these, so we are very careful to NOT select (which the models do even when deleting),
294
+	 * and so we only use wpdb directly and only do minimal joins.
295
+	 * Transactions are considered "junk" if they're failed for longer than a week.
296
+	 * Also, there is an extra check for payments related to the transaction, because if a transaction has a payment on
297
+	 * it, it's probably not junk (regardless of what status it has).
298
+	 * The downside to this approach is that is addons are listening for object deletions
299
+	 * on EEM_Base::delete() they won't be notified of this.  However, there is an action that plugins can hook into
300
+	 * to catch these types of deletions.
301
+	 *
302
+	 * @global WPDB $wpdb
303
+	 * @return mixed
304
+	 */
305
+	public function delete_junk_transactions()
306
+	{
307
+		/** @type WPDB $wpdb */
308
+		global $wpdb;
309
+		$deleted             = false;
310
+		$time_to_leave_alone = apply_filters(
311
+			'FHEE__EEM_Transaction__delete_junk_transactions__time_to_leave_alone'
312
+			, WEEK_IN_SECONDS
313
+		);
314
+
315
+
316
+		/**
317
+		 * This allows code to filter the query arguments used for retrieving the transaction IDs to delete.
318
+		 * Useful for plugins that want to exclude transactions matching certain query parameters.
319
+		 * The query parameters should be in the format accepted by the EEM_Base model queries.
320
+		 */
321
+		$ids_query = apply_filters(
322
+			'FHEE__EEM_Transaction__delete_junk_transactions__initial_query_args',
323
+			array(
324
+				0 => array(
325
+					'STS_ID'        => EEM_Transaction::failed_status_code,
326
+					'Payment.PAY_ID' => array( 'IS NULL' ),
327
+					'TXN_timestamp' => array('<', time() - $time_to_leave_alone)
328
+				)
329
+			),
330
+			$time_to_leave_alone
331
+		);
332
+
333
+
334
+		/**
335
+		 * This filter is for when code needs to filter the list of transaction ids that represent transactions
336
+		 * about to be deleted based on some other criteria that isn't easily done via the query args filter.
337
+		 */
338
+		$txn_ids = apply_filters(
339
+			'FHEE__EEM_Transaction__delete_junk_transactions__transaction_ids_to_delete',
340
+			EEM_Transaction::instance()->get_col($ids_query, 'TXN_ID'),
341
+			$time_to_leave_alone
342
+		);
343
+		//now that we have the ids to delete
344
+		if (! empty($txn_ids) && is_array($txn_ids)) {
345
+			// first, make sure these TXN's are removed the "ee_locked_transactions" array
346
+			EEM_Transaction::unset_locked_transactions($txn_ids);
347
+			// let's get deletin'...
348
+			// Why no wpdb->prepare?  Because the data is trusted.
349
+			// We got the ids from the original query to get them FROM
350
+			// the db (which is sanitized) so no need to prepare them again.
351
+			$query   = '
352 352
 				DELETE
353 353
 				FROM ' . $this->table() . '
354 354
 				WHERE
355 355
 					TXN_ID IN ( ' . implode(",", $txn_ids) . ')';
356
-            $deleted = $wpdb->query($query);
357
-        }
358
-        if ($deleted) {
359
-            /**
360
-             * Allows code to do something after the transactions have been deleted.
361
-             */
362
-            do_action('AHEE__EEM_Transaction__delete_junk_transactions__successful_deletion', $txn_ids);
363
-        }
364
-
365
-        return $deleted;
366
-    }
367
-
368
-
369
-    /**
370
-     * @param array $transaction_IDs
371
-     *
372
-     * @return bool
373
-     */
374
-    public static function unset_locked_transactions(array $transaction_IDs)
375
-    {
376
-        $locked_transactions = get_option('ee_locked_transactions', array());
377
-        $update              = false;
378
-        foreach ($transaction_IDs as $TXN_ID) {
379
-            if (isset($locked_transactions[$TXN_ID])) {
380
-                unset($locked_transactions[$TXN_ID]);
381
-                $update = true;
382
-            }
383
-        }
384
-        if ($update) {
385
-            update_option('ee_locked_transactions', $locked_transactions);
386
-        }
387
-
388
-        return $update;
389
-    }
390
-
391
-
392
-
393
-    /**
394
-     * returns an array of EE_Transaction objects whose timestamp is greater than
395
-     * the current time minus the session lifespan, which defaults to 60 minutes
396
-     *
397
-     * @return EE_Base_Class[]|EE_Transaction[]
398
-     * @throws EE_Error
399
-     * @throws InvalidArgumentException
400
-     * @throws InvalidDataTypeException
401
-     * @throws InvalidInterfaceException
402
-     */
403
-    public function get_transactions_in_progress()
404
-    {
405
-        return $this->_get_transactions_in_progress();
406
-    }
407
-
408
-
409
-
410
-    /**
411
-     * returns an array of EE_Transaction objects whose timestamp is less than
412
-     * the current time minus the session lifespan, which defaults to 60 minutes
413
-     *
414
-     * @return EE_Base_Class[]|EE_Transaction[]
415
-     * @throws EE_Error
416
-     * @throws InvalidArgumentException
417
-     * @throws InvalidDataTypeException
418
-     * @throws InvalidInterfaceException
419
-     */
420
-    public function get_transactions_not_in_progress()
421
-    {
422
-        return $this->_get_transactions_in_progress('<=');
423
-    }
424
-
425
-
426
-
427
-    /**
428
-     * @param string $comparison
429
-     * @return EE_Base_Class[]|EE_Transaction[]
430
-     * @throws EE_Error
431
-     * @throws InvalidArgumentException
432
-     * @throws InvalidDataTypeException
433
-     * @throws InvalidInterfaceException
434
-     */
435
-    private function _get_transactions_in_progress($comparison = '>=')
436
-    {
437
-        $comparison = $comparison === '>=' || $comparison === '<='
438
-            ? $comparison
439
-            : '>=';
440
-        /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
441
-        $session_lifespan = LoaderFactory::getLoader()->getShared(
442
-            'EventEspresso\core\domain\values\session\SessionLifespan'
443
-        );
444
-        return $this->get_all(
445
-            array(
446
-                array(
447
-                    'TXN_timestamp' => array(
448
-                        $comparison,
449
-                        $session_lifespan->expiration()
450
-                    ),
451
-                    'STS_ID' => array(
452
-                        '!=',
453
-                        EEM_Transaction::complete_status_code
454
-                    ),
455
-                )
456
-            )
457
-        );
458
-    }
356
+			$deleted = $wpdb->query($query);
357
+		}
358
+		if ($deleted) {
359
+			/**
360
+			 * Allows code to do something after the transactions have been deleted.
361
+			 */
362
+			do_action('AHEE__EEM_Transaction__delete_junk_transactions__successful_deletion', $txn_ids);
363
+		}
364
+
365
+		return $deleted;
366
+	}
367
+
368
+
369
+	/**
370
+	 * @param array $transaction_IDs
371
+	 *
372
+	 * @return bool
373
+	 */
374
+	public static function unset_locked_transactions(array $transaction_IDs)
375
+	{
376
+		$locked_transactions = get_option('ee_locked_transactions', array());
377
+		$update              = false;
378
+		foreach ($transaction_IDs as $TXN_ID) {
379
+			if (isset($locked_transactions[$TXN_ID])) {
380
+				unset($locked_transactions[$TXN_ID]);
381
+				$update = true;
382
+			}
383
+		}
384
+		if ($update) {
385
+			update_option('ee_locked_transactions', $locked_transactions);
386
+		}
387
+
388
+		return $update;
389
+	}
390
+
391
+
392
+
393
+	/**
394
+	 * returns an array of EE_Transaction objects whose timestamp is greater than
395
+	 * the current time minus the session lifespan, which defaults to 60 minutes
396
+	 *
397
+	 * @return EE_Base_Class[]|EE_Transaction[]
398
+	 * @throws EE_Error
399
+	 * @throws InvalidArgumentException
400
+	 * @throws InvalidDataTypeException
401
+	 * @throws InvalidInterfaceException
402
+	 */
403
+	public function get_transactions_in_progress()
404
+	{
405
+		return $this->_get_transactions_in_progress();
406
+	}
407
+
408
+
409
+
410
+	/**
411
+	 * returns an array of EE_Transaction objects whose timestamp is less than
412
+	 * the current time minus the session lifespan, which defaults to 60 minutes
413
+	 *
414
+	 * @return EE_Base_Class[]|EE_Transaction[]
415
+	 * @throws EE_Error
416
+	 * @throws InvalidArgumentException
417
+	 * @throws InvalidDataTypeException
418
+	 * @throws InvalidInterfaceException
419
+	 */
420
+	public function get_transactions_not_in_progress()
421
+	{
422
+		return $this->_get_transactions_in_progress('<=');
423
+	}
424
+
425
+
426
+
427
+	/**
428
+	 * @param string $comparison
429
+	 * @return EE_Base_Class[]|EE_Transaction[]
430
+	 * @throws EE_Error
431
+	 * @throws InvalidArgumentException
432
+	 * @throws InvalidDataTypeException
433
+	 * @throws InvalidInterfaceException
434
+	 */
435
+	private function _get_transactions_in_progress($comparison = '>=')
436
+	{
437
+		$comparison = $comparison === '>=' || $comparison === '<='
438
+			? $comparison
439
+			: '>=';
440
+		/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
441
+		$session_lifespan = LoaderFactory::getLoader()->getShared(
442
+			'EventEspresso\core\domain\values\session\SessionLifespan'
443
+		);
444
+		return $this->get_all(
445
+			array(
446
+				array(
447
+					'TXN_timestamp' => array(
448
+						$comparison,
449
+						$session_lifespan->expiration()
450
+					),
451
+					'STS_ID' => array(
452
+						'!=',
453
+						EEM_Transaction::complete_status_code
454
+					),
455
+				)
456
+			)
457
+		);
458
+	}
459 459
 
460 460
 
461 461
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Line_Item.model.php 3 patches
Indentation   +382 added lines, -382 removed lines patch added patch discarded remove patch
@@ -47,391 +47,391 @@
 block discarded – undo
47 47
 class EEM_Line_Item extends EEM_Base
48 48
 {
49 49
 
50
-    /**
51
-     * Tax sub-total is just the total of all the taxes, which should be children
52
-     * of this line item. There should only ever be one tax sub-total, and it should
53
-     * be a direct child of
54
-     */
55
-    const type_tax_sub_total = 'tax-sub-total';
56
-
57
-    /**
58
-     * Tax line items indicate a tax applied to all the taxable line items.
59
-     * Should not have any children line items.
60
-     */
61
-    const type_tax = 'tax';
62
-
63
-    /**
64
-     * Indicating individual items purchased, or discounts or surcharges.
65
-     * The sum of all the regular line items  plus the tax items should equal
66
-     * the grand total.
67
-     * Possible children fo sub-line-items and cancellations.
68
-     */
69
-    const type_line_item = 'line-item';
70
-
71
-    /**
72
-     * line item indicating all the factors that make a single line item.
73
-     * Sub-line items should have NO children line items.
74
-     */
75
-    const type_sub_line_item = 'sub-item';
76
-
77
-    /**
78
-     * line item indicating a sub-total (eg total for an event, or before taxes).
79
-     * Direct children can be line items and other sub-totals
80
-     *
81
-     */
82
-    const type_sub_total = 'sub-total';
83
-
84
-    /**
85
-     * line item for teh grand total of an order. Its direct children
86
-     * should be tax subtotals and subtotals, and possibly a regular line item
87
-     * indicating a transaction-wide discount/surcharge
88
-     */
89
-    const type_total = 'total';
90
-
91
-    /**
92
-     * When a line item is cancelled, a sub-line-item of type 'cancellation'
93
-     * should be created, indicating the quantity that were cancelled
94
-     * (because a line item could have a quantity of 1, and its cancellation item
95
-     * could be for 3, indicating that originally 4 were purchased, but 3 have been
96
-     * cancelled, and only one remains).
97
-     * When items are refunded, a cancellation line item should be made, which points
98
-     * to teh payment model object which actually refunded the payment.
99
-     * Cancellations should NOT have any children line items; the should NOT affect
100
-     * any calculations, and are only meant as a record that cancellations have occurred.
101
-     */
102
-    const type_cancellation = 'cancellation';
103
-
104
-    // private instance of the EEM_Line_Item object
105
-    protected static $_instance = NULL;
106
-
107
-
108
-    /**
109
-     *        private constructor to prevent direct creation
110
-     * @Constructor
111
-     * @access protected
112
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any incoming timezone data that gets saved).  Note this just sends the timezone info to the date time model field objects.  Default is NULL (and will be assumed using the set timezone in the 'timezone_string' wp option)
113
-     * @return \EEM_Line_Item
114
-     */
115
-    protected function __construct($timezone)
116
-    {
117
-        $this->singular_item = __('Line Item', 'event_espresso');
118
-        $this->plural_item = __('Line Items', 'event_espresso');
119
-
120
-        $this->_tables = array(
121
-            'Line_Item' => new EE_Primary_Table('esp_line_item', 'LIN_ID')
122
-        );
123
-        $line_items_can_be_for = apply_filters('FHEE__EEM_Line_Item__line_items_can_be_for', array('Ticket', 'Price', 'Event'));
124
-        $this->_fields = array(
125
-            'Line_Item' => array(
126
-                'LIN_ID' => new EE_Primary_Key_Int_Field('LIN_ID', __("ID", "event_espresso")),
127
-                'LIN_code' => new EE_Slug_Field('LIN_code', __("Code for index into Cart", "event_espresso"), TRUE),
128
-                'TXN_ID' => new EE_Foreign_Key_Int_Field('TXN_ID', __("Transaction ID", "event_espresso"), TRUE, NULL, 'Transaction'),
129
-                'LIN_name' => new EE_Full_HTML_Field('LIN_name', __("Line Item Name", "event_espresso"), FALSE, ''),
130
-                'LIN_desc' => new EE_Full_HTML_Field('LIN_desc', __("Line Item Description", "event_espresso"), TRUE),
131
-                'LIN_unit_price' => new EE_Money_Field('LIN_unit_price', __("Unit Price", "event_espresso"), FALSE, 0),
132
-                'LIN_percent' => new EE_Float_Field('LIN_percent', __("Percent", "event_espresso"), FALSE, 0),
133
-                'LIN_is_taxable' => new EE_Boolean_Field('LIN_is_taxable', __("Taxable", "event_espresso"), FALSE, FALSE),
134
-                'LIN_order' => new EE_Integer_Field('LIN_order', __("Order of Application towards total of parent", "event_espresso"), FALSE, 1),
135
-                'LIN_total' => new EE_Money_Field('LIN_total', __("Total (unit price x quantity)", "event_espresso"), FALSE, 0),
136
-                'LIN_quantity' => new EE_Integer_Field('LIN_quantity', __("Quantity", "event_espresso"), TRUE, 1),
137
-                'LIN_parent' => new EE_Integer_Field('LIN_parent', __("Parent ID (this item goes towards that Line Item's total)", "event_espresso"), TRUE, NULL),
138
-                'LIN_type' => new EE_Enum_Text_Field('LIN_type', __("Type", "event_espresso"), FALSE, 'line-item', array(
139
-                        self::type_line_item => __("Line Item", "event_espresso"),
140
-                        self::type_sub_line_item => __("Sub-Item", "event_espresso"),
141
-                        self::type_sub_total => __("Subtotal", "event_espresso"),
142
-                        self::type_tax_sub_total => __("Tax Subtotal", "event_espresso"),
143
-                        self::type_tax => __("Tax", "event_espresso"),
144
-                        self::type_total => __("Total", "event_espresso"),
145
-                        self::type_cancellation => __('Cancellation', 'event_espresso')
146
-                    )
147
-                ),
148
-                'OBJ_ID' => new EE_Foreign_Key_Int_Field('OBJ_ID', __('ID of Item purchased.', 'event_espresso'), TRUE, NULL, $line_items_can_be_for),
149
-                'OBJ_type' => new EE_Any_Foreign_Model_Name_Field('OBJ_type', __("Model Name this Line Item is for", "event_espresso"), TRUE, NULL, $line_items_can_be_for),
150
-                'LIN_timestamp' => new EE_Datetime_Field('LIN_timestamp', __('When the line item was created', 'event_espresso'), false, EE_Datetime_Field::now, $timezone),
151
-            )
152
-        );
153
-        $this->_model_relations = array(
154
-            'Transaction' => new EE_Belongs_To_Relation(),
155
-            'Ticket' => new EE_Belongs_To_Any_Relation(),
156
-            'Price' => new EE_Belongs_To_Any_Relation(),
157
-            'Event' => new EE_Belongs_To_Any_Relation()
158
-        );
159
-        $this->_model_chain_to_wp_user = 'Transaction.Registration.Event';
160
-        $this->_caps_slug = 'transactions';
161
-        parent::__construct($timezone);
162
-    }
163
-
164
-
165
-    /**
166
-     * Gets all the line items for this transaction of the given type
167
-     * @param string $line_item_type like one of EEM_Line_Item::type_*
168
-     * @param EE_Transaction|int $transaction
169
-     * @return EE_Line_Item[]
170
-     */
171
-    public function get_all_of_type_for_transaction($line_item_type, $transaction)
172
-    {
173
-        $transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
174
-        return $this->get_all(array(array(
175
-            'LIN_type' => $line_item_type,
176
-            'TXN_ID' => $transaction
177
-        )));
178
-    }
179
-
180
-
181
-    /**
182
-     * Gets all line items unrelated to tickets that are normal line items
183
-     * (eg shipping, promotions, and miscellaneous other stuff should probably fit in this category)
184
-     * @param EE_Transaction|int $transaction
185
-     * @return EE_Line_Item[]
186
-     */
187
-    public function get_all_non_ticket_line_items_for_transaction($transaction)
188
-    {
189
-        $transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
190
-        return $this->get_all(array(array(
191
-            'LIN_type' => self::type_line_item,
192
-            'TXN_ID' => $transaction,
193
-            'OR' => array(
194
-                'OBJ_type*notticket' => array('!=', 'Ticket'),
195
-                'OBJ_type*null' => array('IS_NULL'))
196
-        )));
197
-    }
198
-
199
-    /**
200
-     * Deletes line items with no transaction who have passed the transaction cutoff time.
201
-     * This needs to be very efficient
202
-     * because if there are spam bots afoot there will be LOTS of line items
203
-     * @return int count of how many deleted
204
-     */
205
-    public function delete_line_items_with_no_transaction()
206
-    {
207
-        /** @type WPDB $wpdb */
208
-        global $wpdb;
209
-        $time_to_leave_alone = apply_filters(
210
-            'FHEE__EEM_Line_Item__delete_line_items_with_no_transaction__time_to_leave_alone', WEEK_IN_SECONDS
211
-        );
212
-        $query = $wpdb->prepare(
213
-            'DELETE li
50
+	/**
51
+	 * Tax sub-total is just the total of all the taxes, which should be children
52
+	 * of this line item. There should only ever be one tax sub-total, and it should
53
+	 * be a direct child of
54
+	 */
55
+	const type_tax_sub_total = 'tax-sub-total';
56
+
57
+	/**
58
+	 * Tax line items indicate a tax applied to all the taxable line items.
59
+	 * Should not have any children line items.
60
+	 */
61
+	const type_tax = 'tax';
62
+
63
+	/**
64
+	 * Indicating individual items purchased, or discounts or surcharges.
65
+	 * The sum of all the regular line items  plus the tax items should equal
66
+	 * the grand total.
67
+	 * Possible children fo sub-line-items and cancellations.
68
+	 */
69
+	const type_line_item = 'line-item';
70
+
71
+	/**
72
+	 * line item indicating all the factors that make a single line item.
73
+	 * Sub-line items should have NO children line items.
74
+	 */
75
+	const type_sub_line_item = 'sub-item';
76
+
77
+	/**
78
+	 * line item indicating a sub-total (eg total for an event, or before taxes).
79
+	 * Direct children can be line items and other sub-totals
80
+	 *
81
+	 */
82
+	const type_sub_total = 'sub-total';
83
+
84
+	/**
85
+	 * line item for teh grand total of an order. Its direct children
86
+	 * should be tax subtotals and subtotals, and possibly a regular line item
87
+	 * indicating a transaction-wide discount/surcharge
88
+	 */
89
+	const type_total = 'total';
90
+
91
+	/**
92
+	 * When a line item is cancelled, a sub-line-item of type 'cancellation'
93
+	 * should be created, indicating the quantity that were cancelled
94
+	 * (because a line item could have a quantity of 1, and its cancellation item
95
+	 * could be for 3, indicating that originally 4 were purchased, but 3 have been
96
+	 * cancelled, and only one remains).
97
+	 * When items are refunded, a cancellation line item should be made, which points
98
+	 * to teh payment model object which actually refunded the payment.
99
+	 * Cancellations should NOT have any children line items; the should NOT affect
100
+	 * any calculations, and are only meant as a record that cancellations have occurred.
101
+	 */
102
+	const type_cancellation = 'cancellation';
103
+
104
+	// private instance of the EEM_Line_Item object
105
+	protected static $_instance = NULL;
106
+
107
+
108
+	/**
109
+	 *        private constructor to prevent direct creation
110
+	 * @Constructor
111
+	 * @access protected
112
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any incoming timezone data that gets saved).  Note this just sends the timezone info to the date time model field objects.  Default is NULL (and will be assumed using the set timezone in the 'timezone_string' wp option)
113
+	 * @return \EEM_Line_Item
114
+	 */
115
+	protected function __construct($timezone)
116
+	{
117
+		$this->singular_item = __('Line Item', 'event_espresso');
118
+		$this->plural_item = __('Line Items', 'event_espresso');
119
+
120
+		$this->_tables = array(
121
+			'Line_Item' => new EE_Primary_Table('esp_line_item', 'LIN_ID')
122
+		);
123
+		$line_items_can_be_for = apply_filters('FHEE__EEM_Line_Item__line_items_can_be_for', array('Ticket', 'Price', 'Event'));
124
+		$this->_fields = array(
125
+			'Line_Item' => array(
126
+				'LIN_ID' => new EE_Primary_Key_Int_Field('LIN_ID', __("ID", "event_espresso")),
127
+				'LIN_code' => new EE_Slug_Field('LIN_code', __("Code for index into Cart", "event_espresso"), TRUE),
128
+				'TXN_ID' => new EE_Foreign_Key_Int_Field('TXN_ID', __("Transaction ID", "event_espresso"), TRUE, NULL, 'Transaction'),
129
+				'LIN_name' => new EE_Full_HTML_Field('LIN_name', __("Line Item Name", "event_espresso"), FALSE, ''),
130
+				'LIN_desc' => new EE_Full_HTML_Field('LIN_desc', __("Line Item Description", "event_espresso"), TRUE),
131
+				'LIN_unit_price' => new EE_Money_Field('LIN_unit_price', __("Unit Price", "event_espresso"), FALSE, 0),
132
+				'LIN_percent' => new EE_Float_Field('LIN_percent', __("Percent", "event_espresso"), FALSE, 0),
133
+				'LIN_is_taxable' => new EE_Boolean_Field('LIN_is_taxable', __("Taxable", "event_espresso"), FALSE, FALSE),
134
+				'LIN_order' => new EE_Integer_Field('LIN_order', __("Order of Application towards total of parent", "event_espresso"), FALSE, 1),
135
+				'LIN_total' => new EE_Money_Field('LIN_total', __("Total (unit price x quantity)", "event_espresso"), FALSE, 0),
136
+				'LIN_quantity' => new EE_Integer_Field('LIN_quantity', __("Quantity", "event_espresso"), TRUE, 1),
137
+				'LIN_parent' => new EE_Integer_Field('LIN_parent', __("Parent ID (this item goes towards that Line Item's total)", "event_espresso"), TRUE, NULL),
138
+				'LIN_type' => new EE_Enum_Text_Field('LIN_type', __("Type", "event_espresso"), FALSE, 'line-item', array(
139
+						self::type_line_item => __("Line Item", "event_espresso"),
140
+						self::type_sub_line_item => __("Sub-Item", "event_espresso"),
141
+						self::type_sub_total => __("Subtotal", "event_espresso"),
142
+						self::type_tax_sub_total => __("Tax Subtotal", "event_espresso"),
143
+						self::type_tax => __("Tax", "event_espresso"),
144
+						self::type_total => __("Total", "event_espresso"),
145
+						self::type_cancellation => __('Cancellation', 'event_espresso')
146
+					)
147
+				),
148
+				'OBJ_ID' => new EE_Foreign_Key_Int_Field('OBJ_ID', __('ID of Item purchased.', 'event_espresso'), TRUE, NULL, $line_items_can_be_for),
149
+				'OBJ_type' => new EE_Any_Foreign_Model_Name_Field('OBJ_type', __("Model Name this Line Item is for", "event_espresso"), TRUE, NULL, $line_items_can_be_for),
150
+				'LIN_timestamp' => new EE_Datetime_Field('LIN_timestamp', __('When the line item was created', 'event_espresso'), false, EE_Datetime_Field::now, $timezone),
151
+			)
152
+		);
153
+		$this->_model_relations = array(
154
+			'Transaction' => new EE_Belongs_To_Relation(),
155
+			'Ticket' => new EE_Belongs_To_Any_Relation(),
156
+			'Price' => new EE_Belongs_To_Any_Relation(),
157
+			'Event' => new EE_Belongs_To_Any_Relation()
158
+		);
159
+		$this->_model_chain_to_wp_user = 'Transaction.Registration.Event';
160
+		$this->_caps_slug = 'transactions';
161
+		parent::__construct($timezone);
162
+	}
163
+
164
+
165
+	/**
166
+	 * Gets all the line items for this transaction of the given type
167
+	 * @param string $line_item_type like one of EEM_Line_Item::type_*
168
+	 * @param EE_Transaction|int $transaction
169
+	 * @return EE_Line_Item[]
170
+	 */
171
+	public function get_all_of_type_for_transaction($line_item_type, $transaction)
172
+	{
173
+		$transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
174
+		return $this->get_all(array(array(
175
+			'LIN_type' => $line_item_type,
176
+			'TXN_ID' => $transaction
177
+		)));
178
+	}
179
+
180
+
181
+	/**
182
+	 * Gets all line items unrelated to tickets that are normal line items
183
+	 * (eg shipping, promotions, and miscellaneous other stuff should probably fit in this category)
184
+	 * @param EE_Transaction|int $transaction
185
+	 * @return EE_Line_Item[]
186
+	 */
187
+	public function get_all_non_ticket_line_items_for_transaction($transaction)
188
+	{
189
+		$transaction = EEM_Transaction::instance()->ensure_is_ID($transaction);
190
+		return $this->get_all(array(array(
191
+			'LIN_type' => self::type_line_item,
192
+			'TXN_ID' => $transaction,
193
+			'OR' => array(
194
+				'OBJ_type*notticket' => array('!=', 'Ticket'),
195
+				'OBJ_type*null' => array('IS_NULL'))
196
+		)));
197
+	}
198
+
199
+	/**
200
+	 * Deletes line items with no transaction who have passed the transaction cutoff time.
201
+	 * This needs to be very efficient
202
+	 * because if there are spam bots afoot there will be LOTS of line items
203
+	 * @return int count of how many deleted
204
+	 */
205
+	public function delete_line_items_with_no_transaction()
206
+	{
207
+		/** @type WPDB $wpdb */
208
+		global $wpdb;
209
+		$time_to_leave_alone = apply_filters(
210
+			'FHEE__EEM_Line_Item__delete_line_items_with_no_transaction__time_to_leave_alone', WEEK_IN_SECONDS
211
+		);
212
+		$query = $wpdb->prepare(
213
+			'DELETE li
214 214
 				FROM ' . $this->table() . ' li
215 215
 				LEFT JOIN ' . EEM_Transaction::instance()->table() . ' t ON li.TXN_ID = t.TXN_ID
216 216
 				WHERE t.TXN_ID IS NULL AND li.LIN_timestamp < %s',
217
-            // use GMT time because that's what TXN_timestamps are in
218
-            date('Y-m-d H:i:s', time() - $time_to_leave_alone)
219
-        );
220
-        return $wpdb->query($query);
221
-    }
222
-
223
-
224
-    /**
225
-     * get_line_item_for_transaction_object
226
-     * Gets a transaction's line item record for a specific object such as a EE_Event or EE_Ticket
227
-     *
228
-     * @param int $TXN_ID
229
-     * @param \EE_Base_Class $object
230
-     * @return EE_Line_Item[]
231
-     */
232
-    public function get_line_item_for_transaction_object($TXN_ID, EE_Base_Class $object)
233
-    {
234
-        return $this->get_all(array(array(
235
-            'TXN_ID' => $TXN_ID,
236
-            'OBJ_type' => str_replace('EE_', '', get_class($object)),
237
-            'OBJ_ID' => $object->ID()
238
-        )));
239
-    }
240
-
241
-
242
-    /**
243
-     * get_object_line_items_for_transaction
244
-     * Gets all of the the object line items for a transaction, based on an object type plus an array of object IDs
245
-     *
246
-     * @param int $TXN_ID
247
-     * @param string $OBJ_type
248
-     * @param array $OBJ_IDs
249
-     * @return EE_Line_Item[]
250
-     */
251
-    public function get_object_line_items_for_transaction($TXN_ID, $OBJ_type = 'Event', $OBJ_IDs = array())
252
-    {
253
-        $query_params = array(
254
-            'OBJ_type' => $OBJ_type,
255
-            // if incoming $OBJ_IDs is an array, then make sure it is formatted correctly for the query
256
-            'OBJ_ID' => is_array($OBJ_IDs) && !isset($OBJ_IDs['IN']) ? array('IN', $OBJ_IDs) : $OBJ_IDs
257
-        );
258
-        if ($TXN_ID) {
259
-            $query_params['TXN_ID'] = $TXN_ID;
260
-        }
261
-        return $this->get_all(array($query_params));
262
-    }
263
-
264
-
265
-    /**
266
-     * get_all_ticket_line_items_for_transaction
267
-     *
268
-     * @param EE_Transaction $transaction
269
-     * @return EE_Line_Item[]
270
-     */
271
-    public function get_all_ticket_line_items_for_transaction(EE_Transaction $transaction)
272
-    {
273
-        return $this->get_all(array(
274
-            array(
275
-                'TXN_ID' => $transaction->ID(),
276
-                'OBJ_type' => 'Ticket',
277
-            )
278
-        ));
279
-    }
280
-
281
-
282
-    /**
283
-     * get_ticket_line_item_for_transaction
284
-     *
285
-     * @param int $TXN_ID
286
-     * @param int $TKT_ID
287
-     * @return \EE_Line_Item
288
-     */
289
-    public function get_ticket_line_item_for_transaction($TXN_ID, $TKT_ID)
290
-    {
291
-        return $this->get_one(array(
292
-            array(
293
-                'TXN_ID' => EEM_Transaction::instance()->ensure_is_ID($TXN_ID),
294
-                'OBJ_ID' => $TKT_ID,
295
-                'OBJ_type' => 'Ticket',
296
-            )
297
-        ));
298
-    }
299
-
300
-
301
-    /**
302
-     * get_existing_promotion_line_item
303
-     * searches the cart for existing line items for the specified promotion
304
-     *
305
-     * @since   1.0.0
306
-     *
307
-     * @param EE_Line_Item $parent_line_item
308
-     * @param EE_Promotion $promotion
309
-     * @return EE_Line_Item
310
-     */
311
-    public function get_existing_promotion_line_item(EE_Line_Item $parent_line_item, EE_Promotion $promotion)
312
-    {
313
-        return $this->get_one(array(
314
-            array(
315
-                'TXN_ID' => $parent_line_item->TXN_ID(),
316
-                'LIN_parent' => $parent_line_item->ID(),
317
-                'OBJ_type' => 'Promotion',
318
-                'OBJ_ID' => $promotion->ID()
319
-            )
320
-        ));
321
-    }
322
-
323
-
324
-    /**
325
-     * get_all_promotion_line_items
326
-     * searches the cart for any and all existing promotion line items
327
-     *
328
-     * @since   1.0.0
329
-     *
330
-     * @param EE_Line_Item $parent_line_item
331
-     * @return EE_Line_Item[]
332
-     */
333
-    public function get_all_promotion_line_items(EE_Line_Item $parent_line_item)
334
-    {
335
-        return $this->get_all(array(
336
-            array(
337
-                'TXN_ID' => $parent_line_item->TXN_ID(),
338
-                'LIN_parent' => $parent_line_item->ID(),
339
-                'OBJ_type' => 'Promotion'
340
-            )
341
-        ));
342
-    }
343
-
344
-    /**
345
-     * Gets the registration's corresponding line item.
346
-     * Note: basically does NOT support having multiple line items for a single ticket,
347
-     * which would happen if some of the registrations had a price modifier while others didn't.
348
-     * In order to support that, we'd probably need a LIN_ID on registrations or something.
349
-     * @param EE_Registration $registration
350
-     * @return EE_Line_ITem
351
-     */
352
-    public function get_line_item_for_registration(EE_Registration $registration)
353
-    {
354
-        return $this->get_one($this->line_item_for_registration_query_params($registration));
355
-    }
356
-
357
-    /**
358
-     * Gets the query params used to retrieve a specific line item for the given registration
359
-     * @param EE_Registration $registration
360
-     * @param array $original_query_params any extra query params you'd like to be merged with
361
-     * @return array like EEM_Base::get_all()'s $query_params
362
-     */
363
-    public function line_item_for_registration_query_params(EE_Registration $registration, $original_query_params = array())
364
-    {
365
-        return array_replace_recursive($original_query_params, array(
366
-            array(
367
-                'OBJ_ID' => $registration->ticket_ID(),
368
-                'OBJ_type' => 'Ticket',
369
-                'TXN_ID' => $registration->transaction_ID()
370
-            )
371
-        ));
372
-    }
373
-
374
-
375
-    /**
376
-     * @return EE_Base_Class[]|EE_Line_Item[]
377
-     * @throws EE_Error
378
-     */
379
-    public function get_total_line_items_with_no_transaction()
380
-    {
381
-        return $this->get_total_line_items_for_carts();
382
-    }
383
-
384
-
385
-    /**
386
-     * @return EE_Base_Class[]|EE_Line_Item[]
387
-     * @throws EE_Error
388
-     */
389
-    public function get_total_line_items_for_active_carts()
390
-    {
391
-        return $this->get_total_line_items_for_carts(false);
392
-    }
393
-
394
-
395
-    /**
396
-     * @return EE_Base_Class[]|EE_Line_Item[]
397
-     * @throws EE_Error
398
-     */
399
-    public function get_total_line_items_for_expired_carts()
400
-    {
401
-        return $this->get_total_line_items_for_carts(true);
402
-    }
403
-
404
-
405
-    /**
406
-     * Returns an array of grand total line items where the TXN_ID is 0.
407
-     * If $expired is set to true, then only line items for expired sessions will be returned.
408
-     * If $expired is set to false, then only line items for active sessions will be returned.
409
-     *
410
-     * @param bool|null $expired
411
-     * @return EE_Base_Class[]|EE_Line_Item[]
412
-     * @throws InvalidInterfaceException
413
-     * @throws InvalidDataTypeException
414
-     * @throws EE_Error
415
-     * @throws InvalidArgumentException
416
-     */
417
-    private function get_total_line_items_for_carts($expired = null)
418
-    {
419
-        $where_params = array(
420
-            'TXN_ID' => 0,
421
-            'LIN_type' => 'total',
422
-        );
423
-        if ($expired !== null) {
424
-            /** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
425
-            $session_lifespan = LoaderFactory::getLoader()->getShared(
426
-                'EventEspresso\core\domain\values\session\SessionLifespan'
427
-            );
428
-            $where_params['LIN_timestamp'] = array(
429
-                $expired ? '<=' : '>',
430
-                $session_lifespan->expiration(),
431
-            );
432
-        }
433
-        return $this->get_all(array($where_params));
434
-    }
217
+			// use GMT time because that's what TXN_timestamps are in
218
+			date('Y-m-d H:i:s', time() - $time_to_leave_alone)
219
+		);
220
+		return $wpdb->query($query);
221
+	}
222
+
223
+
224
+	/**
225
+	 * get_line_item_for_transaction_object
226
+	 * Gets a transaction's line item record for a specific object such as a EE_Event or EE_Ticket
227
+	 *
228
+	 * @param int $TXN_ID
229
+	 * @param \EE_Base_Class $object
230
+	 * @return EE_Line_Item[]
231
+	 */
232
+	public function get_line_item_for_transaction_object($TXN_ID, EE_Base_Class $object)
233
+	{
234
+		return $this->get_all(array(array(
235
+			'TXN_ID' => $TXN_ID,
236
+			'OBJ_type' => str_replace('EE_', '', get_class($object)),
237
+			'OBJ_ID' => $object->ID()
238
+		)));
239
+	}
240
+
241
+
242
+	/**
243
+	 * get_object_line_items_for_transaction
244
+	 * Gets all of the the object line items for a transaction, based on an object type plus an array of object IDs
245
+	 *
246
+	 * @param int $TXN_ID
247
+	 * @param string $OBJ_type
248
+	 * @param array $OBJ_IDs
249
+	 * @return EE_Line_Item[]
250
+	 */
251
+	public function get_object_line_items_for_transaction($TXN_ID, $OBJ_type = 'Event', $OBJ_IDs = array())
252
+	{
253
+		$query_params = array(
254
+			'OBJ_type' => $OBJ_type,
255
+			// if incoming $OBJ_IDs is an array, then make sure it is formatted correctly for the query
256
+			'OBJ_ID' => is_array($OBJ_IDs) && !isset($OBJ_IDs['IN']) ? array('IN', $OBJ_IDs) : $OBJ_IDs
257
+		);
258
+		if ($TXN_ID) {
259
+			$query_params['TXN_ID'] = $TXN_ID;
260
+		}
261
+		return $this->get_all(array($query_params));
262
+	}
263
+
264
+
265
+	/**
266
+	 * get_all_ticket_line_items_for_transaction
267
+	 *
268
+	 * @param EE_Transaction $transaction
269
+	 * @return EE_Line_Item[]
270
+	 */
271
+	public function get_all_ticket_line_items_for_transaction(EE_Transaction $transaction)
272
+	{
273
+		return $this->get_all(array(
274
+			array(
275
+				'TXN_ID' => $transaction->ID(),
276
+				'OBJ_type' => 'Ticket',
277
+			)
278
+		));
279
+	}
280
+
281
+
282
+	/**
283
+	 * get_ticket_line_item_for_transaction
284
+	 *
285
+	 * @param int $TXN_ID
286
+	 * @param int $TKT_ID
287
+	 * @return \EE_Line_Item
288
+	 */
289
+	public function get_ticket_line_item_for_transaction($TXN_ID, $TKT_ID)
290
+	{
291
+		return $this->get_one(array(
292
+			array(
293
+				'TXN_ID' => EEM_Transaction::instance()->ensure_is_ID($TXN_ID),
294
+				'OBJ_ID' => $TKT_ID,
295
+				'OBJ_type' => 'Ticket',
296
+			)
297
+		));
298
+	}
299
+
300
+
301
+	/**
302
+	 * get_existing_promotion_line_item
303
+	 * searches the cart for existing line items for the specified promotion
304
+	 *
305
+	 * @since   1.0.0
306
+	 *
307
+	 * @param EE_Line_Item $parent_line_item
308
+	 * @param EE_Promotion $promotion
309
+	 * @return EE_Line_Item
310
+	 */
311
+	public function get_existing_promotion_line_item(EE_Line_Item $parent_line_item, EE_Promotion $promotion)
312
+	{
313
+		return $this->get_one(array(
314
+			array(
315
+				'TXN_ID' => $parent_line_item->TXN_ID(),
316
+				'LIN_parent' => $parent_line_item->ID(),
317
+				'OBJ_type' => 'Promotion',
318
+				'OBJ_ID' => $promotion->ID()
319
+			)
320
+		));
321
+	}
322
+
323
+
324
+	/**
325
+	 * get_all_promotion_line_items
326
+	 * searches the cart for any and all existing promotion line items
327
+	 *
328
+	 * @since   1.0.0
329
+	 *
330
+	 * @param EE_Line_Item $parent_line_item
331
+	 * @return EE_Line_Item[]
332
+	 */
333
+	public function get_all_promotion_line_items(EE_Line_Item $parent_line_item)
334
+	{
335
+		return $this->get_all(array(
336
+			array(
337
+				'TXN_ID' => $parent_line_item->TXN_ID(),
338
+				'LIN_parent' => $parent_line_item->ID(),
339
+				'OBJ_type' => 'Promotion'
340
+			)
341
+		));
342
+	}
343
+
344
+	/**
345
+	 * Gets the registration's corresponding line item.
346
+	 * Note: basically does NOT support having multiple line items for a single ticket,
347
+	 * which would happen if some of the registrations had a price modifier while others didn't.
348
+	 * In order to support that, we'd probably need a LIN_ID on registrations or something.
349
+	 * @param EE_Registration $registration
350
+	 * @return EE_Line_ITem
351
+	 */
352
+	public function get_line_item_for_registration(EE_Registration $registration)
353
+	{
354
+		return $this->get_one($this->line_item_for_registration_query_params($registration));
355
+	}
356
+
357
+	/**
358
+	 * Gets the query params used to retrieve a specific line item for the given registration
359
+	 * @param EE_Registration $registration
360
+	 * @param array $original_query_params any extra query params you'd like to be merged with
361
+	 * @return array like EEM_Base::get_all()'s $query_params
362
+	 */
363
+	public function line_item_for_registration_query_params(EE_Registration $registration, $original_query_params = array())
364
+	{
365
+		return array_replace_recursive($original_query_params, array(
366
+			array(
367
+				'OBJ_ID' => $registration->ticket_ID(),
368
+				'OBJ_type' => 'Ticket',
369
+				'TXN_ID' => $registration->transaction_ID()
370
+			)
371
+		));
372
+	}
373
+
374
+
375
+	/**
376
+	 * @return EE_Base_Class[]|EE_Line_Item[]
377
+	 * @throws EE_Error
378
+	 */
379
+	public function get_total_line_items_with_no_transaction()
380
+	{
381
+		return $this->get_total_line_items_for_carts();
382
+	}
383
+
384
+
385
+	/**
386
+	 * @return EE_Base_Class[]|EE_Line_Item[]
387
+	 * @throws EE_Error
388
+	 */
389
+	public function get_total_line_items_for_active_carts()
390
+	{
391
+		return $this->get_total_line_items_for_carts(false);
392
+	}
393
+
394
+
395
+	/**
396
+	 * @return EE_Base_Class[]|EE_Line_Item[]
397
+	 * @throws EE_Error
398
+	 */
399
+	public function get_total_line_items_for_expired_carts()
400
+	{
401
+		return $this->get_total_line_items_for_carts(true);
402
+	}
403
+
404
+
405
+	/**
406
+	 * Returns an array of grand total line items where the TXN_ID is 0.
407
+	 * If $expired is set to true, then only line items for expired sessions will be returned.
408
+	 * If $expired is set to false, then only line items for active sessions will be returned.
409
+	 *
410
+	 * @param bool|null $expired
411
+	 * @return EE_Base_Class[]|EE_Line_Item[]
412
+	 * @throws InvalidInterfaceException
413
+	 * @throws InvalidDataTypeException
414
+	 * @throws EE_Error
415
+	 * @throws InvalidArgumentException
416
+	 */
417
+	private function get_total_line_items_for_carts($expired = null)
418
+	{
419
+		$where_params = array(
420
+			'TXN_ID' => 0,
421
+			'LIN_type' => 'total',
422
+		);
423
+		if ($expired !== null) {
424
+			/** @var EventEspresso\core\domain\values\session\SessionLifespan $session_lifespan */
425
+			$session_lifespan = LoaderFactory::getLoader()->getShared(
426
+				'EventEspresso\core\domain\values\session\SessionLifespan'
427
+			);
428
+			$where_params['LIN_timestamp'] = array(
429
+				$expired ? '<=' : '>',
430
+				$session_lifespan->expiration(),
431
+			);
432
+		}
433
+		return $this->get_all(array($where_params));
434
+	}
435 435
 
436 436
 
437 437
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\exceptions\InvalidInterfaceException;
5 5
 use EventEspresso\core\services\loaders\LoaderFactory;
6 6
 
7
-if (!defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
7
+if ( ! defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
8 8
 
9 9
 /**
10 10
  * Event Espresso
@@ -211,8 +211,8 @@  discard block
 block discarded – undo
211 211
         );
212 212
         $query = $wpdb->prepare(
213 213
             'DELETE li
214
-				FROM ' . $this->table() . ' li
215
-				LEFT JOIN ' . EEM_Transaction::instance()->table() . ' t ON li.TXN_ID = t.TXN_ID
214
+				FROM ' . $this->table().' li
215
+				LEFT JOIN ' . EEM_Transaction::instance()->table().' t ON li.TXN_ID = t.TXN_ID
216 216
 				WHERE t.TXN_ID IS NULL AND li.LIN_timestamp < %s',
217 217
             // use GMT time because that's what TXN_timestamps are in
218 218
             date('Y-m-d H:i:s', time() - $time_to_leave_alone)
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
         $query_params = array(
254 254
             'OBJ_type' => $OBJ_type,
255 255
             // if incoming $OBJ_IDs is an array, then make sure it is formatted correctly for the query
256
-            'OBJ_ID' => is_array($OBJ_IDs) && !isset($OBJ_IDs['IN']) ? array('IN', $OBJ_IDs) : $OBJ_IDs
256
+            'OBJ_ID' => is_array($OBJ_IDs) && ! isset($OBJ_IDs['IN']) ? array('IN', $OBJ_IDs) : $OBJ_IDs
257 257
         );
258 258
         if ($TXN_ID) {
259 259
             $query_params['TXN_ID'] = $TXN_ID;
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -4,7 +4,9 @@
 block discarded – undo
4 4
 use EventEspresso\core\exceptions\InvalidInterfaceException;
5 5
 use EventEspresso\core\services\loaders\LoaderFactory;
6 6
 
7
-if (!defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
7
+if (!defined('EVENT_ESPRESSO_VERSION')) {
8
+	exit('No direct script access allowed');
9
+}
8 10
 
9 11
 /**
10 12
  * Event Espresso
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -515,8 +515,8 @@  discard block
 block discarded – undo
515 515
     protected function __construct($timezone = null)
516 516
     {
517 517
         // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
518
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+            throw new EE_Error(
520 520
                 sprintf(
521 521
                     __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522 522
                         'event_espresso'),
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
          *
537 537
          * @var EE_Table_Base[] $_tables
538 538
          */
539
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
539
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
540 540
         foreach ($this->_tables as $table_alias => $table_obj) {
541 541
             /** @var $table_obj EE_Table_Base */
542 542
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -551,10 +551,10 @@  discard block
 block discarded – undo
551 551
          *
552 552
          * @param EE_Model_Field_Base[] $_fields
553 553
          */
554
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
554
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
555 555
         $this->_invalidate_field_caches();
556 556
         foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
557
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
558 558
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559 559
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
560 560
             }
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
          *
583 583
          * @param EE_Model_Relation_Base[] $_model_relations
584 584
          */
585
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
585
+        $this->_model_relations = (array) apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
586 586
             $this->_model_relations);
587 587
         foreach ($this->_model_relations as $model_name => $relation_obj) {
588 588
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -594,12 +594,12 @@  discard block
 block discarded – undo
594 594
         }
595 595
         $this->set_timezone($timezone);
596 596
         //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
597
+        if ( ! $this->_default_where_conditions_strategy) {
598 598
             //nothing was set during child constructor, so set default
599 599
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600 600
         }
601 601
         $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
602
+        if ( ! $this->_minimum_where_conditions_strategy) {
603 603
             //nothing was set during child constructor, so set default
604 604
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605 605
         }
@@ -612,7 +612,7 @@  discard block
 block discarded – undo
612 612
         //initialize the standard cap restriction generators if none were specified by the child constructor
613 613
         if ($this->_cap_restriction_generators !== false) {
614 614
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
615
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
616 616
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
617 617
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618 618
                         new EE_Restriction_Generator_Protected(),
@@ -625,10 +625,10 @@  discard block
 block discarded – undo
625 625
         //if there are cap restriction generators, use them to make the default cap restrictions
626 626
         if ($this->_cap_restriction_generators !== false) {
627 627
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
628
+                if ( ! $generator_object) {
629 629
                     continue;
630 630
                 }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
631
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
632 632
                     throw new EE_Error(
633 633
                         sprintf(
634 634
                             __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
@@ -639,12 +639,12 @@  discard block
 block discarded – undo
639 639
                     );
640 640
                 }
641 641
                 $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
642
+                if ( ! $generator_object->construction_finalized()) {
643 643
                     $generator_object->_construct_finalize($this, $action);
644 644
                 }
645 645
             }
646 646
         }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
647
+        do_action('AHEE__'.get_class($this).'__construct__end');
648 648
     }
649 649
 
650 650
 
@@ -657,7 +657,7 @@  discard block
 block discarded – undo
657 657
      */
658 658
     public static function set_model_query_blog_id($blog_id = 0)
659 659
     {
660
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
660
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
661 661
     }
662 662
 
663 663
 
@@ -691,7 +691,7 @@  discard block
 block discarded – undo
691 691
     public static function instance($timezone = null)
692 692
     {
693 693
         // check if instance of Espresso_model already exists
694
-        if (! static::$_instance instanceof static) {
694
+        if ( ! static::$_instance instanceof static) {
695 695
             // instantiate Espresso_model
696 696
             static::$_instance = new static(
697 697
                 $timezone,
@@ -730,7 +730,7 @@  discard block
 block discarded – undo
730 730
             foreach ($r->getDefaultProperties() as $property => $value) {
731 731
                 //don't set instance to null like it was originally,
732 732
                 //but it's static anyways, and we're ignoring static properties (for now at least)
733
-                if (! isset($static_properties[$property])) {
733
+                if ( ! isset($static_properties[$property])) {
734 734
                     static::$_instance->{$property} = $value;
735 735
                 }
736 736
             }
@@ -754,7 +754,7 @@  discard block
 block discarded – undo
754 754
      */
755 755
     private static function getLoader()
756 756
     {
757
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
757
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
758 758
             EEM_Base::$loader = LoaderFactory::getLoader();
759 759
         }
760 760
         return EEM_Base::$loader;
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
      */
775 775
     public function status_array($translated = false)
776 776
     {
777
-        if (! array_key_exists('Status', $this->_model_relations)) {
777
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
778 778
             return array();
779 779
         }
780 780
         $model_name = $this->get_this_model_name();
@@ -977,17 +977,17 @@  discard block
 block discarded – undo
977 977
     public function wp_user_field_name()
978 978
     {
979 979
         try {
980
-            if (! empty($this->_model_chain_to_wp_user)) {
980
+            if ( ! empty($this->_model_chain_to_wp_user)) {
981 981
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982 982
                 $last_model_name = end($models_to_follow_to_wp_users);
983 983
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
984
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
985 985
             } else {
986 986
                 $model_with_fk_to_wp_users = $this;
987 987
                 $model_chain_to_wp_user = '';
988 988
             }
989 989
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
990
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
991 991
         } catch (EE_Error $e) {
992 992
             return false;
993 993
         }
@@ -1055,7 +1055,7 @@  discard block
 block discarded – undo
1055 1055
      */
1056 1056
     protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057 1057
     {
1058
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1058
+        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select); ;
1059 1059
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1060 1060
         $select_expressions = $columns_to_select === null
1061 1061
             ? $this->_construct_default_select_sql($model_query_info)
@@ -1063,11 +1063,11 @@  discard block
 block discarded – undo
1063 1063
         if ($this->_custom_selections instanceof CustomSelects) {
1064 1064
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065 1065
             $select_expressions .= $select_expressions
1066
-                ? ', ' . $custom_expressions
1066
+                ? ', '.$custom_expressions
1067 1067
                 : $custom_expressions;
1068 1068
         }
1069 1069
 
1070
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1070
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1071 1071
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072 1072
     }
1073 1073
 
@@ -1084,7 +1084,7 @@  discard block
 block discarded – undo
1084 1084
      */
1085 1085
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086 1086
     {
1087
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1087
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088 1088
             return null;
1089 1089
         }
1090 1090
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
         if (is_array($columns_to_select)) {
1134 1134
             $select_sql_array = array();
1135 1135
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1136
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137 1137
                     throw new EE_Error(
1138 1138
                         sprintf(
1139 1139
                             __(
@@ -1145,7 +1145,7 @@  discard block
 block discarded – undo
1145 1145
                         )
1146 1146
                     );
1147 1147
                 }
1148
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1148
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149 1149
                     throw new EE_Error(
1150 1150
                         sprintf(
1151 1151
                             esc_html__(
@@ -1217,7 +1217,7 @@  discard block
 block discarded – undo
1217 1217
      */
1218 1218
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219 1219
     {
1220
-        if (! isset($query_params[0])) {
1220
+        if ( ! isset($query_params[0])) {
1221 1221
             $query_params[0] = array();
1222 1222
         }
1223 1223
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1242,7 +1242,7 @@  discard block
 block discarded – undo
1242 1242
      */
1243 1243
     public function get_one($query_params = array())
1244 1244
     {
1245
-        if (! is_array($query_params)) {
1245
+        if ( ! is_array($query_params)) {
1246 1246
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1247 1247
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248 1248
                     gettype($query_params)), '4.6.0');
@@ -1433,7 +1433,7 @@  discard block
 block discarded – undo
1433 1433
                 return array();
1434 1434
             }
1435 1435
         }
1436
-        if (! is_array($query_params)) {
1436
+        if ( ! is_array($query_params)) {
1437 1437
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438 1438
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439 1439
                     gettype($query_params)), '4.6.0');
@@ -1443,7 +1443,7 @@  discard block
 block discarded – undo
1443 1443
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444 1444
         $query_params['limit'] = $limit;
1445 1445
         //set direction
1446
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1446
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1447 1447
         $query_params['order_by'] = $operand === '>'
1448 1448
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1449 1449
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1521,7 +1521,7 @@  discard block
 block discarded – undo
1521 1521
     {
1522 1522
         $field_settings = $this->field_settings_for($field_name);
1523 1523
         //if not a valid EE_Datetime_Field then throw error
1524
-        if (! $field_settings instanceof EE_Datetime_Field) {
1524
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1525 1525
             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.',
1526 1526
                 'event_espresso'), $field_name));
1527 1527
         }
@@ -1672,7 +1672,7 @@  discard block
 block discarded – undo
1672 1672
      */
1673 1673
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1674 1674
     {
1675
-        if (! is_array($query_params)) {
1675
+        if ( ! is_array($query_params)) {
1676 1676
             EE_Error::doing_it_wrong('EEM_Base::update',
1677 1677
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1678 1678
                     gettype($query_params)), '4.6.0');
@@ -1694,7 +1694,7 @@  discard block
 block discarded – undo
1694 1694
          * @param EEM_Base $model           the model being queried
1695 1695
          * @param array    $query_params    see EEM_Base::get_all()
1696 1696
          */
1697
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1697
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1698 1698
             $query_params);
1699 1699
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1700 1700
         //to do that, for each table, verify that it's PK isn't null.
@@ -1708,7 +1708,7 @@  discard block
 block discarded – undo
1708 1708
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1709 1709
         foreach ($wpdb_select_results as $wpdb_result) {
1710 1710
             // type cast stdClass as array
1711
-            $wpdb_result = (array)$wpdb_result;
1711
+            $wpdb_result = (array) $wpdb_result;
1712 1712
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1713 1713
             if ($this->has_primary_key_field()) {
1714 1714
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1725,13 +1725,13 @@  discard block
 block discarded – undo
1725 1725
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1726 1726
                     //if there is no private key for this table on the results, it means there's no entry
1727 1727
                     //in this table, right? so insert a row in the current table, using any fields available
1728
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1728
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1729 1729
                            && $wpdb_result[$this_table_pk_column])
1730 1730
                     ) {
1731 1731
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1732 1732
                             $main_table_pk_value);
1733 1733
                         //if we died here, report the error
1734
-                        if (! $success) {
1734
+                        if ( ! $success) {
1735 1735
                             return false;
1736 1736
                         }
1737 1737
                     }
@@ -1762,7 +1762,7 @@  discard block
 block discarded – undo
1762 1762
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1763 1763
                 }
1764 1764
             }
1765
-            if (! $model_objs_affected_ids) {
1765
+            if ( ! $model_objs_affected_ids) {
1766 1766
                 //wait wait wait- if nothing was affected let's stop here
1767 1767
                 return 0;
1768 1768
             }
@@ -1789,7 +1789,7 @@  discard block
 block discarded – undo
1789 1789
                . $model_query_info->get_full_join_sql()
1790 1790
                . " SET "
1791 1791
                . $this->_construct_update_sql($fields_n_values)
1792
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1792
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1793 1793
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1794 1794
         /**
1795 1795
          * Action called after a model update call has been made.
@@ -1800,7 +1800,7 @@  discard block
 block discarded – undo
1800 1800
          * @param int      $rows_affected
1801 1801
          */
1802 1802
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1803
-        return $rows_affected;//how many supposedly got updated
1803
+        return $rows_affected; //how many supposedly got updated
1804 1804
     }
1805 1805
 
1806 1806
 
@@ -1828,7 +1828,7 @@  discard block
 block discarded – undo
1828 1828
         }
1829 1829
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1830 1830
         $select_expressions = $field->get_qualified_column();
1831
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1831
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1832 1832
         return $this->_do_wpdb_query('get_col', array($SQL));
1833 1833
     }
1834 1834
 
@@ -1846,7 +1846,7 @@  discard block
 block discarded – undo
1846 1846
     {
1847 1847
         $query_params['limit'] = 1;
1848 1848
         $col = $this->get_col($query_params, $field_to_select);
1849
-        if (! empty($col)) {
1849
+        if ( ! empty($col)) {
1850 1850
             return reset($col);
1851 1851
         }
1852 1852
         return null;
@@ -1877,7 +1877,7 @@  discard block
 block discarded – undo
1877 1877
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1878 1878
             $value_sql = $prepared_value === null ? 'NULL'
1879 1879
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1880
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1880
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1881 1881
         }
1882 1882
         return implode(",", $cols_n_values);
1883 1883
     }
@@ -2059,7 +2059,7 @@  discard block
 block discarded – undo
2059 2059
          * @param int      $rows_deleted
2060 2060
          */
2061 2061
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2062
-        return $rows_deleted;//how many supposedly got deleted
2062
+        return $rows_deleted; //how many supposedly got deleted
2063 2063
     }
2064 2064
 
2065 2065
 
@@ -2209,7 +2209,7 @@  discard block
 block discarded – undo
2209 2209
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2210 2210
                 //make sure we have unique $ids
2211 2211
                 $ids = array_unique($ids);
2212
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2212
+                $query[] = $column.' IN('.implode(',', $ids).')';
2213 2213
             }
2214 2214
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2215 2215
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2217,7 +2217,7 @@  discard block
 block discarded – undo
2217 2217
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2218 2218
                 $values_for_each_combined_primary_key_for_a_row = array();
2219 2219
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2220
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2220
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2221 2221
                 }
2222 2222
                 $ways_to_identify_a_row[] = '('
2223 2223
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2237,8 +2237,8 @@  discard block
 block discarded – undo
2237 2237
      */
2238 2238
     public function get_field_by_column($qualified_column_name)
2239 2239
     {
2240
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2241
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2240
+       foreach ($this->field_settings(true) as $field_name => $field_obj) {
2241
+           if ($field_obj->get_qualified_column() === $qualified_column_name) {
2242 2242
                return $field_obj;
2243 2243
            }
2244 2244
        }
@@ -2289,9 +2289,9 @@  discard block
 block discarded – undo
2289 2289
                 $column_to_count = '*';
2290 2290
             }
2291 2291
         }
2292
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2293
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2294
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2292
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2293
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2294
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2295 2295
     }
2296 2296
 
2297 2297
 
@@ -2313,14 +2313,14 @@  discard block
 block discarded – undo
2313 2313
             $field_obj = $this->get_primary_key_field();
2314 2314
         }
2315 2315
         $column_to_count = $field_obj->get_qualified_column();
2316
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2316
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2317 2317
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2318 2318
         $data_type = $field_obj->get_wpdb_data_type();
2319 2319
         if ($data_type === '%d' || $data_type === '%s') {
2320
-            return (float)$return_value;
2320
+            return (float) $return_value;
2321 2321
         }
2322 2322
         //must be %f
2323
-        return (float)$return_value;
2323
+        return (float) $return_value;
2324 2324
     }
2325 2325
 
2326 2326
 
@@ -2340,13 +2340,13 @@  discard block
 block discarded – undo
2340 2340
         //if we're in maintenance mode level 2, DON'T run any queries
2341 2341
         //because level 2 indicates the database needs updating and
2342 2342
         //is probably out of sync with the code
2343
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2343
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2344 2344
             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.",
2345 2345
                 "event_espresso")));
2346 2346
         }
2347 2347
         /** @type WPDB $wpdb */
2348 2348
         global $wpdb;
2349
-        if (! method_exists($wpdb, $wpdb_method)) {
2349
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2350 2350
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2351 2351
                 'event_espresso'), $wpdb_method));
2352 2352
         }
@@ -2358,7 +2358,7 @@  discard block
 block discarded – undo
2358 2358
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2359 2359
         if (WP_DEBUG) {
2360 2360
             $wpdb->show_errors($old_show_errors_value);
2361
-            if (! empty($wpdb->last_error)) {
2361
+            if ( ! empty($wpdb->last_error)) {
2362 2362
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2363 2363
             }
2364 2364
             if ($result === false) {
@@ -2419,7 +2419,7 @@  discard block
 block discarded – undo
2419 2419
                     return $result;
2420 2420
                     break;
2421 2421
             }
2422
-            if (! empty($error_message)) {
2422
+            if ( ! empty($error_message)) {
2423 2423
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2424 2424
                 trigger_error($error_message);
2425 2425
             }
@@ -2495,11 +2495,11 @@  discard block
 block discarded – undo
2495 2495
      */
2496 2496
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2497 2497
     {
2498
-        return " FROM " . $model_query_info->get_full_join_sql() .
2499
-               $model_query_info->get_where_sql() .
2500
-               $model_query_info->get_group_by_sql() .
2501
-               $model_query_info->get_having_sql() .
2502
-               $model_query_info->get_order_by_sql() .
2498
+        return " FROM ".$model_query_info->get_full_join_sql().
2499
+               $model_query_info->get_where_sql().
2500
+               $model_query_info->get_group_by_sql().
2501
+               $model_query_info->get_having_sql().
2502
+               $model_query_info->get_order_by_sql().
2503 2503
                $model_query_info->get_limit_sql();
2504 2504
     }
2505 2505
 
@@ -2695,12 +2695,12 @@  discard block
 block discarded – undo
2695 2695
         $related_model = $this->get_related_model_obj($model_name);
2696 2696
         //we're just going to use the query params on the related model's normal get_all query,
2697 2697
         //except add a condition to say to match the current mod
2698
-        if (! isset($query_params['default_where_conditions'])) {
2698
+        if ( ! isset($query_params['default_where_conditions'])) {
2699 2699
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2700 2700
         }
2701 2701
         $this_model_name = $this->get_this_model_name();
2702 2702
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2703
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2703
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2704 2704
         return $related_model->count($query_params, $field_to_count, $distinct);
2705 2705
     }
2706 2706
 
@@ -2720,7 +2720,7 @@  discard block
 block discarded – undo
2720 2720
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2721 2721
     {
2722 2722
         $related_model = $this->get_related_model_obj($model_name);
2723
-        if (! is_array($query_params)) {
2723
+        if ( ! is_array($query_params)) {
2724 2724
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2725 2725
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2726 2726
                     gettype($query_params)), '4.6.0');
@@ -2728,12 +2728,12 @@  discard block
 block discarded – undo
2728 2728
         }
2729 2729
         //we're just going to use the query params on the related model's normal get_all query,
2730 2730
         //except add a condition to say to match the current mod
2731
-        if (! isset($query_params['default_where_conditions'])) {
2731
+        if ( ! isset($query_params['default_where_conditions'])) {
2732 2732
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2733 2733
         }
2734 2734
         $this_model_name = $this->get_this_model_name();
2735 2735
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2736
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2736
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2737 2737
         return $related_model->sum($query_params, $field_to_sum);
2738 2738
     }
2739 2739
 
@@ -2786,7 +2786,7 @@  discard block
 block discarded – undo
2786 2786
                 $field_with_model_name = $field;
2787 2787
             }
2788 2788
         }
2789
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2789
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2790 2790
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2791 2791
                 $this->get_this_model_name()));
2792 2792
         }
@@ -2819,7 +2819,7 @@  discard block
 block discarded – undo
2819 2819
          * @param array    $fields_n_values keys are the fields and values are their new values
2820 2820
          * @param EEM_Base $model           the model used
2821 2821
          */
2822
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2822
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2823 2823
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2824 2824
             $main_table = $this->_get_main_table();
2825 2825
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2926,7 +2926,7 @@  discard block
 block discarded – undo
2926 2926
         }
2927 2927
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2928 2928
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2929
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2929
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2930 2930
         }
2931 2931
         //if there is nothing to base this search on, then we shouldn't find anything
2932 2932
         if (empty($query_params)) {
@@ -3012,7 +3012,7 @@  discard block
 block discarded – undo
3012 3012
             //its not the main table, so we should have already saved the main table's PK which we just inserted
3013 3013
             //so add the fk to the main table as a column
3014 3014
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3015
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3015
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
3016 3016
         }
3017 3017
         //insert the new entry
3018 3018
         $result = $this->_do_wpdb_query('insert',
@@ -3216,7 +3216,7 @@  discard block
 block discarded – undo
3216 3216
                     $query_info_carrier,
3217 3217
                     'group_by'
3218 3218
                 );
3219
-            } elseif (! empty ($query_params['group_by'])) {
3219
+            } elseif ( ! empty ($query_params['group_by'])) {
3220 3220
                 $this->_extract_related_model_info_from_query_param(
3221 3221
                     $query_params['group_by'],
3222 3222
                     $query_info_carrier,
@@ -3238,7 +3238,7 @@  discard block
 block discarded – undo
3238 3238
                     $query_info_carrier,
3239 3239
                     'order_by'
3240 3240
                 );
3241
-            } elseif (! empty($query_params['order_by'])) {
3241
+            } elseif ( ! empty($query_params['order_by'])) {
3242 3242
                 $this->_extract_related_model_info_from_query_param(
3243 3243
                     $query_params['order_by'],
3244 3244
                     $query_info_carrier,
@@ -3274,8 +3274,8 @@  discard block
 block discarded – undo
3274 3274
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3275 3275
         $query_param_type
3276 3276
     ) {
3277
-        if (! empty($sub_query_params)) {
3278
-            $sub_query_params = (array)$sub_query_params;
3277
+        if ( ! empty($sub_query_params)) {
3278
+            $sub_query_params = (array) $sub_query_params;
3279 3279
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3280 3280
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3281 3281
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3286,7 +3286,7 @@  discard block
 block discarded – undo
3286 3286
                 //of array('Registration.TXN_ID'=>23)
3287 3287
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3288 3288
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3289
-                    if (! is_array($possibly_array_of_params)) {
3289
+                    if ( ! is_array($possibly_array_of_params)) {
3290 3290
                         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'))",
3291 3291
                             "event_espresso"),
3292 3292
                             $param, $possibly_array_of_params));
@@ -3303,7 +3303,7 @@  discard block
 block discarded – undo
3303 3303
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3304 3304
                     //indicating that $possible_array_of_params[1] is actually a field name,
3305 3305
                     //from which we should extract query parameters!
3306
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3306
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3307 3307
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3308 3308
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3309 3309
                     }
@@ -3333,8 +3333,8 @@  discard block
 block discarded – undo
3333 3333
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3334 3334
         $query_param_type
3335 3335
     ) {
3336
-        if (! empty($sub_query_params)) {
3337
-            if (! is_array($sub_query_params)) {
3336
+        if ( ! empty($sub_query_params)) {
3337
+            if ( ! is_array($sub_query_params)) {
3338 3338
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3339 3339
                     $sub_query_params));
3340 3340
             }
@@ -3363,7 +3363,7 @@  discard block
 block discarded – undo
3363 3363
      */
3364 3364
     public function _create_model_query_info_carrier($query_params)
3365 3365
     {
3366
-        if (! is_array($query_params)) {
3366
+        if ( ! is_array($query_params)) {
3367 3367
             EE_Error::doing_it_wrong(
3368 3368
                 'EEM_Base::_create_model_query_info_carrier',
3369 3369
                 sprintf(
@@ -3439,7 +3439,7 @@  discard block
 block discarded – undo
3439 3439
         //set limit
3440 3440
         if (array_key_exists('limit', $query_params)) {
3441 3441
             if (is_array($query_params['limit'])) {
3442
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3442
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3443 3443
                     $e = sprintf(
3444 3444
                         __(
3445 3445
                             "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)",
@@ -3447,12 +3447,12 @@  discard block
 block discarded – undo
3447 3447
                         ),
3448 3448
                         http_build_query($query_params['limit'])
3449 3449
                     );
3450
-                    throw new EE_Error($e . "|" . $e);
3450
+                    throw new EE_Error($e."|".$e);
3451 3451
                 }
3452 3452
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3453
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3454
-            } elseif (! empty ($query_params['limit'])) {
3455
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3453
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3454
+            } elseif ( ! empty ($query_params['limit'])) {
3455
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3456 3456
             }
3457 3457
         }
3458 3458
         //set order by
@@ -3484,10 +3484,10 @@  discard block
 block discarded – undo
3484 3484
                 $order_array = array();
3485 3485
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3486 3486
                     $order = $this->_extract_order($order);
3487
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3487
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3488 3488
                 }
3489
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3490
-            } elseif (! empty ($query_params['order_by'])) {
3489
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3490
+            } elseif ( ! empty ($query_params['order_by'])) {
3491 3491
                 $this->_extract_related_model_info_from_query_param(
3492 3492
                     $query_params['order_by'],
3493 3493
                     $query_object,
@@ -3498,18 +3498,18 @@  discard block
 block discarded – undo
3498 3498
                     ? $this->_extract_order($query_params['order'])
3499 3499
                     : 'DESC';
3500 3500
                 $query_object->set_order_by_sql(
3501
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3501
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3502 3502
                 );
3503 3503
             }
3504 3504
         }
3505 3505
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3506
-        if (! array_key_exists('order_by', $query_params)
3506
+        if ( ! array_key_exists('order_by', $query_params)
3507 3507
             && array_key_exists('order', $query_params)
3508 3508
             && ! empty($query_params['order'])
3509 3509
         ) {
3510 3510
             $pk_field = $this->get_primary_key_field();
3511 3511
             $order = $this->_extract_order($query_params['order']);
3512
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3512
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3513 3513
         }
3514 3514
         //set group by
3515 3515
         if (array_key_exists('group_by', $query_params)) {
@@ -3519,10 +3519,10 @@  discard block
 block discarded – undo
3519 3519
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3520 3520
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3521 3521
                 }
3522
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3523
-            } elseif (! empty ($query_params['group_by'])) {
3522
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3523
+            } elseif ( ! empty ($query_params['group_by'])) {
3524 3524
                 $query_object->set_group_by_sql(
3525
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3525
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3526 3526
                 );
3527 3527
             }
3528 3528
         }
@@ -3532,7 +3532,7 @@  discard block
 block discarded – undo
3532 3532
         }
3533 3533
         //now, just verify they didn't pass anything wack
3534 3534
         foreach ($query_params as $query_key => $query_value) {
3535
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3535
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3536 3536
                 throw new EE_Error(
3537 3537
                     sprintf(
3538 3538
                         __(
@@ -3631,22 +3631,22 @@  discard block
 block discarded – undo
3631 3631
         $where_query_params = array()
3632 3632
     ) {
3633 3633
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3634
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3634
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3635 3635
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3636 3636
                 "event_espresso"), $use_default_where_conditions,
3637 3637
                 implode(", ", $allowed_used_default_where_conditions_values)));
3638 3638
         }
3639 3639
         $universal_query_params = array();
3640
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3640
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3641 3641
             $universal_query_params = $this->_get_default_where_conditions();
3642
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3642
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3643 3643
             $universal_query_params = $this->_get_minimum_where_conditions();
3644 3644
         }
3645 3645
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3646 3646
             $related_model = $this->get_related_model_obj($model_name);
3647
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3647
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3648 3648
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3649
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3649
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3650 3650
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3651 3651
             } else {
3652 3652
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3679,7 +3679,7 @@  discard block
 block discarded – undo
3679 3679
      * @param bool $for_this_model false means this is for OTHER related models
3680 3680
      * @return bool
3681 3681
      */
3682
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3682
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3683 3683
     {
3684 3684
         return (
3685 3685
                    $for_this_model
@@ -3758,7 +3758,7 @@  discard block
 block discarded – undo
3758 3758
     ) {
3759 3759
         $null_friendly_where_conditions = array();
3760 3760
         $none_overridden = true;
3761
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3761
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3762 3762
         foreach ($default_where_conditions as $key => $val) {
3763 3763
             if (isset($provided_where_conditions[$key])) {
3764 3764
                 $none_overridden = false;
@@ -3876,7 +3876,7 @@  discard block
 block discarded – undo
3876 3876
             foreach ($tables as $table_obj) {
3877 3877
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3878 3878
                                        . $table_obj->get_fully_qualified_pk_column();
3879
-                if (! in_array($qualified_pk_column, $selects)) {
3879
+                if ( ! in_array($qualified_pk_column, $selects)) {
3880 3880
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3881 3881
                 }
3882 3882
             }
@@ -4022,9 +4022,9 @@  discard block
 block discarded – undo
4022 4022
         $query_parameter_type
4023 4023
     ) {
4024 4024
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4025
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4025
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4026 4026
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4027
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4027
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4028 4028
                 if ($possible_join_string === '') {
4029 4029
                     //nothing left to $query_param
4030 4030
                     //we should actually end in a field name, not a model like this!
@@ -4151,7 +4151,7 @@  discard block
 block discarded – undo
4151 4151
     {
4152 4152
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4153 4153
         if ($SQL) {
4154
-            return " WHERE " . $SQL;
4154
+            return " WHERE ".$SQL;
4155 4155
         }
4156 4156
         return '';
4157 4157
     }
@@ -4170,7 +4170,7 @@  discard block
 block discarded – undo
4170 4170
     {
4171 4171
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4172 4172
         if ($SQL) {
4173
-            return " HAVING " . $SQL;
4173
+            return " HAVING ".$SQL;
4174 4174
         }
4175 4175
         return '';
4176 4176
     }
@@ -4189,7 +4189,7 @@  discard block
 block discarded – undo
4189 4189
     {
4190 4190
         $where_clauses = array();
4191 4191
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4192
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4192
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
4193 4193
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4194 4194
                 switch ($query_param) {
4195 4195
                     case 'not':
@@ -4217,7 +4217,7 @@  discard block
 block discarded – undo
4217 4217
             } else {
4218 4218
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4219 4219
                 //if it's not a normal field, maybe it's a custom selection?
4220
-                if (! $field_obj) {
4220
+                if ( ! $field_obj) {
4221 4221
                     if ($this->_custom_selections instanceof CustomSelects) {
4222 4222
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4223 4223
                     } else {
@@ -4226,7 +4226,7 @@  discard block
 block discarded – undo
4226 4226
                     }
4227 4227
                 }
4228 4228
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4229
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4229
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4230 4230
             }
4231 4231
         }
4232 4232
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4247,7 +4247,7 @@  discard block
 block discarded – undo
4247 4247
         if ($field) {
4248 4248
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4249 4249
                 $query_param);
4250
-            return $table_alias_prefix . $field->get_qualified_column();
4250
+            return $table_alias_prefix.$field->get_qualified_column();
4251 4251
         }
4252 4252
         if ($this->_custom_selections instanceof CustomSelects
4253 4253
             && in_array($query_param, $this->_custom_selections->columnAliases(), true)
@@ -4304,7 +4304,7 @@  discard block
 block discarded – undo
4304 4304
     {
4305 4305
         if (is_array($op_and_value)) {
4306 4306
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4307
-            if (! $operator) {
4307
+            if ( ! $operator) {
4308 4308
                 $php_array_like_string = array();
4309 4309
                 foreach ($op_and_value as $key => $value) {
4310 4310
                     $php_array_like_string[] = "$key=>$value";
@@ -4326,14 +4326,14 @@  discard block
 block discarded – undo
4326 4326
         }
4327 4327
         //check to see if the value is actually another field
4328 4328
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4329
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4329
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4330 4330
         }
4331 4331
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4332 4332
             //in this case, the value should be an array, or at least a comma-separated list
4333 4333
             //it will need to handle a little differently
4334 4334
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4335 4335
             //note: $cleaned_value has already been run through $wpdb->prepare()
4336
-            return $operator . SP . $cleaned_value;
4336
+            return $operator.SP.$cleaned_value;
4337 4337
         }
4338 4338
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4339 4339
             //the value should be an array with count of two.
@@ -4349,7 +4349,7 @@  discard block
 block discarded – undo
4349 4349
                 );
4350 4350
             }
4351 4351
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4352
-            return $operator . SP . $cleaned_value;
4352
+            return $operator.SP.$cleaned_value;
4353 4353
         }
4354 4354
         if (in_array($operator, $this->valid_null_style_operators())) {
4355 4355
             if ($value !== null) {
@@ -4369,10 +4369,10 @@  discard block
 block discarded – undo
4369 4369
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4370 4370
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4371 4371
             //remove other junk. So just treat it as a string.
4372
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4372
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4373 4373
         }
4374
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4375
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4374
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4375
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4376 4376
         }
4377 4377
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4378 4378
             throw new EE_Error(
@@ -4386,7 +4386,7 @@  discard block
 block discarded – undo
4386 4386
                 )
4387 4387
             );
4388 4388
         }
4389
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4389
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4390 4390
             throw new EE_Error(
4391 4391
                 sprintf(
4392 4392
                     __(
@@ -4426,7 +4426,7 @@  discard block
 block discarded – undo
4426 4426
         foreach ($values as $value) {
4427 4427
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4428 4428
         }
4429
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4429
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4430 4430
     }
4431 4431
 
4432 4432
 
@@ -4467,7 +4467,7 @@  discard block
 block discarded – undo
4467 4467
                                 . $main_table->get_table_name()
4468 4468
                                 . " WHERE FALSE";
4469 4469
         }
4470
-        return "(" . implode(",", $cleaned_values) . ")";
4470
+        return "(".implode(",", $cleaned_values).")";
4471 4471
     }
4472 4472
 
4473 4473
 
@@ -4486,7 +4486,7 @@  discard block
 block discarded – undo
4486 4486
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4487 4487
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4488 4488
         } //$field_obj should really just be a data type
4489
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4489
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4490 4490
             throw new EE_Error(
4491 4491
                 sprintf(
4492 4492
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4614,10 +4614,10 @@  discard block
 block discarded – undo
4614 4614
      */
4615 4615
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4616 4616
     {
4617
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4617
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4618 4618
         $qualified_columns = array();
4619 4619
         foreach ($this->field_settings() as $field_name => $field) {
4620
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4620
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4621 4621
         }
4622 4622
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4623 4623
     }
@@ -4641,11 +4641,11 @@  discard block
 block discarded – undo
4641 4641
             if ($table_obj instanceof EE_Primary_Table) {
4642 4642
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4643 4643
                     ? $table_obj->get_select_join_limit($limit)
4644
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4644
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4645 4645
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4646 4646
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4647 4647
                     ? $table_obj->get_select_join_limit_join($limit)
4648
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4648
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4649 4649
             }
4650 4650
         }
4651 4651
         return $SQL;
@@ -4733,12 +4733,12 @@  discard block
 block discarded – undo
4733 4733
      */
4734 4734
     public function get_related_model_obj($model_name)
4735 4735
     {
4736
-        $model_classname = "EEM_" . $model_name;
4737
-        if (! class_exists($model_classname)) {
4736
+        $model_classname = "EEM_".$model_name;
4737
+        if ( ! class_exists($model_classname)) {
4738 4738
             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",
4739 4739
                 'event_espresso'), $model_name, $model_classname));
4740 4740
         }
4741
-        return call_user_func($model_classname . "::instance");
4741
+        return call_user_func($model_classname."::instance");
4742 4742
     }
4743 4743
 
4744 4744
 
@@ -4785,7 +4785,7 @@  discard block
 block discarded – undo
4785 4785
     public function related_settings_for($relation_name)
4786 4786
     {
4787 4787
         $relatedModels = $this->relation_settings();
4788
-        if (! array_key_exists($relation_name, $relatedModels)) {
4788
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4789 4789
             throw new EE_Error(
4790 4790
                 sprintf(
4791 4791
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4813,7 +4813,7 @@  discard block
 block discarded – undo
4813 4813
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4814 4814
     {
4815 4815
         $fieldSettings = $this->field_settings($include_db_only_fields);
4816
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4816
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4817 4817
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4818 4818
                 get_class($this)));
4819 4819
         }
@@ -4886,7 +4886,7 @@  discard block
 block discarded – undo
4886 4886
                     break;
4887 4887
                 }
4888 4888
             }
4889
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4889
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4890 4890
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4891 4891
                     get_class($this)));
4892 4892
             }
@@ -4945,7 +4945,7 @@  discard block
 block discarded – undo
4945 4945
      */
4946 4946
     public function get_foreign_key_to($model_name)
4947 4947
     {
4948
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4948
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4949 4949
             foreach ($this->field_settings() as $field) {
4950 4950
                 if (
4951 4951
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4955,7 +4955,7 @@  discard block
 block discarded – undo
4955 4955
                     break;
4956 4956
                 }
4957 4957
             }
4958
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4958
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4959 4959
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4960 4960
                     'event_espresso'), $model_name, get_class($this)));
4961 4961
             }
@@ -5006,7 +5006,7 @@  discard block
 block discarded – undo
5006 5006
             foreach ($this->_fields as $fields_corresponding_to_table) {
5007 5007
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5008 5008
                     /** @var $field_obj EE_Model_Field_Base */
5009
-                    if (! $field_obj->is_db_only_field()) {
5009
+                    if ( ! $field_obj->is_db_only_field()) {
5010 5010
                         $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5011 5011
                     }
5012 5012
                 }
@@ -5035,7 +5035,7 @@  discard block
 block discarded – undo
5035 5035
         $count_if_model_has_no_primary_key = 0;
5036 5036
         $has_primary_key = $this->has_primary_key_field();
5037 5037
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5038
-        foreach ((array)$rows as $row) {
5038
+        foreach ((array) $rows as $row) {
5039 5039
             if (empty($row)) {
5040 5040
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5041 5041
                 return array();
@@ -5053,7 +5053,7 @@  discard block
 block discarded – undo
5053 5053
                 }
5054 5054
             }
5055 5055
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5056
-            if (! $classInstance) {
5056
+            if ( ! $classInstance) {
5057 5057
                 throw new EE_Error(
5058 5058
                     sprintf(
5059 5059
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5172,7 +5172,7 @@  discard block
 block discarded – undo
5172 5172
      */
5173 5173
     public function instantiate_class_from_array_or_object($cols_n_values)
5174 5174
     {
5175
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5175
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5176 5176
             $cols_n_values = get_object_vars($cols_n_values);
5177 5177
         }
5178 5178
         $primary_key = null;
@@ -5197,7 +5197,7 @@  discard block
 block discarded – undo
5197 5197
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5198 5198
         if ($primary_key) {
5199 5199
             $classInstance = $this->get_from_entity_map($primary_key);
5200
-            if (! $classInstance) {
5200
+            if ( ! $classInstance) {
5201 5201
                 $classInstance = EE_Registry::instance()
5202 5202
                                             ->load_class($className,
5203 5203
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -5246,12 +5246,12 @@  discard block
 block discarded – undo
5246 5246
     public function add_to_entity_map(EE_Base_Class $object)
5247 5247
     {
5248 5248
         $className = $this->_get_class_name();
5249
-        if (! $object instanceof $className) {
5249
+        if ( ! $object instanceof $className) {
5250 5250
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5251 5251
                 is_object($object) ? get_class($object) : $object, $className));
5252 5252
         }
5253 5253
         /** @var $object EE_Base_Class */
5254
-        if (! $object->ID()) {
5254
+        if ( ! $object->ID()) {
5255 5255
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5256 5256
                 "event_espresso"), get_class($this)));
5257 5257
         }
@@ -5320,7 +5320,7 @@  discard block
 block discarded – undo
5320 5320
             //there is a primary key on this table and its not set. Use defaults for all its columns
5321 5321
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5322 5322
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5323
-                    if (! $field_obj->is_db_only_field()) {
5323
+                    if ( ! $field_obj->is_db_only_field()) {
5324 5324
                         //prepare field as if its coming from db
5325 5325
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5326 5326
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5329,7 +5329,7 @@  discard block
 block discarded – undo
5329 5329
             } else {
5330 5330
                 //the table's rows existed. Use their values
5331 5331
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5332
-                    if (! $field_obj->is_db_only_field()) {
5332
+                    if ( ! $field_obj->is_db_only_field()) {
5333 5333
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5334 5334
                             $cols_n_values, $field_obj->get_qualified_column(),
5335 5335
                             $field_obj->get_table_column()
@@ -5444,7 +5444,7 @@  discard block
 block discarded – undo
5444 5444
      */
5445 5445
     private function _get_class_name()
5446 5446
     {
5447
-        return "EE_" . $this->get_this_model_name();
5447
+        return "EE_".$this->get_this_model_name();
5448 5448
     }
5449 5449
 
5450 5450
 
@@ -5459,7 +5459,7 @@  discard block
 block discarded – undo
5459 5459
      */
5460 5460
     public function item_name($quantity = 1)
5461 5461
     {
5462
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5462
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5463 5463
     }
5464 5464
 
5465 5465
 
@@ -5492,7 +5492,7 @@  discard block
 block discarded – undo
5492 5492
     {
5493 5493
         $className = get_class($this);
5494 5494
         $tagName = "FHEE__{$className}__{$methodName}";
5495
-        if (! has_filter($tagName)) {
5495
+        if ( ! has_filter($tagName)) {
5496 5496
             throw new EE_Error(
5497 5497
                 sprintf(
5498 5498
                     __('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 );',
@@ -5718,7 +5718,7 @@  discard block
 block discarded – undo
5718 5718
         $key_vals_in_combined_pk = array();
5719 5719
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5720 5720
         foreach ($key_fields as $key_field_name => $field_obj) {
5721
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5721
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5722 5722
                 return null;
5723 5723
             }
5724 5724
         }
@@ -5739,7 +5739,7 @@  discard block
 block discarded – undo
5739 5739
     {
5740 5740
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5741 5741
         foreach ($keys_it_should_have as $key) {
5742
-            if (! isset($key_vals[$key])) {
5742
+            if ( ! isset($key_vals[$key])) {
5743 5743
                 return false;
5744 5744
             }
5745 5745
         }
@@ -5793,7 +5793,7 @@  discard block
 block discarded – undo
5793 5793
      */
5794 5794
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5795 5795
     {
5796
-        if (! is_array($query_params)) {
5796
+        if ( ! is_array($query_params)) {
5797 5797
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5798 5798
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5799 5799
                     gettype($query_params)), '4.6.0');
@@ -5859,7 +5859,7 @@  discard block
 block discarded – undo
5859 5859
      * Gets the valid operators
5860 5860
      * @return array keys are accepted strings, values are the SQL they are converted to
5861 5861
      */
5862
-    public function valid_operators(){
5862
+    public function valid_operators() {
5863 5863
         return $this->_valid_operators;
5864 5864
     }
5865 5865
 
@@ -5947,7 +5947,7 @@  discard block
 block discarded – undo
5947 5947
      */
5948 5948
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5949 5949
     {
5950
-        if (! $this->has_primary_key_field()) {
5950
+        if ( ! $this->has_primary_key_field()) {
5951 5951
             if (WP_DEBUG) {
5952 5952
                 EE_Error::add_error(
5953 5953
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5960,7 +5960,7 @@  discard block
 block discarded – undo
5960 5960
         $IDs = array();
5961 5961
         foreach ($model_objects as $model_object) {
5962 5962
             $id = $model_object->ID();
5963
-            if (! $id) {
5963
+            if ( ! $id) {
5964 5964
                 if ($filter_out_empty_ids) {
5965 5965
                     continue;
5966 5966
                 }
@@ -6056,8 +6056,8 @@  discard block
 block discarded – undo
6056 6056
         $missing_caps = array();
6057 6057
         $cap_restrictions = $this->cap_restrictions($context);
6058 6058
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6059
-            if (! EE_Capabilities::instance()
6060
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6059
+            if ( ! EE_Capabilities::instance()
6060
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6061 6061
             ) {
6062 6062
                 $missing_caps[$cap] = $restriction_if_no_cap;
6063 6063
             }
@@ -6209,7 +6209,7 @@  discard block
 block discarded – undo
6209 6209
     {
6210 6210
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6211 6211
             if ($query_param_key === $logic_query_param_key
6212
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6212
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6213 6213
             ) {
6214 6214
                 return true;
6215 6215
             }
Please login to merge, or discard this patch.
Indentation   +6177 added lines, -6177 removed lines patch added patch discarded remove patch
@@ -34,6185 +34,6185 @@
 block discarded – undo
34 34
 abstract class EEM_Base extends EE_Base implements ResettableInterface
35 35
 {
36 36
 
37
-    /**
38
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
-     * They almost always WILL NOT, but it's not necessarily a requirement.
41
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
-     *
43
-     * @var boolean
44
-     */
45
-    private $_values_already_prepared_by_model_object = 0;
46
-
47
-    /**
48
-     * when $_values_already_prepared_by_model_object equals this, we assume
49
-     * the data is just like form input that needs to have the model fields'
50
-     * prepare_for_set and prepare_for_use_in_db called on it
51
-     */
52
-    const not_prepared_by_model_object = 0;
53
-
54
-    /**
55
-     * when $_values_already_prepared_by_model_object equals this, we
56
-     * assume this value is coming from a model object and doesn't need to have
57
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
58
-     */
59
-    const prepared_by_model_object = 1;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the values are already to be used in the database (ie no processing is done
64
-     * on them by the model's fields)
65
-     */
66
-    const prepared_for_use_in_db = 2;
67
-
68
-
69
-    protected $singular_item = 'Item';
70
-
71
-    protected $plural_item   = 'Items';
72
-
73
-    /**
74
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
-     */
76
-    protected $_tables;
77
-
78
-    /**
79
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
-     *
83
-     * @var \EE_Model_Field_Base[][] $_fields
84
-     */
85
-    protected $_fields;
86
-
87
-    /**
88
-     * array of different kinds of relations
89
-     *
90
-     * @var \EE_Model_Relation_Base[] $_model_relations
91
-     */
92
-    protected $_model_relations;
93
-
94
-    /**
95
-     * @var \EE_Index[] $_indexes
96
-     */
97
-    protected $_indexes = array();
98
-
99
-    /**
100
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
101
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
-     * by setting the same columns as used in these queries in the query yourself.
103
-     *
104
-     * @var EE_Default_Where_Conditions
105
-     */
106
-    protected $_default_where_conditions_strategy;
107
-
108
-    /**
109
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
-     * This is particularly useful when you want something between 'none' and 'default'
111
-     *
112
-     * @var EE_Default_Where_Conditions
113
-     */
114
-    protected $_minimum_where_conditions_strategy;
115
-
116
-    /**
117
-     * String describing how to find the "owner" of this model's objects.
118
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
-     * But when there isn't, this indicates which related model, or transiently-related model,
120
-     * has the foreign key to the wp_users table.
121
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
-     * related to events, and events have a foreign key to wp_users.
123
-     * On EEM_Transaction, this would be 'Transaction.Event'
124
-     *
125
-     * @var string
126
-     */
127
-    protected $_model_chain_to_wp_user = '';
128
-
129
-    /**
130
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
-     * don't need it (particularly CPT models)
132
-     *
133
-     * @var bool
134
-     */
135
-    protected $_ignore_where_strategy = false;
136
-
137
-    /**
138
-     * String used in caps relating to this model. Eg, if the caps relating to this
139
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
-     *
141
-     * @var string. If null it hasn't been initialized yet. If false then we
142
-     * have indicated capabilities don't apply to this
143
-     */
144
-    protected $_caps_slug = null;
145
-
146
-    /**
147
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
-     * and next-level keys are capability names, and each's value is a
149
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
-     * they specify which context to use (ie, frontend, backend, edit or delete)
151
-     * and then each capability in the corresponding sub-array that they're missing
152
-     * adds the where conditions onto the query.
153
-     *
154
-     * @var array
155
-     */
156
-    protected $_cap_restrictions = array(
157
-        self::caps_read       => array(),
158
-        self::caps_read_admin => array(),
159
-        self::caps_edit       => array(),
160
-        self::caps_delete     => array(),
161
-    );
162
-
163
-    /**
164
-     * Array defining which cap restriction generators to use to create default
165
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
166
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
-     * automatically set this to false (not just null).
169
-     *
170
-     * @var EE_Restriction_Generator_Base[]
171
-     */
172
-    protected $_cap_restriction_generators = array();
173
-
174
-    /**
175
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
-     */
177
-    const caps_read       = 'read';
178
-
179
-    const caps_read_admin = 'read_admin';
180
-
181
-    const caps_edit       = 'edit';
182
-
183
-    const caps_delete     = 'delete';
184
-
185
-    /**
186
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
-     * maps to 'read' because when looking for relevant permissions we're going to use
189
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
190
-     *
191
-     * @var array
192
-     */
193
-    protected $_cap_contexts_to_cap_action_map = array(
194
-        self::caps_read       => 'read',
195
-        self::caps_read_admin => 'read',
196
-        self::caps_edit       => 'edit',
197
-        self::caps_delete     => 'delete',
198
-    );
199
-
200
-    /**
201
-     * Timezone
202
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
-     * EE_Datetime_Field data type will have access to it.
206
-     *
207
-     * @var string
208
-     */
209
-    protected $_timezone;
210
-
211
-
212
-    /**
213
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
-     * multisite.
215
-     *
216
-     * @var int
217
-     */
218
-    protected static $_model_query_blog_id;
219
-
220
-    /**
221
-     * A copy of _fields, except the array keys are the model names pointed to by
222
-     * the field
223
-     *
224
-     * @var EE_Model_Field_Base[]
225
-     */
226
-    private $_cache_foreign_key_to_fields = array();
227
-
228
-    /**
229
-     * Cached list of all the fields on the model, indexed by their name
230
-     *
231
-     * @var EE_Model_Field_Base[]
232
-     */
233
-    private $_cached_fields = null;
234
-
235
-    /**
236
-     * Cached list of all the fields on the model, except those that are
237
-     * marked as only pertinent to the database
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cached_fields_non_db_only = null;
242
-
243
-    /**
244
-     * A cached reference to the primary key for quick lookup
245
-     *
246
-     * @var EE_Model_Field_Base
247
-     */
248
-    private $_primary_key_field = null;
249
-
250
-    /**
251
-     * Flag indicating whether this model has a primary key or not
252
-     *
253
-     * @var boolean
254
-     */
255
-    protected $_has_primary_key_field = null;
256
-
257
-    /**
258
-     * Whether or not this model is based off a table in WP core only (CPTs should set
259
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
-     * This should be true for models that deal with data that should exist independent of EE.
261
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
263
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
265
-     * @var boolean
266
-     */
267
-    protected $_wp_core_model = false;
268
-
269
-    /**
270
-     *    List of valid operators that can be used for querying.
271
-     * The keys are all operators we'll accept, the values are the real SQL
272
-     * operators used
273
-     *
274
-     * @var array
275
-     */
276
-    protected $_valid_operators = array(
277
-        '='           => '=',
278
-        '<='          => '<=',
279
-        '<'           => '<',
280
-        '>='          => '>=',
281
-        '>'           => '>',
282
-        '!='          => '!=',
283
-        'LIKE'        => 'LIKE',
284
-        'like'        => 'LIKE',
285
-        'NOT_LIKE'    => 'NOT LIKE',
286
-        'not_like'    => 'NOT LIKE',
287
-        'NOT LIKE'    => 'NOT LIKE',
288
-        'not like'    => 'NOT LIKE',
289
-        'IN'          => 'IN',
290
-        'in'          => 'IN',
291
-        'NOT_IN'      => 'NOT IN',
292
-        'not_in'      => 'NOT IN',
293
-        'NOT IN'      => 'NOT IN',
294
-        'not in'      => 'NOT IN',
295
-        'between'     => 'BETWEEN',
296
-        'BETWEEN'     => 'BETWEEN',
297
-        'IS_NOT_NULL' => 'IS NOT NULL',
298
-        'is_not_null' => 'IS NOT NULL',
299
-        'IS NOT NULL' => 'IS NOT NULL',
300
-        'is not null' => 'IS NOT NULL',
301
-        'IS_NULL'     => 'IS NULL',
302
-        'is_null'     => 'IS NULL',
303
-        'IS NULL'     => 'IS NULL',
304
-        'is null'     => 'IS NULL',
305
-        'REGEXP'      => 'REGEXP',
306
-        'regexp'      => 'REGEXP',
307
-        'NOT_REGEXP'  => 'NOT REGEXP',
308
-        'not_regexp'  => 'NOT REGEXP',
309
-        'NOT REGEXP'  => 'NOT REGEXP',
310
-        'not regexp'  => 'NOT REGEXP',
311
-    );
312
-
313
-    /**
314
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
-     *
316
-     * @var array
317
-     */
318
-    protected $_in_style_operators = array('IN', 'NOT IN');
319
-
320
-    /**
321
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
-     * '12-31-2012'"
323
-     *
324
-     * @var array
325
-     */
326
-    protected $_between_style_operators = array('BETWEEN');
327
-
328
-    /**
329
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
-     * @var array
331
-     */
332
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
-    /**
334
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
-     * on a join table.
336
-     *
337
-     * @var array
338
-     */
339
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
-
341
-    /**
342
-     * Allowed values for $query_params['order'] for ordering in queries
343
-     *
344
-     * @var array
345
-     */
346
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
-
348
-    /**
349
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
351
-     *
352
-     * @var array
353
-     */
354
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
-
356
-    /**
357
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
359
-     *
360
-     * @var array
361
-     */
362
-    private $_allowed_query_params = array(
363
-        0,
364
-        'limit',
365
-        'order_by',
366
-        'group_by',
367
-        'having',
368
-        'force_join',
369
-        'order',
370
-        'on_join_limit',
371
-        'default_where_conditions',
372
-        'caps',
373
-        'extra_selects'
374
-    );
375
-
376
-    /**
377
-     * All the data types that can be used in $wpdb->prepare statements.
378
-     *
379
-     * @var array
380
-     */
381
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
-
383
-    /**
384
-     * @var EE_Registry $EE
385
-     */
386
-    protected $EE = null;
387
-
388
-
389
-    /**
390
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
-     *
392
-     * @var int
393
-     */
394
-    protected $_show_next_x_db_queries = 0;
395
-
396
-    /**
397
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
-     * WHERE, GROUP_BY, etc.
400
-     *
401
-     * @var CustomSelects
402
-     */
403
-    protected $_custom_selections = array();
404
-
405
-    /**
406
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
-     * caches every model object we've fetched from the DB on this request
408
-     *
409
-     * @var array
410
-     */
411
-    protected $_entity_map;
412
-
413
-    /**
414
-     * @var LoaderInterface $loader
415
-     */
416
-    private static $loader;
417
-
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
520
-                sprintf(
521
-                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
-                        'event_espresso'),
523
-                    get_class($this)
524
-                )
525
-            );
526
-        }
527
-        /**
528
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
-         */
530
-        if (empty(EEM_Base::$_model_query_blog_id)) {
531
-            EEM_Base::set_model_query_blog_id();
532
-        }
533
-        /**
534
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
-         * just use EE_Register_Model_Extension
536
-         *
537
-         * @var EE_Table_Base[] $_tables
538
-         */
539
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
-        foreach ($this->_tables as $table_alias => $table_obj) {
541
-            /** @var $table_obj EE_Table_Base */
542
-            $table_obj->_construct_finalize_with_alias($table_alias);
543
-            if ($table_obj instanceof EE_Secondary_Table) {
544
-                /** @var $table_obj EE_Secondary_Table */
545
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
-            }
547
-        }
548
-        /**
549
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
-         * EE_Register_Model_Extension
551
-         *
552
-         * @param EE_Model_Field_Base[] $_fields
553
-         */
554
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
-        $this->_invalidate_field_caches();
556
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
-            }
561
-            foreach ($fields_for_table as $field_name => $field_obj) {
562
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
-                //primary key field base has a slightly different _construct_finalize
564
-                /** @var $field_obj EE_Model_Field_Base */
565
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
-            }
567
-        }
568
-        // everything is related to Extra_Meta
569
-        if (get_class($this) !== 'EEM_Extra_Meta') {
570
-            //make extra meta related to everything, but don't block deleting things just
571
-            //because they have related extra meta info. For now just orphan those extra meta
572
-            //in the future we should automatically delete them
573
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        //and change logs
576
-        if (get_class($this) !== 'EEM_Change_Log') {
577
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        /**
580
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
-         * EE_Register_Model_Extension
582
-         *
583
-         * @param EE_Model_Relation_Base[] $_model_relations
584
-         */
585
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
-            $this->_model_relations);
587
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
588
-            /** @var $relation_obj EE_Model_Relation_Base */
589
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
-        }
591
-        foreach ($this->_indexes as $index_name => $index_obj) {
592
-            /** @var $index_obj EE_Index */
593
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
-        }
595
-        $this->set_timezone($timezone);
596
-        //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
603
-            //nothing was set during child constructor, so set default
604
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
-        }
606
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
608
-        //to indicate to NOT set it, set it to the logical default
609
-        if ($this->_caps_slug === null) {
610
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
-        }
612
-        //initialize the standard cap restriction generators if none were specified by the child constructor
613
-        if ($this->_cap_restriction_generators !== false) {
614
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
617
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
-                        new EE_Restriction_Generator_Protected(),
619
-                        $cap_context,
620
-                        $this
621
-                    );
622
-                }
623
-            }
624
-        }
625
-        //if there are cap restriction generators, use them to make the default cap restrictions
626
-        if ($this->_cap_restriction_generators !== false) {
627
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
629
-                    continue;
630
-                }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
-                    throw new EE_Error(
633
-                        sprintf(
634
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
-                                'event_espresso'),
636
-                            $context,
637
-                            $this->get_this_model_name()
638
-                        )
639
-                    );
640
-                }
641
-                $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
643
-                    $generator_object->_construct_finalize($this, $action);
644
-                }
645
-            }
646
-        }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
-    }
649
-
650
-
651
-
652
-    /**
653
-     * Used to set the $_model_query_blog_id static property.
654
-     *
655
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
656
-     *                      value for get_current_blog_id() will be used.
657
-     */
658
-    public static function set_model_query_blog_id($blog_id = 0)
659
-    {
660
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
661
-    }
662
-
663
-
664
-
665
-    /**
666
-     * Returns whatever is set as the internal $model_query_blog_id.
667
-     *
668
-     * @return int
669
-     */
670
-    public static function get_model_query_blog_id()
671
-    {
672
-        return EEM_Base::$_model_query_blog_id;
673
-    }
674
-
675
-
676
-
677
-    /**
678
-     * This function is a singleton method used to instantiate the Espresso_model object
679
-     *
680
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
681
-     *                                (and any incoming timezone data that gets saved).
682
-     *                                Note this just sends the timezone info to the date time model field objects.
683
-     *                                Default is NULL
684
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
685
-     * @return static (as in the concrete child class)
686
-     * @throws EE_Error
687
-     * @throws InvalidArgumentException
688
-     * @throws InvalidDataTypeException
689
-     * @throws InvalidInterfaceException
690
-     */
691
-    public static function instance($timezone = null)
692
-    {
693
-        // check if instance of Espresso_model already exists
694
-        if (! static::$_instance instanceof static) {
695
-            // instantiate Espresso_model
696
-            static::$_instance = new static(
697
-                $timezone,
698
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
699
-            );
700
-        }
701
-        //we might have a timezone set, let set_timezone decide what to do with it
702
-        static::$_instance->set_timezone($timezone);
703
-        // Espresso_model object
704
-        return static::$_instance;
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     * resets the model and returns it
711
-     *
712
-     * @param null | string $timezone
713
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
714
-     * all its properties reset; if it wasn't instantiated, returns null)
715
-     * @throws EE_Error
716
-     * @throws ReflectionException
717
-     * @throws InvalidArgumentException
718
-     * @throws InvalidDataTypeException
719
-     * @throws InvalidInterfaceException
720
-     */
721
-    public static function reset($timezone = null)
722
-    {
723
-        if (static::$_instance instanceof EEM_Base) {
724
-            //let's try to NOT swap out the current instance for a new one
725
-            //because if someone has a reference to it, we can't remove their reference
726
-            //so it's best to keep using the same reference, but change the original object
727
-            //reset all its properties to their original values as defined in the class
728
-            $r = new ReflectionClass(get_class(static::$_instance));
729
-            $static_properties = $r->getStaticProperties();
730
-            foreach ($r->getDefaultProperties() as $property => $value) {
731
-                //don't set instance to null like it was originally,
732
-                //but it's static anyways, and we're ignoring static properties (for now at least)
733
-                if (! isset($static_properties[$property])) {
734
-                    static::$_instance->{$property} = $value;
735
-                }
736
-            }
737
-            //and then directly call its constructor again, like we would if we were creating a new one
738
-            static::$_instance->__construct(
739
-                $timezone,
740
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
741
-            );
742
-            return self::instance();
743
-        }
744
-        return null;
745
-    }
746
-
747
-
748
-
749
-    /**
750
-     * @return LoaderInterface
751
-     * @throws InvalidArgumentException
752
-     * @throws InvalidDataTypeException
753
-     * @throws InvalidInterfaceException
754
-     */
755
-    private static function getLoader()
756
-    {
757
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
758
-            EEM_Base::$loader = LoaderFactory::getLoader();
759
-        }
760
-        return EEM_Base::$loader;
761
-    }
762
-
763
-
764
-
765
-    /**
766
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
767
-     *
768
-     * @param  boolean $translated return localized strings or JUST the array.
769
-     * @return array
770
-     * @throws EE_Error
771
-     * @throws InvalidArgumentException
772
-     * @throws InvalidDataTypeException
773
-     * @throws InvalidInterfaceException
774
-     */
775
-    public function status_array($translated = false)
776
-    {
777
-        if (! array_key_exists('Status', $this->_model_relations)) {
778
-            return array();
779
-        }
780
-        $model_name = $this->get_this_model_name();
781
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
782
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
783
-        $status_array = array();
784
-        foreach ($stati as $status) {
785
-            $status_array[$status->ID()] = $status->get('STS_code');
786
-        }
787
-        return $translated
788
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
789
-            : $status_array;
790
-    }
791
-
792
-
793
-
794
-    /**
795
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
796
-     *
797
-     * @param array $query_params             {
798
-     * @var array $0 (where) array {
799
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
800
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
801
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
802
-     *                                        conditions based on related models (and even
803
-     *                                        models-related-to-related-models) prepend the model's name onto the field
804
-     *                                        name. Eg,
805
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
806
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
807
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
808
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
809
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
810
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
811
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
812
-     *                                        to Venues (even when each of those models actually consisted of two
813
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
814
-     *                                        just having
815
-     *                                        "Venue.VNU_ID", you could have
816
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
817
-     *                                        events are related to Registrations, which are related to Attendees). You
818
-     *                                        can take it even further with
819
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
820
-     *                                        (from the default of '='), change the value to an numerically-indexed
821
-     *                                        array, where the first item in the list is the operator. eg: array(
822
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
823
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
824
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
825
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
826
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
827
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
828
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
829
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
830
-     *                                        the value is a field, simply provide a third array item (true) to the
831
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
832
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
833
-     *                                        Note: you can also use related model field names like you would any other
834
-     *                                        field name. eg:
835
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
836
-     *                                        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__>' =>
837
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
838
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
839
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
840
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
841
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
842
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
843
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
844
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
845
-     *                                        "stick" until you specify an AND. eg
846
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
847
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
848
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
849
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
850
-     *                                        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 >>
851
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
852
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
853
-     *                                        too, eg:
854
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
855
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
856
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
857
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
858
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
859
-     *                                        the OFFSET, the 2nd is the LIMIT
860
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
861
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
862
-     *                                        following format array('on_join_limit'
863
-     *                                        => array( 'table_alias', array(1,2) ) ).
864
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
865
-     *                                        values are either 'ASC' or 'DESC'.
866
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
867
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
868
-     *                                        DESC..." respectively. Like the
869
-     *                                        'where' conditions, these fields can be on related models. Eg
870
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
871
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
872
-     *                                        Attendee, Price, Datetime, etc.)
873
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
874
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
875
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
876
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
877
-     *                                        order by the primary key. Eg,
878
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
879
-     *                                        //(will join with the Datetime model's table(s) and order by its field
880
-     *                                        DTT_EVT_start) or
881
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
882
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
883
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
884
-     *                                        'group_by'=>'VNU_ID', or
885
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
886
-     *                                        if no
887
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
888
-     *                                        model's primary key (or combined primary keys). This avoids some
889
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
890
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
891
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
892
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
893
-     *                                        results)
894
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
895
-     *                                        array where values are models to be joined in the query.Eg
896
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
897
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
898
-     *                                        probably only want to do this in hopes of increasing efficiency, as
899
-     *                                        related models which belongs to the current model
900
-     *                                        (ie, the current model has a foreign key to them, like how Registration
901
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
902
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
903
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
904
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
905
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
906
-     *                                        default where conditions set it to 'other_models_only'. If you only want
907
-     *                                        this model's default where conditions added to the query, use
908
-     *                                        'this_model_only'. If you want to use all default where conditions
909
-     *                                        (default), set to 'all'.
910
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
911
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
912
-     *                                        everything? Or should we only show the current user items they should be
913
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
914
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
915
-     *                                        }
916
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
917
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
918
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
919
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
920
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
921
-     *                                        array( array(
922
-     *                                        'OR'=>array(
923
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
924
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
925
-     *                                        )
926
-     *                                        ),
927
-     *                                        'limit'=>10,
928
-     *                                        'group_by'=>'TXN_ID'
929
-     *                                        ));
930
-     *                                        get all the answers to the question titled "shirt size" for event with id
931
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
932
-     *                                        'Question.QST_display_text'=>'shirt size',
933
-     *                                        'Registration.Event.EVT_ID'=>12
934
-     *                                        ),
935
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
936
-     *                                        ));
937
-     * @throws EE_Error
938
-     */
939
-    public function get_all($query_params = array())
940
-    {
941
-        if (isset($query_params['limit'])
942
-            && ! isset($query_params['group_by'])
943
-        ) {
944
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
945
-        }
946
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
947
-    }
948
-
949
-
950
-
951
-    /**
952
-     * Modifies the query parameters so we only get back model objects
953
-     * that "belong" to the current user
954
-     *
955
-     * @param array $query_params @see EEM_Base::get_all()
956
-     * @return array like EEM_Base::get_all
957
-     */
958
-    public function alter_query_params_to_only_include_mine($query_params = array())
959
-    {
960
-        $wp_user_field_name = $this->wp_user_field_name();
961
-        if ($wp_user_field_name) {
962
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
963
-        }
964
-        return $query_params;
965
-    }
966
-
967
-
968
-
969
-    /**
970
-     * Returns the name of the field's name that points to the WP_User table
971
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
972
-     * foreign key to the WP_User table)
973
-     *
974
-     * @return string|boolean string on success, boolean false when there is no
975
-     * foreign key to the WP_User table
976
-     */
977
-    public function wp_user_field_name()
978
-    {
979
-        try {
980
-            if (! empty($this->_model_chain_to_wp_user)) {
981
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982
-                $last_model_name = end($models_to_follow_to_wp_users);
983
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
985
-            } else {
986
-                $model_with_fk_to_wp_users = $this;
987
-                $model_chain_to_wp_user = '';
988
-            }
989
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
991
-        } catch (EE_Error $e) {
992
-            return false;
993
-        }
994
-    }
995
-
996
-
997
-
998
-    /**
999
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
1000
-     * (or transiently-related model) has a foreign key to the wp_users table;
1001
-     * useful for finding if model objects of this type are 'owned' by the current user.
1002
-     * This is an empty string when the foreign key is on this model and when it isn't,
1003
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
1004
-     * (or transiently-related model)
1005
-     *
1006
-     * @return string
1007
-     */
1008
-    public function model_chain_to_wp_user()
1009
-    {
1010
-        return $this->_model_chain_to_wp_user;
1011
-    }
1012
-
1013
-
1014
-
1015
-    /**
1016
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1017
-     * like how registrations don't have a foreign key to wp_users, but the
1018
-     * events they are for are), or is unrelated to wp users.
1019
-     * generally available
1020
-     *
1021
-     * @return boolean
1022
-     */
1023
-    public function is_owned()
1024
-    {
1025
-        if ($this->model_chain_to_wp_user()) {
1026
-            return true;
1027
-        }
1028
-        try {
1029
-            $this->get_foreign_key_to('WP_User');
1030
-            return true;
1031
-        } catch (EE_Error $e) {
1032
-            return false;
1033
-        }
1034
-    }
1035
-
1036
-
1037
-    /**
1038
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1039
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1040
-     * the model)
1041
-     *
1042
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1043
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1044
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1045
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1046
-     *                                  override this and set the select to "*", or a specific column name, like
1047
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1048
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1049
-     *                                  the aliases used to refer to this selection, and values are to be
1050
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1051
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1052
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1053
-     * @throws EE_Error
1054
-     * @throws InvalidArgumentException
1055
-     */
1056
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057
-    {
1058
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1059
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1060
-        $select_expressions = $columns_to_select === null
1061
-            ? $this->_construct_default_select_sql($model_query_info)
1062
-            : '';
1063
-        if ($this->_custom_selections instanceof CustomSelects) {
1064
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065
-            $select_expressions .= $select_expressions
1066
-                ? ', ' . $custom_expressions
1067
-                : $custom_expressions;
1068
-        }
1069
-
1070
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1071
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072
-    }
1073
-
1074
-
1075
-    /**
1076
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1077
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1078
-     * method of including extra select information.
1079
-     *
1080
-     * @param array             $query_params
1081
-     * @param null|array|string $columns_to_select
1082
-     * @return null|CustomSelects
1083
-     * @throws InvalidArgumentException
1084
-     */
1085
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086
-    {
1087
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088
-            return null;
1089
-        }
1090
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1091
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1092
-        return new CustomSelects($selects);
1093
-    }
1094
-
1095
-
1096
-
1097
-    /**
1098
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1099
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1100
-     * take care of joins, field preparation etc.
1101
-     *
1102
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1103
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1104
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1105
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1106
-     *                                  override this and set the select to "*", or a specific column name, like
1107
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1108
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1109
-     *                                  the aliases used to refer to this selection, and values are to be
1110
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1111
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1112
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1113
-     * @throws EE_Error
1114
-     */
1115
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1116
-    {
1117
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1118
-    }
1119
-
1120
-
1121
-
1122
-    /**
1123
-     * For creating a custom select statement
1124
-     *
1125
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1126
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1127
-     *                                 SQL, and 1=>is the datatype
1128
-     * @throws EE_Error
1129
-     * @return string
1130
-     */
1131
-    private function _construct_select_from_input($columns_to_select)
1132
-    {
1133
-        if (is_array($columns_to_select)) {
1134
-            $select_sql_array = array();
1135
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137
-                    throw new EE_Error(
1138
-                        sprintf(
1139
-                            __(
1140
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1141
-                                'event_espresso'
1142
-                            ),
1143
-                            $selection_and_datatype,
1144
-                            $alias
1145
-                        )
1146
-                    );
1147
-                }
1148
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149
-                    throw new EE_Error(
1150
-                        sprintf(
1151
-                            esc_html__(
1152
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1153
-                                'event_espresso'
1154
-                            ),
1155
-                            $selection_and_datatype[1],
1156
-                            $selection_and_datatype[0],
1157
-                            $alias,
1158
-                            implode(', ', $this->_valid_wpdb_data_types)
1159
-                        )
1160
-                    );
1161
-                }
1162
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1163
-            }
1164
-            $columns_to_select_string = implode(', ', $select_sql_array);
1165
-        } else {
1166
-            $columns_to_select_string = $columns_to_select;
1167
-        }
1168
-        return $columns_to_select_string;
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1175
-     *
1176
-     * @return string
1177
-     * @throws EE_Error
1178
-     */
1179
-    public function primary_key_name()
1180
-    {
1181
-        return $this->get_primary_key_field()->get_name();
1182
-    }
1183
-
1184
-
1185
-
1186
-    /**
1187
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1188
-     * If there is no primary key on this model, $id is treated as primary key string
1189
-     *
1190
-     * @param mixed $id int or string, depending on the type of the model's primary key
1191
-     * @return EE_Base_Class
1192
-     */
1193
-    public function get_one_by_ID($id)
1194
-    {
1195
-        if ($this->get_from_entity_map($id)) {
1196
-            return $this->get_from_entity_map($id);
1197
-        }
1198
-        return $this->get_one(
1199
-            $this->alter_query_params_to_restrict_by_ID(
1200
-                $id,
1201
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1202
-            )
1203
-        );
1204
-    }
1205
-
1206
-
1207
-
1208
-    /**
1209
-     * Alters query parameters to only get items with this ID are returned.
1210
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1211
-     * or could just be a simple primary key ID
1212
-     *
1213
-     * @param int   $id
1214
-     * @param array $query_params
1215
-     * @return array of normal query params, @see EEM_Base::get_all
1216
-     * @throws EE_Error
1217
-     */
1218
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219
-    {
1220
-        if (! isset($query_params[0])) {
1221
-            $query_params[0] = array();
1222
-        }
1223
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1224
-        if ($conditions_from_id === null) {
1225
-            $query_params[0][$this->primary_key_name()] = $id;
1226
-        } else {
1227
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1228
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1229
-        }
1230
-        return $query_params;
1231
-    }
1232
-
1233
-
1234
-
1235
-    /**
1236
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1237
-     * array. If no item is found, null is returned.
1238
-     *
1239
-     * @param array $query_params like EEM_Base's $query_params variable.
1240
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1241
-     * @throws EE_Error
1242
-     */
1243
-    public function get_one($query_params = array())
1244
-    {
1245
-        if (! is_array($query_params)) {
1246
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1247
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248
-                    gettype($query_params)), '4.6.0');
1249
-            $query_params = array();
1250
-        }
1251
-        $query_params['limit'] = 1;
1252
-        $items = $this->get_all($query_params);
1253
-        if (empty($items)) {
1254
-            return null;
1255
-        }
1256
-        return array_shift($items);
1257
-    }
1258
-
1259
-
1260
-
1261
-    /**
1262
-     * Returns the next x number of items in sequence from the given value as
1263
-     * found in the database matching the given query conditions.
1264
-     *
1265
-     * @param mixed $current_field_value    Value used for the reference point.
1266
-     * @param null  $field_to_order_by      What field is used for the
1267
-     *                                      reference point.
1268
-     * @param int   $limit                  How many to return.
1269
-     * @param array $query_params           Extra conditions on the query.
1270
-     * @param null  $columns_to_select      If left null, then an array of
1271
-     *                                      EE_Base_Class objects is returned,
1272
-     *                                      otherwise you can indicate just the
1273
-     *                                      columns you want returned.
1274
-     * @return EE_Base_Class[]|array
1275
-     * @throws EE_Error
1276
-     */
1277
-    public function next_x(
1278
-        $current_field_value,
1279
-        $field_to_order_by = null,
1280
-        $limit = 1,
1281
-        $query_params = array(),
1282
-        $columns_to_select = null
1283
-    ) {
1284
-        return $this->_get_consecutive(
1285
-            $current_field_value,
1286
-            '>',
1287
-            $field_to_order_by,
1288
-            $limit,
1289
-            $query_params,
1290
-            $columns_to_select
1291
-        );
1292
-    }
1293
-
1294
-
1295
-
1296
-    /**
1297
-     * Returns the previous x number of items in sequence from the given value
1298
-     * as found in the database matching the given query conditions.
1299
-     *
1300
-     * @param mixed $current_field_value    Value used for the reference point.
1301
-     * @param null  $field_to_order_by      What field is used for the
1302
-     *                                      reference point.
1303
-     * @param int   $limit                  How many to return.
1304
-     * @param array $query_params           Extra conditions on the query.
1305
-     * @param null  $columns_to_select      If left null, then an array of
1306
-     *                                      EE_Base_Class objects is returned,
1307
-     *                                      otherwise you can indicate just the
1308
-     *                                      columns you want returned.
1309
-     * @return EE_Base_Class[]|array
1310
-     * @throws EE_Error
1311
-     */
1312
-    public function previous_x(
1313
-        $current_field_value,
1314
-        $field_to_order_by = null,
1315
-        $limit = 1,
1316
-        $query_params = array(),
1317
-        $columns_to_select = null
1318
-    ) {
1319
-        return $this->_get_consecutive(
1320
-            $current_field_value,
1321
-            '<',
1322
-            $field_to_order_by,
1323
-            $limit,
1324
-            $query_params,
1325
-            $columns_to_select
1326
-        );
1327
-    }
1328
-
1329
-
1330
-
1331
-    /**
1332
-     * Returns the next item in sequence from the given value as found in the
1333
-     * database matching the given query conditions.
1334
-     *
1335
-     * @param mixed $current_field_value    Value used for the reference point.
1336
-     * @param null  $field_to_order_by      What field is used for the
1337
-     *                                      reference point.
1338
-     * @param array $query_params           Extra conditions on the query.
1339
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1340
-     *                                      object is returned, otherwise you
1341
-     *                                      can indicate just the columns you
1342
-     *                                      want and a single array indexed by
1343
-     *                                      the columns will be returned.
1344
-     * @return EE_Base_Class|null|array()
1345
-     * @throws EE_Error
1346
-     */
1347
-    public function next(
1348
-        $current_field_value,
1349
-        $field_to_order_by = null,
1350
-        $query_params = array(),
1351
-        $columns_to_select = null
1352
-    ) {
1353
-        $results = $this->_get_consecutive(
1354
-            $current_field_value,
1355
-            '>',
1356
-            $field_to_order_by,
1357
-            1,
1358
-            $query_params,
1359
-            $columns_to_select
1360
-        );
1361
-        return empty($results) ? null : reset($results);
1362
-    }
1363
-
1364
-
1365
-
1366
-    /**
1367
-     * Returns the previous item in sequence from the given value as found in
1368
-     * the database matching the given query conditions.
1369
-     *
1370
-     * @param mixed $current_field_value    Value used for the reference point.
1371
-     * @param null  $field_to_order_by      What field is used for the
1372
-     *                                      reference point.
1373
-     * @param array $query_params           Extra conditions on the query.
1374
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1375
-     *                                      object is returned, otherwise you
1376
-     *                                      can indicate just the columns you
1377
-     *                                      want and a single array indexed by
1378
-     *                                      the columns will be returned.
1379
-     * @return EE_Base_Class|null|array()
1380
-     * @throws EE_Error
1381
-     */
1382
-    public function previous(
1383
-        $current_field_value,
1384
-        $field_to_order_by = null,
1385
-        $query_params = array(),
1386
-        $columns_to_select = null
1387
-    ) {
1388
-        $results = $this->_get_consecutive(
1389
-            $current_field_value,
1390
-            '<',
1391
-            $field_to_order_by,
1392
-            1,
1393
-            $query_params,
1394
-            $columns_to_select
1395
-        );
1396
-        return empty($results) ? null : reset($results);
1397
-    }
1398
-
1399
-
1400
-
1401
-    /**
1402
-     * Returns the a consecutive number of items in sequence from the given
1403
-     * value as found in the database matching the given query conditions.
1404
-     *
1405
-     * @param mixed  $current_field_value   Value used for the reference point.
1406
-     * @param string $operand               What operand is used for the sequence.
1407
-     * @param string $field_to_order_by     What field is used for the reference point.
1408
-     * @param int    $limit                 How many to return.
1409
-     * @param array  $query_params          Extra conditions on the query.
1410
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1411
-     *                                      otherwise you can indicate just the columns you want returned.
1412
-     * @return EE_Base_Class[]|array
1413
-     * @throws EE_Error
1414
-     */
1415
-    protected function _get_consecutive(
1416
-        $current_field_value,
1417
-        $operand = '>',
1418
-        $field_to_order_by = null,
1419
-        $limit = 1,
1420
-        $query_params = array(),
1421
-        $columns_to_select = null
1422
-    ) {
1423
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1424
-        if (empty($field_to_order_by)) {
1425
-            if ($this->has_primary_key_field()) {
1426
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1427
-            } else {
1428
-                if (WP_DEBUG) {
1429
-                    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).',
1430
-                        'event_espresso'));
1431
-                }
1432
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1433
-                return array();
1434
-            }
1435
-        }
1436
-        if (! is_array($query_params)) {
1437
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439
-                    gettype($query_params)), '4.6.0');
1440
-            $query_params = array();
1441
-        }
1442
-        //let's add the where query param for consecutive look up.
1443
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444
-        $query_params['limit'] = $limit;
1445
-        //set direction
1446
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1447
-        $query_params['order_by'] = $operand === '>'
1448
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1449
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1450
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1451
-        if (empty($columns_to_select)) {
1452
-            return $this->get_all($query_params);
1453
-        }
1454
-        //getting just the fields
1455
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1456
-    }
1457
-
1458
-
1459
-
1460
-    /**
1461
-     * This sets the _timezone property after model object has been instantiated.
1462
-     *
1463
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1464
-     */
1465
-    public function set_timezone($timezone)
1466
-    {
1467
-        if ($timezone !== null) {
1468
-            $this->_timezone = $timezone;
1469
-        }
1470
-        //note we need to loop through relations and set the timezone on those objects as well.
1471
-        foreach ($this->_model_relations as $relation) {
1472
-            $relation->set_timezone($timezone);
1473
-        }
1474
-        //and finally we do the same for any datetime fields
1475
-        foreach ($this->_fields as $field) {
1476
-            if ($field instanceof EE_Datetime_Field) {
1477
-                $field->set_timezone($timezone);
1478
-            }
1479
-        }
1480
-    }
1481
-
1482
-
1483
-
1484
-    /**
1485
-     * This just returns whatever is set for the current timezone.
1486
-     *
1487
-     * @access public
1488
-     * @return string
1489
-     */
1490
-    public function get_timezone()
1491
-    {
1492
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1493
-        if (empty($this->_timezone)) {
1494
-            foreach ($this->_fields as $field) {
1495
-                if ($field instanceof EE_Datetime_Field) {
1496
-                    $this->set_timezone($field->get_timezone());
1497
-                    break;
1498
-                }
1499
-            }
1500
-        }
1501
-        //if timezone STILL empty then return the default timezone for the site.
1502
-        if (empty($this->_timezone)) {
1503
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1504
-        }
1505
-        return $this->_timezone;
1506
-    }
1507
-
1508
-
1509
-
1510
-    /**
1511
-     * This returns the date formats set for the given field name and also ensures that
1512
-     * $this->_timezone property is set correctly.
1513
-     *
1514
-     * @since 4.6.x
1515
-     * @param string $field_name The name of the field the formats are being retrieved for.
1516
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1517
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1518
-     * @return array formats in an array with the date format first, and the time format last.
1519
-     */
1520
-    public function get_formats_for($field_name, $pretty = false)
1521
-    {
1522
-        $field_settings = $this->field_settings_for($field_name);
1523
-        //if not a valid EE_Datetime_Field then throw error
1524
-        if (! $field_settings instanceof EE_Datetime_Field) {
1525
-            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.',
1526
-                'event_espresso'), $field_name));
1527
-        }
1528
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1529
-        //the field.
1530
-        $this->_timezone = $field_settings->get_timezone();
1531
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1532
-    }
1533
-
1534
-
1535
-
1536
-    /**
1537
-     * This returns the current time in a format setup for a query on this model.
1538
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1539
-     * it will return:
1540
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1541
-     *  NOW
1542
-     *  - or a unix timestamp (equivalent to time())
1543
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1544
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1545
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1546
-     * @since 4.6.x
1547
-     * @param string $field_name       The field the current time is needed for.
1548
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1549
-     *                                 formatted string matching the set format for the field in the set timezone will
1550
-     *                                 be returned.
1551
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1552
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1553
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1554
-     *                                 exception is triggered.
1555
-     */
1556
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1557
-    {
1558
-        $formats = $this->get_formats_for($field_name);
1559
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1560
-        if ($timestamp) {
1561
-            return $DateTime->format('U');
1562
-        }
1563
-        //not returning timestamp, so return formatted string in timezone.
1564
-        switch ($what) {
1565
-            case 'time' :
1566
-                return $DateTime->format($formats[1]);
1567
-                break;
1568
-            case 'date' :
1569
-                return $DateTime->format($formats[0]);
1570
-                break;
1571
-            default :
1572
-                return $DateTime->format(implode(' ', $formats));
1573
-                break;
1574
-        }
1575
-    }
1576
-
1577
-
1578
-
1579
-    /**
1580
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1581
-     * for the model are.  Returns a DateTime object.
1582
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1583
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1584
-     * ignored.
1585
-     *
1586
-     * @param string $field_name      The field being setup.
1587
-     * @param string $timestring      The date time string being used.
1588
-     * @param string $incoming_format The format for the time string.
1589
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1590
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1591
-     *                                format is
1592
-     *                                'U', this is ignored.
1593
-     * @return DateTime
1594
-     * @throws EE_Error
1595
-     */
1596
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1597
-    {
1598
-        //just using this to ensure the timezone is set correctly internally
1599
-        $this->get_formats_for($field_name);
1600
-        //load EEH_DTT_Helper
1601
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1604
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1605
-    }
1606
-
1607
-
1608
-
1609
-    /**
1610
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1611
-     *
1612
-     * @return EE_Table_Base[]
1613
-     */
1614
-    public function get_tables()
1615
-    {
1616
-        return $this->_tables;
1617
-    }
1618
-
1619
-
1620
-
1621
-    /**
1622
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1623
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1624
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1625
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1626
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1627
-     * model object with EVT_ID = 1
1628
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1629
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1630
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1631
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1632
-     * are not specified)
1633
-     *
1634
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1635
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1636
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1637
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1638
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1639
-     *                                         ID=34, we'd use this method as follows:
1640
-     *                                         EEM_Transaction::instance()->update(
1641
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1642
-     *                                         array(array('TXN_ID'=>34)));
1643
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1644
-     *                                         in client code into what's expected to be stored on each field. Eg,
1645
-     *                                         consider updating Question's QST_admin_label field is of type
1646
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1647
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1648
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1649
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1650
-     *                                         TRUE, it is assumed that you've already called
1651
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1652
-     *                                         malicious javascript. However, if
1653
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1654
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1655
-     *                                         and every other field, before insertion. We provide this parameter
1656
-     *                                         because model objects perform their prepare_for_set function on all
1657
-     *                                         their values, and so don't need to be called again (and in many cases,
1658
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1659
-     *                                         prepare_for_set method...)
1660
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1661
-     *                                         in this model's entity map according to $fields_n_values that match
1662
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1663
-     *                                         by setting this to FALSE, but be aware that model objects being used
1664
-     *                                         could get out-of-sync with the database
1665
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1666
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1667
-     *                                         bad)
1668
-     * @throws EE_Error
1669
-     */
1670
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1671
-    {
1672
-        if (! is_array($query_params)) {
1673
-            EE_Error::doing_it_wrong('EEM_Base::update',
1674
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1675
-                    gettype($query_params)), '4.6.0');
1676
-            $query_params = array();
1677
-        }
1678
-        /**
1679
-         * Action called before a model update call has been made.
1680
-         *
1681
-         * @param EEM_Base $model
1682
-         * @param array    $fields_n_values the updated fields and their new values
1683
-         * @param array    $query_params    @see EEM_Base::get_all()
1684
-         */
1685
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1686
-        /**
1687
-         * Filters the fields about to be updated given the query parameters. You can provide the
1688
-         * $query_params to $this->get_all() to find exactly which records will be updated
1689
-         *
1690
-         * @param array    $fields_n_values fields and their new values
1691
-         * @param EEM_Base $model           the model being queried
1692
-         * @param array    $query_params    see EEM_Base::get_all()
1693
-         */
1694
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1695
-            $query_params);
1696
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1697
-        //to do that, for each table, verify that it's PK isn't null.
1698
-        $tables = $this->get_tables();
1699
-        //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
1700
-        //NOTE: we should make this code more efficient by NOT querying twice
1701
-        //before the real update, but that needs to first go through ALPHA testing
1702
-        //as it's dangerous. says Mike August 8 2014
1703
-        //we want to make sure the default_where strategy is ignored
1704
-        $this->_ignore_where_strategy = true;
1705
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1706
-        foreach ($wpdb_select_results as $wpdb_result) {
1707
-            // type cast stdClass as array
1708
-            $wpdb_result = (array)$wpdb_result;
1709
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1710
-            if ($this->has_primary_key_field()) {
1711
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1712
-            } else {
1713
-                //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)
1714
-                $main_table_pk_value = null;
1715
-            }
1716
-            //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
1717
-            //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
1718
-            if (count($tables) > 1) {
1719
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1720
-                //in that table, and so we'll want to insert one
1721
-                foreach ($tables as $table_obj) {
1722
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1723
-                    //if there is no private key for this table on the results, it means there's no entry
1724
-                    //in this table, right? so insert a row in the current table, using any fields available
1725
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1726
-                           && $wpdb_result[$this_table_pk_column])
1727
-                    ) {
1728
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1729
-                            $main_table_pk_value);
1730
-                        //if we died here, report the error
1731
-                        if (! $success) {
1732
-                            return false;
1733
-                        }
1734
-                    }
1735
-                }
1736
-            }
1737
-            //				//and now check that if we have cached any models by that ID on the model, that
1738
-            //				//they also get updated properly
1739
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1740
-            //				if( $model_object ){
1741
-            //					foreach( $fields_n_values as $field => $value ){
1742
-            //						$model_object->set($field, $value);
1743
-            //let's make sure default_where strategy is followed now
1744
-            $this->_ignore_where_strategy = false;
1745
-        }
1746
-        //if we want to keep model objects in sync, AND
1747
-        //if this wasn't called from a model object (to update itself)
1748
-        //then we want to make sure we keep all the existing
1749
-        //model objects in sync with the db
1750
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1751
-            if ($this->has_primary_key_field()) {
1752
-                $model_objs_affected_ids = $this->get_col($query_params);
1753
-            } else {
1754
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1755
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1756
-                $model_objs_affected_ids = array();
1757
-                foreach ($models_affected_key_columns as $row) {
1758
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1759
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1760
-                }
1761
-            }
1762
-            if (! $model_objs_affected_ids) {
1763
-                //wait wait wait- if nothing was affected let's stop here
1764
-                return 0;
1765
-            }
1766
-            foreach ($model_objs_affected_ids as $id) {
1767
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1768
-                if ($model_obj_in_entity_map) {
1769
-                    foreach ($fields_n_values as $field => $new_value) {
1770
-                        $model_obj_in_entity_map->set($field, $new_value);
1771
-                    }
1772
-                }
1773
-            }
1774
-            //if there is a primary key on this model, we can now do a slight optimization
1775
-            if ($this->has_primary_key_field()) {
1776
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1777
-                $query_params = array(
1778
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1779
-                    'limit'                    => count($model_objs_affected_ids),
1780
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1781
-                );
1782
-            }
1783
-        }
1784
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1785
-        $SQL = "UPDATE "
1786
-               . $model_query_info->get_full_join_sql()
1787
-               . " SET "
1788
-               . $this->_construct_update_sql($fields_n_values)
1789
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1790
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1791
-        /**
1792
-         * Action called after a model update call has been made.
1793
-         *
1794
-         * @param EEM_Base $model
1795
-         * @param array    $fields_n_values the updated fields and their new values
1796
-         * @param array    $query_params    @see EEM_Base::get_all()
1797
-         * @param int      $rows_affected
1798
-         */
1799
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1800
-        return $rows_affected;//how many supposedly got updated
1801
-    }
1802
-
1803
-
1804
-
1805
-    /**
1806
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1807
-     * are teh values of the field specified (or by default the primary key field)
1808
-     * that matched the query params. Note that you should pass the name of the
1809
-     * model FIELD, not the database table's column name.
1810
-     *
1811
-     * @param array  $query_params @see EEM_Base::get_all()
1812
-     * @param string $field_to_select
1813
-     * @return array just like $wpdb->get_col()
1814
-     * @throws EE_Error
1815
-     */
1816
-    public function get_col($query_params = array(), $field_to_select = null)
1817
-    {
1818
-        if ($field_to_select) {
1819
-            $field = $this->field_settings_for($field_to_select);
1820
-        } elseif ($this->has_primary_key_field()) {
1821
-            $field = $this->get_primary_key_field();
1822
-        } else {
1823
-            //no primary key, just grab the first column
1824
-            $field = reset($this->field_settings());
1825
-        }
1826
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1827
-        $select_expressions = $field->get_qualified_column();
1828
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1829
-        return $this->_do_wpdb_query('get_col', array($SQL));
1830
-    }
1831
-
1832
-
1833
-
1834
-    /**
1835
-     * Returns a single column value for a single row from the database
1836
-     *
1837
-     * @param array  $query_params    @see EEM_Base::get_all()
1838
-     * @param string $field_to_select @see EEM_Base::get_col()
1839
-     * @return string
1840
-     * @throws EE_Error
1841
-     */
1842
-    public function get_var($query_params = array(), $field_to_select = null)
1843
-    {
1844
-        $query_params['limit'] = 1;
1845
-        $col = $this->get_col($query_params, $field_to_select);
1846
-        if (! empty($col)) {
1847
-            return reset($col);
1848
-        }
1849
-        return null;
1850
-    }
1851
-
1852
-
1853
-
1854
-    /**
1855
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1856
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1857
-     * injection, but currently no further filtering is done
1858
-     *
1859
-     * @global      $wpdb
1860
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1861
-     *                               be updated to in the DB
1862
-     * @return string of SQL
1863
-     * @throws EE_Error
1864
-     */
1865
-    public function _construct_update_sql($fields_n_values)
1866
-    {
1867
-        /** @type WPDB $wpdb */
1868
-        global $wpdb;
1869
-        $cols_n_values = array();
1870
-        foreach ($fields_n_values as $field_name => $value) {
1871
-            $field_obj = $this->field_settings_for($field_name);
1872
-            //if the value is NULL, we want to assign the value to that.
1873
-            //wpdb->prepare doesn't really handle that properly
1874
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1875
-            $value_sql = $prepared_value === null ? 'NULL'
1876
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1877
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1878
-        }
1879
-        return implode(",", $cols_n_values);
1880
-    }
1881
-
1882
-
1883
-
1884
-    /**
1885
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1886
-     * Performs a HARD delete, meaning the database row should always be removed,
1887
-     * not just have a flag field on it switched
1888
-     * Wrapper for EEM_Base::delete_permanently()
1889
-     *
1890
-     * @param mixed $id
1891
-     * @param boolean $allow_blocking
1892
-     * @return int the number of rows deleted
1893
-     * @throws EE_Error
1894
-     */
1895
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1896
-    {
1897
-        return $this->delete_permanently(
1898
-            array(
1899
-                array($this->get_primary_key_field()->get_name() => $id),
1900
-                'limit' => 1,
1901
-            ),
1902
-            $allow_blocking
1903
-        );
1904
-    }
1905
-
1906
-
1907
-
1908
-    /**
1909
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1910
-     * Wrapper for EEM_Base::delete()
1911
-     *
1912
-     * @param mixed $id
1913
-     * @param boolean $allow_blocking
1914
-     * @return int the number of rows deleted
1915
-     * @throws EE_Error
1916
-     */
1917
-    public function delete_by_ID($id, $allow_blocking = true)
1918
-    {
1919
-        return $this->delete(
1920
-            array(
1921
-                array($this->get_primary_key_field()->get_name() => $id),
1922
-                'limit' => 1,
1923
-            ),
1924
-            $allow_blocking
1925
-        );
1926
-    }
1927
-
1928
-
1929
-
1930
-    /**
1931
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1932
-     * meaning if the model has a field that indicates its been "trashed" or
1933
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1934
-     *
1935
-     * @see EEM_Base::delete_permanently
1936
-     * @param array   $query_params
1937
-     * @param boolean $allow_blocking
1938
-     * @return int how many rows got deleted
1939
-     * @throws EE_Error
1940
-     */
1941
-    public function delete($query_params, $allow_blocking = true)
1942
-    {
1943
-        return $this->delete_permanently($query_params, $allow_blocking);
1944
-    }
1945
-
1946
-
1947
-
1948
-    /**
1949
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1950
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1951
-     * as archived, not actually deleted
1952
-     *
1953
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1954
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1955
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1956
-     *                                deletes regardless of other objects which may depend on it. Its generally
1957
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1958
-     *                                DB
1959
-     * @return int how many rows got deleted
1960
-     * @throws EE_Error
1961
-     */
1962
-    public function delete_permanently($query_params, $allow_blocking = true)
1963
-    {
1964
-        /**
1965
-         * Action called just before performing a real deletion query. You can use the
1966
-         * model and its $query_params to find exactly which items will be deleted
1967
-         *
1968
-         * @param EEM_Base $model
1969
-         * @param array    $query_params   @see EEM_Base::get_all()
1970
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1971
-         *                                 to block (prevent) this deletion
1972
-         */
1973
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1974
-        //some MySQL databases may be running safe mode, which may restrict
1975
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1976
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1977
-        //to delete them
1978
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1979
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1980
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1981
-            $columns_and_ids_for_deleting
1982
-        );
1983
-        /**
1984
-         * Allows client code to act on the items being deleted before the query is actually executed.
1985
-         *
1986
-         * @param EEM_Base $this  The model instance being acted on.
1987
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1988
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1989
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1990
-         *                                                  derived from the incoming query parameters.
1991
-         *                                                  @see details on the structure of this array in the phpdocs
1992
-         *                                                  for the `_get_ids_for_delete_method`
1993
-         *
1994
-         */
1995
-        do_action('AHEE__EEM_Base__delete__before_query',
1996
-            $this,
1997
-            $query_params,
1998
-            $allow_blocking,
1999
-            $columns_and_ids_for_deleting
2000
-        );
2001
-        if ($deletion_where_query_part) {
2002
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2003
-            $table_aliases = array_keys($this->_tables);
2004
-            $SQL = "DELETE "
2005
-                   . implode(", ", $table_aliases)
2006
-                   . " FROM "
2007
-                   . $model_query_info->get_full_join_sql()
2008
-                   . " WHERE "
2009
-                   . $deletion_where_query_part;
2010
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2011
-        } else {
2012
-            $rows_deleted = 0;
2013
-        }
2014
-
2015
-        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2016
-        //there was no error with the delete query.
2017
-        if ($this->has_primary_key_field()
2018
-            && $rows_deleted !== false
2019
-            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2020
-        ) {
2021
-            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2022
-            foreach ($ids_for_removal as $id) {
2023
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2024
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2025
-                }
2026
-            }
2027
-
2028
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2029
-            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2030
-            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2031
-            // (although it is possible).
2032
-            //Note this can be skipped by using the provided filter and returning false.
2033
-            if (apply_filters(
2034
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2035
-                ! $this instanceof EEM_Extra_Meta,
2036
-                $this
2037
-            )) {
2038
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2039
-                    0 => array(
2040
-                        'EXM_type' => $this->get_this_model_name(),
2041
-                        'OBJ_ID'   => array(
2042
-                            'IN',
2043
-                            $ids_for_removal
2044
-                        )
2045
-                    )
2046
-                ));
2047
-            }
2048
-        }
2049
-
2050
-        /**
2051
-         * Action called just after performing a real deletion query. Although at this point the
2052
-         * items should have been deleted
2053
-         *
2054
-         * @param EEM_Base $model
2055
-         * @param array    $query_params @see EEM_Base::get_all()
2056
-         * @param int      $rows_deleted
2057
-         */
2058
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2059
-        return $rows_deleted;//how many supposedly got deleted
2060
-    }
2061
-
2062
-
2063
-
2064
-    /**
2065
-     * Checks all the relations that throw error messages when there are blocking related objects
2066
-     * for related model objects. If there are any related model objects on those relations,
2067
-     * adds an EE_Error, and return true
2068
-     *
2069
-     * @param EE_Base_Class|int $this_model_obj_or_id
2070
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2071
-     *                                                 should be ignored when determining whether there are related
2072
-     *                                                 model objects which block this model object's deletion. Useful
2073
-     *                                                 if you know A is related to B and are considering deleting A,
2074
-     *                                                 but want to see if A has any other objects blocking its deletion
2075
-     *                                                 before removing the relation between A and B
2076
-     * @return boolean
2077
-     * @throws EE_Error
2078
-     */
2079
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2080
-    {
2081
-        //first, if $ignore_this_model_obj was supplied, get its model
2082
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2083
-            $ignored_model = $ignore_this_model_obj->get_model();
2084
-        } else {
2085
-            $ignored_model = null;
2086
-        }
2087
-        //now check all the relations of $this_model_obj_or_id and see if there
2088
-        //are any related model objects blocking it?
2089
-        $is_blocked = false;
2090
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2091
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2092
-                //if $ignore_this_model_obj was supplied, then for the query
2093
-                //on that model needs to be told to ignore $ignore_this_model_obj
2094
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2095
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2096
-                        array(
2097
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2098
-                                '!=',
2099
-                                $ignore_this_model_obj->ID(),
2100
-                            ),
2101
-                        ),
2102
-                    ));
2103
-                } else {
2104
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2105
-                }
2106
-                if ($related_model_objects) {
2107
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2108
-                    $is_blocked = true;
2109
-                }
2110
-            }
2111
-        }
2112
-        return $is_blocked;
2113
-    }
2114
-
2115
-
2116
-    /**
2117
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2118
-     * @param array $row_results_for_deleting
2119
-     * @param bool  $allow_blocking
2120
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2121
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2122
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2123
-     *                 deleted. Example:
2124
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2125
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2126
-     *                 where each element is a group of columns and values that get deleted. Example:
2127
-     *                      array(
2128
-     *                          0 => array(
2129
-     *                              'Term_Relationship.object_id' => 1
2130
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2131
-     *                          ),
2132
-     *                          1 => array(
2133
-     *                              'Term_Relationship.object_id' => 1
2134
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2135
-     *                          )
2136
-     *                      )
2137
-     * @throws EE_Error
2138
-     */
2139
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2140
-    {
2141
-        $ids_to_delete_indexed_by_column = array();
2142
-        if ($this->has_primary_key_field()) {
2143
-            $primary_table = $this->_get_main_table();
2144
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2145
-            $other_tables = $this->_get_other_tables();
2146
-            $ids_to_delete_indexed_by_column = $query = array();
2147
-            foreach ($row_results_for_deleting as $item_to_delete) {
2148
-                //before we mark this item for deletion,
2149
-                //make sure there's no related entities blocking its deletion (if we're checking)
2150
-                if (
2151
-                    $allow_blocking
2152
-                    && $this->delete_is_blocked_by_related_models(
2153
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2154
-                    )
2155
-                ) {
2156
-                    continue;
2157
-                }
2158
-                //primary table deletes
2159
-                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2160
-                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2161
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2162
-                }
2163
-            }
2164
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2165
-            $fields = $this->get_combined_primary_key_fields();
2166
-            foreach ($row_results_for_deleting as $item_to_delete) {
2167
-                $ids_to_delete_indexed_by_column_for_row = array();
2168
-                foreach ($fields as $cpk_field) {
2169
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2170
-                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2171
-                            $item_to_delete[$cpk_field->get_qualified_column()];
2172
-                    }
2173
-                }
2174
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2175
-            }
2176
-        } else {
2177
-            //so there's no primary key and no combined key...
2178
-            //sorry, can't help you
2179
-            throw new EE_Error(
2180
-                sprintf(
2181
-                    __(
2182
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2183
-                        "event_espresso"
2184
-                    ), get_class($this)
2185
-                )
2186
-            );
2187
-        }
2188
-        return $ids_to_delete_indexed_by_column;
2189
-    }
2190
-
2191
-
2192
-    /**
2193
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2194
-     * the corresponding query_part for the query performing the delete.
2195
-     *
2196
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2197
-     * @return string
2198
-     * @throws EE_Error
2199
-     */
2200
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2201
-        $query_part = '';
2202
-        if (empty($ids_to_delete_indexed_by_column)) {
2203
-            return $query_part;
2204
-        } elseif ($this->has_primary_key_field()) {
2205
-            $query = array();
2206
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2207
-                //make sure we have unique $ids
2208
-                $ids = array_unique($ids);
2209
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2210
-            }
2211
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2212
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2213
-            $ways_to_identify_a_row = array();
2214
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2215
-                $values_for_each_combined_primary_key_for_a_row = array();
2216
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2217
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2218
-                }
2219
-                $ways_to_identify_a_row[] = '('
2220
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2221
-                                            . ')';
2222
-            }
2223
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2224
-        }
2225
-        return $query_part;
2226
-    }
2227
-
2228
-
2229
-
2230
-    /**
2231
-     * Gets the model field by the fully qualified name
2232
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2233
-     * @return EE_Model_Field_Base
2234
-     */
2235
-    public function get_field_by_column($qualified_column_name)
2236
-    {
2237
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2238
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2239
-               return $field_obj;
2240
-           }
2241
-       }
2242
-        throw new EE_Error(
2243
-            sprintf(
2244
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2245
-                $this->get_this_model_name(),
2246
-                $qualified_column_name
2247
-            )
2248
-        );
2249
-    }
2250
-
2251
-
2252
-
2253
-    /**
2254
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2255
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2256
-     * column
2257
-     *
2258
-     * @param array  $query_params   like EEM_Base::get_all's
2259
-     * @param string $field_to_count field on model to count by (not column name)
2260
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2261
-     *                               that by the setting $distinct to TRUE;
2262
-     * @return int
2263
-     * @throws EE_Error
2264
-     */
2265
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2266
-    {
2267
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2268
-        if ($field_to_count) {
2269
-            $field_obj = $this->field_settings_for($field_to_count);
2270
-            $column_to_count = $field_obj->get_qualified_column();
2271
-        } elseif ($this->has_primary_key_field()) {
2272
-            $pk_field_obj = $this->get_primary_key_field();
2273
-            $column_to_count = $pk_field_obj->get_qualified_column();
2274
-        } else {
2275
-            //there's no primary key
2276
-            //if we're counting distinct items, and there's no primary key,
2277
-            //we need to list out the columns for distinction;
2278
-            //otherwise we can just use star
2279
-            if ($distinct) {
2280
-                $columns_to_use = array();
2281
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2282
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2283
-                }
2284
-                $column_to_count = implode(',', $columns_to_use);
2285
-            } else {
2286
-                $column_to_count = '*';
2287
-            }
2288
-        }
2289
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2290
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2291
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2292
-    }
2293
-
2294
-
2295
-
2296
-    /**
2297
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2298
-     *
2299
-     * @param array  $query_params like EEM_Base::get_all
2300
-     * @param string $field_to_sum name of field (array key in $_fields array)
2301
-     * @return float
2302
-     * @throws EE_Error
2303
-     */
2304
-    public function sum($query_params, $field_to_sum = null)
2305
-    {
2306
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2307
-        if ($field_to_sum) {
2308
-            $field_obj = $this->field_settings_for($field_to_sum);
2309
-        } else {
2310
-            $field_obj = $this->get_primary_key_field();
2311
-        }
2312
-        $column_to_count = $field_obj->get_qualified_column();
2313
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2314
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2315
-        $data_type = $field_obj->get_wpdb_data_type();
2316
-        if ($data_type === '%d' || $data_type === '%s') {
2317
-            return (float)$return_value;
2318
-        }
2319
-        //must be %f
2320
-        return (float)$return_value;
2321
-    }
2322
-
2323
-
2324
-
2325
-    /**
2326
-     * Just calls the specified method on $wpdb with the given arguments
2327
-     * Consolidates a little extra error handling code
2328
-     *
2329
-     * @param string $wpdb_method
2330
-     * @param array  $arguments_to_provide
2331
-     * @throws EE_Error
2332
-     * @global wpdb  $wpdb
2333
-     * @return mixed
2334
-     */
2335
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2336
-    {
2337
-        //if we're in maintenance mode level 2, DON'T run any queries
2338
-        //because level 2 indicates the database needs updating and
2339
-        //is probably out of sync with the code
2340
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2341
-            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.",
2342
-                "event_espresso")));
2343
-        }
2344
-        /** @type WPDB $wpdb */
2345
-        global $wpdb;
2346
-        if (! method_exists($wpdb, $wpdb_method)) {
2347
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2348
-                'event_espresso'), $wpdb_method));
2349
-        }
2350
-        if (WP_DEBUG) {
2351
-            $old_show_errors_value = $wpdb->show_errors;
2352
-            $wpdb->show_errors(false);
2353
-        }
2354
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2355
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2356
-        if (WP_DEBUG) {
2357
-            $wpdb->show_errors($old_show_errors_value);
2358
-            if (! empty($wpdb->last_error)) {
2359
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2360
-            }
2361
-            if ($result === false) {
2362
-                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"',
2363
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2364
-            }
2365
-        } elseif ($result === false) {
2366
-            EE_Error::add_error(
2367
-                sprintf(
2368
-                    __('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"',
2369
-                        'event_espresso'),
2370
-                    $wpdb_method,
2371
-                    var_export($arguments_to_provide, true),
2372
-                    $wpdb->last_error
2373
-                ),
2374
-                __FILE__,
2375
-                __FUNCTION__,
2376
-                __LINE__
2377
-            );
2378
-        }
2379
-        return $result;
2380
-    }
2381
-
2382
-
2383
-
2384
-    /**
2385
-     * Attempts to run the indicated WPDB method with the provided arguments,
2386
-     * and if there's an error tries to verify the DB is correct. Uses
2387
-     * the static property EEM_Base::$_db_verification_level to determine whether
2388
-     * we should try to fix the EE core db, the addons, or just give up
2389
-     *
2390
-     * @param string $wpdb_method
2391
-     * @param array  $arguments_to_provide
2392
-     * @return mixed
2393
-     */
2394
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2395
-    {
2396
-        /** @type WPDB $wpdb */
2397
-        global $wpdb;
2398
-        $wpdb->last_error = null;
2399
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2400
-        // was there an error running the query? but we don't care on new activations
2401
-        // (we're going to setup the DB anyway on new activations)
2402
-        if (($result === false || ! empty($wpdb->last_error))
2403
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2404
-        ) {
2405
-            switch (EEM_Base::$_db_verification_level) {
2406
-                case EEM_Base::db_verified_none :
2407
-                    // let's double-check core's DB
2408
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2409
-                    break;
2410
-                case EEM_Base::db_verified_core :
2411
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2412
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2413
-                    break;
2414
-                case EEM_Base::db_verified_addons :
2415
-                    // ummmm... you in trouble
2416
-                    return $result;
2417
-                    break;
2418
-            }
2419
-            if (! empty($error_message)) {
2420
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2421
-                trigger_error($error_message);
2422
-            }
2423
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2424
-        }
2425
-        return $result;
2426
-    }
2427
-
2428
-
2429
-
2430
-    /**
2431
-     * Verifies the EE core database is up-to-date and records that we've done it on
2432
-     * EEM_Base::$_db_verification_level
2433
-     *
2434
-     * @param string $wpdb_method
2435
-     * @param array  $arguments_to_provide
2436
-     * @return string
2437
-     */
2438
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2439
-    {
2440
-        /** @type WPDB $wpdb */
2441
-        global $wpdb;
2442
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2443
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2444
-        $error_message = sprintf(
2445
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2446
-                'event_espresso'),
2447
-            $wpdb->last_error,
2448
-            $wpdb_method,
2449
-            wp_json_encode($arguments_to_provide)
2450
-        );
2451
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2452
-        return $error_message;
2453
-    }
2454
-
2455
-
2456
-
2457
-    /**
2458
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2459
-     * EEM_Base::$_db_verification_level
2460
-     *
2461
-     * @param $wpdb_method
2462
-     * @param $arguments_to_provide
2463
-     * @return string
2464
-     */
2465
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2466
-    {
2467
-        /** @type WPDB $wpdb */
2468
-        global $wpdb;
2469
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2470
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2471
-        $error_message = sprintf(
2472
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2473
-                'event_espresso'),
2474
-            $wpdb->last_error,
2475
-            $wpdb_method,
2476
-            wp_json_encode($arguments_to_provide)
2477
-        );
2478
-        EE_System::instance()->initialize_addons();
2479
-        return $error_message;
2480
-    }
2481
-
2482
-
2483
-
2484
-    /**
2485
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2486
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2487
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2488
-     * ..."
2489
-     *
2490
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2491
-     * @return string
2492
-     */
2493
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2494
-    {
2495
-        return " FROM " . $model_query_info->get_full_join_sql() .
2496
-               $model_query_info->get_where_sql() .
2497
-               $model_query_info->get_group_by_sql() .
2498
-               $model_query_info->get_having_sql() .
2499
-               $model_query_info->get_order_by_sql() .
2500
-               $model_query_info->get_limit_sql();
2501
-    }
2502
-
2503
-
2504
-
2505
-    /**
2506
-     * Set to easily debug the next X queries ran from this model.
2507
-     *
2508
-     * @param int $count
2509
-     */
2510
-    public function show_next_x_db_queries($count = 1)
2511
-    {
2512
-        $this->_show_next_x_db_queries = $count;
2513
-    }
2514
-
2515
-
2516
-
2517
-    /**
2518
-     * @param $sql_query
2519
-     */
2520
-    public function show_db_query_if_previously_requested($sql_query)
2521
-    {
2522
-        if ($this->_show_next_x_db_queries > 0) {
2523
-            echo $sql_query;
2524
-            $this->_show_next_x_db_queries--;
2525
-        }
2526
-    }
2527
-
2528
-
2529
-
2530
-    /**
2531
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2532
-     * There are the 3 cases:
2533
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2534
-     * $otherModelObject has no ID, it is first saved.
2535
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2536
-     * has no ID, it is first saved.
2537
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2538
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2539
-     * join table
2540
-     *
2541
-     * @param        EE_Base_Class                     /int $thisModelObject
2542
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2543
-     * @param string $relationName                     , key in EEM_Base::_relations
2544
-     *                                                 an attendee to a group, you also want to specify which role they
2545
-     *                                                 will have in that group. So you would use this parameter to
2546
-     *                                                 specify array('role-column-name'=>'role-id')
2547
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2548
-     *                                                 to for relation to methods that allow you to further specify
2549
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2550
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2551
-     *                                                 because these will be inserted in any new rows created as well.
2552
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2553
-     * @throws EE_Error
2554
-     */
2555
-    public function add_relationship_to(
2556
-        $id_or_obj,
2557
-        $other_model_id_or_obj,
2558
-        $relationName,
2559
-        $extra_join_model_fields_n_values = array()
2560
-    ) {
2561
-        $relation_obj = $this->related_settings_for($relationName);
2562
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2563
-    }
2564
-
2565
-
2566
-
2567
-    /**
2568
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2569
-     * There are the 3 cases:
2570
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2571
-     * error
2572
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2573
-     * an error
2574
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2575
-     *
2576
-     * @param        EE_Base_Class /int $id_or_obj
2577
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2578
-     * @param string $relationName key in EEM_Base::_relations
2579
-     * @return boolean of success
2580
-     * @throws EE_Error
2581
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2582
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2583
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2584
-     *                             because these will be inserted in any new rows created as well.
2585
-     */
2586
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2587
-    {
2588
-        $relation_obj = $this->related_settings_for($relationName);
2589
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2590
-    }
2591
-
2592
-
2593
-
2594
-    /**
2595
-     * @param mixed           $id_or_obj
2596
-     * @param string          $relationName
2597
-     * @param array           $where_query_params
2598
-     * @param EE_Base_Class[] objects to which relations were removed
2599
-     * @return \EE_Base_Class[]
2600
-     * @throws EE_Error
2601
-     */
2602
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2603
-    {
2604
-        $relation_obj = $this->related_settings_for($relationName);
2605
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2606
-    }
2607
-
2608
-
2609
-
2610
-    /**
2611
-     * Gets all the related items of the specified $model_name, using $query_params.
2612
-     * Note: by default, we remove the "default query params"
2613
-     * because we want to get even deleted items etc.
2614
-     *
2615
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2616
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2617
-     * @param array  $query_params like EEM_Base::get_all
2618
-     * @return EE_Base_Class[]
2619
-     * @throws EE_Error
2620
-     */
2621
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2622
-    {
2623
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2624
-        $relation_settings = $this->related_settings_for($model_name);
2625
-        return $relation_settings->get_all_related($model_obj, $query_params);
2626
-    }
2627
-
2628
-
2629
-
2630
-    /**
2631
-     * Deletes all the model objects across the relation indicated by $model_name
2632
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2633
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2634
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2635
-     *
2636
-     * @param EE_Base_Class|int|string $id_or_obj
2637
-     * @param string                   $model_name
2638
-     * @param array                    $query_params
2639
-     * @return int how many deleted
2640
-     * @throws EE_Error
2641
-     */
2642
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2643
-    {
2644
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2645
-        $relation_settings = $this->related_settings_for($model_name);
2646
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2647
-    }
2648
-
2649
-
2650
-
2651
-    /**
2652
-     * Hard deletes all the model objects across the relation indicated by $model_name
2653
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2654
-     * the model objects can't be hard deleted because of blocking related model objects,
2655
-     * just does a soft-delete on them instead.
2656
-     *
2657
-     * @param EE_Base_Class|int|string $id_or_obj
2658
-     * @param string                   $model_name
2659
-     * @param array                    $query_params
2660
-     * @return int how many deleted
2661
-     * @throws EE_Error
2662
-     */
2663
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2664
-    {
2665
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2666
-        $relation_settings = $this->related_settings_for($model_name);
2667
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2668
-    }
2669
-
2670
-
2671
-
2672
-    /**
2673
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2674
-     * unless otherwise specified in the $query_params
2675
-     *
2676
-     * @param        int             /EE_Base_Class $id_or_obj
2677
-     * @param string $model_name     like 'Event', or 'Registration'
2678
-     * @param array  $query_params   like EEM_Base::get_all's
2679
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2680
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2681
-     *                               that by the setting $distinct to TRUE;
2682
-     * @return int
2683
-     * @throws EE_Error
2684
-     */
2685
-    public function count_related(
2686
-        $id_or_obj,
2687
-        $model_name,
2688
-        $query_params = array(),
2689
-        $field_to_count = null,
2690
-        $distinct = false
2691
-    ) {
2692
-        $related_model = $this->get_related_model_obj($model_name);
2693
-        //we're just going to use the query params on the related model's normal get_all query,
2694
-        //except add a condition to say to match the current mod
2695
-        if (! isset($query_params['default_where_conditions'])) {
2696
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2697
-        }
2698
-        $this_model_name = $this->get_this_model_name();
2699
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2700
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2701
-        return $related_model->count($query_params, $field_to_count, $distinct);
2702
-    }
2703
-
2704
-
2705
-
2706
-    /**
2707
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2708
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2709
-     *
2710
-     * @param        int           /EE_Base_Class $id_or_obj
2711
-     * @param string $model_name   like 'Event', or 'Registration'
2712
-     * @param array  $query_params like EEM_Base::get_all's
2713
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2714
-     * @return float
2715
-     * @throws EE_Error
2716
-     */
2717
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2718
-    {
2719
-        $related_model = $this->get_related_model_obj($model_name);
2720
-        if (! is_array($query_params)) {
2721
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2722
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2723
-                    gettype($query_params)), '4.6.0');
2724
-            $query_params = array();
2725
-        }
2726
-        //we're just going to use the query params on the related model's normal get_all query,
2727
-        //except add a condition to say to match the current mod
2728
-        if (! isset($query_params['default_where_conditions'])) {
2729
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2730
-        }
2731
-        $this_model_name = $this->get_this_model_name();
2732
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2733
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2734
-        return $related_model->sum($query_params, $field_to_sum);
2735
-    }
2736
-
2737
-
2738
-
2739
-    /**
2740
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2741
-     * $modelObject
2742
-     *
2743
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2744
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2745
-     * @param array               $query_params     like EEM_Base::get_all's
2746
-     * @return EE_Base_Class
2747
-     * @throws EE_Error
2748
-     */
2749
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2750
-    {
2751
-        $query_params['limit'] = 1;
2752
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2753
-        if ($results) {
2754
-            return array_shift($results);
2755
-        }
2756
-        return null;
2757
-    }
2758
-
2759
-
2760
-
2761
-    /**
2762
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2763
-     *
2764
-     * @return string
2765
-     */
2766
-    public function get_this_model_name()
2767
-    {
2768
-        return str_replace("EEM_", "", get_class($this));
2769
-    }
2770
-
2771
-
2772
-
2773
-    /**
2774
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2775
-     *
2776
-     * @return EE_Any_Foreign_Model_Name_Field
2777
-     * @throws EE_Error
2778
-     */
2779
-    public function get_field_containing_related_model_name()
2780
-    {
2781
-        foreach ($this->field_settings(true) as $field) {
2782
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2783
-                $field_with_model_name = $field;
2784
-            }
2785
-        }
2786
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2787
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2788
-                $this->get_this_model_name()));
2789
-        }
2790
-        return $field_with_model_name;
2791
-    }
2792
-
2793
-
2794
-
2795
-    /**
2796
-     * Inserts a new entry into the database, for each table.
2797
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2798
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2799
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2800
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2801
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2802
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2803
-     *
2804
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2805
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2806
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2807
-     *                              of EEM_Base)
2808
-     * @return int new primary key on main table that got inserted
2809
-     * @throws EE_Error
2810
-     */
2811
-    public function insert($field_n_values)
2812
-    {
2813
-        /**
2814
-         * Filters the fields and their values before inserting an item using the models
2815
-         *
2816
-         * @param array    $fields_n_values keys are the fields and values are their new values
2817
-         * @param EEM_Base $model           the model used
2818
-         */
2819
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2820
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2821
-            $main_table = $this->_get_main_table();
2822
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2823
-            if ($new_id !== false) {
2824
-                foreach ($this->_get_other_tables() as $other_table) {
2825
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2826
-                }
2827
-            }
2828
-            /**
2829
-             * Done just after attempting to insert a new model object
2830
-             *
2831
-             * @param EEM_Base   $model           used
2832
-             * @param array      $fields_n_values fields and their values
2833
-             * @param int|string the              ID of the newly-inserted model object
2834
-             */
2835
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2836
-            return $new_id;
2837
-        }
2838
-        return false;
2839
-    }
2840
-
2841
-
2842
-
2843
-    /**
2844
-     * Checks that the result would satisfy the unique indexes on this model
2845
-     *
2846
-     * @param array  $field_n_values
2847
-     * @param string $action
2848
-     * @return boolean
2849
-     * @throws EE_Error
2850
-     */
2851
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2852
-    {
2853
-        foreach ($this->unique_indexes() as $index_name => $index) {
2854
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2855
-            if ($this->exists(array($uniqueness_where_params))) {
2856
-                EE_Error::add_error(
2857
-                    sprintf(
2858
-                        __(
2859
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2860
-                            "event_espresso"
2861
-                        ),
2862
-                        $action,
2863
-                        $this->_get_class_name(),
2864
-                        $index_name,
2865
-                        implode(",", $index->field_names()),
2866
-                        http_build_query($uniqueness_where_params)
2867
-                    ),
2868
-                    __FILE__,
2869
-                    __FUNCTION__,
2870
-                    __LINE__
2871
-                );
2872
-                return false;
2873
-            }
2874
-        }
2875
-        return true;
2876
-    }
2877
-
2878
-
2879
-
2880
-    /**
2881
-     * Checks the database for an item that conflicts (ie, if this item were
2882
-     * saved to the DB would break some uniqueness requirement, like a primary key
2883
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2884
-     * can be either an EE_Base_Class or an array of fields n values
2885
-     *
2886
-     * @param EE_Base_Class|array $obj_or_fields_array
2887
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2888
-     *                                                 when looking for conflicts
2889
-     *                                                 (ie, if false, we ignore the model object's primary key
2890
-     *                                                 when finding "conflicts". If true, it's also considered).
2891
-     *                                                 Only works for INT primary key,
2892
-     *                                                 STRING primary keys cannot be ignored
2893
-     * @throws EE_Error
2894
-     * @return EE_Base_Class|array
2895
-     */
2896
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2897
-    {
2898
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2899
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2900
-        } elseif (is_array($obj_or_fields_array)) {
2901
-            $fields_n_values = $obj_or_fields_array;
2902
-        } else {
2903
-            throw new EE_Error(
2904
-                sprintf(
2905
-                    __(
2906
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2907
-                        "event_espresso"
2908
-                    ),
2909
-                    get_class($this),
2910
-                    $obj_or_fields_array
2911
-                )
2912
-            );
2913
-        }
2914
-        $query_params = array();
2915
-        if ($this->has_primary_key_field()
2916
-            && ($include_primary_key
2917
-                || $this->get_primary_key_field()
2918
-                   instanceof
2919
-                   EE_Primary_Key_String_Field)
2920
-            && isset($fields_n_values[$this->primary_key_name()])
2921
-        ) {
2922
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2923
-        }
2924
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2925
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2926
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2927
-        }
2928
-        //if there is nothing to base this search on, then we shouldn't find anything
2929
-        if (empty($query_params)) {
2930
-            return array();
2931
-        }
2932
-        return $this->get_one($query_params);
2933
-    }
2934
-
2935
-
2936
-
2937
-    /**
2938
-     * Like count, but is optimized and returns a boolean instead of an int
2939
-     *
2940
-     * @param array $query_params
2941
-     * @return boolean
2942
-     * @throws EE_Error
2943
-     */
2944
-    public function exists($query_params)
2945
-    {
2946
-        $query_params['limit'] = 1;
2947
-        return $this->count($query_params) > 0;
2948
-    }
2949
-
2950
-
2951
-
2952
-    /**
2953
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2954
-     *
2955
-     * @param int|string $id
2956
-     * @return boolean
2957
-     * @throws EE_Error
2958
-     */
2959
-    public function exists_by_ID($id)
2960
-    {
2961
-        return $this->exists(
2962
-            array(
2963
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2964
-                array(
2965
-                    $this->primary_key_name() => $id,
2966
-                ),
2967
-            )
2968
-        );
2969
-    }
2970
-
2971
-
2972
-
2973
-    /**
2974
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2975
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2976
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2977
-     * on the main table)
2978
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2979
-     * cases where we want to call it directly rather than via insert().
2980
-     *
2981
-     * @access   protected
2982
-     * @param EE_Table_Base $table
2983
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2984
-     *                                       float
2985
-     * @param int           $new_id          for now we assume only int keys
2986
-     * @throws EE_Error
2987
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2988
-     * @return int ID of new row inserted, or FALSE on failure
2989
-     */
2990
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2991
-    {
2992
-        global $wpdb;
2993
-        $insertion_col_n_values = array();
2994
-        $format_for_insertion = array();
2995
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2996
-        foreach ($fields_on_table as $field_name => $field_obj) {
2997
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2998
-            if ($field_obj->is_auto_increment()) {
2999
-                continue;
3000
-            }
3001
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3002
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
3003
-            if ($prepared_value !== null) {
3004
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3005
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3006
-            }
3007
-        }
3008
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3009
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
3010
-            //so add the fk to the main table as a column
3011
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3012
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3013
-        }
3014
-        //insert the new entry
3015
-        $result = $this->_do_wpdb_query('insert',
3016
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
3017
-        if ($result === false) {
3018
-            return false;
3019
-        }
3020
-        //ok, now what do we return for the ID of the newly-inserted thing?
3021
-        if ($this->has_primary_key_field()) {
3022
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3023
-                return $wpdb->insert_id;
3024
-            }
3025
-            //it's not an auto-increment primary key, so
3026
-            //it must have been supplied
3027
-            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3028
-        }
3029
-        //we can't return a  primary key because there is none. instead return
3030
-        //a unique string indicating this model
3031
-        return $this->get_index_primary_key_string($fields_n_values);
3032
-    }
3033
-
3034
-
3035
-
3036
-    /**
3037
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3038
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3039
-     * and there is no default, we pass it along. WPDB will take care of it)
3040
-     *
3041
-     * @param EE_Model_Field_Base $field_obj
3042
-     * @param array               $fields_n_values
3043
-     * @return mixed string|int|float depending on what the table column will be expecting
3044
-     * @throws EE_Error
3045
-     */
3046
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3047
-    {
3048
-        //if this field doesn't allow nullable, don't allow it
3049
-        if (
3050
-            ! $field_obj->is_nullable()
3051
-            && (
3052
-                ! isset($fields_n_values[$field_obj->get_name()])
3053
-                || $fields_n_values[$field_obj->get_name()] === null
3054
-            )
3055
-        ) {
3056
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3057
-        }
3058
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3059
-            ? $fields_n_values[$field_obj->get_name()]
3060
-            : null;
3061
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3062
-    }
3063
-
3064
-
3065
-
3066
-    /**
3067
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3068
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3069
-     * the field's prepare_for_set() method.
3070
-     *
3071
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3072
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3073
-     *                                   top of file)
3074
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3075
-     *                                   $value is a custom selection
3076
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3077
-     */
3078
-    private function _prepare_value_for_use_in_db($value, $field)
3079
-    {
3080
-        if ($field && $field instanceof EE_Model_Field_Base) {
3081
-            switch ($this->_values_already_prepared_by_model_object) {
3082
-                /** @noinspection PhpMissingBreakStatementInspection */
3083
-                case self::not_prepared_by_model_object:
3084
-                    $value = $field->prepare_for_set($value);
3085
-                //purposefully left out "return"
3086
-                case self::prepared_by_model_object:
3087
-                    /** @noinspection SuspiciousAssignmentsInspection */
3088
-                    $value = $field->prepare_for_use_in_db($value);
3089
-                case self::prepared_for_use_in_db:
3090
-                    //leave the value alone
3091
-            }
3092
-            return $value;
3093
-        }
3094
-        return $value;
3095
-    }
3096
-
3097
-
3098
-
3099
-    /**
3100
-     * Returns the main table on this model
3101
-     *
3102
-     * @return EE_Primary_Table
3103
-     * @throws EE_Error
3104
-     */
3105
-    protected function _get_main_table()
3106
-    {
3107
-        foreach ($this->_tables as $table) {
3108
-            if ($table instanceof EE_Primary_Table) {
3109
-                return $table;
3110
-            }
3111
-        }
3112
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3113
-            'event_espresso'), get_class($this)));
3114
-    }
3115
-
3116
-
3117
-
3118
-    /**
3119
-     * table
3120
-     * returns EE_Primary_Table table name
3121
-     *
3122
-     * @return string
3123
-     * @throws EE_Error
3124
-     */
3125
-    public function table()
3126
-    {
3127
-        return $this->_get_main_table()->get_table_name();
3128
-    }
3129
-
3130
-
3131
-
3132
-    /**
3133
-     * table
3134
-     * returns first EE_Secondary_Table table name
3135
-     *
3136
-     * @return string
3137
-     */
3138
-    public function second_table()
3139
-    {
3140
-        // grab second table from tables array
3141
-        $second_table = end($this->_tables);
3142
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3143
-    }
3144
-
3145
-
3146
-
3147
-    /**
3148
-     * get_table_obj_by_alias
3149
-     * returns table name given it's alias
3150
-     *
3151
-     * @param string $table_alias
3152
-     * @return EE_Primary_Table | EE_Secondary_Table
3153
-     */
3154
-    public function get_table_obj_by_alias($table_alias = '')
3155
-    {
3156
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3157
-    }
3158
-
3159
-
3160
-
3161
-    /**
3162
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3163
-     *
3164
-     * @return EE_Secondary_Table[]
3165
-     */
3166
-    protected function _get_other_tables()
3167
-    {
3168
-        $other_tables = array();
3169
-        foreach ($this->_tables as $table_alias => $table) {
3170
-            if ($table instanceof EE_Secondary_Table) {
3171
-                $other_tables[$table_alias] = $table;
3172
-            }
3173
-        }
3174
-        return $other_tables;
3175
-    }
3176
-
3177
-
3178
-
3179
-    /**
3180
-     * Finds all the fields that correspond to the given table
3181
-     *
3182
-     * @param string $table_alias , array key in EEM_Base::_tables
3183
-     * @return EE_Model_Field_Base[]
3184
-     */
3185
-    public function _get_fields_for_table($table_alias)
3186
-    {
3187
-        return $this->_fields[$table_alias];
3188
-    }
3189
-
3190
-
3191
-
3192
-    /**
3193
-     * Recurses through all the where parameters, and finds all the related models we'll need
3194
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3195
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3196
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3197
-     * related Registration, Transaction, and Payment models.
3198
-     *
3199
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3200
-     * @return EE_Model_Query_Info_Carrier
3201
-     * @throws EE_Error
3202
-     */
3203
-    public function _extract_related_models_from_query($query_params)
3204
-    {
3205
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3206
-        if (array_key_exists(0, $query_params)) {
3207
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3208
-        }
3209
-        if (array_key_exists('group_by', $query_params)) {
3210
-            if (is_array($query_params['group_by'])) {
3211
-                $this->_extract_related_models_from_sub_params_array_values(
3212
-                    $query_params['group_by'],
3213
-                    $query_info_carrier,
3214
-                    'group_by'
3215
-                );
3216
-            } elseif (! empty ($query_params['group_by'])) {
3217
-                $this->_extract_related_model_info_from_query_param(
3218
-                    $query_params['group_by'],
3219
-                    $query_info_carrier,
3220
-                    'group_by'
3221
-                );
3222
-            }
3223
-        }
3224
-        if (array_key_exists('having', $query_params)) {
3225
-            $this->_extract_related_models_from_sub_params_array_keys(
3226
-                $query_params[0],
3227
-                $query_info_carrier,
3228
-                'having'
3229
-            );
3230
-        }
3231
-        if (array_key_exists('order_by', $query_params)) {
3232
-            if (is_array($query_params['order_by'])) {
3233
-                $this->_extract_related_models_from_sub_params_array_keys(
3234
-                    $query_params['order_by'],
3235
-                    $query_info_carrier,
3236
-                    'order_by'
3237
-                );
3238
-            } elseif (! empty($query_params['order_by'])) {
3239
-                $this->_extract_related_model_info_from_query_param(
3240
-                    $query_params['order_by'],
3241
-                    $query_info_carrier,
3242
-                    'order_by'
3243
-                );
3244
-            }
3245
-        }
3246
-        if (array_key_exists('force_join', $query_params)) {
3247
-            $this->_extract_related_models_from_sub_params_array_values(
3248
-                $query_params['force_join'],
3249
-                $query_info_carrier,
3250
-                'force_join'
3251
-            );
3252
-        }
3253
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3254
-        return $query_info_carrier;
3255
-    }
3256
-
3257
-
3258
-
3259
-    /**
3260
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3261
-     *
3262
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3263
-     *                                                      $query_params['having']
3264
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3265
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3266
-     * @throws EE_Error
3267
-     * @return \EE_Model_Query_Info_Carrier
3268
-     */
3269
-    private function _extract_related_models_from_sub_params_array_keys(
3270
-        $sub_query_params,
3271
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3272
-        $query_param_type
3273
-    ) {
3274
-        if (! empty($sub_query_params)) {
3275
-            $sub_query_params = (array)$sub_query_params;
3276
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3277
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3278
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3279
-                    $query_param_type);
3280
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3281
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3282
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3283
-                //of array('Registration.TXN_ID'=>23)
3284
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3285
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3286
-                    if (! is_array($possibly_array_of_params)) {
3287
-                        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'))",
3288
-                            "event_espresso"),
3289
-                            $param, $possibly_array_of_params));
3290
-                    }
3291
-                    $this->_extract_related_models_from_sub_params_array_keys(
3292
-                        $possibly_array_of_params,
3293
-                        $model_query_info_carrier, $query_param_type
3294
-                    );
3295
-                } elseif ($query_param_type === 0 //ie WHERE
3296
-                          && is_array($possibly_array_of_params)
3297
-                          && isset($possibly_array_of_params[2])
3298
-                          && $possibly_array_of_params[2] == true
3299
-                ) {
3300
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3301
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3302
-                    //from which we should extract query parameters!
3303
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3304
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3305
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3306
-                    }
3307
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3308
-                        $model_query_info_carrier, $query_param_type);
3309
-                }
3310
-            }
3311
-        }
3312
-        return $model_query_info_carrier;
3313
-    }
3314
-
3315
-
3316
-
3317
-    /**
3318
-     * For extracting related models from forced_joins, where the array values contain the info about what
3319
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3320
-     *
3321
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3322
-     *                                                      $query_params['having']
3323
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3324
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3325
-     * @throws EE_Error
3326
-     * @return \EE_Model_Query_Info_Carrier
3327
-     */
3328
-    private function _extract_related_models_from_sub_params_array_values(
3329
-        $sub_query_params,
3330
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3331
-        $query_param_type
3332
-    ) {
3333
-        if (! empty($sub_query_params)) {
3334
-            if (! is_array($sub_query_params)) {
3335
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3336
-                    $sub_query_params));
3337
-            }
3338
-            foreach ($sub_query_params as $param) {
3339
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3340
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3341
-                    $query_param_type);
3342
-            }
3343
-        }
3344
-        return $model_query_info_carrier;
3345
-    }
3346
-
3347
-
3348
-
3349
-    /**
3350
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3351
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3352
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3353
-     * but use them in a different order. Eg, we need to know what models we are querying
3354
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3355
-     * other models before we can finalize the where clause SQL.
3356
-     *
3357
-     * @param array $query_params
3358
-     * @throws EE_Error
3359
-     * @return EE_Model_Query_Info_Carrier
3360
-     */
3361
-    public function _create_model_query_info_carrier($query_params)
3362
-    {
3363
-        if (! is_array($query_params)) {
3364
-            EE_Error::doing_it_wrong(
3365
-                'EEM_Base::_create_model_query_info_carrier',
3366
-                sprintf(
3367
-                    __(
3368
-                        '$query_params should be an array, you passed a variable of type %s',
3369
-                        'event_espresso'
3370
-                    ),
3371
-                    gettype($query_params)
3372
-                ),
3373
-                '4.6.0'
3374
-            );
3375
-            $query_params = array();
3376
-        }
3377
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3378
-        //first check if we should alter the query to account for caps or not
3379
-        //because the caps might require us to do extra joins
3380
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3381
-            $query_params[0] = $where_query_params = array_replace_recursive(
3382
-                $where_query_params,
3383
-                $this->caps_where_conditions(
3384
-                    $query_params['caps']
3385
-                )
3386
-            );
3387
-        }
3388
-        $query_object = $this->_extract_related_models_from_query($query_params);
3389
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3390
-        foreach ($where_query_params as $key => $value) {
3391
-            if (is_int($key)) {
3392
-                throw new EE_Error(
3393
-                    sprintf(
3394
-                        __(
3395
-                            "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.",
3396
-                            "event_espresso"
3397
-                        ),
3398
-                        $key,
3399
-                        var_export($value, true),
3400
-                        var_export($query_params, true),
3401
-                        get_class($this)
3402
-                    )
3403
-                );
3404
-            }
3405
-        }
3406
-        if (
3407
-            array_key_exists('default_where_conditions', $query_params)
3408
-            && ! empty($query_params['default_where_conditions'])
3409
-        ) {
3410
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3411
-        } else {
3412
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3413
-        }
3414
-        $where_query_params = array_merge(
3415
-            $this->_get_default_where_conditions_for_models_in_query(
3416
-                $query_object,
3417
-                $use_default_where_conditions,
3418
-                $where_query_params
3419
-            ),
3420
-            $where_query_params
3421
-        );
3422
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3423
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3424
-        // So we need to setup a subquery and use that for the main join.
3425
-        // Note for now this only works on the primary table for the model.
3426
-        // So for instance, you could set the limit array like this:
3427
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3428
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3429
-            $query_object->set_main_model_join_sql(
3430
-                $this->_construct_limit_join_select(
3431
-                    $query_params['on_join_limit'][0],
3432
-                    $query_params['on_join_limit'][1]
3433
-                )
3434
-            );
3435
-        }
3436
-        //set limit
3437
-        if (array_key_exists('limit', $query_params)) {
3438
-            if (is_array($query_params['limit'])) {
3439
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3440
-                    $e = sprintf(
3441
-                        __(
3442
-                            "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)",
3443
-                            "event_espresso"
3444
-                        ),
3445
-                        http_build_query($query_params['limit'])
3446
-                    );
3447
-                    throw new EE_Error($e . "|" . $e);
3448
-                }
3449
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3450
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3451
-            } elseif (! empty ($query_params['limit'])) {
3452
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3453
-            }
3454
-        }
3455
-        //set order by
3456
-        if (array_key_exists('order_by', $query_params)) {
3457
-            if (is_array($query_params['order_by'])) {
3458
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3459
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3460
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3461
-                if (array_key_exists('order', $query_params)) {
3462
-                    throw new EE_Error(
3463
-                        sprintf(
3464
-                            __(
3465
-                                "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 ",
3466
-                                "event_espresso"
3467
-                            ),
3468
-                            get_class($this),
3469
-                            implode(", ", array_keys($query_params['order_by'])),
3470
-                            implode(", ", $query_params['order_by']),
3471
-                            $query_params['order']
3472
-                        )
3473
-                    );
3474
-                }
3475
-                $this->_extract_related_models_from_sub_params_array_keys(
3476
-                    $query_params['order_by'],
3477
-                    $query_object,
3478
-                    'order_by'
3479
-                );
3480
-                //assume it's an array of fields to order by
3481
-                $order_array = array();
3482
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3483
-                    $order = $this->_extract_order($order);
3484
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3485
-                }
3486
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3487
-            } elseif (! empty ($query_params['order_by'])) {
3488
-                $this->_extract_related_model_info_from_query_param(
3489
-                    $query_params['order_by'],
3490
-                    $query_object,
3491
-                    'order',
3492
-                    $query_params['order_by']
3493
-                );
3494
-                $order = isset($query_params['order'])
3495
-                    ? $this->_extract_order($query_params['order'])
3496
-                    : 'DESC';
3497
-                $query_object->set_order_by_sql(
3498
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3499
-                );
3500
-            }
3501
-        }
3502
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3503
-        if (! array_key_exists('order_by', $query_params)
3504
-            && array_key_exists('order', $query_params)
3505
-            && ! empty($query_params['order'])
3506
-        ) {
3507
-            $pk_field = $this->get_primary_key_field();
3508
-            $order = $this->_extract_order($query_params['order']);
3509
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3510
-        }
3511
-        //set group by
3512
-        if (array_key_exists('group_by', $query_params)) {
3513
-            if (is_array($query_params['group_by'])) {
3514
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3515
-                $group_by_array = array();
3516
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3517
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3518
-                }
3519
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3520
-            } elseif (! empty ($query_params['group_by'])) {
3521
-                $query_object->set_group_by_sql(
3522
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3523
-                );
3524
-            }
3525
-        }
3526
-        //set having
3527
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3528
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3529
-        }
3530
-        //now, just verify they didn't pass anything wack
3531
-        foreach ($query_params as $query_key => $query_value) {
3532
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3533
-                throw new EE_Error(
3534
-                    sprintf(
3535
-                        __(
3536
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3537
-                            'event_espresso'
3538
-                        ),
3539
-                        $query_key,
3540
-                        get_class($this),
3541
-                        //						print_r( $this->_allowed_query_params, TRUE )
3542
-                        implode(',', $this->_allowed_query_params)
3543
-                    )
3544
-                );
3545
-            }
3546
-        }
3547
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3548
-        if (empty($main_model_join_sql)) {
3549
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3550
-        }
3551
-        return $query_object;
3552
-    }
3553
-
3554
-
3555
-
3556
-    /**
3557
-     * Gets the where conditions that should be imposed on the query based on the
3558
-     * context (eg reading frontend, backend, edit or delete).
3559
-     *
3560
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3561
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3562
-     * @throws EE_Error
3563
-     */
3564
-    public function caps_where_conditions($context = self::caps_read)
3565
-    {
3566
-        EEM_Base::verify_is_valid_cap_context($context);
3567
-        $cap_where_conditions = array();
3568
-        $cap_restrictions = $this->caps_missing($context);
3569
-        /**
3570
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3571
-         */
3572
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3573
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3574
-                $restriction_if_no_cap->get_default_where_conditions());
3575
-        }
3576
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3577
-            $cap_restrictions);
3578
-    }
3579
-
3580
-
3581
-
3582
-    /**
3583
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3584
-     * otherwise throws an exception
3585
-     *
3586
-     * @param string $should_be_order_string
3587
-     * @return string either ASC, asc, DESC or desc
3588
-     * @throws EE_Error
3589
-     */
3590
-    private function _extract_order($should_be_order_string)
3591
-    {
3592
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3593
-            return $should_be_order_string;
3594
-        }
3595
-        throw new EE_Error(
3596
-            sprintf(
3597
-                __(
3598
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3599
-                    "event_espresso"
3600
-                ), get_class($this), $should_be_order_string
3601
-            )
3602
-        );
3603
-    }
3604
-
3605
-
3606
-
3607
-    /**
3608
-     * Looks at all the models which are included in this query, and asks each
3609
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3610
-     * so they can be merged
3611
-     *
3612
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3613
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3614
-     *                                                                  'none' means NO default where conditions will
3615
-     *                                                                  be used AT ALL during this query.
3616
-     *                                                                  'other_models_only' means default where
3617
-     *                                                                  conditions from other models will be used, but
3618
-     *                                                                  not for this primary model. 'all', the default,
3619
-     *                                                                  means default where conditions will apply as
3620
-     *                                                                  normal
3621
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3622
-     * @throws EE_Error
3623
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3624
-     */
3625
-    private function _get_default_where_conditions_for_models_in_query(
3626
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3627
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3628
-        $where_query_params = array()
3629
-    ) {
3630
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3631
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3632
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3633
-                "event_espresso"), $use_default_where_conditions,
3634
-                implode(", ", $allowed_used_default_where_conditions_values)));
3635
-        }
3636
-        $universal_query_params = array();
3637
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3638
-            $universal_query_params = $this->_get_default_where_conditions();
3639
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3640
-            $universal_query_params = $this->_get_minimum_where_conditions();
3641
-        }
3642
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3643
-            $related_model = $this->get_related_model_obj($model_name);
3644
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3645
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3646
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3647
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3648
-            } else {
3649
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3650
-                continue;
3651
-            }
3652
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3653
-                $related_model_universal_where_params,
3654
-                $where_query_params,
3655
-                $related_model,
3656
-                $model_relation_path
3657
-            );
3658
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3659
-                $universal_query_params,
3660
-                $overrides
3661
-            );
3662
-        }
3663
-        return $universal_query_params;
3664
-    }
3665
-
3666
-
3667
-
3668
-    /**
3669
-     * Determines whether or not we should use default where conditions for the model in question
3670
-     * (this model, or other related models).
3671
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3672
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3673
-     * We should use default where conditions on related models when they requested to use default where conditions
3674
-     * on all models, or specifically just on other related models
3675
-     * @param      $default_where_conditions_value
3676
-     * @param bool $for_this_model false means this is for OTHER related models
3677
-     * @return bool
3678
-     */
3679
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3680
-    {
3681
-        return (
3682
-                   $for_this_model
3683
-                   && in_array(
3684
-                       $default_where_conditions_value,
3685
-                       array(
3686
-                           EEM_Base::default_where_conditions_all,
3687
-                           EEM_Base::default_where_conditions_this_only,
3688
-                           EEM_Base::default_where_conditions_minimum_others,
3689
-                       ),
3690
-                       true
3691
-                   )
3692
-               )
3693
-               || (
3694
-                   ! $for_this_model
3695
-                   && in_array(
3696
-                       $default_where_conditions_value,
3697
-                       array(
3698
-                           EEM_Base::default_where_conditions_all,
3699
-                           EEM_Base::default_where_conditions_others_only,
3700
-                       ),
3701
-                       true
3702
-                   )
3703
-               );
3704
-    }
3705
-
3706
-    /**
3707
-     * Determines whether or not we should use default minimum conditions for the model in question
3708
-     * (this model, or other related models).
3709
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3710
-     * where conditions.
3711
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3712
-     * on this model or others
3713
-     * @param      $default_where_conditions_value
3714
-     * @param bool $for_this_model false means this is for OTHER related models
3715
-     * @return bool
3716
-     */
3717
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3718
-    {
3719
-        return (
3720
-                   $for_this_model
3721
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3722
-               )
3723
-               || (
3724
-                   ! $for_this_model
3725
-                   && in_array(
3726
-                       $default_where_conditions_value,
3727
-                       array(
3728
-                           EEM_Base::default_where_conditions_minimum_others,
3729
-                           EEM_Base::default_where_conditions_minimum_all,
3730
-                       ),
3731
-                       true
3732
-                   )
3733
-               );
3734
-    }
3735
-
3736
-
3737
-    /**
3738
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3739
-     * then we also add a special where condition which allows for that model's primary key
3740
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3741
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3742
-     *
3743
-     * @param array    $default_where_conditions
3744
-     * @param array    $provided_where_conditions
3745
-     * @param EEM_Base $model
3746
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3747
-     * @return array like EEM_Base::get_all's $query_params[0]
3748
-     * @throws EE_Error
3749
-     */
3750
-    private function _override_defaults_or_make_null_friendly(
3751
-        $default_where_conditions,
3752
-        $provided_where_conditions,
3753
-        $model,
3754
-        $model_relation_path
3755
-    ) {
3756
-        $null_friendly_where_conditions = array();
3757
-        $none_overridden = true;
3758
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3759
-        foreach ($default_where_conditions as $key => $val) {
3760
-            if (isset($provided_where_conditions[$key])) {
3761
-                $none_overridden = false;
3762
-            } else {
3763
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3764
-            }
3765
-        }
3766
-        if ($none_overridden && $default_where_conditions) {
3767
-            if ($model->has_primary_key_field()) {
3768
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3769
-                                                                                . "."
3770
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3771
-            }/*else{
37
+	/**
38
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
41
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
+	 *
43
+	 * @var boolean
44
+	 */
45
+	private $_values_already_prepared_by_model_object = 0;
46
+
47
+	/**
48
+	 * when $_values_already_prepared_by_model_object equals this, we assume
49
+	 * the data is just like form input that needs to have the model fields'
50
+	 * prepare_for_set and prepare_for_use_in_db called on it
51
+	 */
52
+	const not_prepared_by_model_object = 0;
53
+
54
+	/**
55
+	 * when $_values_already_prepared_by_model_object equals this, we
56
+	 * assume this value is coming from a model object and doesn't need to have
57
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
58
+	 */
59
+	const prepared_by_model_object = 1;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the values are already to be used in the database (ie no processing is done
64
+	 * on them by the model's fields)
65
+	 */
66
+	const prepared_for_use_in_db = 2;
67
+
68
+
69
+	protected $singular_item = 'Item';
70
+
71
+	protected $plural_item   = 'Items';
72
+
73
+	/**
74
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
+	 */
76
+	protected $_tables;
77
+
78
+	/**
79
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
+	 *
83
+	 * @var \EE_Model_Field_Base[][] $_fields
84
+	 */
85
+	protected $_fields;
86
+
87
+	/**
88
+	 * array of different kinds of relations
89
+	 *
90
+	 * @var \EE_Model_Relation_Base[] $_model_relations
91
+	 */
92
+	protected $_model_relations;
93
+
94
+	/**
95
+	 * @var \EE_Index[] $_indexes
96
+	 */
97
+	protected $_indexes = array();
98
+
99
+	/**
100
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
101
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
+	 * by setting the same columns as used in these queries in the query yourself.
103
+	 *
104
+	 * @var EE_Default_Where_Conditions
105
+	 */
106
+	protected $_default_where_conditions_strategy;
107
+
108
+	/**
109
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
+	 * This is particularly useful when you want something between 'none' and 'default'
111
+	 *
112
+	 * @var EE_Default_Where_Conditions
113
+	 */
114
+	protected $_minimum_where_conditions_strategy;
115
+
116
+	/**
117
+	 * String describing how to find the "owner" of this model's objects.
118
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
+	 * But when there isn't, this indicates which related model, or transiently-related model,
120
+	 * has the foreign key to the wp_users table.
121
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
+	 * related to events, and events have a foreign key to wp_users.
123
+	 * On EEM_Transaction, this would be 'Transaction.Event'
124
+	 *
125
+	 * @var string
126
+	 */
127
+	protected $_model_chain_to_wp_user = '';
128
+
129
+	/**
130
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
+	 * don't need it (particularly CPT models)
132
+	 *
133
+	 * @var bool
134
+	 */
135
+	protected $_ignore_where_strategy = false;
136
+
137
+	/**
138
+	 * String used in caps relating to this model. Eg, if the caps relating to this
139
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
+	 *
141
+	 * @var string. If null it hasn't been initialized yet. If false then we
142
+	 * have indicated capabilities don't apply to this
143
+	 */
144
+	protected $_caps_slug = null;
145
+
146
+	/**
147
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
+	 * and next-level keys are capability names, and each's value is a
149
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
151
+	 * and then each capability in the corresponding sub-array that they're missing
152
+	 * adds the where conditions onto the query.
153
+	 *
154
+	 * @var array
155
+	 */
156
+	protected $_cap_restrictions = array(
157
+		self::caps_read       => array(),
158
+		self::caps_read_admin => array(),
159
+		self::caps_edit       => array(),
160
+		self::caps_delete     => array(),
161
+	);
162
+
163
+	/**
164
+	 * Array defining which cap restriction generators to use to create default
165
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
166
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
+	 * automatically set this to false (not just null).
169
+	 *
170
+	 * @var EE_Restriction_Generator_Base[]
171
+	 */
172
+	protected $_cap_restriction_generators = array();
173
+
174
+	/**
175
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
+	 */
177
+	const caps_read       = 'read';
178
+
179
+	const caps_read_admin = 'read_admin';
180
+
181
+	const caps_edit       = 'edit';
182
+
183
+	const caps_delete     = 'delete';
184
+
185
+	/**
186
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
+	 * maps to 'read' because when looking for relevant permissions we're going to use
189
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
190
+	 *
191
+	 * @var array
192
+	 */
193
+	protected $_cap_contexts_to_cap_action_map = array(
194
+		self::caps_read       => 'read',
195
+		self::caps_read_admin => 'read',
196
+		self::caps_edit       => 'edit',
197
+		self::caps_delete     => 'delete',
198
+	);
199
+
200
+	/**
201
+	 * Timezone
202
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
+	 * EE_Datetime_Field data type will have access to it.
206
+	 *
207
+	 * @var string
208
+	 */
209
+	protected $_timezone;
210
+
211
+
212
+	/**
213
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
+	 * multisite.
215
+	 *
216
+	 * @var int
217
+	 */
218
+	protected static $_model_query_blog_id;
219
+
220
+	/**
221
+	 * A copy of _fields, except the array keys are the model names pointed to by
222
+	 * the field
223
+	 *
224
+	 * @var EE_Model_Field_Base[]
225
+	 */
226
+	private $_cache_foreign_key_to_fields = array();
227
+
228
+	/**
229
+	 * Cached list of all the fields on the model, indexed by their name
230
+	 *
231
+	 * @var EE_Model_Field_Base[]
232
+	 */
233
+	private $_cached_fields = null;
234
+
235
+	/**
236
+	 * Cached list of all the fields on the model, except those that are
237
+	 * marked as only pertinent to the database
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cached_fields_non_db_only = null;
242
+
243
+	/**
244
+	 * A cached reference to the primary key for quick lookup
245
+	 *
246
+	 * @var EE_Model_Field_Base
247
+	 */
248
+	private $_primary_key_field = null;
249
+
250
+	/**
251
+	 * Flag indicating whether this model has a primary key or not
252
+	 *
253
+	 * @var boolean
254
+	 */
255
+	protected $_has_primary_key_field = null;
256
+
257
+	/**
258
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
259
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
+	 * This should be true for models that deal with data that should exist independent of EE.
261
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
263
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
265
+	 * @var boolean
266
+	 */
267
+	protected $_wp_core_model = false;
268
+
269
+	/**
270
+	 *    List of valid operators that can be used for querying.
271
+	 * The keys are all operators we'll accept, the values are the real SQL
272
+	 * operators used
273
+	 *
274
+	 * @var array
275
+	 */
276
+	protected $_valid_operators = array(
277
+		'='           => '=',
278
+		'<='          => '<=',
279
+		'<'           => '<',
280
+		'>='          => '>=',
281
+		'>'           => '>',
282
+		'!='          => '!=',
283
+		'LIKE'        => 'LIKE',
284
+		'like'        => 'LIKE',
285
+		'NOT_LIKE'    => 'NOT LIKE',
286
+		'not_like'    => 'NOT LIKE',
287
+		'NOT LIKE'    => 'NOT LIKE',
288
+		'not like'    => 'NOT LIKE',
289
+		'IN'          => 'IN',
290
+		'in'          => 'IN',
291
+		'NOT_IN'      => 'NOT IN',
292
+		'not_in'      => 'NOT IN',
293
+		'NOT IN'      => 'NOT IN',
294
+		'not in'      => 'NOT IN',
295
+		'between'     => 'BETWEEN',
296
+		'BETWEEN'     => 'BETWEEN',
297
+		'IS_NOT_NULL' => 'IS NOT NULL',
298
+		'is_not_null' => 'IS NOT NULL',
299
+		'IS NOT NULL' => 'IS NOT NULL',
300
+		'is not null' => 'IS NOT NULL',
301
+		'IS_NULL'     => 'IS NULL',
302
+		'is_null'     => 'IS NULL',
303
+		'IS NULL'     => 'IS NULL',
304
+		'is null'     => 'IS NULL',
305
+		'REGEXP'      => 'REGEXP',
306
+		'regexp'      => 'REGEXP',
307
+		'NOT_REGEXP'  => 'NOT REGEXP',
308
+		'not_regexp'  => 'NOT REGEXP',
309
+		'NOT REGEXP'  => 'NOT REGEXP',
310
+		'not regexp'  => 'NOT REGEXP',
311
+	);
312
+
313
+	/**
314
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
+	 *
316
+	 * @var array
317
+	 */
318
+	protected $_in_style_operators = array('IN', 'NOT IN');
319
+
320
+	/**
321
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
+	 * '12-31-2012'"
323
+	 *
324
+	 * @var array
325
+	 */
326
+	protected $_between_style_operators = array('BETWEEN');
327
+
328
+	/**
329
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
+	 * @var array
331
+	 */
332
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
+	/**
334
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
+	 * on a join table.
336
+	 *
337
+	 * @var array
338
+	 */
339
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
+
341
+	/**
342
+	 * Allowed values for $query_params['order'] for ordering in queries
343
+	 *
344
+	 * @var array
345
+	 */
346
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
+
348
+	/**
349
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
351
+	 *
352
+	 * @var array
353
+	 */
354
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
+
356
+	/**
357
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
359
+	 *
360
+	 * @var array
361
+	 */
362
+	private $_allowed_query_params = array(
363
+		0,
364
+		'limit',
365
+		'order_by',
366
+		'group_by',
367
+		'having',
368
+		'force_join',
369
+		'order',
370
+		'on_join_limit',
371
+		'default_where_conditions',
372
+		'caps',
373
+		'extra_selects'
374
+	);
375
+
376
+	/**
377
+	 * All the data types that can be used in $wpdb->prepare statements.
378
+	 *
379
+	 * @var array
380
+	 */
381
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
+
383
+	/**
384
+	 * @var EE_Registry $EE
385
+	 */
386
+	protected $EE = null;
387
+
388
+
389
+	/**
390
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
+	 *
392
+	 * @var int
393
+	 */
394
+	protected $_show_next_x_db_queries = 0;
395
+
396
+	/**
397
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
+	 * WHERE, GROUP_BY, etc.
400
+	 *
401
+	 * @var CustomSelects
402
+	 */
403
+	protected $_custom_selections = array();
404
+
405
+	/**
406
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
+	 * caches every model object we've fetched from the DB on this request
408
+	 *
409
+	 * @var array
410
+	 */
411
+	protected $_entity_map;
412
+
413
+	/**
414
+	 * @var LoaderInterface $loader
415
+	 */
416
+	private static $loader;
417
+
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error (
520
+				sprintf(
521
+					__('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
+						'event_espresso'),
523
+					get_class($this)
524
+				)
525
+			);
526
+		}
527
+		/**
528
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
+		 */
530
+		if (empty(EEM_Base::$_model_query_blog_id)) {
531
+			EEM_Base::set_model_query_blog_id();
532
+		}
533
+		/**
534
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
+		 * just use EE_Register_Model_Extension
536
+		 *
537
+		 * @var EE_Table_Base[] $_tables
538
+		 */
539
+		$this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+		foreach ($this->_tables as $table_alias => $table_obj) {
541
+			/** @var $table_obj EE_Table_Base */
542
+			$table_obj->_construct_finalize_with_alias($table_alias);
543
+			if ($table_obj instanceof EE_Secondary_Table) {
544
+				/** @var $table_obj EE_Secondary_Table */
545
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
+			}
547
+		}
548
+		/**
549
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
+		 * EE_Register_Model_Extension
551
+		 *
552
+		 * @param EE_Model_Field_Base[] $_fields
553
+		 */
554
+		$this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+		$this->_invalidate_field_caches();
556
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
557
+			if (! array_key_exists($table_alias, $this->_tables)) {
558
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
+			}
561
+			foreach ($fields_for_table as $field_name => $field_obj) {
562
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
+				//primary key field base has a slightly different _construct_finalize
564
+				/** @var $field_obj EE_Model_Field_Base */
565
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
+			}
567
+		}
568
+		// everything is related to Extra_Meta
569
+		if (get_class($this) !== 'EEM_Extra_Meta') {
570
+			//make extra meta related to everything, but don't block deleting things just
571
+			//because they have related extra meta info. For now just orphan those extra meta
572
+			//in the future we should automatically delete them
573
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		//and change logs
576
+		if (get_class($this) !== 'EEM_Change_Log') {
577
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		/**
580
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
+		 * EE_Register_Model_Extension
582
+		 *
583
+		 * @param EE_Model_Relation_Base[] $_model_relations
584
+		 */
585
+		$this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+			$this->_model_relations);
587
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
588
+			/** @var $relation_obj EE_Model_Relation_Base */
589
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
+		}
591
+		foreach ($this->_indexes as $index_name => $index_obj) {
592
+			/** @var $index_obj EE_Index */
593
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
+		}
595
+		$this->set_timezone($timezone);
596
+		//finalize default where condition strategy, or set default
597
+		if (! $this->_default_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
602
+		if (! $this->_minimum_where_conditions_strategy) {
603
+			//nothing was set during child constructor, so set default
604
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
+		}
606
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
608
+		//to indicate to NOT set it, set it to the logical default
609
+		if ($this->_caps_slug === null) {
610
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
+		}
612
+		//initialize the standard cap restriction generators if none were specified by the child constructor
613
+		if ($this->_cap_restriction_generators !== false) {
614
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
617
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
+						new EE_Restriction_Generator_Protected(),
619
+						$cap_context,
620
+						$this
621
+					);
622
+				}
623
+			}
624
+		}
625
+		//if there are cap restriction generators, use them to make the default cap restrictions
626
+		if ($this->_cap_restriction_generators !== false) {
627
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
+				if (! $generator_object) {
629
+					continue;
630
+				}
631
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+					throw new EE_Error(
633
+						sprintf(
634
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
+								'event_espresso'),
636
+							$context,
637
+							$this->get_this_model_name()
638
+						)
639
+					);
640
+				}
641
+				$action = $this->cap_action_for_context($context);
642
+				if (! $generator_object->construction_finalized()) {
643
+					$generator_object->_construct_finalize($this, $action);
644
+				}
645
+			}
646
+		}
647
+		do_action('AHEE__' . get_class($this) . '__construct__end');
648
+	}
649
+
650
+
651
+
652
+	/**
653
+	 * Used to set the $_model_query_blog_id static property.
654
+	 *
655
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
656
+	 *                      value for get_current_blog_id() will be used.
657
+	 */
658
+	public static function set_model_query_blog_id($blog_id = 0)
659
+	{
660
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
661
+	}
662
+
663
+
664
+
665
+	/**
666
+	 * Returns whatever is set as the internal $model_query_blog_id.
667
+	 *
668
+	 * @return int
669
+	 */
670
+	public static function get_model_query_blog_id()
671
+	{
672
+		return EEM_Base::$_model_query_blog_id;
673
+	}
674
+
675
+
676
+
677
+	/**
678
+	 * This function is a singleton method used to instantiate the Espresso_model object
679
+	 *
680
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
681
+	 *                                (and any incoming timezone data that gets saved).
682
+	 *                                Note this just sends the timezone info to the date time model field objects.
683
+	 *                                Default is NULL
684
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
685
+	 * @return static (as in the concrete child class)
686
+	 * @throws EE_Error
687
+	 * @throws InvalidArgumentException
688
+	 * @throws InvalidDataTypeException
689
+	 * @throws InvalidInterfaceException
690
+	 */
691
+	public static function instance($timezone = null)
692
+	{
693
+		// check if instance of Espresso_model already exists
694
+		if (! static::$_instance instanceof static) {
695
+			// instantiate Espresso_model
696
+			static::$_instance = new static(
697
+				$timezone,
698
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
699
+			);
700
+		}
701
+		//we might have a timezone set, let set_timezone decide what to do with it
702
+		static::$_instance->set_timezone($timezone);
703
+		// Espresso_model object
704
+		return static::$_instance;
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 * resets the model and returns it
711
+	 *
712
+	 * @param null | string $timezone
713
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
714
+	 * all its properties reset; if it wasn't instantiated, returns null)
715
+	 * @throws EE_Error
716
+	 * @throws ReflectionException
717
+	 * @throws InvalidArgumentException
718
+	 * @throws InvalidDataTypeException
719
+	 * @throws InvalidInterfaceException
720
+	 */
721
+	public static function reset($timezone = null)
722
+	{
723
+		if (static::$_instance instanceof EEM_Base) {
724
+			//let's try to NOT swap out the current instance for a new one
725
+			//because if someone has a reference to it, we can't remove their reference
726
+			//so it's best to keep using the same reference, but change the original object
727
+			//reset all its properties to their original values as defined in the class
728
+			$r = new ReflectionClass(get_class(static::$_instance));
729
+			$static_properties = $r->getStaticProperties();
730
+			foreach ($r->getDefaultProperties() as $property => $value) {
731
+				//don't set instance to null like it was originally,
732
+				//but it's static anyways, and we're ignoring static properties (for now at least)
733
+				if (! isset($static_properties[$property])) {
734
+					static::$_instance->{$property} = $value;
735
+				}
736
+			}
737
+			//and then directly call its constructor again, like we would if we were creating a new one
738
+			static::$_instance->__construct(
739
+				$timezone,
740
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
741
+			);
742
+			return self::instance();
743
+		}
744
+		return null;
745
+	}
746
+
747
+
748
+
749
+	/**
750
+	 * @return LoaderInterface
751
+	 * @throws InvalidArgumentException
752
+	 * @throws InvalidDataTypeException
753
+	 * @throws InvalidInterfaceException
754
+	 */
755
+	private static function getLoader()
756
+	{
757
+		if(! EEM_Base::$loader instanceof LoaderInterface) {
758
+			EEM_Base::$loader = LoaderFactory::getLoader();
759
+		}
760
+		return EEM_Base::$loader;
761
+	}
762
+
763
+
764
+
765
+	/**
766
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
767
+	 *
768
+	 * @param  boolean $translated return localized strings or JUST the array.
769
+	 * @return array
770
+	 * @throws EE_Error
771
+	 * @throws InvalidArgumentException
772
+	 * @throws InvalidDataTypeException
773
+	 * @throws InvalidInterfaceException
774
+	 */
775
+	public function status_array($translated = false)
776
+	{
777
+		if (! array_key_exists('Status', $this->_model_relations)) {
778
+			return array();
779
+		}
780
+		$model_name = $this->get_this_model_name();
781
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
782
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
783
+		$status_array = array();
784
+		foreach ($stati as $status) {
785
+			$status_array[$status->ID()] = $status->get('STS_code');
786
+		}
787
+		return $translated
788
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
789
+			: $status_array;
790
+	}
791
+
792
+
793
+
794
+	/**
795
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
796
+	 *
797
+	 * @param array $query_params             {
798
+	 * @var array $0 (where) array {
799
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
800
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
801
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
802
+	 *                                        conditions based on related models (and even
803
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
804
+	 *                                        name. Eg,
805
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
806
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
807
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
808
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
809
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
810
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
811
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
812
+	 *                                        to Venues (even when each of those models actually consisted of two
813
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
814
+	 *                                        just having
815
+	 *                                        "Venue.VNU_ID", you could have
816
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
817
+	 *                                        events are related to Registrations, which are related to Attendees). You
818
+	 *                                        can take it even further with
819
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
820
+	 *                                        (from the default of '='), change the value to an numerically-indexed
821
+	 *                                        array, where the first item in the list is the operator. eg: array(
822
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
823
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
824
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
825
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
826
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
827
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
828
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
829
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
830
+	 *                                        the value is a field, simply provide a third array item (true) to the
831
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
832
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
833
+	 *                                        Note: you can also use related model field names like you would any other
834
+	 *                                        field name. eg:
835
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
836
+	 *                                        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__>' =>
837
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
838
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
839
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
840
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
841
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
842
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
843
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
844
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
845
+	 *                                        "stick" until you specify an AND. eg
846
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
847
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
848
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
849
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
850
+	 *                                        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 >>
851
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
852
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
853
+	 *                                        too, eg:
854
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
855
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
856
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
857
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
858
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
859
+	 *                                        the OFFSET, the 2nd is the LIMIT
860
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
861
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
862
+	 *                                        following format array('on_join_limit'
863
+	 *                                        => array( 'table_alias', array(1,2) ) ).
864
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
865
+	 *                                        values are either 'ASC' or 'DESC'.
866
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
867
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
868
+	 *                                        DESC..." respectively. Like the
869
+	 *                                        'where' conditions, these fields can be on related models. Eg
870
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
871
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
872
+	 *                                        Attendee, Price, Datetime, etc.)
873
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
874
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
875
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
876
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
877
+	 *                                        order by the primary key. Eg,
878
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
879
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
880
+	 *                                        DTT_EVT_start) or
881
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
882
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
883
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
884
+	 *                                        'group_by'=>'VNU_ID', or
885
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
886
+	 *                                        if no
887
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
888
+	 *                                        model's primary key (or combined primary keys). This avoids some
889
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
890
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
891
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
892
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
893
+	 *                                        results)
894
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
895
+	 *                                        array where values are models to be joined in the query.Eg
896
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
897
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
898
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
899
+	 *                                        related models which belongs to the current model
900
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
901
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
902
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
903
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
904
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
905
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
906
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
907
+	 *                                        this model's default where conditions added to the query, use
908
+	 *                                        'this_model_only'. If you want to use all default where conditions
909
+	 *                                        (default), set to 'all'.
910
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
911
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
912
+	 *                                        everything? Or should we only show the current user items they should be
913
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
914
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
915
+	 *                                        }
916
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
917
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
918
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
919
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
920
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
921
+	 *                                        array( array(
922
+	 *                                        'OR'=>array(
923
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
924
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
925
+	 *                                        )
926
+	 *                                        ),
927
+	 *                                        'limit'=>10,
928
+	 *                                        'group_by'=>'TXN_ID'
929
+	 *                                        ));
930
+	 *                                        get all the answers to the question titled "shirt size" for event with id
931
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
932
+	 *                                        'Question.QST_display_text'=>'shirt size',
933
+	 *                                        'Registration.Event.EVT_ID'=>12
934
+	 *                                        ),
935
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
936
+	 *                                        ));
937
+	 * @throws EE_Error
938
+	 */
939
+	public function get_all($query_params = array())
940
+	{
941
+		if (isset($query_params['limit'])
942
+			&& ! isset($query_params['group_by'])
943
+		) {
944
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
945
+		}
946
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
947
+	}
948
+
949
+
950
+
951
+	/**
952
+	 * Modifies the query parameters so we only get back model objects
953
+	 * that "belong" to the current user
954
+	 *
955
+	 * @param array $query_params @see EEM_Base::get_all()
956
+	 * @return array like EEM_Base::get_all
957
+	 */
958
+	public function alter_query_params_to_only_include_mine($query_params = array())
959
+	{
960
+		$wp_user_field_name = $this->wp_user_field_name();
961
+		if ($wp_user_field_name) {
962
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
963
+		}
964
+		return $query_params;
965
+	}
966
+
967
+
968
+
969
+	/**
970
+	 * Returns the name of the field's name that points to the WP_User table
971
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
972
+	 * foreign key to the WP_User table)
973
+	 *
974
+	 * @return string|boolean string on success, boolean false when there is no
975
+	 * foreign key to the WP_User table
976
+	 */
977
+	public function wp_user_field_name()
978
+	{
979
+		try {
980
+			if (! empty($this->_model_chain_to_wp_user)) {
981
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982
+				$last_model_name = end($models_to_follow_to_wp_users);
983
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
985
+			} else {
986
+				$model_with_fk_to_wp_users = $this;
987
+				$model_chain_to_wp_user = '';
988
+			}
989
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
991
+		} catch (EE_Error $e) {
992
+			return false;
993
+		}
994
+	}
995
+
996
+
997
+
998
+	/**
999
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
1000
+	 * (or transiently-related model) has a foreign key to the wp_users table;
1001
+	 * useful for finding if model objects of this type are 'owned' by the current user.
1002
+	 * This is an empty string when the foreign key is on this model and when it isn't,
1003
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
1004
+	 * (or transiently-related model)
1005
+	 *
1006
+	 * @return string
1007
+	 */
1008
+	public function model_chain_to_wp_user()
1009
+	{
1010
+		return $this->_model_chain_to_wp_user;
1011
+	}
1012
+
1013
+
1014
+
1015
+	/**
1016
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1017
+	 * like how registrations don't have a foreign key to wp_users, but the
1018
+	 * events they are for are), or is unrelated to wp users.
1019
+	 * generally available
1020
+	 *
1021
+	 * @return boolean
1022
+	 */
1023
+	public function is_owned()
1024
+	{
1025
+		if ($this->model_chain_to_wp_user()) {
1026
+			return true;
1027
+		}
1028
+		try {
1029
+			$this->get_foreign_key_to('WP_User');
1030
+			return true;
1031
+		} catch (EE_Error $e) {
1032
+			return false;
1033
+		}
1034
+	}
1035
+
1036
+
1037
+	/**
1038
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1039
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1040
+	 * the model)
1041
+	 *
1042
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1043
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1044
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1045
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1046
+	 *                                  override this and set the select to "*", or a specific column name, like
1047
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1048
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1049
+	 *                                  the aliases used to refer to this selection, and values are to be
1050
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1051
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1052
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1053
+	 * @throws EE_Error
1054
+	 * @throws InvalidArgumentException
1055
+	 */
1056
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057
+	{
1058
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1059
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1060
+		$select_expressions = $columns_to_select === null
1061
+			? $this->_construct_default_select_sql($model_query_info)
1062
+			: '';
1063
+		if ($this->_custom_selections instanceof CustomSelects) {
1064
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065
+			$select_expressions .= $select_expressions
1066
+				? ', ' . $custom_expressions
1067
+				: $custom_expressions;
1068
+		}
1069
+
1070
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1071
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072
+	}
1073
+
1074
+
1075
+	/**
1076
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1077
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1078
+	 * method of including extra select information.
1079
+	 *
1080
+	 * @param array             $query_params
1081
+	 * @param null|array|string $columns_to_select
1082
+	 * @return null|CustomSelects
1083
+	 * @throws InvalidArgumentException
1084
+	 */
1085
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086
+	{
1087
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088
+			return null;
1089
+		}
1090
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1091
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1092
+		return new CustomSelects($selects);
1093
+	}
1094
+
1095
+
1096
+
1097
+	/**
1098
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1099
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1100
+	 * take care of joins, field preparation etc.
1101
+	 *
1102
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1103
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1104
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1105
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1106
+	 *                                  override this and set the select to "*", or a specific column name, like
1107
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1108
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1109
+	 *                                  the aliases used to refer to this selection, and values are to be
1110
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1111
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1112
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1113
+	 * @throws EE_Error
1114
+	 */
1115
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1116
+	{
1117
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1118
+	}
1119
+
1120
+
1121
+
1122
+	/**
1123
+	 * For creating a custom select statement
1124
+	 *
1125
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1126
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1127
+	 *                                 SQL, and 1=>is the datatype
1128
+	 * @throws EE_Error
1129
+	 * @return string
1130
+	 */
1131
+	private function _construct_select_from_input($columns_to_select)
1132
+	{
1133
+		if (is_array($columns_to_select)) {
1134
+			$select_sql_array = array();
1135
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137
+					throw new EE_Error(
1138
+						sprintf(
1139
+							__(
1140
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1141
+								'event_espresso'
1142
+							),
1143
+							$selection_and_datatype,
1144
+							$alias
1145
+						)
1146
+					);
1147
+				}
1148
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149
+					throw new EE_Error(
1150
+						sprintf(
1151
+							esc_html__(
1152
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1153
+								'event_espresso'
1154
+							),
1155
+							$selection_and_datatype[1],
1156
+							$selection_and_datatype[0],
1157
+							$alias,
1158
+							implode(', ', $this->_valid_wpdb_data_types)
1159
+						)
1160
+					);
1161
+				}
1162
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1163
+			}
1164
+			$columns_to_select_string = implode(', ', $select_sql_array);
1165
+		} else {
1166
+			$columns_to_select_string = $columns_to_select;
1167
+		}
1168
+		return $columns_to_select_string;
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1175
+	 *
1176
+	 * @return string
1177
+	 * @throws EE_Error
1178
+	 */
1179
+	public function primary_key_name()
1180
+	{
1181
+		return $this->get_primary_key_field()->get_name();
1182
+	}
1183
+
1184
+
1185
+
1186
+	/**
1187
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1188
+	 * If there is no primary key on this model, $id is treated as primary key string
1189
+	 *
1190
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1191
+	 * @return EE_Base_Class
1192
+	 */
1193
+	public function get_one_by_ID($id)
1194
+	{
1195
+		if ($this->get_from_entity_map($id)) {
1196
+			return $this->get_from_entity_map($id);
1197
+		}
1198
+		return $this->get_one(
1199
+			$this->alter_query_params_to_restrict_by_ID(
1200
+				$id,
1201
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1202
+			)
1203
+		);
1204
+	}
1205
+
1206
+
1207
+
1208
+	/**
1209
+	 * Alters query parameters to only get items with this ID are returned.
1210
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1211
+	 * or could just be a simple primary key ID
1212
+	 *
1213
+	 * @param int   $id
1214
+	 * @param array $query_params
1215
+	 * @return array of normal query params, @see EEM_Base::get_all
1216
+	 * @throws EE_Error
1217
+	 */
1218
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219
+	{
1220
+		if (! isset($query_params[0])) {
1221
+			$query_params[0] = array();
1222
+		}
1223
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1224
+		if ($conditions_from_id === null) {
1225
+			$query_params[0][$this->primary_key_name()] = $id;
1226
+		} else {
1227
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1228
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1229
+		}
1230
+		return $query_params;
1231
+	}
1232
+
1233
+
1234
+
1235
+	/**
1236
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1237
+	 * array. If no item is found, null is returned.
1238
+	 *
1239
+	 * @param array $query_params like EEM_Base's $query_params variable.
1240
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1241
+	 * @throws EE_Error
1242
+	 */
1243
+	public function get_one($query_params = array())
1244
+	{
1245
+		if (! is_array($query_params)) {
1246
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1247
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248
+					gettype($query_params)), '4.6.0');
1249
+			$query_params = array();
1250
+		}
1251
+		$query_params['limit'] = 1;
1252
+		$items = $this->get_all($query_params);
1253
+		if (empty($items)) {
1254
+			return null;
1255
+		}
1256
+		return array_shift($items);
1257
+	}
1258
+
1259
+
1260
+
1261
+	/**
1262
+	 * Returns the next x number of items in sequence from the given value as
1263
+	 * found in the database matching the given query conditions.
1264
+	 *
1265
+	 * @param mixed $current_field_value    Value used for the reference point.
1266
+	 * @param null  $field_to_order_by      What field is used for the
1267
+	 *                                      reference point.
1268
+	 * @param int   $limit                  How many to return.
1269
+	 * @param array $query_params           Extra conditions on the query.
1270
+	 * @param null  $columns_to_select      If left null, then an array of
1271
+	 *                                      EE_Base_Class objects is returned,
1272
+	 *                                      otherwise you can indicate just the
1273
+	 *                                      columns you want returned.
1274
+	 * @return EE_Base_Class[]|array
1275
+	 * @throws EE_Error
1276
+	 */
1277
+	public function next_x(
1278
+		$current_field_value,
1279
+		$field_to_order_by = null,
1280
+		$limit = 1,
1281
+		$query_params = array(),
1282
+		$columns_to_select = null
1283
+	) {
1284
+		return $this->_get_consecutive(
1285
+			$current_field_value,
1286
+			'>',
1287
+			$field_to_order_by,
1288
+			$limit,
1289
+			$query_params,
1290
+			$columns_to_select
1291
+		);
1292
+	}
1293
+
1294
+
1295
+
1296
+	/**
1297
+	 * Returns the previous x number of items in sequence from the given value
1298
+	 * as found in the database matching the given query conditions.
1299
+	 *
1300
+	 * @param mixed $current_field_value    Value used for the reference point.
1301
+	 * @param null  $field_to_order_by      What field is used for the
1302
+	 *                                      reference point.
1303
+	 * @param int   $limit                  How many to return.
1304
+	 * @param array $query_params           Extra conditions on the query.
1305
+	 * @param null  $columns_to_select      If left null, then an array of
1306
+	 *                                      EE_Base_Class objects is returned,
1307
+	 *                                      otherwise you can indicate just the
1308
+	 *                                      columns you want returned.
1309
+	 * @return EE_Base_Class[]|array
1310
+	 * @throws EE_Error
1311
+	 */
1312
+	public function previous_x(
1313
+		$current_field_value,
1314
+		$field_to_order_by = null,
1315
+		$limit = 1,
1316
+		$query_params = array(),
1317
+		$columns_to_select = null
1318
+	) {
1319
+		return $this->_get_consecutive(
1320
+			$current_field_value,
1321
+			'<',
1322
+			$field_to_order_by,
1323
+			$limit,
1324
+			$query_params,
1325
+			$columns_to_select
1326
+		);
1327
+	}
1328
+
1329
+
1330
+
1331
+	/**
1332
+	 * Returns the next item in sequence from the given value as found in the
1333
+	 * database matching the given query conditions.
1334
+	 *
1335
+	 * @param mixed $current_field_value    Value used for the reference point.
1336
+	 * @param null  $field_to_order_by      What field is used for the
1337
+	 *                                      reference point.
1338
+	 * @param array $query_params           Extra conditions on the query.
1339
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1340
+	 *                                      object is returned, otherwise you
1341
+	 *                                      can indicate just the columns you
1342
+	 *                                      want and a single array indexed by
1343
+	 *                                      the columns will be returned.
1344
+	 * @return EE_Base_Class|null|array()
1345
+	 * @throws EE_Error
1346
+	 */
1347
+	public function next(
1348
+		$current_field_value,
1349
+		$field_to_order_by = null,
1350
+		$query_params = array(),
1351
+		$columns_to_select = null
1352
+	) {
1353
+		$results = $this->_get_consecutive(
1354
+			$current_field_value,
1355
+			'>',
1356
+			$field_to_order_by,
1357
+			1,
1358
+			$query_params,
1359
+			$columns_to_select
1360
+		);
1361
+		return empty($results) ? null : reset($results);
1362
+	}
1363
+
1364
+
1365
+
1366
+	/**
1367
+	 * Returns the previous item in sequence from the given value as found in
1368
+	 * the database matching the given query conditions.
1369
+	 *
1370
+	 * @param mixed $current_field_value    Value used for the reference point.
1371
+	 * @param null  $field_to_order_by      What field is used for the
1372
+	 *                                      reference point.
1373
+	 * @param array $query_params           Extra conditions on the query.
1374
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1375
+	 *                                      object is returned, otherwise you
1376
+	 *                                      can indicate just the columns you
1377
+	 *                                      want and a single array indexed by
1378
+	 *                                      the columns will be returned.
1379
+	 * @return EE_Base_Class|null|array()
1380
+	 * @throws EE_Error
1381
+	 */
1382
+	public function previous(
1383
+		$current_field_value,
1384
+		$field_to_order_by = null,
1385
+		$query_params = array(),
1386
+		$columns_to_select = null
1387
+	) {
1388
+		$results = $this->_get_consecutive(
1389
+			$current_field_value,
1390
+			'<',
1391
+			$field_to_order_by,
1392
+			1,
1393
+			$query_params,
1394
+			$columns_to_select
1395
+		);
1396
+		return empty($results) ? null : reset($results);
1397
+	}
1398
+
1399
+
1400
+
1401
+	/**
1402
+	 * Returns the a consecutive number of items in sequence from the given
1403
+	 * value as found in the database matching the given query conditions.
1404
+	 *
1405
+	 * @param mixed  $current_field_value   Value used for the reference point.
1406
+	 * @param string $operand               What operand is used for the sequence.
1407
+	 * @param string $field_to_order_by     What field is used for the reference point.
1408
+	 * @param int    $limit                 How many to return.
1409
+	 * @param array  $query_params          Extra conditions on the query.
1410
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1411
+	 *                                      otherwise you can indicate just the columns you want returned.
1412
+	 * @return EE_Base_Class[]|array
1413
+	 * @throws EE_Error
1414
+	 */
1415
+	protected function _get_consecutive(
1416
+		$current_field_value,
1417
+		$operand = '>',
1418
+		$field_to_order_by = null,
1419
+		$limit = 1,
1420
+		$query_params = array(),
1421
+		$columns_to_select = null
1422
+	) {
1423
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1424
+		if (empty($field_to_order_by)) {
1425
+			if ($this->has_primary_key_field()) {
1426
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1427
+			} else {
1428
+				if (WP_DEBUG) {
1429
+					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).',
1430
+						'event_espresso'));
1431
+				}
1432
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1433
+				return array();
1434
+			}
1435
+		}
1436
+		if (! is_array($query_params)) {
1437
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439
+					gettype($query_params)), '4.6.0');
1440
+			$query_params = array();
1441
+		}
1442
+		//let's add the where query param for consecutive look up.
1443
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444
+		$query_params['limit'] = $limit;
1445
+		//set direction
1446
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1447
+		$query_params['order_by'] = $operand === '>'
1448
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1449
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1450
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1451
+		if (empty($columns_to_select)) {
1452
+			return $this->get_all($query_params);
1453
+		}
1454
+		//getting just the fields
1455
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1456
+	}
1457
+
1458
+
1459
+
1460
+	/**
1461
+	 * This sets the _timezone property after model object has been instantiated.
1462
+	 *
1463
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1464
+	 */
1465
+	public function set_timezone($timezone)
1466
+	{
1467
+		if ($timezone !== null) {
1468
+			$this->_timezone = $timezone;
1469
+		}
1470
+		//note we need to loop through relations and set the timezone on those objects as well.
1471
+		foreach ($this->_model_relations as $relation) {
1472
+			$relation->set_timezone($timezone);
1473
+		}
1474
+		//and finally we do the same for any datetime fields
1475
+		foreach ($this->_fields as $field) {
1476
+			if ($field instanceof EE_Datetime_Field) {
1477
+				$field->set_timezone($timezone);
1478
+			}
1479
+		}
1480
+	}
1481
+
1482
+
1483
+
1484
+	/**
1485
+	 * This just returns whatever is set for the current timezone.
1486
+	 *
1487
+	 * @access public
1488
+	 * @return string
1489
+	 */
1490
+	public function get_timezone()
1491
+	{
1492
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1493
+		if (empty($this->_timezone)) {
1494
+			foreach ($this->_fields as $field) {
1495
+				if ($field instanceof EE_Datetime_Field) {
1496
+					$this->set_timezone($field->get_timezone());
1497
+					break;
1498
+				}
1499
+			}
1500
+		}
1501
+		//if timezone STILL empty then return the default timezone for the site.
1502
+		if (empty($this->_timezone)) {
1503
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1504
+		}
1505
+		return $this->_timezone;
1506
+	}
1507
+
1508
+
1509
+
1510
+	/**
1511
+	 * This returns the date formats set for the given field name and also ensures that
1512
+	 * $this->_timezone property is set correctly.
1513
+	 *
1514
+	 * @since 4.6.x
1515
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1516
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1517
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1518
+	 * @return array formats in an array with the date format first, and the time format last.
1519
+	 */
1520
+	public function get_formats_for($field_name, $pretty = false)
1521
+	{
1522
+		$field_settings = $this->field_settings_for($field_name);
1523
+		//if not a valid EE_Datetime_Field then throw error
1524
+		if (! $field_settings instanceof EE_Datetime_Field) {
1525
+			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.',
1526
+				'event_espresso'), $field_name));
1527
+		}
1528
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1529
+		//the field.
1530
+		$this->_timezone = $field_settings->get_timezone();
1531
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1532
+	}
1533
+
1534
+
1535
+
1536
+	/**
1537
+	 * This returns the current time in a format setup for a query on this model.
1538
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1539
+	 * it will return:
1540
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1541
+	 *  NOW
1542
+	 *  - or a unix timestamp (equivalent to time())
1543
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1544
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1545
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1546
+	 * @since 4.6.x
1547
+	 * @param string $field_name       The field the current time is needed for.
1548
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1549
+	 *                                 formatted string matching the set format for the field in the set timezone will
1550
+	 *                                 be returned.
1551
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1552
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1553
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1554
+	 *                                 exception is triggered.
1555
+	 */
1556
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1557
+	{
1558
+		$formats = $this->get_formats_for($field_name);
1559
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1560
+		if ($timestamp) {
1561
+			return $DateTime->format('U');
1562
+		}
1563
+		//not returning timestamp, so return formatted string in timezone.
1564
+		switch ($what) {
1565
+			case 'time' :
1566
+				return $DateTime->format($formats[1]);
1567
+				break;
1568
+			case 'date' :
1569
+				return $DateTime->format($formats[0]);
1570
+				break;
1571
+			default :
1572
+				return $DateTime->format(implode(' ', $formats));
1573
+				break;
1574
+		}
1575
+	}
1576
+
1577
+
1578
+
1579
+	/**
1580
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1581
+	 * for the model are.  Returns a DateTime object.
1582
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1583
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1584
+	 * ignored.
1585
+	 *
1586
+	 * @param string $field_name      The field being setup.
1587
+	 * @param string $timestring      The date time string being used.
1588
+	 * @param string $incoming_format The format for the time string.
1589
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1590
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1591
+	 *                                format is
1592
+	 *                                'U', this is ignored.
1593
+	 * @return DateTime
1594
+	 * @throws EE_Error
1595
+	 */
1596
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1597
+	{
1598
+		//just using this to ensure the timezone is set correctly internally
1599
+		$this->get_formats_for($field_name);
1600
+		//load EEH_DTT_Helper
1601
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1604
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1605
+	}
1606
+
1607
+
1608
+
1609
+	/**
1610
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1611
+	 *
1612
+	 * @return EE_Table_Base[]
1613
+	 */
1614
+	public function get_tables()
1615
+	{
1616
+		return $this->_tables;
1617
+	}
1618
+
1619
+
1620
+
1621
+	/**
1622
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1623
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1624
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1625
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1626
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1627
+	 * model object with EVT_ID = 1
1628
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1629
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1630
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1631
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1632
+	 * are not specified)
1633
+	 *
1634
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1635
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1636
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1637
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1638
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1639
+	 *                                         ID=34, we'd use this method as follows:
1640
+	 *                                         EEM_Transaction::instance()->update(
1641
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1642
+	 *                                         array(array('TXN_ID'=>34)));
1643
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1644
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1645
+	 *                                         consider updating Question's QST_admin_label field is of type
1646
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1647
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1648
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1649
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1650
+	 *                                         TRUE, it is assumed that you've already called
1651
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1652
+	 *                                         malicious javascript. However, if
1653
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1654
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1655
+	 *                                         and every other field, before insertion. We provide this parameter
1656
+	 *                                         because model objects perform their prepare_for_set function on all
1657
+	 *                                         their values, and so don't need to be called again (and in many cases,
1658
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1659
+	 *                                         prepare_for_set method...)
1660
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1661
+	 *                                         in this model's entity map according to $fields_n_values that match
1662
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1663
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1664
+	 *                                         could get out-of-sync with the database
1665
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1666
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1667
+	 *                                         bad)
1668
+	 * @throws EE_Error
1669
+	 */
1670
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1671
+	{
1672
+		if (! is_array($query_params)) {
1673
+			EE_Error::doing_it_wrong('EEM_Base::update',
1674
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1675
+					gettype($query_params)), '4.6.0');
1676
+			$query_params = array();
1677
+		}
1678
+		/**
1679
+		 * Action called before a model update call has been made.
1680
+		 *
1681
+		 * @param EEM_Base $model
1682
+		 * @param array    $fields_n_values the updated fields and their new values
1683
+		 * @param array    $query_params    @see EEM_Base::get_all()
1684
+		 */
1685
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1686
+		/**
1687
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1688
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1689
+		 *
1690
+		 * @param array    $fields_n_values fields and their new values
1691
+		 * @param EEM_Base $model           the model being queried
1692
+		 * @param array    $query_params    see EEM_Base::get_all()
1693
+		 */
1694
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1695
+			$query_params);
1696
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1697
+		//to do that, for each table, verify that it's PK isn't null.
1698
+		$tables = $this->get_tables();
1699
+		//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
1700
+		//NOTE: we should make this code more efficient by NOT querying twice
1701
+		//before the real update, but that needs to first go through ALPHA testing
1702
+		//as it's dangerous. says Mike August 8 2014
1703
+		//we want to make sure the default_where strategy is ignored
1704
+		$this->_ignore_where_strategy = true;
1705
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1706
+		foreach ($wpdb_select_results as $wpdb_result) {
1707
+			// type cast stdClass as array
1708
+			$wpdb_result = (array)$wpdb_result;
1709
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1710
+			if ($this->has_primary_key_field()) {
1711
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1712
+			} else {
1713
+				//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)
1714
+				$main_table_pk_value = null;
1715
+			}
1716
+			//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
1717
+			//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
1718
+			if (count($tables) > 1) {
1719
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1720
+				//in that table, and so we'll want to insert one
1721
+				foreach ($tables as $table_obj) {
1722
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1723
+					//if there is no private key for this table on the results, it means there's no entry
1724
+					//in this table, right? so insert a row in the current table, using any fields available
1725
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1726
+						   && $wpdb_result[$this_table_pk_column])
1727
+					) {
1728
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1729
+							$main_table_pk_value);
1730
+						//if we died here, report the error
1731
+						if (! $success) {
1732
+							return false;
1733
+						}
1734
+					}
1735
+				}
1736
+			}
1737
+			//				//and now check that if we have cached any models by that ID on the model, that
1738
+			//				//they also get updated properly
1739
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1740
+			//				if( $model_object ){
1741
+			//					foreach( $fields_n_values as $field => $value ){
1742
+			//						$model_object->set($field, $value);
1743
+			//let's make sure default_where strategy is followed now
1744
+			$this->_ignore_where_strategy = false;
1745
+		}
1746
+		//if we want to keep model objects in sync, AND
1747
+		//if this wasn't called from a model object (to update itself)
1748
+		//then we want to make sure we keep all the existing
1749
+		//model objects in sync with the db
1750
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1751
+			if ($this->has_primary_key_field()) {
1752
+				$model_objs_affected_ids = $this->get_col($query_params);
1753
+			} else {
1754
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1755
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1756
+				$model_objs_affected_ids = array();
1757
+				foreach ($models_affected_key_columns as $row) {
1758
+					$combined_index_key = $this->get_index_primary_key_string($row);
1759
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1760
+				}
1761
+			}
1762
+			if (! $model_objs_affected_ids) {
1763
+				//wait wait wait- if nothing was affected let's stop here
1764
+				return 0;
1765
+			}
1766
+			foreach ($model_objs_affected_ids as $id) {
1767
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1768
+				if ($model_obj_in_entity_map) {
1769
+					foreach ($fields_n_values as $field => $new_value) {
1770
+						$model_obj_in_entity_map->set($field, $new_value);
1771
+					}
1772
+				}
1773
+			}
1774
+			//if there is a primary key on this model, we can now do a slight optimization
1775
+			if ($this->has_primary_key_field()) {
1776
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1777
+				$query_params = array(
1778
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1779
+					'limit'                    => count($model_objs_affected_ids),
1780
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1781
+				);
1782
+			}
1783
+		}
1784
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1785
+		$SQL = "UPDATE "
1786
+			   . $model_query_info->get_full_join_sql()
1787
+			   . " SET "
1788
+			   . $this->_construct_update_sql($fields_n_values)
1789
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1790
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1791
+		/**
1792
+		 * Action called after a model update call has been made.
1793
+		 *
1794
+		 * @param EEM_Base $model
1795
+		 * @param array    $fields_n_values the updated fields and their new values
1796
+		 * @param array    $query_params    @see EEM_Base::get_all()
1797
+		 * @param int      $rows_affected
1798
+		 */
1799
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1800
+		return $rows_affected;//how many supposedly got updated
1801
+	}
1802
+
1803
+
1804
+
1805
+	/**
1806
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1807
+	 * are teh values of the field specified (or by default the primary key field)
1808
+	 * that matched the query params. Note that you should pass the name of the
1809
+	 * model FIELD, not the database table's column name.
1810
+	 *
1811
+	 * @param array  $query_params @see EEM_Base::get_all()
1812
+	 * @param string $field_to_select
1813
+	 * @return array just like $wpdb->get_col()
1814
+	 * @throws EE_Error
1815
+	 */
1816
+	public function get_col($query_params = array(), $field_to_select = null)
1817
+	{
1818
+		if ($field_to_select) {
1819
+			$field = $this->field_settings_for($field_to_select);
1820
+		} elseif ($this->has_primary_key_field()) {
1821
+			$field = $this->get_primary_key_field();
1822
+		} else {
1823
+			//no primary key, just grab the first column
1824
+			$field = reset($this->field_settings());
1825
+		}
1826
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1827
+		$select_expressions = $field->get_qualified_column();
1828
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1829
+		return $this->_do_wpdb_query('get_col', array($SQL));
1830
+	}
1831
+
1832
+
1833
+
1834
+	/**
1835
+	 * Returns a single column value for a single row from the database
1836
+	 *
1837
+	 * @param array  $query_params    @see EEM_Base::get_all()
1838
+	 * @param string $field_to_select @see EEM_Base::get_col()
1839
+	 * @return string
1840
+	 * @throws EE_Error
1841
+	 */
1842
+	public function get_var($query_params = array(), $field_to_select = null)
1843
+	{
1844
+		$query_params['limit'] = 1;
1845
+		$col = $this->get_col($query_params, $field_to_select);
1846
+		if (! empty($col)) {
1847
+			return reset($col);
1848
+		}
1849
+		return null;
1850
+	}
1851
+
1852
+
1853
+
1854
+	/**
1855
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1856
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1857
+	 * injection, but currently no further filtering is done
1858
+	 *
1859
+	 * @global      $wpdb
1860
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1861
+	 *                               be updated to in the DB
1862
+	 * @return string of SQL
1863
+	 * @throws EE_Error
1864
+	 */
1865
+	public function _construct_update_sql($fields_n_values)
1866
+	{
1867
+		/** @type WPDB $wpdb */
1868
+		global $wpdb;
1869
+		$cols_n_values = array();
1870
+		foreach ($fields_n_values as $field_name => $value) {
1871
+			$field_obj = $this->field_settings_for($field_name);
1872
+			//if the value is NULL, we want to assign the value to that.
1873
+			//wpdb->prepare doesn't really handle that properly
1874
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1875
+			$value_sql = $prepared_value === null ? 'NULL'
1876
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1877
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1878
+		}
1879
+		return implode(",", $cols_n_values);
1880
+	}
1881
+
1882
+
1883
+
1884
+	/**
1885
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1886
+	 * Performs a HARD delete, meaning the database row should always be removed,
1887
+	 * not just have a flag field on it switched
1888
+	 * Wrapper for EEM_Base::delete_permanently()
1889
+	 *
1890
+	 * @param mixed $id
1891
+	 * @param boolean $allow_blocking
1892
+	 * @return int the number of rows deleted
1893
+	 * @throws EE_Error
1894
+	 */
1895
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1896
+	{
1897
+		return $this->delete_permanently(
1898
+			array(
1899
+				array($this->get_primary_key_field()->get_name() => $id),
1900
+				'limit' => 1,
1901
+			),
1902
+			$allow_blocking
1903
+		);
1904
+	}
1905
+
1906
+
1907
+
1908
+	/**
1909
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1910
+	 * Wrapper for EEM_Base::delete()
1911
+	 *
1912
+	 * @param mixed $id
1913
+	 * @param boolean $allow_blocking
1914
+	 * @return int the number of rows deleted
1915
+	 * @throws EE_Error
1916
+	 */
1917
+	public function delete_by_ID($id, $allow_blocking = true)
1918
+	{
1919
+		return $this->delete(
1920
+			array(
1921
+				array($this->get_primary_key_field()->get_name() => $id),
1922
+				'limit' => 1,
1923
+			),
1924
+			$allow_blocking
1925
+		);
1926
+	}
1927
+
1928
+
1929
+
1930
+	/**
1931
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1932
+	 * meaning if the model has a field that indicates its been "trashed" or
1933
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1934
+	 *
1935
+	 * @see EEM_Base::delete_permanently
1936
+	 * @param array   $query_params
1937
+	 * @param boolean $allow_blocking
1938
+	 * @return int how many rows got deleted
1939
+	 * @throws EE_Error
1940
+	 */
1941
+	public function delete($query_params, $allow_blocking = true)
1942
+	{
1943
+		return $this->delete_permanently($query_params, $allow_blocking);
1944
+	}
1945
+
1946
+
1947
+
1948
+	/**
1949
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1950
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1951
+	 * as archived, not actually deleted
1952
+	 *
1953
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1954
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1955
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1956
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1957
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1958
+	 *                                DB
1959
+	 * @return int how many rows got deleted
1960
+	 * @throws EE_Error
1961
+	 */
1962
+	public function delete_permanently($query_params, $allow_blocking = true)
1963
+	{
1964
+		/**
1965
+		 * Action called just before performing a real deletion query. You can use the
1966
+		 * model and its $query_params to find exactly which items will be deleted
1967
+		 *
1968
+		 * @param EEM_Base $model
1969
+		 * @param array    $query_params   @see EEM_Base::get_all()
1970
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1971
+		 *                                 to block (prevent) this deletion
1972
+		 */
1973
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1974
+		//some MySQL databases may be running safe mode, which may restrict
1975
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1976
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1977
+		//to delete them
1978
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1979
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1980
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1981
+			$columns_and_ids_for_deleting
1982
+		);
1983
+		/**
1984
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1985
+		 *
1986
+		 * @param EEM_Base $this  The model instance being acted on.
1987
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1988
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1989
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1990
+		 *                                                  derived from the incoming query parameters.
1991
+		 *                                                  @see details on the structure of this array in the phpdocs
1992
+		 *                                                  for the `_get_ids_for_delete_method`
1993
+		 *
1994
+		 */
1995
+		do_action('AHEE__EEM_Base__delete__before_query',
1996
+			$this,
1997
+			$query_params,
1998
+			$allow_blocking,
1999
+			$columns_and_ids_for_deleting
2000
+		);
2001
+		if ($deletion_where_query_part) {
2002
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2003
+			$table_aliases = array_keys($this->_tables);
2004
+			$SQL = "DELETE "
2005
+				   . implode(", ", $table_aliases)
2006
+				   . " FROM "
2007
+				   . $model_query_info->get_full_join_sql()
2008
+				   . " WHERE "
2009
+				   . $deletion_where_query_part;
2010
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2011
+		} else {
2012
+			$rows_deleted = 0;
2013
+		}
2014
+
2015
+		//Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2016
+		//there was no error with the delete query.
2017
+		if ($this->has_primary_key_field()
2018
+			&& $rows_deleted !== false
2019
+			&& isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2020
+		) {
2021
+			$ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2022
+			foreach ($ids_for_removal as $id) {
2023
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2024
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2025
+				}
2026
+			}
2027
+
2028
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2029
+			//`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2030
+			//unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2031
+			// (although it is possible).
2032
+			//Note this can be skipped by using the provided filter and returning false.
2033
+			if (apply_filters(
2034
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2035
+				! $this instanceof EEM_Extra_Meta,
2036
+				$this
2037
+			)) {
2038
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2039
+					0 => array(
2040
+						'EXM_type' => $this->get_this_model_name(),
2041
+						'OBJ_ID'   => array(
2042
+							'IN',
2043
+							$ids_for_removal
2044
+						)
2045
+					)
2046
+				));
2047
+			}
2048
+		}
2049
+
2050
+		/**
2051
+		 * Action called just after performing a real deletion query. Although at this point the
2052
+		 * items should have been deleted
2053
+		 *
2054
+		 * @param EEM_Base $model
2055
+		 * @param array    $query_params @see EEM_Base::get_all()
2056
+		 * @param int      $rows_deleted
2057
+		 */
2058
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2059
+		return $rows_deleted;//how many supposedly got deleted
2060
+	}
2061
+
2062
+
2063
+
2064
+	/**
2065
+	 * Checks all the relations that throw error messages when there are blocking related objects
2066
+	 * for related model objects. If there are any related model objects on those relations,
2067
+	 * adds an EE_Error, and return true
2068
+	 *
2069
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2070
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2071
+	 *                                                 should be ignored when determining whether there are related
2072
+	 *                                                 model objects which block this model object's deletion. Useful
2073
+	 *                                                 if you know A is related to B and are considering deleting A,
2074
+	 *                                                 but want to see if A has any other objects blocking its deletion
2075
+	 *                                                 before removing the relation between A and B
2076
+	 * @return boolean
2077
+	 * @throws EE_Error
2078
+	 */
2079
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2080
+	{
2081
+		//first, if $ignore_this_model_obj was supplied, get its model
2082
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2083
+			$ignored_model = $ignore_this_model_obj->get_model();
2084
+		} else {
2085
+			$ignored_model = null;
2086
+		}
2087
+		//now check all the relations of $this_model_obj_or_id and see if there
2088
+		//are any related model objects blocking it?
2089
+		$is_blocked = false;
2090
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2091
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2092
+				//if $ignore_this_model_obj was supplied, then for the query
2093
+				//on that model needs to be told to ignore $ignore_this_model_obj
2094
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2095
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2096
+						array(
2097
+							$ignored_model->get_primary_key_field()->get_name() => array(
2098
+								'!=',
2099
+								$ignore_this_model_obj->ID(),
2100
+							),
2101
+						),
2102
+					));
2103
+				} else {
2104
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2105
+				}
2106
+				if ($related_model_objects) {
2107
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2108
+					$is_blocked = true;
2109
+				}
2110
+			}
2111
+		}
2112
+		return $is_blocked;
2113
+	}
2114
+
2115
+
2116
+	/**
2117
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2118
+	 * @param array $row_results_for_deleting
2119
+	 * @param bool  $allow_blocking
2120
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2121
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2122
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2123
+	 *                 deleted. Example:
2124
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2125
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2126
+	 *                 where each element is a group of columns and values that get deleted. Example:
2127
+	 *                      array(
2128
+	 *                          0 => array(
2129
+	 *                              'Term_Relationship.object_id' => 1
2130
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2131
+	 *                          ),
2132
+	 *                          1 => array(
2133
+	 *                              'Term_Relationship.object_id' => 1
2134
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2135
+	 *                          )
2136
+	 *                      )
2137
+	 * @throws EE_Error
2138
+	 */
2139
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2140
+	{
2141
+		$ids_to_delete_indexed_by_column = array();
2142
+		if ($this->has_primary_key_field()) {
2143
+			$primary_table = $this->_get_main_table();
2144
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2145
+			$other_tables = $this->_get_other_tables();
2146
+			$ids_to_delete_indexed_by_column = $query = array();
2147
+			foreach ($row_results_for_deleting as $item_to_delete) {
2148
+				//before we mark this item for deletion,
2149
+				//make sure there's no related entities blocking its deletion (if we're checking)
2150
+				if (
2151
+					$allow_blocking
2152
+					&& $this->delete_is_blocked_by_related_models(
2153
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2154
+					)
2155
+				) {
2156
+					continue;
2157
+				}
2158
+				//primary table deletes
2159
+				if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2160
+					$ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2161
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2162
+				}
2163
+			}
2164
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2165
+			$fields = $this->get_combined_primary_key_fields();
2166
+			foreach ($row_results_for_deleting as $item_to_delete) {
2167
+				$ids_to_delete_indexed_by_column_for_row = array();
2168
+				foreach ($fields as $cpk_field) {
2169
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2170
+						$ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2171
+							$item_to_delete[$cpk_field->get_qualified_column()];
2172
+					}
2173
+				}
2174
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2175
+			}
2176
+		} else {
2177
+			//so there's no primary key and no combined key...
2178
+			//sorry, can't help you
2179
+			throw new EE_Error(
2180
+				sprintf(
2181
+					__(
2182
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2183
+						"event_espresso"
2184
+					), get_class($this)
2185
+				)
2186
+			);
2187
+		}
2188
+		return $ids_to_delete_indexed_by_column;
2189
+	}
2190
+
2191
+
2192
+	/**
2193
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2194
+	 * the corresponding query_part for the query performing the delete.
2195
+	 *
2196
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2197
+	 * @return string
2198
+	 * @throws EE_Error
2199
+	 */
2200
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2201
+		$query_part = '';
2202
+		if (empty($ids_to_delete_indexed_by_column)) {
2203
+			return $query_part;
2204
+		} elseif ($this->has_primary_key_field()) {
2205
+			$query = array();
2206
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2207
+				//make sure we have unique $ids
2208
+				$ids = array_unique($ids);
2209
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2210
+			}
2211
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2212
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2213
+			$ways_to_identify_a_row = array();
2214
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2215
+				$values_for_each_combined_primary_key_for_a_row = array();
2216
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2217
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2218
+				}
2219
+				$ways_to_identify_a_row[] = '('
2220
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2221
+											. ')';
2222
+			}
2223
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2224
+		}
2225
+		return $query_part;
2226
+	}
2227
+
2228
+
2229
+
2230
+	/**
2231
+	 * Gets the model field by the fully qualified name
2232
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2233
+	 * @return EE_Model_Field_Base
2234
+	 */
2235
+	public function get_field_by_column($qualified_column_name)
2236
+	{
2237
+	   foreach($this->field_settings(true) as $field_name => $field_obj){
2238
+		   if($field_obj->get_qualified_column() === $qualified_column_name){
2239
+			   return $field_obj;
2240
+		   }
2241
+	   }
2242
+		throw new EE_Error(
2243
+			sprintf(
2244
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2245
+				$this->get_this_model_name(),
2246
+				$qualified_column_name
2247
+			)
2248
+		);
2249
+	}
2250
+
2251
+
2252
+
2253
+	/**
2254
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2255
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2256
+	 * column
2257
+	 *
2258
+	 * @param array  $query_params   like EEM_Base::get_all's
2259
+	 * @param string $field_to_count field on model to count by (not column name)
2260
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2261
+	 *                               that by the setting $distinct to TRUE;
2262
+	 * @return int
2263
+	 * @throws EE_Error
2264
+	 */
2265
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2266
+	{
2267
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2268
+		if ($field_to_count) {
2269
+			$field_obj = $this->field_settings_for($field_to_count);
2270
+			$column_to_count = $field_obj->get_qualified_column();
2271
+		} elseif ($this->has_primary_key_field()) {
2272
+			$pk_field_obj = $this->get_primary_key_field();
2273
+			$column_to_count = $pk_field_obj->get_qualified_column();
2274
+		} else {
2275
+			//there's no primary key
2276
+			//if we're counting distinct items, and there's no primary key,
2277
+			//we need to list out the columns for distinction;
2278
+			//otherwise we can just use star
2279
+			if ($distinct) {
2280
+				$columns_to_use = array();
2281
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2282
+					$columns_to_use[] = $field_obj->get_qualified_column();
2283
+				}
2284
+				$column_to_count = implode(',', $columns_to_use);
2285
+			} else {
2286
+				$column_to_count = '*';
2287
+			}
2288
+		}
2289
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2290
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2291
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2292
+	}
2293
+
2294
+
2295
+
2296
+	/**
2297
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2298
+	 *
2299
+	 * @param array  $query_params like EEM_Base::get_all
2300
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2301
+	 * @return float
2302
+	 * @throws EE_Error
2303
+	 */
2304
+	public function sum($query_params, $field_to_sum = null)
2305
+	{
2306
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2307
+		if ($field_to_sum) {
2308
+			$field_obj = $this->field_settings_for($field_to_sum);
2309
+		} else {
2310
+			$field_obj = $this->get_primary_key_field();
2311
+		}
2312
+		$column_to_count = $field_obj->get_qualified_column();
2313
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2314
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2315
+		$data_type = $field_obj->get_wpdb_data_type();
2316
+		if ($data_type === '%d' || $data_type === '%s') {
2317
+			return (float)$return_value;
2318
+		}
2319
+		//must be %f
2320
+		return (float)$return_value;
2321
+	}
2322
+
2323
+
2324
+
2325
+	/**
2326
+	 * Just calls the specified method on $wpdb with the given arguments
2327
+	 * Consolidates a little extra error handling code
2328
+	 *
2329
+	 * @param string $wpdb_method
2330
+	 * @param array  $arguments_to_provide
2331
+	 * @throws EE_Error
2332
+	 * @global wpdb  $wpdb
2333
+	 * @return mixed
2334
+	 */
2335
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2336
+	{
2337
+		//if we're in maintenance mode level 2, DON'T run any queries
2338
+		//because level 2 indicates the database needs updating and
2339
+		//is probably out of sync with the code
2340
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2341
+			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.",
2342
+				"event_espresso")));
2343
+		}
2344
+		/** @type WPDB $wpdb */
2345
+		global $wpdb;
2346
+		if (! method_exists($wpdb, $wpdb_method)) {
2347
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2348
+				'event_espresso'), $wpdb_method));
2349
+		}
2350
+		if (WP_DEBUG) {
2351
+			$old_show_errors_value = $wpdb->show_errors;
2352
+			$wpdb->show_errors(false);
2353
+		}
2354
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2355
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2356
+		if (WP_DEBUG) {
2357
+			$wpdb->show_errors($old_show_errors_value);
2358
+			if (! empty($wpdb->last_error)) {
2359
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2360
+			}
2361
+			if ($result === false) {
2362
+				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"',
2363
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2364
+			}
2365
+		} elseif ($result === false) {
2366
+			EE_Error::add_error(
2367
+				sprintf(
2368
+					__('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"',
2369
+						'event_espresso'),
2370
+					$wpdb_method,
2371
+					var_export($arguments_to_provide, true),
2372
+					$wpdb->last_error
2373
+				),
2374
+				__FILE__,
2375
+				__FUNCTION__,
2376
+				__LINE__
2377
+			);
2378
+		}
2379
+		return $result;
2380
+	}
2381
+
2382
+
2383
+
2384
+	/**
2385
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2386
+	 * and if there's an error tries to verify the DB is correct. Uses
2387
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2388
+	 * we should try to fix the EE core db, the addons, or just give up
2389
+	 *
2390
+	 * @param string $wpdb_method
2391
+	 * @param array  $arguments_to_provide
2392
+	 * @return mixed
2393
+	 */
2394
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2395
+	{
2396
+		/** @type WPDB $wpdb */
2397
+		global $wpdb;
2398
+		$wpdb->last_error = null;
2399
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2400
+		// was there an error running the query? but we don't care on new activations
2401
+		// (we're going to setup the DB anyway on new activations)
2402
+		if (($result === false || ! empty($wpdb->last_error))
2403
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2404
+		) {
2405
+			switch (EEM_Base::$_db_verification_level) {
2406
+				case EEM_Base::db_verified_none :
2407
+					// let's double-check core's DB
2408
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2409
+					break;
2410
+				case EEM_Base::db_verified_core :
2411
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2412
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2413
+					break;
2414
+				case EEM_Base::db_verified_addons :
2415
+					// ummmm... you in trouble
2416
+					return $result;
2417
+					break;
2418
+			}
2419
+			if (! empty($error_message)) {
2420
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2421
+				trigger_error($error_message);
2422
+			}
2423
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2424
+		}
2425
+		return $result;
2426
+	}
2427
+
2428
+
2429
+
2430
+	/**
2431
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2432
+	 * EEM_Base::$_db_verification_level
2433
+	 *
2434
+	 * @param string $wpdb_method
2435
+	 * @param array  $arguments_to_provide
2436
+	 * @return string
2437
+	 */
2438
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2439
+	{
2440
+		/** @type WPDB $wpdb */
2441
+		global $wpdb;
2442
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2443
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2444
+		$error_message = sprintf(
2445
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2446
+				'event_espresso'),
2447
+			$wpdb->last_error,
2448
+			$wpdb_method,
2449
+			wp_json_encode($arguments_to_provide)
2450
+		);
2451
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2452
+		return $error_message;
2453
+	}
2454
+
2455
+
2456
+
2457
+	/**
2458
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2459
+	 * EEM_Base::$_db_verification_level
2460
+	 *
2461
+	 * @param $wpdb_method
2462
+	 * @param $arguments_to_provide
2463
+	 * @return string
2464
+	 */
2465
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2466
+	{
2467
+		/** @type WPDB $wpdb */
2468
+		global $wpdb;
2469
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2470
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2471
+		$error_message = sprintf(
2472
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2473
+				'event_espresso'),
2474
+			$wpdb->last_error,
2475
+			$wpdb_method,
2476
+			wp_json_encode($arguments_to_provide)
2477
+		);
2478
+		EE_System::instance()->initialize_addons();
2479
+		return $error_message;
2480
+	}
2481
+
2482
+
2483
+
2484
+	/**
2485
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2486
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2487
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2488
+	 * ..."
2489
+	 *
2490
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2491
+	 * @return string
2492
+	 */
2493
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2494
+	{
2495
+		return " FROM " . $model_query_info->get_full_join_sql() .
2496
+			   $model_query_info->get_where_sql() .
2497
+			   $model_query_info->get_group_by_sql() .
2498
+			   $model_query_info->get_having_sql() .
2499
+			   $model_query_info->get_order_by_sql() .
2500
+			   $model_query_info->get_limit_sql();
2501
+	}
2502
+
2503
+
2504
+
2505
+	/**
2506
+	 * Set to easily debug the next X queries ran from this model.
2507
+	 *
2508
+	 * @param int $count
2509
+	 */
2510
+	public function show_next_x_db_queries($count = 1)
2511
+	{
2512
+		$this->_show_next_x_db_queries = $count;
2513
+	}
2514
+
2515
+
2516
+
2517
+	/**
2518
+	 * @param $sql_query
2519
+	 */
2520
+	public function show_db_query_if_previously_requested($sql_query)
2521
+	{
2522
+		if ($this->_show_next_x_db_queries > 0) {
2523
+			echo $sql_query;
2524
+			$this->_show_next_x_db_queries--;
2525
+		}
2526
+	}
2527
+
2528
+
2529
+
2530
+	/**
2531
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2532
+	 * There are the 3 cases:
2533
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2534
+	 * $otherModelObject has no ID, it is first saved.
2535
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2536
+	 * has no ID, it is first saved.
2537
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2538
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2539
+	 * join table
2540
+	 *
2541
+	 * @param        EE_Base_Class                     /int $thisModelObject
2542
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2543
+	 * @param string $relationName                     , key in EEM_Base::_relations
2544
+	 *                                                 an attendee to a group, you also want to specify which role they
2545
+	 *                                                 will have in that group. So you would use this parameter to
2546
+	 *                                                 specify array('role-column-name'=>'role-id')
2547
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2548
+	 *                                                 to for relation to methods that allow you to further specify
2549
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2550
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2551
+	 *                                                 because these will be inserted in any new rows created as well.
2552
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2553
+	 * @throws EE_Error
2554
+	 */
2555
+	public function add_relationship_to(
2556
+		$id_or_obj,
2557
+		$other_model_id_or_obj,
2558
+		$relationName,
2559
+		$extra_join_model_fields_n_values = array()
2560
+	) {
2561
+		$relation_obj = $this->related_settings_for($relationName);
2562
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2563
+	}
2564
+
2565
+
2566
+
2567
+	/**
2568
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2569
+	 * There are the 3 cases:
2570
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2571
+	 * error
2572
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2573
+	 * an error
2574
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2575
+	 *
2576
+	 * @param        EE_Base_Class /int $id_or_obj
2577
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2578
+	 * @param string $relationName key in EEM_Base::_relations
2579
+	 * @return boolean of success
2580
+	 * @throws EE_Error
2581
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2582
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2583
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2584
+	 *                             because these will be inserted in any new rows created as well.
2585
+	 */
2586
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2587
+	{
2588
+		$relation_obj = $this->related_settings_for($relationName);
2589
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2590
+	}
2591
+
2592
+
2593
+
2594
+	/**
2595
+	 * @param mixed           $id_or_obj
2596
+	 * @param string          $relationName
2597
+	 * @param array           $where_query_params
2598
+	 * @param EE_Base_Class[] objects to which relations were removed
2599
+	 * @return \EE_Base_Class[]
2600
+	 * @throws EE_Error
2601
+	 */
2602
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2603
+	{
2604
+		$relation_obj = $this->related_settings_for($relationName);
2605
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2606
+	}
2607
+
2608
+
2609
+
2610
+	/**
2611
+	 * Gets all the related items of the specified $model_name, using $query_params.
2612
+	 * Note: by default, we remove the "default query params"
2613
+	 * because we want to get even deleted items etc.
2614
+	 *
2615
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2616
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2617
+	 * @param array  $query_params like EEM_Base::get_all
2618
+	 * @return EE_Base_Class[]
2619
+	 * @throws EE_Error
2620
+	 */
2621
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2622
+	{
2623
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2624
+		$relation_settings = $this->related_settings_for($model_name);
2625
+		return $relation_settings->get_all_related($model_obj, $query_params);
2626
+	}
2627
+
2628
+
2629
+
2630
+	/**
2631
+	 * Deletes all the model objects across the relation indicated by $model_name
2632
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2633
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2634
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2635
+	 *
2636
+	 * @param EE_Base_Class|int|string $id_or_obj
2637
+	 * @param string                   $model_name
2638
+	 * @param array                    $query_params
2639
+	 * @return int how many deleted
2640
+	 * @throws EE_Error
2641
+	 */
2642
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2643
+	{
2644
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2645
+		$relation_settings = $this->related_settings_for($model_name);
2646
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2647
+	}
2648
+
2649
+
2650
+
2651
+	/**
2652
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2653
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2654
+	 * the model objects can't be hard deleted because of blocking related model objects,
2655
+	 * just does a soft-delete on them instead.
2656
+	 *
2657
+	 * @param EE_Base_Class|int|string $id_or_obj
2658
+	 * @param string                   $model_name
2659
+	 * @param array                    $query_params
2660
+	 * @return int how many deleted
2661
+	 * @throws EE_Error
2662
+	 */
2663
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2664
+	{
2665
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2666
+		$relation_settings = $this->related_settings_for($model_name);
2667
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2668
+	}
2669
+
2670
+
2671
+
2672
+	/**
2673
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2674
+	 * unless otherwise specified in the $query_params
2675
+	 *
2676
+	 * @param        int             /EE_Base_Class $id_or_obj
2677
+	 * @param string $model_name     like 'Event', or 'Registration'
2678
+	 * @param array  $query_params   like EEM_Base::get_all's
2679
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2680
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2681
+	 *                               that by the setting $distinct to TRUE;
2682
+	 * @return int
2683
+	 * @throws EE_Error
2684
+	 */
2685
+	public function count_related(
2686
+		$id_or_obj,
2687
+		$model_name,
2688
+		$query_params = array(),
2689
+		$field_to_count = null,
2690
+		$distinct = false
2691
+	) {
2692
+		$related_model = $this->get_related_model_obj($model_name);
2693
+		//we're just going to use the query params on the related model's normal get_all query,
2694
+		//except add a condition to say to match the current mod
2695
+		if (! isset($query_params['default_where_conditions'])) {
2696
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2697
+		}
2698
+		$this_model_name = $this->get_this_model_name();
2699
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2700
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2701
+		return $related_model->count($query_params, $field_to_count, $distinct);
2702
+	}
2703
+
2704
+
2705
+
2706
+	/**
2707
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2708
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2709
+	 *
2710
+	 * @param        int           /EE_Base_Class $id_or_obj
2711
+	 * @param string $model_name   like 'Event', or 'Registration'
2712
+	 * @param array  $query_params like EEM_Base::get_all's
2713
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2714
+	 * @return float
2715
+	 * @throws EE_Error
2716
+	 */
2717
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2718
+	{
2719
+		$related_model = $this->get_related_model_obj($model_name);
2720
+		if (! is_array($query_params)) {
2721
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2722
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2723
+					gettype($query_params)), '4.6.0');
2724
+			$query_params = array();
2725
+		}
2726
+		//we're just going to use the query params on the related model's normal get_all query,
2727
+		//except add a condition to say to match the current mod
2728
+		if (! isset($query_params['default_where_conditions'])) {
2729
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2730
+		}
2731
+		$this_model_name = $this->get_this_model_name();
2732
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2733
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2734
+		return $related_model->sum($query_params, $field_to_sum);
2735
+	}
2736
+
2737
+
2738
+
2739
+	/**
2740
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2741
+	 * $modelObject
2742
+	 *
2743
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2744
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2745
+	 * @param array               $query_params     like EEM_Base::get_all's
2746
+	 * @return EE_Base_Class
2747
+	 * @throws EE_Error
2748
+	 */
2749
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2750
+	{
2751
+		$query_params['limit'] = 1;
2752
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2753
+		if ($results) {
2754
+			return array_shift($results);
2755
+		}
2756
+		return null;
2757
+	}
2758
+
2759
+
2760
+
2761
+	/**
2762
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2763
+	 *
2764
+	 * @return string
2765
+	 */
2766
+	public function get_this_model_name()
2767
+	{
2768
+		return str_replace("EEM_", "", get_class($this));
2769
+	}
2770
+
2771
+
2772
+
2773
+	/**
2774
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2775
+	 *
2776
+	 * @return EE_Any_Foreign_Model_Name_Field
2777
+	 * @throws EE_Error
2778
+	 */
2779
+	public function get_field_containing_related_model_name()
2780
+	{
2781
+		foreach ($this->field_settings(true) as $field) {
2782
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2783
+				$field_with_model_name = $field;
2784
+			}
2785
+		}
2786
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2787
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2788
+				$this->get_this_model_name()));
2789
+		}
2790
+		return $field_with_model_name;
2791
+	}
2792
+
2793
+
2794
+
2795
+	/**
2796
+	 * Inserts a new entry into the database, for each table.
2797
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2798
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2799
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2800
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2801
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2802
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2803
+	 *
2804
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2805
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2806
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2807
+	 *                              of EEM_Base)
2808
+	 * @return int new primary key on main table that got inserted
2809
+	 * @throws EE_Error
2810
+	 */
2811
+	public function insert($field_n_values)
2812
+	{
2813
+		/**
2814
+		 * Filters the fields and their values before inserting an item using the models
2815
+		 *
2816
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2817
+		 * @param EEM_Base $model           the model used
2818
+		 */
2819
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2820
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2821
+			$main_table = $this->_get_main_table();
2822
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2823
+			if ($new_id !== false) {
2824
+				foreach ($this->_get_other_tables() as $other_table) {
2825
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2826
+				}
2827
+			}
2828
+			/**
2829
+			 * Done just after attempting to insert a new model object
2830
+			 *
2831
+			 * @param EEM_Base   $model           used
2832
+			 * @param array      $fields_n_values fields and their values
2833
+			 * @param int|string the              ID of the newly-inserted model object
2834
+			 */
2835
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2836
+			return $new_id;
2837
+		}
2838
+		return false;
2839
+	}
2840
+
2841
+
2842
+
2843
+	/**
2844
+	 * Checks that the result would satisfy the unique indexes on this model
2845
+	 *
2846
+	 * @param array  $field_n_values
2847
+	 * @param string $action
2848
+	 * @return boolean
2849
+	 * @throws EE_Error
2850
+	 */
2851
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2852
+	{
2853
+		foreach ($this->unique_indexes() as $index_name => $index) {
2854
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2855
+			if ($this->exists(array($uniqueness_where_params))) {
2856
+				EE_Error::add_error(
2857
+					sprintf(
2858
+						__(
2859
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2860
+							"event_espresso"
2861
+						),
2862
+						$action,
2863
+						$this->_get_class_name(),
2864
+						$index_name,
2865
+						implode(",", $index->field_names()),
2866
+						http_build_query($uniqueness_where_params)
2867
+					),
2868
+					__FILE__,
2869
+					__FUNCTION__,
2870
+					__LINE__
2871
+				);
2872
+				return false;
2873
+			}
2874
+		}
2875
+		return true;
2876
+	}
2877
+
2878
+
2879
+
2880
+	/**
2881
+	 * Checks the database for an item that conflicts (ie, if this item were
2882
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2883
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2884
+	 * can be either an EE_Base_Class or an array of fields n values
2885
+	 *
2886
+	 * @param EE_Base_Class|array $obj_or_fields_array
2887
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2888
+	 *                                                 when looking for conflicts
2889
+	 *                                                 (ie, if false, we ignore the model object's primary key
2890
+	 *                                                 when finding "conflicts". If true, it's also considered).
2891
+	 *                                                 Only works for INT primary key,
2892
+	 *                                                 STRING primary keys cannot be ignored
2893
+	 * @throws EE_Error
2894
+	 * @return EE_Base_Class|array
2895
+	 */
2896
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2897
+	{
2898
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2899
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2900
+		} elseif (is_array($obj_or_fields_array)) {
2901
+			$fields_n_values = $obj_or_fields_array;
2902
+		} else {
2903
+			throw new EE_Error(
2904
+				sprintf(
2905
+					__(
2906
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2907
+						"event_espresso"
2908
+					),
2909
+					get_class($this),
2910
+					$obj_or_fields_array
2911
+				)
2912
+			);
2913
+		}
2914
+		$query_params = array();
2915
+		if ($this->has_primary_key_field()
2916
+			&& ($include_primary_key
2917
+				|| $this->get_primary_key_field()
2918
+				   instanceof
2919
+				   EE_Primary_Key_String_Field)
2920
+			&& isset($fields_n_values[$this->primary_key_name()])
2921
+		) {
2922
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2923
+		}
2924
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2925
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2926
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2927
+		}
2928
+		//if there is nothing to base this search on, then we shouldn't find anything
2929
+		if (empty($query_params)) {
2930
+			return array();
2931
+		}
2932
+		return $this->get_one($query_params);
2933
+	}
2934
+
2935
+
2936
+
2937
+	/**
2938
+	 * Like count, but is optimized and returns a boolean instead of an int
2939
+	 *
2940
+	 * @param array $query_params
2941
+	 * @return boolean
2942
+	 * @throws EE_Error
2943
+	 */
2944
+	public function exists($query_params)
2945
+	{
2946
+		$query_params['limit'] = 1;
2947
+		return $this->count($query_params) > 0;
2948
+	}
2949
+
2950
+
2951
+
2952
+	/**
2953
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2954
+	 *
2955
+	 * @param int|string $id
2956
+	 * @return boolean
2957
+	 * @throws EE_Error
2958
+	 */
2959
+	public function exists_by_ID($id)
2960
+	{
2961
+		return $this->exists(
2962
+			array(
2963
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2964
+				array(
2965
+					$this->primary_key_name() => $id,
2966
+				),
2967
+			)
2968
+		);
2969
+	}
2970
+
2971
+
2972
+
2973
+	/**
2974
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2975
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2976
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2977
+	 * on the main table)
2978
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2979
+	 * cases where we want to call it directly rather than via insert().
2980
+	 *
2981
+	 * @access   protected
2982
+	 * @param EE_Table_Base $table
2983
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2984
+	 *                                       float
2985
+	 * @param int           $new_id          for now we assume only int keys
2986
+	 * @throws EE_Error
2987
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2988
+	 * @return int ID of new row inserted, or FALSE on failure
2989
+	 */
2990
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2991
+	{
2992
+		global $wpdb;
2993
+		$insertion_col_n_values = array();
2994
+		$format_for_insertion = array();
2995
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2996
+		foreach ($fields_on_table as $field_name => $field_obj) {
2997
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2998
+			if ($field_obj->is_auto_increment()) {
2999
+				continue;
3000
+			}
3001
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3002
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
3003
+			if ($prepared_value !== null) {
3004
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3005
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
3006
+			}
3007
+		}
3008
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3009
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
3010
+			//so add the fk to the main table as a column
3011
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3012
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3013
+		}
3014
+		//insert the new entry
3015
+		$result = $this->_do_wpdb_query('insert',
3016
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
3017
+		if ($result === false) {
3018
+			return false;
3019
+		}
3020
+		//ok, now what do we return for the ID of the newly-inserted thing?
3021
+		if ($this->has_primary_key_field()) {
3022
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3023
+				return $wpdb->insert_id;
3024
+			}
3025
+			//it's not an auto-increment primary key, so
3026
+			//it must have been supplied
3027
+			return $fields_n_values[$this->get_primary_key_field()->get_name()];
3028
+		}
3029
+		//we can't return a  primary key because there is none. instead return
3030
+		//a unique string indicating this model
3031
+		return $this->get_index_primary_key_string($fields_n_values);
3032
+	}
3033
+
3034
+
3035
+
3036
+	/**
3037
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3038
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3039
+	 * and there is no default, we pass it along. WPDB will take care of it)
3040
+	 *
3041
+	 * @param EE_Model_Field_Base $field_obj
3042
+	 * @param array               $fields_n_values
3043
+	 * @return mixed string|int|float depending on what the table column will be expecting
3044
+	 * @throws EE_Error
3045
+	 */
3046
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3047
+	{
3048
+		//if this field doesn't allow nullable, don't allow it
3049
+		if (
3050
+			! $field_obj->is_nullable()
3051
+			&& (
3052
+				! isset($fields_n_values[$field_obj->get_name()])
3053
+				|| $fields_n_values[$field_obj->get_name()] === null
3054
+			)
3055
+		) {
3056
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3057
+		}
3058
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3059
+			? $fields_n_values[$field_obj->get_name()]
3060
+			: null;
3061
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3062
+	}
3063
+
3064
+
3065
+
3066
+	/**
3067
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3068
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3069
+	 * the field's prepare_for_set() method.
3070
+	 *
3071
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3072
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3073
+	 *                                   top of file)
3074
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3075
+	 *                                   $value is a custom selection
3076
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3077
+	 */
3078
+	private function _prepare_value_for_use_in_db($value, $field)
3079
+	{
3080
+		if ($field && $field instanceof EE_Model_Field_Base) {
3081
+			switch ($this->_values_already_prepared_by_model_object) {
3082
+				/** @noinspection PhpMissingBreakStatementInspection */
3083
+				case self::not_prepared_by_model_object:
3084
+					$value = $field->prepare_for_set($value);
3085
+				//purposefully left out "return"
3086
+				case self::prepared_by_model_object:
3087
+					/** @noinspection SuspiciousAssignmentsInspection */
3088
+					$value = $field->prepare_for_use_in_db($value);
3089
+				case self::prepared_for_use_in_db:
3090
+					//leave the value alone
3091
+			}
3092
+			return $value;
3093
+		}
3094
+		return $value;
3095
+	}
3096
+
3097
+
3098
+
3099
+	/**
3100
+	 * Returns the main table on this model
3101
+	 *
3102
+	 * @return EE_Primary_Table
3103
+	 * @throws EE_Error
3104
+	 */
3105
+	protected function _get_main_table()
3106
+	{
3107
+		foreach ($this->_tables as $table) {
3108
+			if ($table instanceof EE_Primary_Table) {
3109
+				return $table;
3110
+			}
3111
+		}
3112
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3113
+			'event_espresso'), get_class($this)));
3114
+	}
3115
+
3116
+
3117
+
3118
+	/**
3119
+	 * table
3120
+	 * returns EE_Primary_Table table name
3121
+	 *
3122
+	 * @return string
3123
+	 * @throws EE_Error
3124
+	 */
3125
+	public function table()
3126
+	{
3127
+		return $this->_get_main_table()->get_table_name();
3128
+	}
3129
+
3130
+
3131
+
3132
+	/**
3133
+	 * table
3134
+	 * returns first EE_Secondary_Table table name
3135
+	 *
3136
+	 * @return string
3137
+	 */
3138
+	public function second_table()
3139
+	{
3140
+		// grab second table from tables array
3141
+		$second_table = end($this->_tables);
3142
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3143
+	}
3144
+
3145
+
3146
+
3147
+	/**
3148
+	 * get_table_obj_by_alias
3149
+	 * returns table name given it's alias
3150
+	 *
3151
+	 * @param string $table_alias
3152
+	 * @return EE_Primary_Table | EE_Secondary_Table
3153
+	 */
3154
+	public function get_table_obj_by_alias($table_alias = '')
3155
+	{
3156
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3157
+	}
3158
+
3159
+
3160
+
3161
+	/**
3162
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3163
+	 *
3164
+	 * @return EE_Secondary_Table[]
3165
+	 */
3166
+	protected function _get_other_tables()
3167
+	{
3168
+		$other_tables = array();
3169
+		foreach ($this->_tables as $table_alias => $table) {
3170
+			if ($table instanceof EE_Secondary_Table) {
3171
+				$other_tables[$table_alias] = $table;
3172
+			}
3173
+		}
3174
+		return $other_tables;
3175
+	}
3176
+
3177
+
3178
+
3179
+	/**
3180
+	 * Finds all the fields that correspond to the given table
3181
+	 *
3182
+	 * @param string $table_alias , array key in EEM_Base::_tables
3183
+	 * @return EE_Model_Field_Base[]
3184
+	 */
3185
+	public function _get_fields_for_table($table_alias)
3186
+	{
3187
+		return $this->_fields[$table_alias];
3188
+	}
3189
+
3190
+
3191
+
3192
+	/**
3193
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3194
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3195
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3196
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3197
+	 * related Registration, Transaction, and Payment models.
3198
+	 *
3199
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3200
+	 * @return EE_Model_Query_Info_Carrier
3201
+	 * @throws EE_Error
3202
+	 */
3203
+	public function _extract_related_models_from_query($query_params)
3204
+	{
3205
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3206
+		if (array_key_exists(0, $query_params)) {
3207
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3208
+		}
3209
+		if (array_key_exists('group_by', $query_params)) {
3210
+			if (is_array($query_params['group_by'])) {
3211
+				$this->_extract_related_models_from_sub_params_array_values(
3212
+					$query_params['group_by'],
3213
+					$query_info_carrier,
3214
+					'group_by'
3215
+				);
3216
+			} elseif (! empty ($query_params['group_by'])) {
3217
+				$this->_extract_related_model_info_from_query_param(
3218
+					$query_params['group_by'],
3219
+					$query_info_carrier,
3220
+					'group_by'
3221
+				);
3222
+			}
3223
+		}
3224
+		if (array_key_exists('having', $query_params)) {
3225
+			$this->_extract_related_models_from_sub_params_array_keys(
3226
+				$query_params[0],
3227
+				$query_info_carrier,
3228
+				'having'
3229
+			);
3230
+		}
3231
+		if (array_key_exists('order_by', $query_params)) {
3232
+			if (is_array($query_params['order_by'])) {
3233
+				$this->_extract_related_models_from_sub_params_array_keys(
3234
+					$query_params['order_by'],
3235
+					$query_info_carrier,
3236
+					'order_by'
3237
+				);
3238
+			} elseif (! empty($query_params['order_by'])) {
3239
+				$this->_extract_related_model_info_from_query_param(
3240
+					$query_params['order_by'],
3241
+					$query_info_carrier,
3242
+					'order_by'
3243
+				);
3244
+			}
3245
+		}
3246
+		if (array_key_exists('force_join', $query_params)) {
3247
+			$this->_extract_related_models_from_sub_params_array_values(
3248
+				$query_params['force_join'],
3249
+				$query_info_carrier,
3250
+				'force_join'
3251
+			);
3252
+		}
3253
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3254
+		return $query_info_carrier;
3255
+	}
3256
+
3257
+
3258
+
3259
+	/**
3260
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3261
+	 *
3262
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3263
+	 *                                                      $query_params['having']
3264
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3265
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3266
+	 * @throws EE_Error
3267
+	 * @return \EE_Model_Query_Info_Carrier
3268
+	 */
3269
+	private function _extract_related_models_from_sub_params_array_keys(
3270
+		$sub_query_params,
3271
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3272
+		$query_param_type
3273
+	) {
3274
+		if (! empty($sub_query_params)) {
3275
+			$sub_query_params = (array)$sub_query_params;
3276
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3277
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3278
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3279
+					$query_param_type);
3280
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3281
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3282
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3283
+				//of array('Registration.TXN_ID'=>23)
3284
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3285
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3286
+					if (! is_array($possibly_array_of_params)) {
3287
+						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'))",
3288
+							"event_espresso"),
3289
+							$param, $possibly_array_of_params));
3290
+					}
3291
+					$this->_extract_related_models_from_sub_params_array_keys(
3292
+						$possibly_array_of_params,
3293
+						$model_query_info_carrier, $query_param_type
3294
+					);
3295
+				} elseif ($query_param_type === 0 //ie WHERE
3296
+						  && is_array($possibly_array_of_params)
3297
+						  && isset($possibly_array_of_params[2])
3298
+						  && $possibly_array_of_params[2] == true
3299
+				) {
3300
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3301
+					//indicating that $possible_array_of_params[1] is actually a field name,
3302
+					//from which we should extract query parameters!
3303
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3304
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3305
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3306
+					}
3307
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3308
+						$model_query_info_carrier, $query_param_type);
3309
+				}
3310
+			}
3311
+		}
3312
+		return $model_query_info_carrier;
3313
+	}
3314
+
3315
+
3316
+
3317
+	/**
3318
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3319
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3320
+	 *
3321
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3322
+	 *                                                      $query_params['having']
3323
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3324
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3325
+	 * @throws EE_Error
3326
+	 * @return \EE_Model_Query_Info_Carrier
3327
+	 */
3328
+	private function _extract_related_models_from_sub_params_array_values(
3329
+		$sub_query_params,
3330
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3331
+		$query_param_type
3332
+	) {
3333
+		if (! empty($sub_query_params)) {
3334
+			if (! is_array($sub_query_params)) {
3335
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3336
+					$sub_query_params));
3337
+			}
3338
+			foreach ($sub_query_params as $param) {
3339
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3340
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3341
+					$query_param_type);
3342
+			}
3343
+		}
3344
+		return $model_query_info_carrier;
3345
+	}
3346
+
3347
+
3348
+
3349
+	/**
3350
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3351
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3352
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3353
+	 * but use them in a different order. Eg, we need to know what models we are querying
3354
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3355
+	 * other models before we can finalize the where clause SQL.
3356
+	 *
3357
+	 * @param array $query_params
3358
+	 * @throws EE_Error
3359
+	 * @return EE_Model_Query_Info_Carrier
3360
+	 */
3361
+	public function _create_model_query_info_carrier($query_params)
3362
+	{
3363
+		if (! is_array($query_params)) {
3364
+			EE_Error::doing_it_wrong(
3365
+				'EEM_Base::_create_model_query_info_carrier',
3366
+				sprintf(
3367
+					__(
3368
+						'$query_params should be an array, you passed a variable of type %s',
3369
+						'event_espresso'
3370
+					),
3371
+					gettype($query_params)
3372
+				),
3373
+				'4.6.0'
3374
+			);
3375
+			$query_params = array();
3376
+		}
3377
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3378
+		//first check if we should alter the query to account for caps or not
3379
+		//because the caps might require us to do extra joins
3380
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3381
+			$query_params[0] = $where_query_params = array_replace_recursive(
3382
+				$where_query_params,
3383
+				$this->caps_where_conditions(
3384
+					$query_params['caps']
3385
+				)
3386
+			);
3387
+		}
3388
+		$query_object = $this->_extract_related_models_from_query($query_params);
3389
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3390
+		foreach ($where_query_params as $key => $value) {
3391
+			if (is_int($key)) {
3392
+				throw new EE_Error(
3393
+					sprintf(
3394
+						__(
3395
+							"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.",
3396
+							"event_espresso"
3397
+						),
3398
+						$key,
3399
+						var_export($value, true),
3400
+						var_export($query_params, true),
3401
+						get_class($this)
3402
+					)
3403
+				);
3404
+			}
3405
+		}
3406
+		if (
3407
+			array_key_exists('default_where_conditions', $query_params)
3408
+			&& ! empty($query_params['default_where_conditions'])
3409
+		) {
3410
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3411
+		} else {
3412
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3413
+		}
3414
+		$where_query_params = array_merge(
3415
+			$this->_get_default_where_conditions_for_models_in_query(
3416
+				$query_object,
3417
+				$use_default_where_conditions,
3418
+				$where_query_params
3419
+			),
3420
+			$where_query_params
3421
+		);
3422
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3423
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3424
+		// So we need to setup a subquery and use that for the main join.
3425
+		// Note for now this only works on the primary table for the model.
3426
+		// So for instance, you could set the limit array like this:
3427
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3428
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3429
+			$query_object->set_main_model_join_sql(
3430
+				$this->_construct_limit_join_select(
3431
+					$query_params['on_join_limit'][0],
3432
+					$query_params['on_join_limit'][1]
3433
+				)
3434
+			);
3435
+		}
3436
+		//set limit
3437
+		if (array_key_exists('limit', $query_params)) {
3438
+			if (is_array($query_params['limit'])) {
3439
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3440
+					$e = sprintf(
3441
+						__(
3442
+							"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)",
3443
+							"event_espresso"
3444
+						),
3445
+						http_build_query($query_params['limit'])
3446
+					);
3447
+					throw new EE_Error($e . "|" . $e);
3448
+				}
3449
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3450
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3451
+			} elseif (! empty ($query_params['limit'])) {
3452
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3453
+			}
3454
+		}
3455
+		//set order by
3456
+		if (array_key_exists('order_by', $query_params)) {
3457
+			if (is_array($query_params['order_by'])) {
3458
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3459
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3460
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3461
+				if (array_key_exists('order', $query_params)) {
3462
+					throw new EE_Error(
3463
+						sprintf(
3464
+							__(
3465
+								"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 ",
3466
+								"event_espresso"
3467
+							),
3468
+							get_class($this),
3469
+							implode(", ", array_keys($query_params['order_by'])),
3470
+							implode(", ", $query_params['order_by']),
3471
+							$query_params['order']
3472
+						)
3473
+					);
3474
+				}
3475
+				$this->_extract_related_models_from_sub_params_array_keys(
3476
+					$query_params['order_by'],
3477
+					$query_object,
3478
+					'order_by'
3479
+				);
3480
+				//assume it's an array of fields to order by
3481
+				$order_array = array();
3482
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3483
+					$order = $this->_extract_order($order);
3484
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3485
+				}
3486
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3487
+			} elseif (! empty ($query_params['order_by'])) {
3488
+				$this->_extract_related_model_info_from_query_param(
3489
+					$query_params['order_by'],
3490
+					$query_object,
3491
+					'order',
3492
+					$query_params['order_by']
3493
+				);
3494
+				$order = isset($query_params['order'])
3495
+					? $this->_extract_order($query_params['order'])
3496
+					: 'DESC';
3497
+				$query_object->set_order_by_sql(
3498
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3499
+				);
3500
+			}
3501
+		}
3502
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3503
+		if (! array_key_exists('order_by', $query_params)
3504
+			&& array_key_exists('order', $query_params)
3505
+			&& ! empty($query_params['order'])
3506
+		) {
3507
+			$pk_field = $this->get_primary_key_field();
3508
+			$order = $this->_extract_order($query_params['order']);
3509
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3510
+		}
3511
+		//set group by
3512
+		if (array_key_exists('group_by', $query_params)) {
3513
+			if (is_array($query_params['group_by'])) {
3514
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3515
+				$group_by_array = array();
3516
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3517
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3518
+				}
3519
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3520
+			} elseif (! empty ($query_params['group_by'])) {
3521
+				$query_object->set_group_by_sql(
3522
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3523
+				);
3524
+			}
3525
+		}
3526
+		//set having
3527
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3528
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3529
+		}
3530
+		//now, just verify they didn't pass anything wack
3531
+		foreach ($query_params as $query_key => $query_value) {
3532
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3533
+				throw new EE_Error(
3534
+					sprintf(
3535
+						__(
3536
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3537
+							'event_espresso'
3538
+						),
3539
+						$query_key,
3540
+						get_class($this),
3541
+						//						print_r( $this->_allowed_query_params, TRUE )
3542
+						implode(',', $this->_allowed_query_params)
3543
+					)
3544
+				);
3545
+			}
3546
+		}
3547
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3548
+		if (empty($main_model_join_sql)) {
3549
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3550
+		}
3551
+		return $query_object;
3552
+	}
3553
+
3554
+
3555
+
3556
+	/**
3557
+	 * Gets the where conditions that should be imposed on the query based on the
3558
+	 * context (eg reading frontend, backend, edit or delete).
3559
+	 *
3560
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3561
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3562
+	 * @throws EE_Error
3563
+	 */
3564
+	public function caps_where_conditions($context = self::caps_read)
3565
+	{
3566
+		EEM_Base::verify_is_valid_cap_context($context);
3567
+		$cap_where_conditions = array();
3568
+		$cap_restrictions = $this->caps_missing($context);
3569
+		/**
3570
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3571
+		 */
3572
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3573
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3574
+				$restriction_if_no_cap->get_default_where_conditions());
3575
+		}
3576
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3577
+			$cap_restrictions);
3578
+	}
3579
+
3580
+
3581
+
3582
+	/**
3583
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3584
+	 * otherwise throws an exception
3585
+	 *
3586
+	 * @param string $should_be_order_string
3587
+	 * @return string either ASC, asc, DESC or desc
3588
+	 * @throws EE_Error
3589
+	 */
3590
+	private function _extract_order($should_be_order_string)
3591
+	{
3592
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3593
+			return $should_be_order_string;
3594
+		}
3595
+		throw new EE_Error(
3596
+			sprintf(
3597
+				__(
3598
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3599
+					"event_espresso"
3600
+				), get_class($this), $should_be_order_string
3601
+			)
3602
+		);
3603
+	}
3604
+
3605
+
3606
+
3607
+	/**
3608
+	 * Looks at all the models which are included in this query, and asks each
3609
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3610
+	 * so they can be merged
3611
+	 *
3612
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3613
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3614
+	 *                                                                  'none' means NO default where conditions will
3615
+	 *                                                                  be used AT ALL during this query.
3616
+	 *                                                                  'other_models_only' means default where
3617
+	 *                                                                  conditions from other models will be used, but
3618
+	 *                                                                  not for this primary model. 'all', the default,
3619
+	 *                                                                  means default where conditions will apply as
3620
+	 *                                                                  normal
3621
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3622
+	 * @throws EE_Error
3623
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3624
+	 */
3625
+	private function _get_default_where_conditions_for_models_in_query(
3626
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3627
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3628
+		$where_query_params = array()
3629
+	) {
3630
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3631
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3632
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3633
+				"event_espresso"), $use_default_where_conditions,
3634
+				implode(", ", $allowed_used_default_where_conditions_values)));
3635
+		}
3636
+		$universal_query_params = array();
3637
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3638
+			$universal_query_params = $this->_get_default_where_conditions();
3639
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3640
+			$universal_query_params = $this->_get_minimum_where_conditions();
3641
+		}
3642
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3643
+			$related_model = $this->get_related_model_obj($model_name);
3644
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3645
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3646
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3647
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3648
+			} else {
3649
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3650
+				continue;
3651
+			}
3652
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3653
+				$related_model_universal_where_params,
3654
+				$where_query_params,
3655
+				$related_model,
3656
+				$model_relation_path
3657
+			);
3658
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3659
+				$universal_query_params,
3660
+				$overrides
3661
+			);
3662
+		}
3663
+		return $universal_query_params;
3664
+	}
3665
+
3666
+
3667
+
3668
+	/**
3669
+	 * Determines whether or not we should use default where conditions for the model in question
3670
+	 * (this model, or other related models).
3671
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3672
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3673
+	 * We should use default where conditions on related models when they requested to use default where conditions
3674
+	 * on all models, or specifically just on other related models
3675
+	 * @param      $default_where_conditions_value
3676
+	 * @param bool $for_this_model false means this is for OTHER related models
3677
+	 * @return bool
3678
+	 */
3679
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3680
+	{
3681
+		return (
3682
+				   $for_this_model
3683
+				   && in_array(
3684
+					   $default_where_conditions_value,
3685
+					   array(
3686
+						   EEM_Base::default_where_conditions_all,
3687
+						   EEM_Base::default_where_conditions_this_only,
3688
+						   EEM_Base::default_where_conditions_minimum_others,
3689
+					   ),
3690
+					   true
3691
+				   )
3692
+			   )
3693
+			   || (
3694
+				   ! $for_this_model
3695
+				   && in_array(
3696
+					   $default_where_conditions_value,
3697
+					   array(
3698
+						   EEM_Base::default_where_conditions_all,
3699
+						   EEM_Base::default_where_conditions_others_only,
3700
+					   ),
3701
+					   true
3702
+				   )
3703
+			   );
3704
+	}
3705
+
3706
+	/**
3707
+	 * Determines whether or not we should use default minimum conditions for the model in question
3708
+	 * (this model, or other related models).
3709
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3710
+	 * where conditions.
3711
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3712
+	 * on this model or others
3713
+	 * @param      $default_where_conditions_value
3714
+	 * @param bool $for_this_model false means this is for OTHER related models
3715
+	 * @return bool
3716
+	 */
3717
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3718
+	{
3719
+		return (
3720
+				   $for_this_model
3721
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3722
+			   )
3723
+			   || (
3724
+				   ! $for_this_model
3725
+				   && in_array(
3726
+					   $default_where_conditions_value,
3727
+					   array(
3728
+						   EEM_Base::default_where_conditions_minimum_others,
3729
+						   EEM_Base::default_where_conditions_minimum_all,
3730
+					   ),
3731
+					   true
3732
+				   )
3733
+			   );
3734
+	}
3735
+
3736
+
3737
+	/**
3738
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3739
+	 * then we also add a special where condition which allows for that model's primary key
3740
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3741
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3742
+	 *
3743
+	 * @param array    $default_where_conditions
3744
+	 * @param array    $provided_where_conditions
3745
+	 * @param EEM_Base $model
3746
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3747
+	 * @return array like EEM_Base::get_all's $query_params[0]
3748
+	 * @throws EE_Error
3749
+	 */
3750
+	private function _override_defaults_or_make_null_friendly(
3751
+		$default_where_conditions,
3752
+		$provided_where_conditions,
3753
+		$model,
3754
+		$model_relation_path
3755
+	) {
3756
+		$null_friendly_where_conditions = array();
3757
+		$none_overridden = true;
3758
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3759
+		foreach ($default_where_conditions as $key => $val) {
3760
+			if (isset($provided_where_conditions[$key])) {
3761
+				$none_overridden = false;
3762
+			} else {
3763
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3764
+			}
3765
+		}
3766
+		if ($none_overridden && $default_where_conditions) {
3767
+			if ($model->has_primary_key_field()) {
3768
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3769
+																				. "."
3770
+																				. $model->primary_key_name()] = array('IS NULL');
3771
+			}/*else{
3772 3772
 				//@todo NO PK, use other defaults
3773 3773
 			}*/
3774
-        }
3775
-        return $null_friendly_where_conditions;
3776
-    }
3777
-
3778
-
3779
-
3780
-    /**
3781
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3782
-     * default where conditions on all get_all, update, and delete queries done by this model.
3783
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3784
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3785
-     *
3786
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3787
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3788
-     */
3789
-    private function _get_default_where_conditions($model_relation_path = null)
3790
-    {
3791
-        if ($this->_ignore_where_strategy) {
3792
-            return array();
3793
-        }
3794
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3795
-    }
3796
-
3797
-
3798
-
3799
-    /**
3800
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3801
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3802
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3803
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3804
-     * Similar to _get_default_where_conditions
3805
-     *
3806
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3807
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3808
-     */
3809
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3810
-    {
3811
-        if ($this->_ignore_where_strategy) {
3812
-            return array();
3813
-        }
3814
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3815
-    }
3816
-
3817
-
3818
-
3819
-    /**
3820
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3821
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3822
-     *
3823
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3824
-     * @return string
3825
-     * @throws EE_Error
3826
-     */
3827
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3828
-    {
3829
-        $selects = $this->_get_columns_to_select_for_this_model();
3830
-        foreach (
3831
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3832
-            $name_of_other_model_included
3833
-        ) {
3834
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3835
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3836
-            foreach ($other_model_selects as $key => $value) {
3837
-                $selects[] = $value;
3838
-            }
3839
-        }
3840
-        return implode(", ", $selects);
3841
-    }
3842
-
3843
-
3844
-
3845
-    /**
3846
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3847
-     * So that's going to be the columns for all the fields on the model
3848
-     *
3849
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3850
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3851
-     */
3852
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3853
-    {
3854
-        $fields = $this->field_settings();
3855
-        $selects = array();
3856
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3857
-            $this->get_this_model_name());
3858
-        foreach ($fields as $field_obj) {
3859
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3860
-                         . $field_obj->get_table_alias()
3861
-                         . "."
3862
-                         . $field_obj->get_table_column()
3863
-                         . " AS '"
3864
-                         . $table_alias_with_model_relation_chain_prefix
3865
-                         . $field_obj->get_table_alias()
3866
-                         . "."
3867
-                         . $field_obj->get_table_column()
3868
-                         . "'";
3869
-        }
3870
-        //make sure we are also getting the PKs of each table
3871
-        $tables = $this->get_tables();
3872
-        if (count($tables) > 1) {
3873
-            foreach ($tables as $table_obj) {
3874
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3875
-                                       . $table_obj->get_fully_qualified_pk_column();
3876
-                if (! in_array($qualified_pk_column, $selects)) {
3877
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3878
-                }
3879
-            }
3880
-        }
3881
-        return $selects;
3882
-    }
3883
-
3884
-
3885
-
3886
-    /**
3887
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3888
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3889
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3890
-     * SQL for joining, and the data types
3891
-     *
3892
-     * @param null|string                 $original_query_param
3893
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3894
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3895
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3896
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3897
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3898
-     *                                                          or 'Registration's
3899
-     * @param string                      $original_query_param what it originally was (eg
3900
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3901
-     *                                                          matches $query_param
3902
-     * @throws EE_Error
3903
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3904
-     */
3905
-    private function _extract_related_model_info_from_query_param(
3906
-        $query_param,
3907
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3908
-        $query_param_type,
3909
-        $original_query_param = null
3910
-    ) {
3911
-        if ($original_query_param === null) {
3912
-            $original_query_param = $query_param;
3913
-        }
3914
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3915
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3916
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3917
-        $allow_fields = in_array(
3918
-            $query_param_type,
3919
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3920
-            true
3921
-        );
3922
-        //check to see if we have a field on this model
3923
-        $this_model_fields = $this->field_settings(true);
3924
-        if (array_key_exists($query_param, $this_model_fields)) {
3925
-            if ($allow_fields) {
3926
-                return;
3927
-            }
3928
-            throw new EE_Error(
3929
-                sprintf(
3930
-                    __(
3931
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3932
-                        "event_espresso"
3933
-                    ),
3934
-                    $query_param, get_class($this), $query_param_type, $original_query_param
3935
-                )
3936
-            );
3937
-        }
3938
-        //check if this is a special logic query param
3939
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3940
-            if ($allow_logic_query_params) {
3941
-                return;
3942
-            }
3943
-            throw new EE_Error(
3944
-                sprintf(
3945
-                    __(
3946
-                        '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',
3947
-                        'event_espresso'
3948
-                    ),
3949
-                    implode('", "', $this->_logic_query_param_keys),
3950
-                    $query_param,
3951
-                    get_class($this),
3952
-                    '<br />',
3953
-                    "\t"
3954
-                    . ' $passed_in_query_info = <pre>'
3955
-                    . print_r($passed_in_query_info, true)
3956
-                    . '</pre>'
3957
-                    . "\n\t"
3958
-                    . ' $query_param_type = '
3959
-                    . $query_param_type
3960
-                    . "\n\t"
3961
-                    . ' $original_query_param = '
3962
-                    . $original_query_param
3963
-                )
3964
-            );
3965
-        }
3966
-        //check if it's a custom selection
3967
-        if ($this->_custom_selections instanceof CustomSelects
3968
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
3969
-        ) {
3970
-            return;
3971
-        }
3972
-        //check if has a model name at the beginning
3973
-        //and
3974
-        //check if it's a field on a related model
3975
-        if ($this->extractJoinModelFromQueryParams(
3976
-            $passed_in_query_info,
3977
-            $query_param,
3978
-            $original_query_param,
3979
-            $query_param_type
3980
-        )) {
3981
-            return;
3982
-        }
3983
-
3984
-        //ok so $query_param didn't start with a model name
3985
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3986
-        //it's wack, that's what it is
3987
-        throw new EE_Error(
3988
-            sprintf(
3989
-                esc_html__(
3990
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3991
-                    "event_espresso"
3992
-                ),
3993
-                $query_param,
3994
-                get_class($this),
3995
-                $query_param_type,
3996
-                $original_query_param
3997
-            )
3998
-        );
3999
-    }
4000
-
4001
-
4002
-    /**
4003
-     * Extracts any possible join model information from the provided possible_join_string.
4004
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4005
-     * parts that should be added to the query.
4006
-     *
4007
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4008
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4009
-     * @param null|string                 $original_query_param
4010
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4011
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4012
-     * @return bool  returns true if a join was added and false if not.
4013
-     * @throws EE_Error
4014
-     */
4015
-    private function extractJoinModelFromQueryParams(
4016
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4017
-        $possible_join_string,
4018
-        $original_query_param,
4019
-        $query_parameter_type
4020
-    ) {
4021
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4022
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4023
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4024
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4025
-                if ($possible_join_string === '') {
4026
-                    //nothing left to $query_param
4027
-                    //we should actually end in a field name, not a model like this!
4028
-                    throw new EE_Error(
4029
-                        sprintf(
4030
-                            esc_html__(
4031
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4032
-                                "event_espresso"
4033
-                            ),
4034
-                            $possible_join_string,
4035
-                            $query_parameter_type,
4036
-                            get_class($this),
4037
-                            $valid_related_model_name
4038
-                        )
4039
-                    );
4040
-                }
4041
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4042
-                $related_model_obj->_extract_related_model_info_from_query_param(
4043
-                    $possible_join_string,
4044
-                    $query_info_carrier,
4045
-                    $query_parameter_type,
4046
-                    $original_query_param
4047
-                );
4048
-                return true;
4049
-            }
4050
-            if ($possible_join_string === $valid_related_model_name) {
4051
-                $this->_add_join_to_model(
4052
-                    $valid_related_model_name,
4053
-                    $query_info_carrier,
4054
-                    $original_query_param
4055
-                );
4056
-                return true;
4057
-            }
4058
-        }
4059
-        return false;
4060
-    }
4061
-
4062
-
4063
-    /**
4064
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4065
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4066
-     * @throws EE_Error
4067
-     */
4068
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4069
-    {
4070
-        if ($this->_custom_selections instanceof CustomSelects
4071
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4072
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4073
-            )
4074
-        ) {
4075
-            $original_selects = $this->_custom_selections->originalSelects();
4076
-            foreach ($original_selects as $alias => $select_configuration) {
4077
-                $this->extractJoinModelFromQueryParams(
4078
-                    $query_info_carrier,
4079
-                    $select_configuration[0],
4080
-                    $select_configuration[0],
4081
-                    'custom_selects'
4082
-                );
4083
-            }
4084
-        }
4085
-    }
4086
-
4087
-
4088
-
4089
-    /**
4090
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4091
-     * and store it on $passed_in_query_info
4092
-     *
4093
-     * @param string                      $model_name
4094
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4095
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4096
-     *                                                          model and $model_name. Eg, if we are querying Event,
4097
-     *                                                          and are adding a join to 'Payment' with the original
4098
-     *                                                          query param key
4099
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4100
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4101
-     *                                                          Payment wants to add default query params so that it
4102
-     *                                                          will know what models to prepend onto its default query
4103
-     *                                                          params or in case it wants to rename tables (in case
4104
-     *                                                          there are multiple joins to the same table)
4105
-     * @return void
4106
-     * @throws EE_Error
4107
-     */
4108
-    private function _add_join_to_model(
4109
-        $model_name,
4110
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4111
-        $original_query_param
4112
-    ) {
4113
-        $relation_obj = $this->related_settings_for($model_name);
4114
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4115
-        //check if the relation is HABTM, because then we're essentially doing two joins
4116
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
4117
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4118
-            $join_model_obj = $relation_obj->get_join_model();
4119
-            //replace the model specified with the join model for this relation chain, whi
4120
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4121
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
4122
-            $passed_in_query_info->merge(
4123
-                new EE_Model_Query_Info_Carrier(
4124
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4125
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4126
-                )
4127
-            );
4128
-        }
4129
-        //now just join to the other table pointed to by the relation object, and add its data types
4130
-        $passed_in_query_info->merge(
4131
-            new EE_Model_Query_Info_Carrier(
4132
-                array($model_relation_chain => $model_name),
4133
-                $relation_obj->get_join_statement($model_relation_chain)
4134
-            )
4135
-        );
4136
-    }
4137
-
4138
-
4139
-
4140
-    /**
4141
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4142
-     *
4143
-     * @param array $where_params like EEM_Base::get_all
4144
-     * @return string of SQL
4145
-     * @throws EE_Error
4146
-     */
4147
-    private function _construct_where_clause($where_params)
4148
-    {
4149
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4150
-        if ($SQL) {
4151
-            return " WHERE " . $SQL;
4152
-        }
4153
-        return '';
4154
-    }
4155
-
4156
-
4157
-
4158
-    /**
4159
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4160
-     * and should be passed HAVING parameters, not WHERE parameters
4161
-     *
4162
-     * @param array $having_params
4163
-     * @return string
4164
-     * @throws EE_Error
4165
-     */
4166
-    private function _construct_having_clause($having_params)
4167
-    {
4168
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4169
-        if ($SQL) {
4170
-            return " HAVING " . $SQL;
4171
-        }
4172
-        return '';
4173
-    }
4174
-
4175
-
4176
-    /**
4177
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4178
-     * Event_Meta.meta_value = 'foo'))"
4179
-     *
4180
-     * @param array  $where_params see EEM_Base::get_all for documentation
4181
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4182
-     * @throws EE_Error
4183
-     * @return string of SQL
4184
-     */
4185
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4186
-    {
4187
-        $where_clauses = array();
4188
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4189
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4190
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4191
-                switch ($query_param) {
4192
-                    case 'not':
4193
-                    case 'NOT':
4194
-                        $where_clauses[] = "! ("
4195
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4196
-                                $glue)
4197
-                                           . ")";
4198
-                        break;
4199
-                    case 'and':
4200
-                    case 'AND':
4201
-                        $where_clauses[] = " ("
4202
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4203
-                                ' AND ')
4204
-                                           . ")";
4205
-                        break;
4206
-                    case 'or':
4207
-                    case 'OR':
4208
-                        $where_clauses[] = " ("
4209
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4210
-                                ' OR ')
4211
-                                           . ")";
4212
-                        break;
4213
-                }
4214
-            } else {
4215
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4216
-                //if it's not a normal field, maybe it's a custom selection?
4217
-                if (! $field_obj) {
4218
-                    if ($this->_custom_selections instanceof CustomSelects) {
4219
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4220
-                    } else {
4221
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4222
-                            "event_espresso"), $query_param));
4223
-                    }
4224
-                }
4225
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4226
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4227
-            }
4228
-        }
4229
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4230
-    }
4231
-
4232
-
4233
-
4234
-    /**
4235
-     * Takes the input parameter and extract the table name (alias) and column name
4236
-     *
4237
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4238
-     * @throws EE_Error
4239
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4240
-     */
4241
-    private function _deduce_column_name_from_query_param($query_param)
4242
-    {
4243
-        $field = $this->_deduce_field_from_query_param($query_param);
4244
-        if ($field) {
4245
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4246
-                $query_param);
4247
-            return $table_alias_prefix . $field->get_qualified_column();
4248
-        }
4249
-        if ($this->_custom_selections instanceof CustomSelects
4250
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4251
-        ) {
4252
-            //maybe it's custom selection item?
4253
-            //if so, just use it as the "column name"
4254
-            return $query_param;
4255
-        }
4256
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4257
-            ? implode(',', $this->_custom_selections->columnAliases())
4258
-            : '';
4259
-        throw new EE_Error(
4260
-            sprintf(
4261
-                __(
4262
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4263
-                    "event_espresso"
4264
-                ), $query_param, $custom_select_aliases
4265
-            )
4266
-        );
4267
-    }
4268
-
4269
-
4270
-
4271
-    /**
4272
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4273
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4274
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4275
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4276
-     *
4277
-     * @param string $condition_query_param_key
4278
-     * @return string
4279
-     */
4280
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4281
-    {
4282
-        $pos_of_star = strpos($condition_query_param_key, '*');
4283
-        if ($pos_of_star === false) {
4284
-            return $condition_query_param_key;
4285
-        }
4286
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4287
-        return $condition_query_param_sans_star;
4288
-    }
4289
-
4290
-
4291
-
4292
-    /**
4293
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4294
-     *
4295
-     * @param                            mixed      array | string    $op_and_value
4296
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4297
-     * @throws EE_Error
4298
-     * @return string
4299
-     */
4300
-    private function _construct_op_and_value($op_and_value, $field_obj)
4301
-    {
4302
-        if (is_array($op_and_value)) {
4303
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4304
-            if (! $operator) {
4305
-                $php_array_like_string = array();
4306
-                foreach ($op_and_value as $key => $value) {
4307
-                    $php_array_like_string[] = "$key=>$value";
4308
-                }
4309
-                throw new EE_Error(
4310
-                    sprintf(
4311
-                        __(
4312
-                            "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))",
4313
-                            "event_espresso"
4314
-                        ),
4315
-                        implode(",", $php_array_like_string)
4316
-                    )
4317
-                );
4318
-            }
4319
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4320
-        } else {
4321
-            $operator = '=';
4322
-            $value = $op_and_value;
4323
-        }
4324
-        //check to see if the value is actually another field
4325
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4326
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4327
-        }
4328
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4329
-            //in this case, the value should be an array, or at least a comma-separated list
4330
-            //it will need to handle a little differently
4331
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4332
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4333
-            return $operator . SP . $cleaned_value;
4334
-        }
4335
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4336
-            //the value should be an array with count of two.
4337
-            if (count($value) !== 2) {
4338
-                throw new EE_Error(
4339
-                    sprintf(
4340
-                        __(
4341
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4342
-                            'event_espresso'
4343
-                        ),
4344
-                        "BETWEEN"
4345
-                    )
4346
-                );
4347
-            }
4348
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4349
-            return $operator . SP . $cleaned_value;
4350
-        }
4351
-        if (in_array($operator, $this->valid_null_style_operators())) {
4352
-            if ($value !== null) {
4353
-                throw new EE_Error(
4354
-                    sprintf(
4355
-                        __(
4356
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4357
-                            "event_espresso"
4358
-                        ),
4359
-                        $value,
4360
-                        $operator
4361
-                    )
4362
-                );
4363
-            }
4364
-            return $operator;
4365
-        }
4366
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4367
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4368
-            //remove other junk. So just treat it as a string.
4369
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4370
-        }
4371
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4372
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4373
-        }
4374
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4375
-            throw new EE_Error(
4376
-                sprintf(
4377
-                    __(
4378
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4379
-                        'event_espresso'
4380
-                    ),
4381
-                    $operator,
4382
-                    $operator
4383
-                )
4384
-            );
4385
-        }
4386
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4387
-            throw new EE_Error(
4388
-                sprintf(
4389
-                    __(
4390
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4391
-                        'event_espresso'
4392
-                    ),
4393
-                    $operator,
4394
-                    $operator
4395
-                )
4396
-            );
4397
-        }
4398
-        throw new EE_Error(
4399
-            sprintf(
4400
-                __(
4401
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4402
-                    "event_espresso"
4403
-                ),
4404
-                http_build_query($op_and_value)
4405
-            )
4406
-        );
4407
-    }
4408
-
4409
-
4410
-
4411
-    /**
4412
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4413
-     *
4414
-     * @param array                      $values
4415
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4416
-     *                                              '%s'
4417
-     * @return string
4418
-     * @throws EE_Error
4419
-     */
4420
-    public function _construct_between_value($values, $field_obj)
4421
-    {
4422
-        $cleaned_values = array();
4423
-        foreach ($values as $value) {
4424
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4425
-        }
4426
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4427
-    }
4428
-
4429
-
4430
-
4431
-    /**
4432
-     * Takes an array or a comma-separated list of $values and cleans them
4433
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4434
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4435
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4436
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4437
-     *
4438
-     * @param mixed                      $values    array or comma-separated string
4439
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4440
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4441
-     * @throws EE_Error
4442
-     */
4443
-    public function _construct_in_value($values, $field_obj)
4444
-    {
4445
-        //check if the value is a CSV list
4446
-        if (is_string($values)) {
4447
-            //in which case, turn it into an array
4448
-            $values = explode(",", $values);
4449
-        }
4450
-        $cleaned_values = array();
4451
-        foreach ($values as $value) {
4452
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4453
-        }
4454
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4455
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4456
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4457
-        if (empty($cleaned_values)) {
4458
-            $all_fields = $this->field_settings();
4459
-            $a_field = array_shift($all_fields);
4460
-            $main_table = $this->_get_main_table();
4461
-            $cleaned_values[] = "SELECT "
4462
-                                . $a_field->get_table_column()
4463
-                                . " FROM "
4464
-                                . $main_table->get_table_name()
4465
-                                . " WHERE FALSE";
4466
-        }
4467
-        return "(" . implode(",", $cleaned_values) . ")";
4468
-    }
4469
-
4470
-
4471
-
4472
-    /**
4473
-     * @param mixed                      $value
4474
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4475
-     * @throws EE_Error
4476
-     * @return false|null|string
4477
-     */
4478
-    private function _wpdb_prepare_using_field($value, $field_obj)
4479
-    {
4480
-        /** @type WPDB $wpdb */
4481
-        global $wpdb;
4482
-        if ($field_obj instanceof EE_Model_Field_Base) {
4483
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4484
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4485
-        } //$field_obj should really just be a data type
4486
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4487
-            throw new EE_Error(
4488
-                sprintf(
4489
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4490
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4491
-                )
4492
-            );
4493
-        }
4494
-        return $wpdb->prepare($field_obj, $value);
4495
-    }
4496
-
4497
-
4498
-
4499
-    /**
4500
-     * Takes the input parameter and finds the model field that it indicates.
4501
-     *
4502
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4503
-     * @throws EE_Error
4504
-     * @return EE_Model_Field_Base
4505
-     */
4506
-    protected function _deduce_field_from_query_param($query_param_name)
4507
-    {
4508
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4509
-        //which will help us find the database table and column
4510
-        $query_param_parts = explode(".", $query_param_name);
4511
-        if (empty($query_param_parts)) {
4512
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4513
-                'event_espresso'), $query_param_name));
4514
-        }
4515
-        $number_of_parts = count($query_param_parts);
4516
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4517
-        if ($number_of_parts === 1) {
4518
-            $field_name = $last_query_param_part;
4519
-            $model_obj = $this;
4520
-        } else {// $number_of_parts >= 2
4521
-            //the last part is the column name, and there are only 2parts. therefore...
4522
-            $field_name = $last_query_param_part;
4523
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4524
-        }
4525
-        try {
4526
-            return $model_obj->field_settings_for($field_name);
4527
-        } catch (EE_Error $e) {
4528
-            return null;
4529
-        }
4530
-    }
4531
-
4532
-
4533
-
4534
-    /**
4535
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4536
-     * alias and column which corresponds to it
4537
-     *
4538
-     * @param string $field_name
4539
-     * @throws EE_Error
4540
-     * @return string
4541
-     */
4542
-    public function _get_qualified_column_for_field($field_name)
4543
-    {
4544
-        $all_fields = $this->field_settings();
4545
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4546
-        if ($field) {
4547
-            return $field->get_qualified_column();
4548
-        }
4549
-        throw new EE_Error(
4550
-            sprintf(
4551
-                __(
4552
-                    "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.",
4553
-                    'event_espresso'
4554
-                ), $field_name, get_class($this)
4555
-            )
4556
-        );
4557
-    }
4558
-
4559
-
4560
-
4561
-    /**
4562
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4563
-     * Example usage:
4564
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4565
-     *      array(),
4566
-     *      ARRAY_A,
4567
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4568
-     *  );
4569
-     * is equivalent to
4570
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4571
-     * and
4572
-     *  EEM_Event::instance()->get_all_wpdb_results(
4573
-     *      array(
4574
-     *          array(
4575
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4576
-     *          ),
4577
-     *          ARRAY_A,
4578
-     *          implode(
4579
-     *              ', ',
4580
-     *              array_merge(
4581
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4582
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4583
-     *              )
4584
-     *          )
4585
-     *      )
4586
-     *  );
4587
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4588
-     *
4589
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4590
-     *                                            and the one whose fields you are selecting for example: when querying
4591
-     *                                            tickets model and selecting fields from the tickets model you would
4592
-     *                                            leave this parameter empty, because no models are needed to join
4593
-     *                                            between the queried model and the selected one. Likewise when
4594
-     *                                            querying the datetime model and selecting fields from the tickets
4595
-     *                                            model, it would also be left empty, because there is a direct
4596
-     *                                            relation from datetimes to tickets, so no model is needed to join
4597
-     *                                            them together. However, when querying from the event model and
4598
-     *                                            selecting fields from the ticket model, you should provide the string
4599
-     *                                            'Datetime', indicating that the event model must first join to the
4600
-     *                                            datetime model in order to find its relation to ticket model.
4601
-     *                                            Also, when querying from the venue model and selecting fields from
4602
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4603
-     *                                            indicating you need to join the venue model to the event model,
4604
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4605
-     *                                            This string is used to deduce the prefix that gets added onto the
4606
-     *                                            models' tables qualified columns
4607
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4608
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4609
-     *                                            qualified column names
4610
-     * @return array|string
4611
-     */
4612
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4613
-    {
4614
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4615
-        $qualified_columns = array();
4616
-        foreach ($this->field_settings() as $field_name => $field) {
4617
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4618
-        }
4619
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4620
-    }
4621
-
4622
-
4623
-
4624
-    /**
4625
-     * constructs the select use on special limit joins
4626
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4627
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4628
-     * (as that is typically where the limits would be set).
4629
-     *
4630
-     * @param  string       $table_alias The table the select is being built for
4631
-     * @param  mixed|string $limit       The limit for this select
4632
-     * @return string                The final select join element for the query.
4633
-     */
4634
-    public function _construct_limit_join_select($table_alias, $limit)
4635
-    {
4636
-        $SQL = '';
4637
-        foreach ($this->_tables as $table_obj) {
4638
-            if ($table_obj instanceof EE_Primary_Table) {
4639
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4640
-                    ? $table_obj->get_select_join_limit($limit)
4641
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4642
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4643
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4644
-                    ? $table_obj->get_select_join_limit_join($limit)
4645
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4646
-            }
4647
-        }
4648
-        return $SQL;
4649
-    }
4650
-
4651
-
4652
-
4653
-    /**
4654
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4655
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4656
-     *
4657
-     * @return string SQL
4658
-     * @throws EE_Error
4659
-     */
4660
-    public function _construct_internal_join()
4661
-    {
4662
-        $SQL = $this->_get_main_table()->get_table_sql();
4663
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4664
-        return $SQL;
4665
-    }
4666
-
4667
-
4668
-
4669
-    /**
4670
-     * Constructs the SQL for joining all the tables on this model.
4671
-     * Normally $alias should be the primary table's alias, but in cases where
4672
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4673
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4674
-     * alias, this will construct SQL like:
4675
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4676
-     * With $alias being a secondary table's alias, this will construct SQL like:
4677
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4678
-     *
4679
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4680
-     * @return string
4681
-     */
4682
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4683
-    {
4684
-        $SQL = '';
4685
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4686
-        foreach ($this->_tables as $table_obj) {
4687
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4688
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4689
-                    //so we're joining to this table, meaning the table is already in
4690
-                    //the FROM statement, BUT the primary table isn't. So we want
4691
-                    //to add the inverse join sql
4692
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4693
-                } else {
4694
-                    //just add a regular JOIN to this table from the primary table
4695
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4696
-                }
4697
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4698
-        }
4699
-        return $SQL;
4700
-    }
4701
-
4702
-
4703
-
4704
-    /**
4705
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4706
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4707
-     * their data type (eg, '%s', '%d', etc)
4708
-     *
4709
-     * @return array
4710
-     */
4711
-    public function _get_data_types()
4712
-    {
4713
-        $data_types = array();
4714
-        foreach ($this->field_settings() as $field_obj) {
4715
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4716
-            /** @var $field_obj EE_Model_Field_Base */
4717
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4718
-        }
4719
-        return $data_types;
4720
-    }
4721
-
4722
-
4723
-
4724
-    /**
4725
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4726
-     *
4727
-     * @param string $model_name
4728
-     * @throws EE_Error
4729
-     * @return EEM_Base
4730
-     */
4731
-    public function get_related_model_obj($model_name)
4732
-    {
4733
-        $model_classname = "EEM_" . $model_name;
4734
-        if (! class_exists($model_classname)) {
4735
-            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",
4736
-                'event_espresso'), $model_name, $model_classname));
4737
-        }
4738
-        return call_user_func($model_classname . "::instance");
4739
-    }
4740
-
4741
-
4742
-
4743
-    /**
4744
-     * Returns the array of EE_ModelRelations for this model.
4745
-     *
4746
-     * @return EE_Model_Relation_Base[]
4747
-     */
4748
-    public function relation_settings()
4749
-    {
4750
-        return $this->_model_relations;
4751
-    }
4752
-
4753
-
4754
-
4755
-    /**
4756
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4757
-     * because without THOSE models, this model probably doesn't have much purpose.
4758
-     * (Eg, without an event, datetimes have little purpose.)
4759
-     *
4760
-     * @return EE_Belongs_To_Relation[]
4761
-     */
4762
-    public function belongs_to_relations()
4763
-    {
4764
-        $belongs_to_relations = array();
4765
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4766
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4767
-                $belongs_to_relations[$model_name] = $relation_obj;
4768
-            }
4769
-        }
4770
-        return $belongs_to_relations;
4771
-    }
4772
-
4773
-
4774
-
4775
-    /**
4776
-     * Returns the specified EE_Model_Relation, or throws an exception
4777
-     *
4778
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4779
-     * @throws EE_Error
4780
-     * @return EE_Model_Relation_Base
4781
-     */
4782
-    public function related_settings_for($relation_name)
4783
-    {
4784
-        $relatedModels = $this->relation_settings();
4785
-        if (! array_key_exists($relation_name, $relatedModels)) {
4786
-            throw new EE_Error(
4787
-                sprintf(
4788
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4789
-                        'event_espresso'),
4790
-                    $relation_name,
4791
-                    $this->_get_class_name(),
4792
-                    implode(', ', array_keys($relatedModels))
4793
-                )
4794
-            );
4795
-        }
4796
-        return $relatedModels[$relation_name];
4797
-    }
4798
-
4799
-
4800
-
4801
-    /**
4802
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4803
-     * fields
4804
-     *
4805
-     * @param string $fieldName
4806
-     * @param boolean $include_db_only_fields
4807
-     * @throws EE_Error
4808
-     * @return EE_Model_Field_Base
4809
-     */
4810
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4811
-    {
4812
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4813
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4814
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4815
-                get_class($this)));
4816
-        }
4817
-        return $fieldSettings[$fieldName];
4818
-    }
4819
-
4820
-
4821
-
4822
-    /**
4823
-     * Checks if this field exists on this model
4824
-     *
4825
-     * @param string $fieldName a key in the model's _field_settings array
4826
-     * @return boolean
4827
-     */
4828
-    public function has_field($fieldName)
4829
-    {
4830
-        $fieldSettings = $this->field_settings(true);
4831
-        if (isset($fieldSettings[$fieldName])) {
4832
-            return true;
4833
-        }
4834
-        return false;
4835
-    }
4836
-
4837
-
4838
-
4839
-    /**
4840
-     * Returns whether or not this model has a relation to the specified model
4841
-     *
4842
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4843
-     * @return boolean
4844
-     */
4845
-    public function has_relation($relation_name)
4846
-    {
4847
-        $relations = $this->relation_settings();
4848
-        if (isset($relations[$relation_name])) {
4849
-            return true;
4850
-        }
4851
-        return false;
4852
-    }
4853
-
4854
-
4855
-
4856
-    /**
4857
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4858
-     * Eg, on EE_Answer that would be ANS_ID field object
4859
-     *
4860
-     * @param $field_obj
4861
-     * @return boolean
4862
-     */
4863
-    public function is_primary_key_field($field_obj)
4864
-    {
4865
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4866
-    }
4867
-
4868
-
4869
-
4870
-    /**
4871
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4872
-     * Eg, on EE_Answer that would be ANS_ID field object
4873
-     *
4874
-     * @return EE_Model_Field_Base
4875
-     * @throws EE_Error
4876
-     */
4877
-    public function get_primary_key_field()
4878
-    {
4879
-        if ($this->_primary_key_field === null) {
4880
-            foreach ($this->field_settings(true) as $field_obj) {
4881
-                if ($this->is_primary_key_field($field_obj)) {
4882
-                    $this->_primary_key_field = $field_obj;
4883
-                    break;
4884
-                }
4885
-            }
4886
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4887
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4888
-                    get_class($this)));
4889
-            }
4890
-        }
4891
-        return $this->_primary_key_field;
4892
-    }
4893
-
4894
-
4895
-
4896
-    /**
4897
-     * Returns whether or not not there is a primary key on this model.
4898
-     * Internally does some caching.
4899
-     *
4900
-     * @return boolean
4901
-     */
4902
-    public function has_primary_key_field()
4903
-    {
4904
-        if ($this->_has_primary_key_field === null) {
4905
-            try {
4906
-                $this->get_primary_key_field();
4907
-                $this->_has_primary_key_field = true;
4908
-            } catch (EE_Error $e) {
4909
-                $this->_has_primary_key_field = false;
4910
-            }
4911
-        }
4912
-        return $this->_has_primary_key_field;
4913
-    }
4914
-
4915
-
4916
-
4917
-    /**
4918
-     * Finds the first field of type $field_class_name.
4919
-     *
4920
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4921
-     *                                 EE_Foreign_Key_Field, etc
4922
-     * @return EE_Model_Field_Base or null if none is found
4923
-     */
4924
-    public function get_a_field_of_type($field_class_name)
4925
-    {
4926
-        foreach ($this->field_settings() as $field) {
4927
-            if ($field instanceof $field_class_name) {
4928
-                return $field;
4929
-            }
4930
-        }
4931
-        return null;
4932
-    }
4933
-
4934
-
4935
-
4936
-    /**
4937
-     * Gets a foreign key field pointing to model.
4938
-     *
4939
-     * @param string $model_name eg Event, Registration, not EEM_Event
4940
-     * @return EE_Foreign_Key_Field_Base
4941
-     * @throws EE_Error
4942
-     */
4943
-    public function get_foreign_key_to($model_name)
4944
-    {
4945
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4946
-            foreach ($this->field_settings() as $field) {
4947
-                if (
4948
-                    $field instanceof EE_Foreign_Key_Field_Base
4949
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4950
-                ) {
4951
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4952
-                    break;
4953
-                }
4954
-            }
4955
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4956
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4957
-                    'event_espresso'), $model_name, get_class($this)));
4958
-            }
4959
-        }
4960
-        return $this->_cache_foreign_key_to_fields[$model_name];
4961
-    }
4962
-
4963
-
4964
-
4965
-    /**
4966
-     * Gets the table name (including $wpdb->prefix) for the table alias
4967
-     *
4968
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4969
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4970
-     *                            Either one works
4971
-     * @return string
4972
-     */
4973
-    public function get_table_for_alias($table_alias)
4974
-    {
4975
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4976
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4977
-    }
4978
-
4979
-
4980
-
4981
-    /**
4982
-     * Returns a flat array of all field son this model, instead of organizing them
4983
-     * by table_alias as they are in the constructor.
4984
-     *
4985
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4986
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4987
-     */
4988
-    public function field_settings($include_db_only_fields = false)
4989
-    {
4990
-        if ($include_db_only_fields) {
4991
-            if ($this->_cached_fields === null) {
4992
-                $this->_cached_fields = array();
4993
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4994
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4995
-                        $this->_cached_fields[$field_name] = $field_obj;
4996
-                    }
4997
-                }
4998
-            }
4999
-            return $this->_cached_fields;
5000
-        }
5001
-        if ($this->_cached_fields_non_db_only === null) {
5002
-            $this->_cached_fields_non_db_only = array();
5003
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5004
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5005
-                    /** @var $field_obj EE_Model_Field_Base */
5006
-                    if (! $field_obj->is_db_only_field()) {
5007
-                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5008
-                    }
5009
-                }
5010
-            }
5011
-        }
5012
-        return $this->_cached_fields_non_db_only;
5013
-    }
5014
-
5015
-
5016
-
5017
-    /**
5018
-     *        cycle though array of attendees and create objects out of each item
5019
-     *
5020
-     * @access        private
5021
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5022
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5023
-     *                           numerically indexed)
5024
-     * @throws EE_Error
5025
-     */
5026
-    protected function _create_objects($rows = array())
5027
-    {
5028
-        $array_of_objects = array();
5029
-        if (empty($rows)) {
5030
-            return array();
5031
-        }
5032
-        $count_if_model_has_no_primary_key = 0;
5033
-        $has_primary_key = $this->has_primary_key_field();
5034
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5035
-        foreach ((array)$rows as $row) {
5036
-            if (empty($row)) {
5037
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5038
-                return array();
5039
-            }
5040
-            //check if we've already set this object in the results array,
5041
-            //in which case there's no need to process it further (again)
5042
-            if ($has_primary_key) {
5043
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5044
-                    $row,
5045
-                    $primary_key_field->get_qualified_column(),
5046
-                    $primary_key_field->get_table_column()
5047
-                );
5048
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5049
-                    continue;
5050
-                }
5051
-            }
5052
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5053
-            if (! $classInstance) {
5054
-                throw new EE_Error(
5055
-                    sprintf(
5056
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5057
-                        $this->get_this_model_name(),
5058
-                        http_build_query($row)
5059
-                    )
5060
-                );
5061
-            }
5062
-            //set the timezone on the instantiated objects
5063
-            $classInstance->set_timezone($this->_timezone);
5064
-            //make sure if there is any timezone setting present that we set the timezone for the object
5065
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5066
-            $array_of_objects[$key] = $classInstance;
5067
-            //also, for all the relations of type BelongsTo, see if we can cache
5068
-            //those related models
5069
-            //(we could do this for other relations too, but if there are conditions
5070
-            //that filtered out some fo the results, then we'd be caching an incomplete set
5071
-            //so it requires a little more thought than just caching them immediately...)
5072
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5073
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5074
-                    //check if this model's INFO is present. If so, cache it on the model
5075
-                    $other_model = $relation_obj->get_other_model();
5076
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5077
-                    //if we managed to make a model object from the results, cache it on the main model object
5078
-                    if ($other_model_obj_maybe) {
5079
-                        //set timezone on these other model objects if they are present
5080
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5081
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5082
-                    }
5083
-                }
5084
-            }
5085
-            //also, if this was a custom select query, let's see if there are any results for the custom select fields
5086
-            //and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5087
-            //the field in the CustomSelects object
5088
-            if ($this->_custom_selections instanceof CustomSelects) {
5089
-                $classInstance->setCustomSelectsValues(
5090
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5091
-                );
5092
-            }
5093
-        }
5094
-        return $array_of_objects;
5095
-    }
5096
-
5097
-
5098
-    /**
5099
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5100
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5101
-     *
5102
-     * @param array $db_results_row
5103
-     * @return array
5104
-     */
5105
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5106
-    {
5107
-        $results = array();
5108
-        if ($this->_custom_selections instanceof CustomSelects) {
5109
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5110
-                if (isset($db_results_row[$alias])) {
5111
-                    $results[$alias] = $this->convertValueToDataType(
5112
-                        $db_results_row[$alias],
5113
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5114
-                    );
5115
-                }
5116
-            }
5117
-        }
5118
-        return $results;
5119
-    }
5120
-
5121
-
5122
-    /**
5123
-     * This will set the value for the given alias
5124
-     * @param string $value
5125
-     * @param string $datatype (one of %d, %s, %f)
5126
-     * @return int|string|float (int for %d, string for %s, float for %f)
5127
-     */
5128
-    protected function convertValueToDataType($value, $datatype)
5129
-    {
5130
-        switch ($datatype) {
5131
-            case '%f':
5132
-                return (float) $value;
5133
-            case '%d':
5134
-                return (int) $value;
5135
-            default:
5136
-                return (string) $value;
5137
-        }
5138
-    }
5139
-
5140
-
5141
-    /**
5142
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5143
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5144
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5145
-     * object (as set in the model_field!).
5146
-     *
5147
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5148
-     */
5149
-    public function create_default_object()
5150
-    {
5151
-        $this_model_fields_and_values = array();
5152
-        //setup the row using default values;
5153
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5154
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5155
-        }
5156
-        $className = $this->_get_class_name();
5157
-        $classInstance = EE_Registry::instance()
5158
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5159
-        return $classInstance;
5160
-    }
5161
-
5162
-
5163
-
5164
-    /**
5165
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5166
-     *                             or an stdClass where each property is the name of a column,
5167
-     * @return EE_Base_Class
5168
-     * @throws EE_Error
5169
-     */
5170
-    public function instantiate_class_from_array_or_object($cols_n_values)
5171
-    {
5172
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5173
-            $cols_n_values = get_object_vars($cols_n_values);
5174
-        }
5175
-        $primary_key = null;
5176
-        //make sure the array only has keys that are fields/columns on this model
5177
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5178
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5179
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5180
-        }
5181
-        $className = $this->_get_class_name();
5182
-        //check we actually found results that we can use to build our model object
5183
-        //if not, return null
5184
-        if ($this->has_primary_key_field()) {
5185
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5186
-                return null;
5187
-            }
5188
-        } else if ($this->unique_indexes()) {
5189
-            $first_column = reset($this_model_fields_n_values);
5190
-            if (empty($first_column)) {
5191
-                return null;
5192
-            }
5193
-        }
5194
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5195
-        if ($primary_key) {
5196
-            $classInstance = $this->get_from_entity_map($primary_key);
5197
-            if (! $classInstance) {
5198
-                $classInstance = EE_Registry::instance()
5199
-                                            ->load_class($className,
5200
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
5201
-                // add this new object to the entity map
5202
-                $classInstance = $this->add_to_entity_map($classInstance);
5203
-            }
5204
-        } else {
5205
-            $classInstance = EE_Registry::instance()
5206
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5207
-                                            true, false);
5208
-        }
5209
-        return $classInstance;
5210
-    }
5211
-
5212
-
5213
-
5214
-    /**
5215
-     * Gets the model object from the  entity map if it exists
5216
-     *
5217
-     * @param int|string $id the ID of the model object
5218
-     * @return EE_Base_Class
5219
-     */
5220
-    public function get_from_entity_map($id)
5221
-    {
5222
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5223
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5224
-    }
5225
-
5226
-
5227
-
5228
-    /**
5229
-     * add_to_entity_map
5230
-     * Adds the object to the model's entity mappings
5231
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5232
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5233
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5234
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5235
-     *        then this method should be called immediately after the update query
5236
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5237
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5238
-     *
5239
-     * @param    EE_Base_Class $object
5240
-     * @throws EE_Error
5241
-     * @return \EE_Base_Class
5242
-     */
5243
-    public function add_to_entity_map(EE_Base_Class $object)
5244
-    {
5245
-        $className = $this->_get_class_name();
5246
-        if (! $object instanceof $className) {
5247
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5248
-                is_object($object) ? get_class($object) : $object, $className));
5249
-        }
5250
-        /** @var $object EE_Base_Class */
5251
-        if (! $object->ID()) {
5252
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5253
-                "event_espresso"), get_class($this)));
5254
-        }
5255
-        // double check it's not already there
5256
-        $classInstance = $this->get_from_entity_map($object->ID());
5257
-        if ($classInstance) {
5258
-            return $classInstance;
5259
-        }
5260
-        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5261
-        return $object;
5262
-    }
5263
-
5264
-
5265
-
5266
-    /**
5267
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5268
-     * if no identifier is provided, then the entire entity map is emptied
5269
-     *
5270
-     * @param int|string $id the ID of the model object
5271
-     * @return boolean
5272
-     */
5273
-    public function clear_entity_map($id = null)
5274
-    {
5275
-        if (empty($id)) {
5276
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5277
-            return true;
5278
-        }
5279
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5280
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5281
-            return true;
5282
-        }
5283
-        return false;
5284
-    }
5285
-
5286
-
5287
-
5288
-    /**
5289
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5290
-     * Given an array where keys are column (or column alias) names and values,
5291
-     * returns an array of their corresponding field names and database values
5292
-     *
5293
-     * @param array $cols_n_values
5294
-     * @return array
5295
-     */
5296
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5297
-    {
5298
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5299
-    }
5300
-
5301
-
5302
-
5303
-    /**
5304
-     * _deduce_fields_n_values_from_cols_n_values
5305
-     * Given an array where keys are column (or column alias) names and values,
5306
-     * returns an array of their corresponding field names and database values
5307
-     *
5308
-     * @param string $cols_n_values
5309
-     * @return array
5310
-     */
5311
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5312
-    {
5313
-        $this_model_fields_n_values = array();
5314
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5315
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5316
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5317
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5318
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5319
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5320
-                    if (! $field_obj->is_db_only_field()) {
5321
-                        //prepare field as if its coming from db
5322
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5323
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5324
-                    }
5325
-                }
5326
-            } else {
5327
-                //the table's rows existed. Use their values
5328
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5329
-                    if (! $field_obj->is_db_only_field()) {
5330
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5331
-                            $cols_n_values, $field_obj->get_qualified_column(),
5332
-                            $field_obj->get_table_column()
5333
-                        );
5334
-                    }
5335
-                }
5336
-            }
5337
-        }
5338
-        return $this_model_fields_n_values;
5339
-    }
5340
-
5341
-
5342
-
5343
-    /**
5344
-     * @param $cols_n_values
5345
-     * @param $qualified_column
5346
-     * @param $regular_column
5347
-     * @return null
5348
-     */
5349
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5350
-    {
5351
-        $value = null;
5352
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5353
-        //does the field on the model relate to this column retrieved from the db?
5354
-        //or is it a db-only field? (not relating to the model)
5355
-        if (isset($cols_n_values[$qualified_column])) {
5356
-            $value = $cols_n_values[$qualified_column];
5357
-        } elseif (isset($cols_n_values[$regular_column])) {
5358
-            $value = $cols_n_values[$regular_column];
5359
-        }
5360
-        return $value;
5361
-    }
5362
-
5363
-
5364
-
5365
-    /**
5366
-     * refresh_entity_map_from_db
5367
-     * Makes sure the model object in the entity map at $id assumes the values
5368
-     * of the database (opposite of EE_base_Class::save())
5369
-     *
5370
-     * @param int|string $id
5371
-     * @return EE_Base_Class
5372
-     * @throws EE_Error
5373
-     */
5374
-    public function refresh_entity_map_from_db($id)
5375
-    {
5376
-        $obj_in_map = $this->get_from_entity_map($id);
5377
-        if ($obj_in_map) {
5378
-            $wpdb_results = $this->_get_all_wpdb_results(
5379
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5380
-            );
5381
-            if ($wpdb_results && is_array($wpdb_results)) {
5382
-                $one_row = reset($wpdb_results);
5383
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5384
-                    $obj_in_map->set_from_db($field_name, $db_value);
5385
-                }
5386
-                //clear the cache of related model objects
5387
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5388
-                    $obj_in_map->clear_cache($relation_name, null, true);
5389
-                }
5390
-            }
5391
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5392
-            return $obj_in_map;
5393
-        }
5394
-        return $this->get_one_by_ID($id);
5395
-    }
5396
-
5397
-
5398
-
5399
-    /**
5400
-     * refresh_entity_map_with
5401
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5402
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5403
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5404
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5405
-     *
5406
-     * @param int|string    $id
5407
-     * @param EE_Base_Class $replacing_model_obj
5408
-     * @return \EE_Base_Class
5409
-     * @throws EE_Error
5410
-     */
5411
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5412
-    {
5413
-        $obj_in_map = $this->get_from_entity_map($id);
5414
-        if ($obj_in_map) {
5415
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5416
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5417
-                    $obj_in_map->set($field_name, $value);
5418
-                }
5419
-                //make the model object in the entity map's cache match the $replacing_model_obj
5420
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5421
-                    $obj_in_map->clear_cache($relation_name, null, true);
5422
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5423
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5424
-                    }
5425
-                }
5426
-            }
5427
-            return $obj_in_map;
5428
-        }
5429
-        $this->add_to_entity_map($replacing_model_obj);
5430
-        return $replacing_model_obj;
5431
-    }
5432
-
5433
-
5434
-
5435
-    /**
5436
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5437
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5438
-     * require_once($this->_getClassName().".class.php");
5439
-     *
5440
-     * @return string
5441
-     */
5442
-    private function _get_class_name()
5443
-    {
5444
-        return "EE_" . $this->get_this_model_name();
5445
-    }
5446
-
5447
-
5448
-
5449
-    /**
5450
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5451
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5452
-     * it would be 'Events'.
5453
-     *
5454
-     * @param int $quantity
5455
-     * @return string
5456
-     */
5457
-    public function item_name($quantity = 1)
5458
-    {
5459
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5460
-    }
5461
-
5462
-
5463
-
5464
-    /**
5465
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5466
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5467
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5468
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5469
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5470
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5471
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5472
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5473
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5474
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5475
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5476
-     *        return $previousReturnValue.$returnString;
5477
-     * }
5478
-     * require('EEM_Answer.model.php');
5479
-     * $answer=EEM_Answer::instance();
5480
-     * echo $answer->my_callback('monkeys',100);
5481
-     * //will output "you called my_callback! and passed args:monkeys,100"
5482
-     *
5483
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5484
-     * @param array  $args       array of original arguments passed to the function
5485
-     * @throws EE_Error
5486
-     * @return mixed whatever the plugin which calls add_filter decides
5487
-     */
5488
-    public function __call($methodName, $args)
5489
-    {
5490
-        $className = get_class($this);
5491
-        $tagName = "FHEE__{$className}__{$methodName}";
5492
-        if (! has_filter($tagName)) {
5493
-            throw new EE_Error(
5494
-                sprintf(
5495
-                    __('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 );',
5496
-                        'event_espresso'),
5497
-                    $methodName,
5498
-                    $className,
5499
-                    $tagName,
5500
-                    '<br />'
5501
-                )
5502
-            );
5503
-        }
5504
-        return apply_filters($tagName, null, $this, $args);
5505
-    }
5506
-
5507
-
5508
-
5509
-    /**
5510
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5511
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5512
-     *
5513
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5514
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5515
-     *                                                       the object's class name
5516
-     *                                                       or object's ID
5517
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5518
-     *                                                       exists in the database. If it does not, we add it
5519
-     * @throws EE_Error
5520
-     * @return EE_Base_Class
5521
-     */
5522
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5523
-    {
5524
-        $className = $this->_get_class_name();
5525
-        if ($base_class_obj_or_id instanceof $className) {
5526
-            $model_object = $base_class_obj_or_id;
5527
-        } else {
5528
-            $primary_key_field = $this->get_primary_key_field();
5529
-            if (
5530
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5531
-                && (
5532
-                    is_int($base_class_obj_or_id)
5533
-                    || is_string($base_class_obj_or_id)
5534
-                )
5535
-            ) {
5536
-                // assume it's an ID.
5537
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5538
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5539
-            } else if (
5540
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5541
-                && is_string($base_class_obj_or_id)
5542
-            ) {
5543
-                // assume its a string representation of the object
5544
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5545
-            } else {
5546
-                throw new EE_Error(
5547
-                    sprintf(
5548
-                        __(
5549
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5550
-                            'event_espresso'
5551
-                        ),
5552
-                        $base_class_obj_or_id,
5553
-                        $this->_get_class_name(),
5554
-                        print_r($base_class_obj_or_id, true)
5555
-                    )
5556
-                );
5557
-            }
5558
-        }
5559
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5560
-            $model_object->save();
5561
-        }
5562
-        return $model_object;
5563
-    }
5564
-
5565
-
5566
-
5567
-    /**
5568
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5569
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5570
-     * returns it ID.
5571
-     *
5572
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5573
-     * @return int|string depending on the type of this model object's ID
5574
-     * @throws EE_Error
5575
-     */
5576
-    public function ensure_is_ID($base_class_obj_or_id)
5577
-    {
5578
-        $className = $this->_get_class_name();
5579
-        if ($base_class_obj_or_id instanceof $className) {
5580
-            /** @var $base_class_obj_or_id EE_Base_Class */
5581
-            $id = $base_class_obj_or_id->ID();
5582
-        } elseif (is_int($base_class_obj_or_id)) {
5583
-            //assume it's an ID
5584
-            $id = $base_class_obj_or_id;
5585
-        } elseif (is_string($base_class_obj_or_id)) {
5586
-            //assume its a string representation of the object
5587
-            $id = $base_class_obj_or_id;
5588
-        } else {
5589
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5590
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5591
-                print_r($base_class_obj_or_id, true)));
5592
-        }
5593
-        return $id;
5594
-    }
5595
-
5596
-
5597
-
5598
-    /**
5599
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5600
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5601
-     * been sanitized and converted into the appropriate domain.
5602
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5603
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5604
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5605
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5606
-     * $EVT = EEM_Event::instance(); $old_setting =
5607
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5608
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5609
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5610
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5611
-     *
5612
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5613
-     * @return void
5614
-     */
5615
-    public function assume_values_already_prepared_by_model_object(
5616
-        $values_already_prepared = self::not_prepared_by_model_object
5617
-    ) {
5618
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5619
-    }
5620
-
5621
-
5622
-
5623
-    /**
5624
-     * Read comments for assume_values_already_prepared_by_model_object()
5625
-     *
5626
-     * @return int
5627
-     */
5628
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5629
-    {
5630
-        return $this->_values_already_prepared_by_model_object;
5631
-    }
5632
-
5633
-
5634
-
5635
-    /**
5636
-     * Gets all the indexes on this model
5637
-     *
5638
-     * @return EE_Index[]
5639
-     */
5640
-    public function indexes()
5641
-    {
5642
-        return $this->_indexes;
5643
-    }
5644
-
5645
-
5646
-
5647
-    /**
5648
-     * Gets all the Unique Indexes on this model
5649
-     *
5650
-     * @return EE_Unique_Index[]
5651
-     */
5652
-    public function unique_indexes()
5653
-    {
5654
-        $unique_indexes = array();
5655
-        foreach ($this->_indexes as $name => $index) {
5656
-            if ($index instanceof EE_Unique_Index) {
5657
-                $unique_indexes [$name] = $index;
5658
-            }
5659
-        }
5660
-        return $unique_indexes;
5661
-    }
5662
-
5663
-
5664
-
5665
-    /**
5666
-     * Gets all the fields which, when combined, make the primary key.
5667
-     * This is usually just an array with 1 element (the primary key), but in cases
5668
-     * where there is no primary key, it's a combination of fields as defined
5669
-     * on a primary index
5670
-     *
5671
-     * @return EE_Model_Field_Base[] indexed by the field's name
5672
-     * @throws EE_Error
5673
-     */
5674
-    public function get_combined_primary_key_fields()
5675
-    {
5676
-        foreach ($this->indexes() as $index) {
5677
-            if ($index instanceof EE_Primary_Key_Index) {
5678
-                return $index->fields();
5679
-            }
5680
-        }
5681
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5682
-    }
5683
-
5684
-
5685
-
5686
-    /**
5687
-     * Used to build a primary key string (when the model has no primary key),
5688
-     * which can be used a unique string to identify this model object.
5689
-     *
5690
-     * @param array $cols_n_values keys are field names, values are their values
5691
-     * @return string
5692
-     * @throws EE_Error
5693
-     */
5694
-    public function get_index_primary_key_string($cols_n_values)
5695
-    {
5696
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5697
-            $this->get_combined_primary_key_fields());
5698
-        return http_build_query($cols_n_values_for_primary_key_index);
5699
-    }
5700
-
5701
-
5702
-
5703
-    /**
5704
-     * Gets the field values from the primary key string
5705
-     *
5706
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5707
-     * @param string $index_primary_key_string
5708
-     * @return null|array
5709
-     * @throws EE_Error
5710
-     */
5711
-    public function parse_index_primary_key_string($index_primary_key_string)
5712
-    {
5713
-        $key_fields = $this->get_combined_primary_key_fields();
5714
-        //check all of them are in the $id
5715
-        $key_vals_in_combined_pk = array();
5716
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5717
-        foreach ($key_fields as $key_field_name => $field_obj) {
5718
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5719
-                return null;
5720
-            }
5721
-        }
5722
-        return $key_vals_in_combined_pk;
5723
-    }
5724
-
5725
-
5726
-
5727
-    /**
5728
-     * verifies that an array of key-value pairs for model fields has a key
5729
-     * for each field comprising the primary key index
5730
-     *
5731
-     * @param array $key_vals
5732
-     * @return boolean
5733
-     * @throws EE_Error
5734
-     */
5735
-    public function has_all_combined_primary_key_fields($key_vals)
5736
-    {
5737
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5738
-        foreach ($keys_it_should_have as $key) {
5739
-            if (! isset($key_vals[$key])) {
5740
-                return false;
5741
-            }
5742
-        }
5743
-        return true;
5744
-    }
5745
-
5746
-
5747
-
5748
-    /**
5749
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5750
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5751
-     *
5752
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5753
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5754
-     * @throws EE_Error
5755
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5756
-     *                                                              indexed)
5757
-     */
5758
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5759
-    {
5760
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5761
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5762
-        } elseif (is_array($model_object_or_attributes_array)) {
5763
-            $attributes_array = $model_object_or_attributes_array;
5764
-        } else {
5765
-            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",
5766
-                "event_espresso"), $model_object_or_attributes_array));
5767
-        }
5768
-        //even copies obviously won't have the same ID, so remove the primary key
5769
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5770
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5771
-            unset($attributes_array[$this->primary_key_name()]);
5772
-        }
5773
-        if (isset($query_params[0])) {
5774
-            $query_params[0] = array_merge($attributes_array, $query_params);
5775
-        } else {
5776
-            $query_params[0] = $attributes_array;
5777
-        }
5778
-        return $this->get_all($query_params);
5779
-    }
5780
-
5781
-
5782
-
5783
-    /**
5784
-     * Gets the first copy we find. See get_all_copies for more details
5785
-     *
5786
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5787
-     * @param array $query_params
5788
-     * @return EE_Base_Class
5789
-     * @throws EE_Error
5790
-     */
5791
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5792
-    {
5793
-        if (! is_array($query_params)) {
5794
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5795
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5796
-                    gettype($query_params)), '4.6.0');
5797
-            $query_params = array();
5798
-        }
5799
-        $query_params['limit'] = 1;
5800
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5801
-        if (is_array($copies)) {
5802
-            return array_shift($copies);
5803
-        }
5804
-        return null;
5805
-    }
5806
-
5807
-
5808
-
5809
-    /**
5810
-     * Updates the item with the specified id. Ignores default query parameters because
5811
-     * we have specified the ID, and its assumed we KNOW what we're doing
5812
-     *
5813
-     * @param array      $fields_n_values keys are field names, values are their new values
5814
-     * @param int|string $id              the value of the primary key to update
5815
-     * @return int number of rows updated
5816
-     * @throws EE_Error
5817
-     */
5818
-    public function update_by_ID($fields_n_values, $id)
5819
-    {
5820
-        $query_params = array(
5821
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5822
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5823
-        );
5824
-        return $this->update($fields_n_values, $query_params);
5825
-    }
5826
-
5827
-
5828
-
5829
-    /**
5830
-     * Changes an operator which was supplied to the models into one usable in SQL
5831
-     *
5832
-     * @param string $operator_supplied
5833
-     * @return string an operator which can be used in SQL
5834
-     * @throws EE_Error
5835
-     */
5836
-    private function _prepare_operator_for_sql($operator_supplied)
5837
-    {
5838
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5839
-            : null;
5840
-        if ($sql_operator) {
5841
-            return $sql_operator;
5842
-        }
5843
-        throw new EE_Error(
5844
-            sprintf(
5845
-                __(
5846
-                    "The operator '%s' is not in the list of valid operators: %s",
5847
-                    "event_espresso"
5848
-                ), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5849
-            )
5850
-        );
5851
-    }
5852
-
5853
-
5854
-
5855
-    /**
5856
-     * Gets the valid operators
5857
-     * @return array keys are accepted strings, values are the SQL they are converted to
5858
-     */
5859
-    public function valid_operators(){
5860
-        return $this->_valid_operators;
5861
-    }
5862
-
5863
-
5864
-
5865
-    /**
5866
-     * Gets the between-style operators (take 2 arguments).
5867
-     * @return array keys are accepted strings, values are the SQL they are converted to
5868
-     */
5869
-    public function valid_between_style_operators()
5870
-    {
5871
-        return array_intersect(
5872
-            $this->valid_operators(),
5873
-            $this->_between_style_operators
5874
-        );
5875
-    }
5876
-
5877
-    /**
5878
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5879
-     * @return array keys are accepted strings, values are the SQL they are converted to
5880
-     */
5881
-    public function valid_like_style_operators()
5882
-    {
5883
-        return array_intersect(
5884
-            $this->valid_operators(),
5885
-            $this->_like_style_operators
5886
-        );
5887
-    }
5888
-
5889
-    /**
5890
-     * Gets the "in"-style operators
5891
-     * @return array keys are accepted strings, values are the SQL they are converted to
5892
-     */
5893
-    public function valid_in_style_operators()
5894
-    {
5895
-        return array_intersect(
5896
-            $this->valid_operators(),
5897
-            $this->_in_style_operators
5898
-        );
5899
-    }
5900
-
5901
-    /**
5902
-     * Gets the "null"-style operators (accept no arguments)
5903
-     * @return array keys are accepted strings, values are the SQL they are converted to
5904
-     */
5905
-    public function valid_null_style_operators()
5906
-    {
5907
-        return array_intersect(
5908
-            $this->valid_operators(),
5909
-            $this->_null_style_operators
5910
-        );
5911
-    }
5912
-
5913
-    /**
5914
-     * Gets an array where keys are the primary keys and values are their 'names'
5915
-     * (as determined by the model object's name() function, which is often overridden)
5916
-     *
5917
-     * @param array $query_params like get_all's
5918
-     * @return string[]
5919
-     * @throws EE_Error
5920
-     */
5921
-    public function get_all_names($query_params = array())
5922
-    {
5923
-        $objs = $this->get_all($query_params);
5924
-        $names = array();
5925
-        foreach ($objs as $obj) {
5926
-            $names[$obj->ID()] = $obj->name();
5927
-        }
5928
-        return $names;
5929
-    }
5930
-
5931
-
5932
-
5933
-    /**
5934
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5935
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5936
-     * this is duplicated effort and reduces efficiency) you would be better to use
5937
-     * array_keys() on $model_objects.
5938
-     *
5939
-     * @param \EE_Base_Class[] $model_objects
5940
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5941
-     *                                               in the returned array
5942
-     * @return array
5943
-     * @throws EE_Error
5944
-     */
5945
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5946
-    {
5947
-        if (! $this->has_primary_key_field()) {
5948
-            if (WP_DEBUG) {
5949
-                EE_Error::add_error(
5950
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5951
-                    __FILE__,
5952
-                    __FUNCTION__,
5953
-                    __LINE__
5954
-                );
5955
-            }
5956
-        }
5957
-        $IDs = array();
5958
-        foreach ($model_objects as $model_object) {
5959
-            $id = $model_object->ID();
5960
-            if (! $id) {
5961
-                if ($filter_out_empty_ids) {
5962
-                    continue;
5963
-                }
5964
-                if (WP_DEBUG) {
5965
-                    EE_Error::add_error(
5966
-                        __(
5967
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5968
-                            'event_espresso'
5969
-                        ),
5970
-                        __FILE__,
5971
-                        __FUNCTION__,
5972
-                        __LINE__
5973
-                    );
5974
-                }
5975
-            }
5976
-            $IDs[] = $id;
5977
-        }
5978
-        return $IDs;
5979
-    }
5980
-
5981
-
5982
-
5983
-    /**
5984
-     * Returns the string used in capabilities relating to this model. If there
5985
-     * are no capabilities that relate to this model returns false
5986
-     *
5987
-     * @return string|false
5988
-     */
5989
-    public function cap_slug()
5990
-    {
5991
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5992
-    }
5993
-
5994
-
5995
-
5996
-    /**
5997
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5998
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5999
-     * only returns the cap restrictions array in that context (ie, the array
6000
-     * at that key)
6001
-     *
6002
-     * @param string $context
6003
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6004
-     * @throws EE_Error
6005
-     */
6006
-    public function cap_restrictions($context = EEM_Base::caps_read)
6007
-    {
6008
-        EEM_Base::verify_is_valid_cap_context($context);
6009
-        //check if we ought to run the restriction generator first
6010
-        if (
6011
-            isset($this->_cap_restriction_generators[$context])
6012
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6013
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6014
-        ) {
6015
-            $this->_cap_restrictions[$context] = array_merge(
6016
-                $this->_cap_restrictions[$context],
6017
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
6018
-            );
6019
-        }
6020
-        //and make sure we've finalized the construction of each restriction
6021
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6022
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6023
-                $where_conditions_obj->_finalize_construct($this);
6024
-            }
6025
-        }
6026
-        return $this->_cap_restrictions[$context];
6027
-    }
6028
-
6029
-
6030
-
6031
-    /**
6032
-     * Indicating whether or not this model thinks its a wp core model
6033
-     *
6034
-     * @return boolean
6035
-     */
6036
-    public function is_wp_core_model()
6037
-    {
6038
-        return $this->_wp_core_model;
6039
-    }
6040
-
6041
-
6042
-
6043
-    /**
6044
-     * Gets all the caps that are missing which impose a restriction on
6045
-     * queries made in this context
6046
-     *
6047
-     * @param string $context one of EEM_Base::caps_ constants
6048
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6049
-     * @throws EE_Error
6050
-     */
6051
-    public function caps_missing($context = EEM_Base::caps_read)
6052
-    {
6053
-        $missing_caps = array();
6054
-        $cap_restrictions = $this->cap_restrictions($context);
6055
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6056
-            if (! EE_Capabilities::instance()
6057
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6058
-            ) {
6059
-                $missing_caps[$cap] = $restriction_if_no_cap;
6060
-            }
6061
-        }
6062
-        return $missing_caps;
6063
-    }
6064
-
6065
-
6066
-
6067
-    /**
6068
-     * Gets the mapping from capability contexts to action strings used in capability names
6069
-     *
6070
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6071
-     * one of 'read', 'edit', or 'delete'
6072
-     */
6073
-    public function cap_contexts_to_cap_action_map()
6074
-    {
6075
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
6076
-            $this);
6077
-    }
6078
-
6079
-
6080
-
6081
-    /**
6082
-     * Gets the action string for the specified capability context
6083
-     *
6084
-     * @param string $context
6085
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6086
-     * @throws EE_Error
6087
-     */
6088
-    public function cap_action_for_context($context)
6089
-    {
6090
-        $mapping = $this->cap_contexts_to_cap_action_map();
6091
-        if (isset($mapping[$context])) {
6092
-            return $mapping[$context];
6093
-        }
6094
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6095
-            return $action;
6096
-        }
6097
-        throw new EE_Error(
6098
-            sprintf(
6099
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6100
-                $context,
6101
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6102
-            )
6103
-        );
6104
-    }
6105
-
6106
-
6107
-
6108
-    /**
6109
-     * Returns all the capability contexts which are valid when querying models
6110
-     *
6111
-     * @return array
6112
-     */
6113
-    public static function valid_cap_contexts()
6114
-    {
6115
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6116
-            self::caps_read,
6117
-            self::caps_read_admin,
6118
-            self::caps_edit,
6119
-            self::caps_delete,
6120
-        ));
6121
-    }
6122
-
6123
-
6124
-
6125
-    /**
6126
-     * Returns all valid options for 'default_where_conditions'
6127
-     *
6128
-     * @return array
6129
-     */
6130
-    public static function valid_default_where_conditions()
6131
-    {
6132
-        return array(
6133
-            EEM_Base::default_where_conditions_all,
6134
-            EEM_Base::default_where_conditions_this_only,
6135
-            EEM_Base::default_where_conditions_others_only,
6136
-            EEM_Base::default_where_conditions_minimum_all,
6137
-            EEM_Base::default_where_conditions_minimum_others,
6138
-            EEM_Base::default_where_conditions_none
6139
-        );
6140
-    }
6141
-
6142
-    // public static function default_where_conditions_full
6143
-    /**
6144
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6145
-     *
6146
-     * @param string $context
6147
-     * @return bool
6148
-     * @throws EE_Error
6149
-     */
6150
-    static public function verify_is_valid_cap_context($context)
6151
-    {
6152
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6153
-        if (in_array($context, $valid_cap_contexts)) {
6154
-            return true;
6155
-        }
6156
-        throw new EE_Error(
6157
-            sprintf(
6158
-                __(
6159
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6160
-                    'event_espresso'
6161
-                ),
6162
-                $context,
6163
-                'EEM_Base',
6164
-                implode(',', $valid_cap_contexts)
6165
-            )
6166
-        );
6167
-    }
6168
-
6169
-
6170
-
6171
-    /**
6172
-     * Clears all the models field caches. This is only useful when a sub-class
6173
-     * might have added a field or something and these caches might be invalidated
6174
-     */
6175
-    protected function _invalidate_field_caches()
6176
-    {
6177
-        $this->_cache_foreign_key_to_fields = array();
6178
-        $this->_cached_fields = null;
6179
-        $this->_cached_fields_non_db_only = null;
6180
-    }
6181
-
6182
-
6183
-
6184
-    /**
6185
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6186
-     * (eg "and", "or", "not").
6187
-     *
6188
-     * @return array
6189
-     */
6190
-    public function logic_query_param_keys()
6191
-    {
6192
-        return $this->_logic_query_param_keys;
6193
-    }
6194
-
6195
-
6196
-
6197
-    /**
6198
-     * Determines whether or not the where query param array key is for a logic query param.
6199
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6200
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6201
-     *
6202
-     * @param $query_param_key
6203
-     * @return bool
6204
-     */
6205
-    public function is_logic_query_param_key($query_param_key)
6206
-    {
6207
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6208
-            if ($query_param_key === $logic_query_param_key
6209
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6210
-            ) {
6211
-                return true;
6212
-            }
6213
-        }
6214
-        return false;
6215
-    }
3774
+		}
3775
+		return $null_friendly_where_conditions;
3776
+	}
3777
+
3778
+
3779
+
3780
+	/**
3781
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3782
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3783
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3784
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3785
+	 *
3786
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3787
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3788
+	 */
3789
+	private function _get_default_where_conditions($model_relation_path = null)
3790
+	{
3791
+		if ($this->_ignore_where_strategy) {
3792
+			return array();
3793
+		}
3794
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3795
+	}
3796
+
3797
+
3798
+
3799
+	/**
3800
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3801
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3802
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3803
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3804
+	 * Similar to _get_default_where_conditions
3805
+	 *
3806
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3807
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3808
+	 */
3809
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3810
+	{
3811
+		if ($this->_ignore_where_strategy) {
3812
+			return array();
3813
+		}
3814
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3815
+	}
3816
+
3817
+
3818
+
3819
+	/**
3820
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3821
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3822
+	 *
3823
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3824
+	 * @return string
3825
+	 * @throws EE_Error
3826
+	 */
3827
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3828
+	{
3829
+		$selects = $this->_get_columns_to_select_for_this_model();
3830
+		foreach (
3831
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3832
+			$name_of_other_model_included
3833
+		) {
3834
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3835
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3836
+			foreach ($other_model_selects as $key => $value) {
3837
+				$selects[] = $value;
3838
+			}
3839
+		}
3840
+		return implode(", ", $selects);
3841
+	}
3842
+
3843
+
3844
+
3845
+	/**
3846
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3847
+	 * So that's going to be the columns for all the fields on the model
3848
+	 *
3849
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3850
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3851
+	 */
3852
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3853
+	{
3854
+		$fields = $this->field_settings();
3855
+		$selects = array();
3856
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3857
+			$this->get_this_model_name());
3858
+		foreach ($fields as $field_obj) {
3859
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3860
+						 . $field_obj->get_table_alias()
3861
+						 . "."
3862
+						 . $field_obj->get_table_column()
3863
+						 . " AS '"
3864
+						 . $table_alias_with_model_relation_chain_prefix
3865
+						 . $field_obj->get_table_alias()
3866
+						 . "."
3867
+						 . $field_obj->get_table_column()
3868
+						 . "'";
3869
+		}
3870
+		//make sure we are also getting the PKs of each table
3871
+		$tables = $this->get_tables();
3872
+		if (count($tables) > 1) {
3873
+			foreach ($tables as $table_obj) {
3874
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3875
+									   . $table_obj->get_fully_qualified_pk_column();
3876
+				if (! in_array($qualified_pk_column, $selects)) {
3877
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3878
+				}
3879
+			}
3880
+		}
3881
+		return $selects;
3882
+	}
3883
+
3884
+
3885
+
3886
+	/**
3887
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3888
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3889
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3890
+	 * SQL for joining, and the data types
3891
+	 *
3892
+	 * @param null|string                 $original_query_param
3893
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3894
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3895
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3896
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3897
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3898
+	 *                                                          or 'Registration's
3899
+	 * @param string                      $original_query_param what it originally was (eg
3900
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3901
+	 *                                                          matches $query_param
3902
+	 * @throws EE_Error
3903
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3904
+	 */
3905
+	private function _extract_related_model_info_from_query_param(
3906
+		$query_param,
3907
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3908
+		$query_param_type,
3909
+		$original_query_param = null
3910
+	) {
3911
+		if ($original_query_param === null) {
3912
+			$original_query_param = $query_param;
3913
+		}
3914
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3915
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3916
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3917
+		$allow_fields = in_array(
3918
+			$query_param_type,
3919
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3920
+			true
3921
+		);
3922
+		//check to see if we have a field on this model
3923
+		$this_model_fields = $this->field_settings(true);
3924
+		if (array_key_exists($query_param, $this_model_fields)) {
3925
+			if ($allow_fields) {
3926
+				return;
3927
+			}
3928
+			throw new EE_Error(
3929
+				sprintf(
3930
+					__(
3931
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3932
+						"event_espresso"
3933
+					),
3934
+					$query_param, get_class($this), $query_param_type, $original_query_param
3935
+				)
3936
+			);
3937
+		}
3938
+		//check if this is a special logic query param
3939
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3940
+			if ($allow_logic_query_params) {
3941
+				return;
3942
+			}
3943
+			throw new EE_Error(
3944
+				sprintf(
3945
+					__(
3946
+						'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',
3947
+						'event_espresso'
3948
+					),
3949
+					implode('", "', $this->_logic_query_param_keys),
3950
+					$query_param,
3951
+					get_class($this),
3952
+					'<br />',
3953
+					"\t"
3954
+					. ' $passed_in_query_info = <pre>'
3955
+					. print_r($passed_in_query_info, true)
3956
+					. '</pre>'
3957
+					. "\n\t"
3958
+					. ' $query_param_type = '
3959
+					. $query_param_type
3960
+					. "\n\t"
3961
+					. ' $original_query_param = '
3962
+					. $original_query_param
3963
+				)
3964
+			);
3965
+		}
3966
+		//check if it's a custom selection
3967
+		if ($this->_custom_selections instanceof CustomSelects
3968
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
3969
+		) {
3970
+			return;
3971
+		}
3972
+		//check if has a model name at the beginning
3973
+		//and
3974
+		//check if it's a field on a related model
3975
+		if ($this->extractJoinModelFromQueryParams(
3976
+			$passed_in_query_info,
3977
+			$query_param,
3978
+			$original_query_param,
3979
+			$query_param_type
3980
+		)) {
3981
+			return;
3982
+		}
3983
+
3984
+		//ok so $query_param didn't start with a model name
3985
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3986
+		//it's wack, that's what it is
3987
+		throw new EE_Error(
3988
+			sprintf(
3989
+				esc_html__(
3990
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3991
+					"event_espresso"
3992
+				),
3993
+				$query_param,
3994
+				get_class($this),
3995
+				$query_param_type,
3996
+				$original_query_param
3997
+			)
3998
+		);
3999
+	}
4000
+
4001
+
4002
+	/**
4003
+	 * Extracts any possible join model information from the provided possible_join_string.
4004
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4005
+	 * parts that should be added to the query.
4006
+	 *
4007
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4008
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4009
+	 * @param null|string                 $original_query_param
4010
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4011
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4012
+	 * @return bool  returns true if a join was added and false if not.
4013
+	 * @throws EE_Error
4014
+	 */
4015
+	private function extractJoinModelFromQueryParams(
4016
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4017
+		$possible_join_string,
4018
+		$original_query_param,
4019
+		$query_parameter_type
4020
+	) {
4021
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4022
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4023
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4024
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4025
+				if ($possible_join_string === '') {
4026
+					//nothing left to $query_param
4027
+					//we should actually end in a field name, not a model like this!
4028
+					throw new EE_Error(
4029
+						sprintf(
4030
+							esc_html__(
4031
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4032
+								"event_espresso"
4033
+							),
4034
+							$possible_join_string,
4035
+							$query_parameter_type,
4036
+							get_class($this),
4037
+							$valid_related_model_name
4038
+						)
4039
+					);
4040
+				}
4041
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4042
+				$related_model_obj->_extract_related_model_info_from_query_param(
4043
+					$possible_join_string,
4044
+					$query_info_carrier,
4045
+					$query_parameter_type,
4046
+					$original_query_param
4047
+				);
4048
+				return true;
4049
+			}
4050
+			if ($possible_join_string === $valid_related_model_name) {
4051
+				$this->_add_join_to_model(
4052
+					$valid_related_model_name,
4053
+					$query_info_carrier,
4054
+					$original_query_param
4055
+				);
4056
+				return true;
4057
+			}
4058
+		}
4059
+		return false;
4060
+	}
4061
+
4062
+
4063
+	/**
4064
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4065
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4066
+	 * @throws EE_Error
4067
+	 */
4068
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4069
+	{
4070
+		if ($this->_custom_selections instanceof CustomSelects
4071
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4072
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4073
+			)
4074
+		) {
4075
+			$original_selects = $this->_custom_selections->originalSelects();
4076
+			foreach ($original_selects as $alias => $select_configuration) {
4077
+				$this->extractJoinModelFromQueryParams(
4078
+					$query_info_carrier,
4079
+					$select_configuration[0],
4080
+					$select_configuration[0],
4081
+					'custom_selects'
4082
+				);
4083
+			}
4084
+		}
4085
+	}
4086
+
4087
+
4088
+
4089
+	/**
4090
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4091
+	 * and store it on $passed_in_query_info
4092
+	 *
4093
+	 * @param string                      $model_name
4094
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4095
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4096
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4097
+	 *                                                          and are adding a join to 'Payment' with the original
4098
+	 *                                                          query param key
4099
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4100
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4101
+	 *                                                          Payment wants to add default query params so that it
4102
+	 *                                                          will know what models to prepend onto its default query
4103
+	 *                                                          params or in case it wants to rename tables (in case
4104
+	 *                                                          there are multiple joins to the same table)
4105
+	 * @return void
4106
+	 * @throws EE_Error
4107
+	 */
4108
+	private function _add_join_to_model(
4109
+		$model_name,
4110
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4111
+		$original_query_param
4112
+	) {
4113
+		$relation_obj = $this->related_settings_for($model_name);
4114
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4115
+		//check if the relation is HABTM, because then we're essentially doing two joins
4116
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
4117
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4118
+			$join_model_obj = $relation_obj->get_join_model();
4119
+			//replace the model specified with the join model for this relation chain, whi
4120
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4121
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
4122
+			$passed_in_query_info->merge(
4123
+				new EE_Model_Query_Info_Carrier(
4124
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4125
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4126
+				)
4127
+			);
4128
+		}
4129
+		//now just join to the other table pointed to by the relation object, and add its data types
4130
+		$passed_in_query_info->merge(
4131
+			new EE_Model_Query_Info_Carrier(
4132
+				array($model_relation_chain => $model_name),
4133
+				$relation_obj->get_join_statement($model_relation_chain)
4134
+			)
4135
+		);
4136
+	}
4137
+
4138
+
4139
+
4140
+	/**
4141
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4142
+	 *
4143
+	 * @param array $where_params like EEM_Base::get_all
4144
+	 * @return string of SQL
4145
+	 * @throws EE_Error
4146
+	 */
4147
+	private function _construct_where_clause($where_params)
4148
+	{
4149
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4150
+		if ($SQL) {
4151
+			return " WHERE " . $SQL;
4152
+		}
4153
+		return '';
4154
+	}
4155
+
4156
+
4157
+
4158
+	/**
4159
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4160
+	 * and should be passed HAVING parameters, not WHERE parameters
4161
+	 *
4162
+	 * @param array $having_params
4163
+	 * @return string
4164
+	 * @throws EE_Error
4165
+	 */
4166
+	private function _construct_having_clause($having_params)
4167
+	{
4168
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4169
+		if ($SQL) {
4170
+			return " HAVING " . $SQL;
4171
+		}
4172
+		return '';
4173
+	}
4174
+
4175
+
4176
+	/**
4177
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4178
+	 * Event_Meta.meta_value = 'foo'))"
4179
+	 *
4180
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4181
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4182
+	 * @throws EE_Error
4183
+	 * @return string of SQL
4184
+	 */
4185
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4186
+	{
4187
+		$where_clauses = array();
4188
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4189
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4190
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4191
+				switch ($query_param) {
4192
+					case 'not':
4193
+					case 'NOT':
4194
+						$where_clauses[] = "! ("
4195
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4196
+								$glue)
4197
+										   . ")";
4198
+						break;
4199
+					case 'and':
4200
+					case 'AND':
4201
+						$where_clauses[] = " ("
4202
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4203
+								' AND ')
4204
+										   . ")";
4205
+						break;
4206
+					case 'or':
4207
+					case 'OR':
4208
+						$where_clauses[] = " ("
4209
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4210
+								' OR ')
4211
+										   . ")";
4212
+						break;
4213
+				}
4214
+			} else {
4215
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4216
+				//if it's not a normal field, maybe it's a custom selection?
4217
+				if (! $field_obj) {
4218
+					if ($this->_custom_selections instanceof CustomSelects) {
4219
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4220
+					} else {
4221
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4222
+							"event_espresso"), $query_param));
4223
+					}
4224
+				}
4225
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4226
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4227
+			}
4228
+		}
4229
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4230
+	}
4231
+
4232
+
4233
+
4234
+	/**
4235
+	 * Takes the input parameter and extract the table name (alias) and column name
4236
+	 *
4237
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4238
+	 * @throws EE_Error
4239
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4240
+	 */
4241
+	private function _deduce_column_name_from_query_param($query_param)
4242
+	{
4243
+		$field = $this->_deduce_field_from_query_param($query_param);
4244
+		if ($field) {
4245
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4246
+				$query_param);
4247
+			return $table_alias_prefix . $field->get_qualified_column();
4248
+		}
4249
+		if ($this->_custom_selections instanceof CustomSelects
4250
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4251
+		) {
4252
+			//maybe it's custom selection item?
4253
+			//if so, just use it as the "column name"
4254
+			return $query_param;
4255
+		}
4256
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4257
+			? implode(',', $this->_custom_selections->columnAliases())
4258
+			: '';
4259
+		throw new EE_Error(
4260
+			sprintf(
4261
+				__(
4262
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4263
+					"event_espresso"
4264
+				), $query_param, $custom_select_aliases
4265
+			)
4266
+		);
4267
+	}
4268
+
4269
+
4270
+
4271
+	/**
4272
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4273
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4274
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4275
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4276
+	 *
4277
+	 * @param string $condition_query_param_key
4278
+	 * @return string
4279
+	 */
4280
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4281
+	{
4282
+		$pos_of_star = strpos($condition_query_param_key, '*');
4283
+		if ($pos_of_star === false) {
4284
+			return $condition_query_param_key;
4285
+		}
4286
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4287
+		return $condition_query_param_sans_star;
4288
+	}
4289
+
4290
+
4291
+
4292
+	/**
4293
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4294
+	 *
4295
+	 * @param                            mixed      array | string    $op_and_value
4296
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4297
+	 * @throws EE_Error
4298
+	 * @return string
4299
+	 */
4300
+	private function _construct_op_and_value($op_and_value, $field_obj)
4301
+	{
4302
+		if (is_array($op_and_value)) {
4303
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4304
+			if (! $operator) {
4305
+				$php_array_like_string = array();
4306
+				foreach ($op_and_value as $key => $value) {
4307
+					$php_array_like_string[] = "$key=>$value";
4308
+				}
4309
+				throw new EE_Error(
4310
+					sprintf(
4311
+						__(
4312
+							"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))",
4313
+							"event_espresso"
4314
+						),
4315
+						implode(",", $php_array_like_string)
4316
+					)
4317
+				);
4318
+			}
4319
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4320
+		} else {
4321
+			$operator = '=';
4322
+			$value = $op_and_value;
4323
+		}
4324
+		//check to see if the value is actually another field
4325
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4326
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4327
+		}
4328
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4329
+			//in this case, the value should be an array, or at least a comma-separated list
4330
+			//it will need to handle a little differently
4331
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4332
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4333
+			return $operator . SP . $cleaned_value;
4334
+		}
4335
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4336
+			//the value should be an array with count of two.
4337
+			if (count($value) !== 2) {
4338
+				throw new EE_Error(
4339
+					sprintf(
4340
+						__(
4341
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4342
+							'event_espresso'
4343
+						),
4344
+						"BETWEEN"
4345
+					)
4346
+				);
4347
+			}
4348
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4349
+			return $operator . SP . $cleaned_value;
4350
+		}
4351
+		if (in_array($operator, $this->valid_null_style_operators())) {
4352
+			if ($value !== null) {
4353
+				throw new EE_Error(
4354
+					sprintf(
4355
+						__(
4356
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4357
+							"event_espresso"
4358
+						),
4359
+						$value,
4360
+						$operator
4361
+					)
4362
+				);
4363
+			}
4364
+			return $operator;
4365
+		}
4366
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4367
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4368
+			//remove other junk. So just treat it as a string.
4369
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4370
+		}
4371
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4372
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4373
+		}
4374
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4375
+			throw new EE_Error(
4376
+				sprintf(
4377
+					__(
4378
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4379
+						'event_espresso'
4380
+					),
4381
+					$operator,
4382
+					$operator
4383
+				)
4384
+			);
4385
+		}
4386
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4387
+			throw new EE_Error(
4388
+				sprintf(
4389
+					__(
4390
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4391
+						'event_espresso'
4392
+					),
4393
+					$operator,
4394
+					$operator
4395
+				)
4396
+			);
4397
+		}
4398
+		throw new EE_Error(
4399
+			sprintf(
4400
+				__(
4401
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4402
+					"event_espresso"
4403
+				),
4404
+				http_build_query($op_and_value)
4405
+			)
4406
+		);
4407
+	}
4408
+
4409
+
4410
+
4411
+	/**
4412
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4413
+	 *
4414
+	 * @param array                      $values
4415
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4416
+	 *                                              '%s'
4417
+	 * @return string
4418
+	 * @throws EE_Error
4419
+	 */
4420
+	public function _construct_between_value($values, $field_obj)
4421
+	{
4422
+		$cleaned_values = array();
4423
+		foreach ($values as $value) {
4424
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4425
+		}
4426
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4427
+	}
4428
+
4429
+
4430
+
4431
+	/**
4432
+	 * Takes an array or a comma-separated list of $values and cleans them
4433
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4434
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4435
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4436
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4437
+	 *
4438
+	 * @param mixed                      $values    array or comma-separated string
4439
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4440
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4441
+	 * @throws EE_Error
4442
+	 */
4443
+	public function _construct_in_value($values, $field_obj)
4444
+	{
4445
+		//check if the value is a CSV list
4446
+		if (is_string($values)) {
4447
+			//in which case, turn it into an array
4448
+			$values = explode(",", $values);
4449
+		}
4450
+		$cleaned_values = array();
4451
+		foreach ($values as $value) {
4452
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4453
+		}
4454
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4455
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4456
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4457
+		if (empty($cleaned_values)) {
4458
+			$all_fields = $this->field_settings();
4459
+			$a_field = array_shift($all_fields);
4460
+			$main_table = $this->_get_main_table();
4461
+			$cleaned_values[] = "SELECT "
4462
+								. $a_field->get_table_column()
4463
+								. " FROM "
4464
+								. $main_table->get_table_name()
4465
+								. " WHERE FALSE";
4466
+		}
4467
+		return "(" . implode(",", $cleaned_values) . ")";
4468
+	}
4469
+
4470
+
4471
+
4472
+	/**
4473
+	 * @param mixed                      $value
4474
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4475
+	 * @throws EE_Error
4476
+	 * @return false|null|string
4477
+	 */
4478
+	private function _wpdb_prepare_using_field($value, $field_obj)
4479
+	{
4480
+		/** @type WPDB $wpdb */
4481
+		global $wpdb;
4482
+		if ($field_obj instanceof EE_Model_Field_Base) {
4483
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4484
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4485
+		} //$field_obj should really just be a data type
4486
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4487
+			throw new EE_Error(
4488
+				sprintf(
4489
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4490
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)
4491
+				)
4492
+			);
4493
+		}
4494
+		return $wpdb->prepare($field_obj, $value);
4495
+	}
4496
+
4497
+
4498
+
4499
+	/**
4500
+	 * Takes the input parameter and finds the model field that it indicates.
4501
+	 *
4502
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4503
+	 * @throws EE_Error
4504
+	 * @return EE_Model_Field_Base
4505
+	 */
4506
+	protected function _deduce_field_from_query_param($query_param_name)
4507
+	{
4508
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4509
+		//which will help us find the database table and column
4510
+		$query_param_parts = explode(".", $query_param_name);
4511
+		if (empty($query_param_parts)) {
4512
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4513
+				'event_espresso'), $query_param_name));
4514
+		}
4515
+		$number_of_parts = count($query_param_parts);
4516
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4517
+		if ($number_of_parts === 1) {
4518
+			$field_name = $last_query_param_part;
4519
+			$model_obj = $this;
4520
+		} else {// $number_of_parts >= 2
4521
+			//the last part is the column name, and there are only 2parts. therefore...
4522
+			$field_name = $last_query_param_part;
4523
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4524
+		}
4525
+		try {
4526
+			return $model_obj->field_settings_for($field_name);
4527
+		} catch (EE_Error $e) {
4528
+			return null;
4529
+		}
4530
+	}
4531
+
4532
+
4533
+
4534
+	/**
4535
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4536
+	 * alias and column which corresponds to it
4537
+	 *
4538
+	 * @param string $field_name
4539
+	 * @throws EE_Error
4540
+	 * @return string
4541
+	 */
4542
+	public function _get_qualified_column_for_field($field_name)
4543
+	{
4544
+		$all_fields = $this->field_settings();
4545
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4546
+		if ($field) {
4547
+			return $field->get_qualified_column();
4548
+		}
4549
+		throw new EE_Error(
4550
+			sprintf(
4551
+				__(
4552
+					"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.",
4553
+					'event_espresso'
4554
+				), $field_name, get_class($this)
4555
+			)
4556
+		);
4557
+	}
4558
+
4559
+
4560
+
4561
+	/**
4562
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4563
+	 * Example usage:
4564
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4565
+	 *      array(),
4566
+	 *      ARRAY_A,
4567
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4568
+	 *  );
4569
+	 * is equivalent to
4570
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4571
+	 * and
4572
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4573
+	 *      array(
4574
+	 *          array(
4575
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4576
+	 *          ),
4577
+	 *          ARRAY_A,
4578
+	 *          implode(
4579
+	 *              ', ',
4580
+	 *              array_merge(
4581
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4582
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4583
+	 *              )
4584
+	 *          )
4585
+	 *      )
4586
+	 *  );
4587
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4588
+	 *
4589
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4590
+	 *                                            and the one whose fields you are selecting for example: when querying
4591
+	 *                                            tickets model and selecting fields from the tickets model you would
4592
+	 *                                            leave this parameter empty, because no models are needed to join
4593
+	 *                                            between the queried model and the selected one. Likewise when
4594
+	 *                                            querying the datetime model and selecting fields from the tickets
4595
+	 *                                            model, it would also be left empty, because there is a direct
4596
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4597
+	 *                                            them together. However, when querying from the event model and
4598
+	 *                                            selecting fields from the ticket model, you should provide the string
4599
+	 *                                            'Datetime', indicating that the event model must first join to the
4600
+	 *                                            datetime model in order to find its relation to ticket model.
4601
+	 *                                            Also, when querying from the venue model and selecting fields from
4602
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4603
+	 *                                            indicating you need to join the venue model to the event model,
4604
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4605
+	 *                                            This string is used to deduce the prefix that gets added onto the
4606
+	 *                                            models' tables qualified columns
4607
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4608
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4609
+	 *                                            qualified column names
4610
+	 * @return array|string
4611
+	 */
4612
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4613
+	{
4614
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4615
+		$qualified_columns = array();
4616
+		foreach ($this->field_settings() as $field_name => $field) {
4617
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4618
+		}
4619
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4620
+	}
4621
+
4622
+
4623
+
4624
+	/**
4625
+	 * constructs the select use on special limit joins
4626
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4627
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4628
+	 * (as that is typically where the limits would be set).
4629
+	 *
4630
+	 * @param  string       $table_alias The table the select is being built for
4631
+	 * @param  mixed|string $limit       The limit for this select
4632
+	 * @return string                The final select join element for the query.
4633
+	 */
4634
+	public function _construct_limit_join_select($table_alias, $limit)
4635
+	{
4636
+		$SQL = '';
4637
+		foreach ($this->_tables as $table_obj) {
4638
+			if ($table_obj instanceof EE_Primary_Table) {
4639
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4640
+					? $table_obj->get_select_join_limit($limit)
4641
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4642
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4643
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4644
+					? $table_obj->get_select_join_limit_join($limit)
4645
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4646
+			}
4647
+		}
4648
+		return $SQL;
4649
+	}
4650
+
4651
+
4652
+
4653
+	/**
4654
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4655
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4656
+	 *
4657
+	 * @return string SQL
4658
+	 * @throws EE_Error
4659
+	 */
4660
+	public function _construct_internal_join()
4661
+	{
4662
+		$SQL = $this->_get_main_table()->get_table_sql();
4663
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4664
+		return $SQL;
4665
+	}
4666
+
4667
+
4668
+
4669
+	/**
4670
+	 * Constructs the SQL for joining all the tables on this model.
4671
+	 * Normally $alias should be the primary table's alias, but in cases where
4672
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4673
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4674
+	 * alias, this will construct SQL like:
4675
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4676
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4677
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4678
+	 *
4679
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4680
+	 * @return string
4681
+	 */
4682
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4683
+	{
4684
+		$SQL = '';
4685
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4686
+		foreach ($this->_tables as $table_obj) {
4687
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4688
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4689
+					//so we're joining to this table, meaning the table is already in
4690
+					//the FROM statement, BUT the primary table isn't. So we want
4691
+					//to add the inverse join sql
4692
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4693
+				} else {
4694
+					//just add a regular JOIN to this table from the primary table
4695
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4696
+				}
4697
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4698
+		}
4699
+		return $SQL;
4700
+	}
4701
+
4702
+
4703
+
4704
+	/**
4705
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4706
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4707
+	 * their data type (eg, '%s', '%d', etc)
4708
+	 *
4709
+	 * @return array
4710
+	 */
4711
+	public function _get_data_types()
4712
+	{
4713
+		$data_types = array();
4714
+		foreach ($this->field_settings() as $field_obj) {
4715
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4716
+			/** @var $field_obj EE_Model_Field_Base */
4717
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4718
+		}
4719
+		return $data_types;
4720
+	}
4721
+
4722
+
4723
+
4724
+	/**
4725
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4726
+	 *
4727
+	 * @param string $model_name
4728
+	 * @throws EE_Error
4729
+	 * @return EEM_Base
4730
+	 */
4731
+	public function get_related_model_obj($model_name)
4732
+	{
4733
+		$model_classname = "EEM_" . $model_name;
4734
+		if (! class_exists($model_classname)) {
4735
+			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",
4736
+				'event_espresso'), $model_name, $model_classname));
4737
+		}
4738
+		return call_user_func($model_classname . "::instance");
4739
+	}
4740
+
4741
+
4742
+
4743
+	/**
4744
+	 * Returns the array of EE_ModelRelations for this model.
4745
+	 *
4746
+	 * @return EE_Model_Relation_Base[]
4747
+	 */
4748
+	public function relation_settings()
4749
+	{
4750
+		return $this->_model_relations;
4751
+	}
4752
+
4753
+
4754
+
4755
+	/**
4756
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4757
+	 * because without THOSE models, this model probably doesn't have much purpose.
4758
+	 * (Eg, without an event, datetimes have little purpose.)
4759
+	 *
4760
+	 * @return EE_Belongs_To_Relation[]
4761
+	 */
4762
+	public function belongs_to_relations()
4763
+	{
4764
+		$belongs_to_relations = array();
4765
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4766
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4767
+				$belongs_to_relations[$model_name] = $relation_obj;
4768
+			}
4769
+		}
4770
+		return $belongs_to_relations;
4771
+	}
4772
+
4773
+
4774
+
4775
+	/**
4776
+	 * Returns the specified EE_Model_Relation, or throws an exception
4777
+	 *
4778
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4779
+	 * @throws EE_Error
4780
+	 * @return EE_Model_Relation_Base
4781
+	 */
4782
+	public function related_settings_for($relation_name)
4783
+	{
4784
+		$relatedModels = $this->relation_settings();
4785
+		if (! array_key_exists($relation_name, $relatedModels)) {
4786
+			throw new EE_Error(
4787
+				sprintf(
4788
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4789
+						'event_espresso'),
4790
+					$relation_name,
4791
+					$this->_get_class_name(),
4792
+					implode(', ', array_keys($relatedModels))
4793
+				)
4794
+			);
4795
+		}
4796
+		return $relatedModels[$relation_name];
4797
+	}
4798
+
4799
+
4800
+
4801
+	/**
4802
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4803
+	 * fields
4804
+	 *
4805
+	 * @param string $fieldName
4806
+	 * @param boolean $include_db_only_fields
4807
+	 * @throws EE_Error
4808
+	 * @return EE_Model_Field_Base
4809
+	 */
4810
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4811
+	{
4812
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4813
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4814
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4815
+				get_class($this)));
4816
+		}
4817
+		return $fieldSettings[$fieldName];
4818
+	}
4819
+
4820
+
4821
+
4822
+	/**
4823
+	 * Checks if this field exists on this model
4824
+	 *
4825
+	 * @param string $fieldName a key in the model's _field_settings array
4826
+	 * @return boolean
4827
+	 */
4828
+	public function has_field($fieldName)
4829
+	{
4830
+		$fieldSettings = $this->field_settings(true);
4831
+		if (isset($fieldSettings[$fieldName])) {
4832
+			return true;
4833
+		}
4834
+		return false;
4835
+	}
4836
+
4837
+
4838
+
4839
+	/**
4840
+	 * Returns whether or not this model has a relation to the specified model
4841
+	 *
4842
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4843
+	 * @return boolean
4844
+	 */
4845
+	public function has_relation($relation_name)
4846
+	{
4847
+		$relations = $this->relation_settings();
4848
+		if (isset($relations[$relation_name])) {
4849
+			return true;
4850
+		}
4851
+		return false;
4852
+	}
4853
+
4854
+
4855
+
4856
+	/**
4857
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4858
+	 * Eg, on EE_Answer that would be ANS_ID field object
4859
+	 *
4860
+	 * @param $field_obj
4861
+	 * @return boolean
4862
+	 */
4863
+	public function is_primary_key_field($field_obj)
4864
+	{
4865
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4866
+	}
4867
+
4868
+
4869
+
4870
+	/**
4871
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4872
+	 * Eg, on EE_Answer that would be ANS_ID field object
4873
+	 *
4874
+	 * @return EE_Model_Field_Base
4875
+	 * @throws EE_Error
4876
+	 */
4877
+	public function get_primary_key_field()
4878
+	{
4879
+		if ($this->_primary_key_field === null) {
4880
+			foreach ($this->field_settings(true) as $field_obj) {
4881
+				if ($this->is_primary_key_field($field_obj)) {
4882
+					$this->_primary_key_field = $field_obj;
4883
+					break;
4884
+				}
4885
+			}
4886
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4887
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4888
+					get_class($this)));
4889
+			}
4890
+		}
4891
+		return $this->_primary_key_field;
4892
+	}
4893
+
4894
+
4895
+
4896
+	/**
4897
+	 * Returns whether or not not there is a primary key on this model.
4898
+	 * Internally does some caching.
4899
+	 *
4900
+	 * @return boolean
4901
+	 */
4902
+	public function has_primary_key_field()
4903
+	{
4904
+		if ($this->_has_primary_key_field === null) {
4905
+			try {
4906
+				$this->get_primary_key_field();
4907
+				$this->_has_primary_key_field = true;
4908
+			} catch (EE_Error $e) {
4909
+				$this->_has_primary_key_field = false;
4910
+			}
4911
+		}
4912
+		return $this->_has_primary_key_field;
4913
+	}
4914
+
4915
+
4916
+
4917
+	/**
4918
+	 * Finds the first field of type $field_class_name.
4919
+	 *
4920
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4921
+	 *                                 EE_Foreign_Key_Field, etc
4922
+	 * @return EE_Model_Field_Base or null if none is found
4923
+	 */
4924
+	public function get_a_field_of_type($field_class_name)
4925
+	{
4926
+		foreach ($this->field_settings() as $field) {
4927
+			if ($field instanceof $field_class_name) {
4928
+				return $field;
4929
+			}
4930
+		}
4931
+		return null;
4932
+	}
4933
+
4934
+
4935
+
4936
+	/**
4937
+	 * Gets a foreign key field pointing to model.
4938
+	 *
4939
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4940
+	 * @return EE_Foreign_Key_Field_Base
4941
+	 * @throws EE_Error
4942
+	 */
4943
+	public function get_foreign_key_to($model_name)
4944
+	{
4945
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4946
+			foreach ($this->field_settings() as $field) {
4947
+				if (
4948
+					$field instanceof EE_Foreign_Key_Field_Base
4949
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4950
+				) {
4951
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4952
+					break;
4953
+				}
4954
+			}
4955
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4956
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4957
+					'event_espresso'), $model_name, get_class($this)));
4958
+			}
4959
+		}
4960
+		return $this->_cache_foreign_key_to_fields[$model_name];
4961
+	}
4962
+
4963
+
4964
+
4965
+	/**
4966
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4967
+	 *
4968
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4969
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4970
+	 *                            Either one works
4971
+	 * @return string
4972
+	 */
4973
+	public function get_table_for_alias($table_alias)
4974
+	{
4975
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4976
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4977
+	}
4978
+
4979
+
4980
+
4981
+	/**
4982
+	 * Returns a flat array of all field son this model, instead of organizing them
4983
+	 * by table_alias as they are in the constructor.
4984
+	 *
4985
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4986
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4987
+	 */
4988
+	public function field_settings($include_db_only_fields = false)
4989
+	{
4990
+		if ($include_db_only_fields) {
4991
+			if ($this->_cached_fields === null) {
4992
+				$this->_cached_fields = array();
4993
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4994
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4995
+						$this->_cached_fields[$field_name] = $field_obj;
4996
+					}
4997
+				}
4998
+			}
4999
+			return $this->_cached_fields;
5000
+		}
5001
+		if ($this->_cached_fields_non_db_only === null) {
5002
+			$this->_cached_fields_non_db_only = array();
5003
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5004
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5005
+					/** @var $field_obj EE_Model_Field_Base */
5006
+					if (! $field_obj->is_db_only_field()) {
5007
+						$this->_cached_fields_non_db_only[$field_name] = $field_obj;
5008
+					}
5009
+				}
5010
+			}
5011
+		}
5012
+		return $this->_cached_fields_non_db_only;
5013
+	}
5014
+
5015
+
5016
+
5017
+	/**
5018
+	 *        cycle though array of attendees and create objects out of each item
5019
+	 *
5020
+	 * @access        private
5021
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5022
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5023
+	 *                           numerically indexed)
5024
+	 * @throws EE_Error
5025
+	 */
5026
+	protected function _create_objects($rows = array())
5027
+	{
5028
+		$array_of_objects = array();
5029
+		if (empty($rows)) {
5030
+			return array();
5031
+		}
5032
+		$count_if_model_has_no_primary_key = 0;
5033
+		$has_primary_key = $this->has_primary_key_field();
5034
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5035
+		foreach ((array)$rows as $row) {
5036
+			if (empty($row)) {
5037
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5038
+				return array();
5039
+			}
5040
+			//check if we've already set this object in the results array,
5041
+			//in which case there's no need to process it further (again)
5042
+			if ($has_primary_key) {
5043
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5044
+					$row,
5045
+					$primary_key_field->get_qualified_column(),
5046
+					$primary_key_field->get_table_column()
5047
+				);
5048
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5049
+					continue;
5050
+				}
5051
+			}
5052
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5053
+			if (! $classInstance) {
5054
+				throw new EE_Error(
5055
+					sprintf(
5056
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5057
+						$this->get_this_model_name(),
5058
+						http_build_query($row)
5059
+					)
5060
+				);
5061
+			}
5062
+			//set the timezone on the instantiated objects
5063
+			$classInstance->set_timezone($this->_timezone);
5064
+			//make sure if there is any timezone setting present that we set the timezone for the object
5065
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5066
+			$array_of_objects[$key] = $classInstance;
5067
+			//also, for all the relations of type BelongsTo, see if we can cache
5068
+			//those related models
5069
+			//(we could do this for other relations too, but if there are conditions
5070
+			//that filtered out some fo the results, then we'd be caching an incomplete set
5071
+			//so it requires a little more thought than just caching them immediately...)
5072
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5073
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5074
+					//check if this model's INFO is present. If so, cache it on the model
5075
+					$other_model = $relation_obj->get_other_model();
5076
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5077
+					//if we managed to make a model object from the results, cache it on the main model object
5078
+					if ($other_model_obj_maybe) {
5079
+						//set timezone on these other model objects if they are present
5080
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5081
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5082
+					}
5083
+				}
5084
+			}
5085
+			//also, if this was a custom select query, let's see if there are any results for the custom select fields
5086
+			//and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5087
+			//the field in the CustomSelects object
5088
+			if ($this->_custom_selections instanceof CustomSelects) {
5089
+				$classInstance->setCustomSelectsValues(
5090
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5091
+				);
5092
+			}
5093
+		}
5094
+		return $array_of_objects;
5095
+	}
5096
+
5097
+
5098
+	/**
5099
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5100
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5101
+	 *
5102
+	 * @param array $db_results_row
5103
+	 * @return array
5104
+	 */
5105
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5106
+	{
5107
+		$results = array();
5108
+		if ($this->_custom_selections instanceof CustomSelects) {
5109
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5110
+				if (isset($db_results_row[$alias])) {
5111
+					$results[$alias] = $this->convertValueToDataType(
5112
+						$db_results_row[$alias],
5113
+						$this->_custom_selections->getDataTypeForAlias($alias)
5114
+					);
5115
+				}
5116
+			}
5117
+		}
5118
+		return $results;
5119
+	}
5120
+
5121
+
5122
+	/**
5123
+	 * This will set the value for the given alias
5124
+	 * @param string $value
5125
+	 * @param string $datatype (one of %d, %s, %f)
5126
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5127
+	 */
5128
+	protected function convertValueToDataType($value, $datatype)
5129
+	{
5130
+		switch ($datatype) {
5131
+			case '%f':
5132
+				return (float) $value;
5133
+			case '%d':
5134
+				return (int) $value;
5135
+			default:
5136
+				return (string) $value;
5137
+		}
5138
+	}
5139
+
5140
+
5141
+	/**
5142
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5143
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5144
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5145
+	 * object (as set in the model_field!).
5146
+	 *
5147
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5148
+	 */
5149
+	public function create_default_object()
5150
+	{
5151
+		$this_model_fields_and_values = array();
5152
+		//setup the row using default values;
5153
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5154
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5155
+		}
5156
+		$className = $this->_get_class_name();
5157
+		$classInstance = EE_Registry::instance()
5158
+									->load_class($className, array($this_model_fields_and_values), false, false);
5159
+		return $classInstance;
5160
+	}
5161
+
5162
+
5163
+
5164
+	/**
5165
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5166
+	 *                             or an stdClass where each property is the name of a column,
5167
+	 * @return EE_Base_Class
5168
+	 * @throws EE_Error
5169
+	 */
5170
+	public function instantiate_class_from_array_or_object($cols_n_values)
5171
+	{
5172
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5173
+			$cols_n_values = get_object_vars($cols_n_values);
5174
+		}
5175
+		$primary_key = null;
5176
+		//make sure the array only has keys that are fields/columns on this model
5177
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5178
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5179
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5180
+		}
5181
+		$className = $this->_get_class_name();
5182
+		//check we actually found results that we can use to build our model object
5183
+		//if not, return null
5184
+		if ($this->has_primary_key_field()) {
5185
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5186
+				return null;
5187
+			}
5188
+		} else if ($this->unique_indexes()) {
5189
+			$first_column = reset($this_model_fields_n_values);
5190
+			if (empty($first_column)) {
5191
+				return null;
5192
+			}
5193
+		}
5194
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5195
+		if ($primary_key) {
5196
+			$classInstance = $this->get_from_entity_map($primary_key);
5197
+			if (! $classInstance) {
5198
+				$classInstance = EE_Registry::instance()
5199
+											->load_class($className,
5200
+												array($this_model_fields_n_values, $this->_timezone), true, false);
5201
+				// add this new object to the entity map
5202
+				$classInstance = $this->add_to_entity_map($classInstance);
5203
+			}
5204
+		} else {
5205
+			$classInstance = EE_Registry::instance()
5206
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5207
+											true, false);
5208
+		}
5209
+		return $classInstance;
5210
+	}
5211
+
5212
+
5213
+
5214
+	/**
5215
+	 * Gets the model object from the  entity map if it exists
5216
+	 *
5217
+	 * @param int|string $id the ID of the model object
5218
+	 * @return EE_Base_Class
5219
+	 */
5220
+	public function get_from_entity_map($id)
5221
+	{
5222
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5223
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5224
+	}
5225
+
5226
+
5227
+
5228
+	/**
5229
+	 * add_to_entity_map
5230
+	 * Adds the object to the model's entity mappings
5231
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5232
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5233
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5234
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5235
+	 *        then this method should be called immediately after the update query
5236
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5237
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5238
+	 *
5239
+	 * @param    EE_Base_Class $object
5240
+	 * @throws EE_Error
5241
+	 * @return \EE_Base_Class
5242
+	 */
5243
+	public function add_to_entity_map(EE_Base_Class $object)
5244
+	{
5245
+		$className = $this->_get_class_name();
5246
+		if (! $object instanceof $className) {
5247
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5248
+				is_object($object) ? get_class($object) : $object, $className));
5249
+		}
5250
+		/** @var $object EE_Base_Class */
5251
+		if (! $object->ID()) {
5252
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5253
+				"event_espresso"), get_class($this)));
5254
+		}
5255
+		// double check it's not already there
5256
+		$classInstance = $this->get_from_entity_map($object->ID());
5257
+		if ($classInstance) {
5258
+			return $classInstance;
5259
+		}
5260
+		$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5261
+		return $object;
5262
+	}
5263
+
5264
+
5265
+
5266
+	/**
5267
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5268
+	 * if no identifier is provided, then the entire entity map is emptied
5269
+	 *
5270
+	 * @param int|string $id the ID of the model object
5271
+	 * @return boolean
5272
+	 */
5273
+	public function clear_entity_map($id = null)
5274
+	{
5275
+		if (empty($id)) {
5276
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5277
+			return true;
5278
+		}
5279
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5280
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5281
+			return true;
5282
+		}
5283
+		return false;
5284
+	}
5285
+
5286
+
5287
+
5288
+	/**
5289
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5290
+	 * Given an array where keys are column (or column alias) names and values,
5291
+	 * returns an array of their corresponding field names and database values
5292
+	 *
5293
+	 * @param array $cols_n_values
5294
+	 * @return array
5295
+	 */
5296
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5297
+	{
5298
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5299
+	}
5300
+
5301
+
5302
+
5303
+	/**
5304
+	 * _deduce_fields_n_values_from_cols_n_values
5305
+	 * Given an array where keys are column (or column alias) names and values,
5306
+	 * returns an array of their corresponding field names and database values
5307
+	 *
5308
+	 * @param string $cols_n_values
5309
+	 * @return array
5310
+	 */
5311
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5312
+	{
5313
+		$this_model_fields_n_values = array();
5314
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5315
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5316
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5317
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5318
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5319
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5320
+					if (! $field_obj->is_db_only_field()) {
5321
+						//prepare field as if its coming from db
5322
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5323
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5324
+					}
5325
+				}
5326
+			} else {
5327
+				//the table's rows existed. Use their values
5328
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5329
+					if (! $field_obj->is_db_only_field()) {
5330
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5331
+							$cols_n_values, $field_obj->get_qualified_column(),
5332
+							$field_obj->get_table_column()
5333
+						);
5334
+					}
5335
+				}
5336
+			}
5337
+		}
5338
+		return $this_model_fields_n_values;
5339
+	}
5340
+
5341
+
5342
+
5343
+	/**
5344
+	 * @param $cols_n_values
5345
+	 * @param $qualified_column
5346
+	 * @param $regular_column
5347
+	 * @return null
5348
+	 */
5349
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5350
+	{
5351
+		$value = null;
5352
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5353
+		//does the field on the model relate to this column retrieved from the db?
5354
+		//or is it a db-only field? (not relating to the model)
5355
+		if (isset($cols_n_values[$qualified_column])) {
5356
+			$value = $cols_n_values[$qualified_column];
5357
+		} elseif (isset($cols_n_values[$regular_column])) {
5358
+			$value = $cols_n_values[$regular_column];
5359
+		}
5360
+		return $value;
5361
+	}
5362
+
5363
+
5364
+
5365
+	/**
5366
+	 * refresh_entity_map_from_db
5367
+	 * Makes sure the model object in the entity map at $id assumes the values
5368
+	 * of the database (opposite of EE_base_Class::save())
5369
+	 *
5370
+	 * @param int|string $id
5371
+	 * @return EE_Base_Class
5372
+	 * @throws EE_Error
5373
+	 */
5374
+	public function refresh_entity_map_from_db($id)
5375
+	{
5376
+		$obj_in_map = $this->get_from_entity_map($id);
5377
+		if ($obj_in_map) {
5378
+			$wpdb_results = $this->_get_all_wpdb_results(
5379
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5380
+			);
5381
+			if ($wpdb_results && is_array($wpdb_results)) {
5382
+				$one_row = reset($wpdb_results);
5383
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5384
+					$obj_in_map->set_from_db($field_name, $db_value);
5385
+				}
5386
+				//clear the cache of related model objects
5387
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5388
+					$obj_in_map->clear_cache($relation_name, null, true);
5389
+				}
5390
+			}
5391
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5392
+			return $obj_in_map;
5393
+		}
5394
+		return $this->get_one_by_ID($id);
5395
+	}
5396
+
5397
+
5398
+
5399
+	/**
5400
+	 * refresh_entity_map_with
5401
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5402
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5403
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5404
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5405
+	 *
5406
+	 * @param int|string    $id
5407
+	 * @param EE_Base_Class $replacing_model_obj
5408
+	 * @return \EE_Base_Class
5409
+	 * @throws EE_Error
5410
+	 */
5411
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5412
+	{
5413
+		$obj_in_map = $this->get_from_entity_map($id);
5414
+		if ($obj_in_map) {
5415
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5416
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5417
+					$obj_in_map->set($field_name, $value);
5418
+				}
5419
+				//make the model object in the entity map's cache match the $replacing_model_obj
5420
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5421
+					$obj_in_map->clear_cache($relation_name, null, true);
5422
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5423
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5424
+					}
5425
+				}
5426
+			}
5427
+			return $obj_in_map;
5428
+		}
5429
+		$this->add_to_entity_map($replacing_model_obj);
5430
+		return $replacing_model_obj;
5431
+	}
5432
+
5433
+
5434
+
5435
+	/**
5436
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5437
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5438
+	 * require_once($this->_getClassName().".class.php");
5439
+	 *
5440
+	 * @return string
5441
+	 */
5442
+	private function _get_class_name()
5443
+	{
5444
+		return "EE_" . $this->get_this_model_name();
5445
+	}
5446
+
5447
+
5448
+
5449
+	/**
5450
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5451
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5452
+	 * it would be 'Events'.
5453
+	 *
5454
+	 * @param int $quantity
5455
+	 * @return string
5456
+	 */
5457
+	public function item_name($quantity = 1)
5458
+	{
5459
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5460
+	}
5461
+
5462
+
5463
+
5464
+	/**
5465
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5466
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5467
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5468
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5469
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5470
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5471
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5472
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5473
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5474
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5475
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5476
+	 *        return $previousReturnValue.$returnString;
5477
+	 * }
5478
+	 * require('EEM_Answer.model.php');
5479
+	 * $answer=EEM_Answer::instance();
5480
+	 * echo $answer->my_callback('monkeys',100);
5481
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5482
+	 *
5483
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5484
+	 * @param array  $args       array of original arguments passed to the function
5485
+	 * @throws EE_Error
5486
+	 * @return mixed whatever the plugin which calls add_filter decides
5487
+	 */
5488
+	public function __call($methodName, $args)
5489
+	{
5490
+		$className = get_class($this);
5491
+		$tagName = "FHEE__{$className}__{$methodName}";
5492
+		if (! has_filter($tagName)) {
5493
+			throw new EE_Error(
5494
+				sprintf(
5495
+					__('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 );',
5496
+						'event_espresso'),
5497
+					$methodName,
5498
+					$className,
5499
+					$tagName,
5500
+					'<br />'
5501
+				)
5502
+			);
5503
+		}
5504
+		return apply_filters($tagName, null, $this, $args);
5505
+	}
5506
+
5507
+
5508
+
5509
+	/**
5510
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5511
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5512
+	 *
5513
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5514
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5515
+	 *                                                       the object's class name
5516
+	 *                                                       or object's ID
5517
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5518
+	 *                                                       exists in the database. If it does not, we add it
5519
+	 * @throws EE_Error
5520
+	 * @return EE_Base_Class
5521
+	 */
5522
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5523
+	{
5524
+		$className = $this->_get_class_name();
5525
+		if ($base_class_obj_or_id instanceof $className) {
5526
+			$model_object = $base_class_obj_or_id;
5527
+		} else {
5528
+			$primary_key_field = $this->get_primary_key_field();
5529
+			if (
5530
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5531
+				&& (
5532
+					is_int($base_class_obj_or_id)
5533
+					|| is_string($base_class_obj_or_id)
5534
+				)
5535
+			) {
5536
+				// assume it's an ID.
5537
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5538
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5539
+			} else if (
5540
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5541
+				&& is_string($base_class_obj_or_id)
5542
+			) {
5543
+				// assume its a string representation of the object
5544
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5545
+			} else {
5546
+				throw new EE_Error(
5547
+					sprintf(
5548
+						__(
5549
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5550
+							'event_espresso'
5551
+						),
5552
+						$base_class_obj_or_id,
5553
+						$this->_get_class_name(),
5554
+						print_r($base_class_obj_or_id, true)
5555
+					)
5556
+				);
5557
+			}
5558
+		}
5559
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5560
+			$model_object->save();
5561
+		}
5562
+		return $model_object;
5563
+	}
5564
+
5565
+
5566
+
5567
+	/**
5568
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5569
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5570
+	 * returns it ID.
5571
+	 *
5572
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5573
+	 * @return int|string depending on the type of this model object's ID
5574
+	 * @throws EE_Error
5575
+	 */
5576
+	public function ensure_is_ID($base_class_obj_or_id)
5577
+	{
5578
+		$className = $this->_get_class_name();
5579
+		if ($base_class_obj_or_id instanceof $className) {
5580
+			/** @var $base_class_obj_or_id EE_Base_Class */
5581
+			$id = $base_class_obj_or_id->ID();
5582
+		} elseif (is_int($base_class_obj_or_id)) {
5583
+			//assume it's an ID
5584
+			$id = $base_class_obj_or_id;
5585
+		} elseif (is_string($base_class_obj_or_id)) {
5586
+			//assume its a string representation of the object
5587
+			$id = $base_class_obj_or_id;
5588
+		} else {
5589
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5590
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5591
+				print_r($base_class_obj_or_id, true)));
5592
+		}
5593
+		return $id;
5594
+	}
5595
+
5596
+
5597
+
5598
+	/**
5599
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5600
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5601
+	 * been sanitized and converted into the appropriate domain.
5602
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5603
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5604
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5605
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5606
+	 * $EVT = EEM_Event::instance(); $old_setting =
5607
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5608
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5609
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5610
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5611
+	 *
5612
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5613
+	 * @return void
5614
+	 */
5615
+	public function assume_values_already_prepared_by_model_object(
5616
+		$values_already_prepared = self::not_prepared_by_model_object
5617
+	) {
5618
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5619
+	}
5620
+
5621
+
5622
+
5623
+	/**
5624
+	 * Read comments for assume_values_already_prepared_by_model_object()
5625
+	 *
5626
+	 * @return int
5627
+	 */
5628
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5629
+	{
5630
+		return $this->_values_already_prepared_by_model_object;
5631
+	}
5632
+
5633
+
5634
+
5635
+	/**
5636
+	 * Gets all the indexes on this model
5637
+	 *
5638
+	 * @return EE_Index[]
5639
+	 */
5640
+	public function indexes()
5641
+	{
5642
+		return $this->_indexes;
5643
+	}
5644
+
5645
+
5646
+
5647
+	/**
5648
+	 * Gets all the Unique Indexes on this model
5649
+	 *
5650
+	 * @return EE_Unique_Index[]
5651
+	 */
5652
+	public function unique_indexes()
5653
+	{
5654
+		$unique_indexes = array();
5655
+		foreach ($this->_indexes as $name => $index) {
5656
+			if ($index instanceof EE_Unique_Index) {
5657
+				$unique_indexes [$name] = $index;
5658
+			}
5659
+		}
5660
+		return $unique_indexes;
5661
+	}
5662
+
5663
+
5664
+
5665
+	/**
5666
+	 * Gets all the fields which, when combined, make the primary key.
5667
+	 * This is usually just an array with 1 element (the primary key), but in cases
5668
+	 * where there is no primary key, it's a combination of fields as defined
5669
+	 * on a primary index
5670
+	 *
5671
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5672
+	 * @throws EE_Error
5673
+	 */
5674
+	public function get_combined_primary_key_fields()
5675
+	{
5676
+		foreach ($this->indexes() as $index) {
5677
+			if ($index instanceof EE_Primary_Key_Index) {
5678
+				return $index->fields();
5679
+			}
5680
+		}
5681
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5682
+	}
5683
+
5684
+
5685
+
5686
+	/**
5687
+	 * Used to build a primary key string (when the model has no primary key),
5688
+	 * which can be used a unique string to identify this model object.
5689
+	 *
5690
+	 * @param array $cols_n_values keys are field names, values are their values
5691
+	 * @return string
5692
+	 * @throws EE_Error
5693
+	 */
5694
+	public function get_index_primary_key_string($cols_n_values)
5695
+	{
5696
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5697
+			$this->get_combined_primary_key_fields());
5698
+		return http_build_query($cols_n_values_for_primary_key_index);
5699
+	}
5700
+
5701
+
5702
+
5703
+	/**
5704
+	 * Gets the field values from the primary key string
5705
+	 *
5706
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5707
+	 * @param string $index_primary_key_string
5708
+	 * @return null|array
5709
+	 * @throws EE_Error
5710
+	 */
5711
+	public function parse_index_primary_key_string($index_primary_key_string)
5712
+	{
5713
+		$key_fields = $this->get_combined_primary_key_fields();
5714
+		//check all of them are in the $id
5715
+		$key_vals_in_combined_pk = array();
5716
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5717
+		foreach ($key_fields as $key_field_name => $field_obj) {
5718
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5719
+				return null;
5720
+			}
5721
+		}
5722
+		return $key_vals_in_combined_pk;
5723
+	}
5724
+
5725
+
5726
+
5727
+	/**
5728
+	 * verifies that an array of key-value pairs for model fields has a key
5729
+	 * for each field comprising the primary key index
5730
+	 *
5731
+	 * @param array $key_vals
5732
+	 * @return boolean
5733
+	 * @throws EE_Error
5734
+	 */
5735
+	public function has_all_combined_primary_key_fields($key_vals)
5736
+	{
5737
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5738
+		foreach ($keys_it_should_have as $key) {
5739
+			if (! isset($key_vals[$key])) {
5740
+				return false;
5741
+			}
5742
+		}
5743
+		return true;
5744
+	}
5745
+
5746
+
5747
+
5748
+	/**
5749
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5750
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5751
+	 *
5752
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5753
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5754
+	 * @throws EE_Error
5755
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5756
+	 *                                                              indexed)
5757
+	 */
5758
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5759
+	{
5760
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5761
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5762
+		} elseif (is_array($model_object_or_attributes_array)) {
5763
+			$attributes_array = $model_object_or_attributes_array;
5764
+		} else {
5765
+			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",
5766
+				"event_espresso"), $model_object_or_attributes_array));
5767
+		}
5768
+		//even copies obviously won't have the same ID, so remove the primary key
5769
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5770
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5771
+			unset($attributes_array[$this->primary_key_name()]);
5772
+		}
5773
+		if (isset($query_params[0])) {
5774
+			$query_params[0] = array_merge($attributes_array, $query_params);
5775
+		} else {
5776
+			$query_params[0] = $attributes_array;
5777
+		}
5778
+		return $this->get_all($query_params);
5779
+	}
5780
+
5781
+
5782
+
5783
+	/**
5784
+	 * Gets the first copy we find. See get_all_copies for more details
5785
+	 *
5786
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5787
+	 * @param array $query_params
5788
+	 * @return EE_Base_Class
5789
+	 * @throws EE_Error
5790
+	 */
5791
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5792
+	{
5793
+		if (! is_array($query_params)) {
5794
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5795
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5796
+					gettype($query_params)), '4.6.0');
5797
+			$query_params = array();
5798
+		}
5799
+		$query_params['limit'] = 1;
5800
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5801
+		if (is_array($copies)) {
5802
+			return array_shift($copies);
5803
+		}
5804
+		return null;
5805
+	}
5806
+
5807
+
5808
+
5809
+	/**
5810
+	 * Updates the item with the specified id. Ignores default query parameters because
5811
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5812
+	 *
5813
+	 * @param array      $fields_n_values keys are field names, values are their new values
5814
+	 * @param int|string $id              the value of the primary key to update
5815
+	 * @return int number of rows updated
5816
+	 * @throws EE_Error
5817
+	 */
5818
+	public function update_by_ID($fields_n_values, $id)
5819
+	{
5820
+		$query_params = array(
5821
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5822
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5823
+		);
5824
+		return $this->update($fields_n_values, $query_params);
5825
+	}
5826
+
5827
+
5828
+
5829
+	/**
5830
+	 * Changes an operator which was supplied to the models into one usable in SQL
5831
+	 *
5832
+	 * @param string $operator_supplied
5833
+	 * @return string an operator which can be used in SQL
5834
+	 * @throws EE_Error
5835
+	 */
5836
+	private function _prepare_operator_for_sql($operator_supplied)
5837
+	{
5838
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5839
+			: null;
5840
+		if ($sql_operator) {
5841
+			return $sql_operator;
5842
+		}
5843
+		throw new EE_Error(
5844
+			sprintf(
5845
+				__(
5846
+					"The operator '%s' is not in the list of valid operators: %s",
5847
+					"event_espresso"
5848
+				), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5849
+			)
5850
+		);
5851
+	}
5852
+
5853
+
5854
+
5855
+	/**
5856
+	 * Gets the valid operators
5857
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5858
+	 */
5859
+	public function valid_operators(){
5860
+		return $this->_valid_operators;
5861
+	}
5862
+
5863
+
5864
+
5865
+	/**
5866
+	 * Gets the between-style operators (take 2 arguments).
5867
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5868
+	 */
5869
+	public function valid_between_style_operators()
5870
+	{
5871
+		return array_intersect(
5872
+			$this->valid_operators(),
5873
+			$this->_between_style_operators
5874
+		);
5875
+	}
5876
+
5877
+	/**
5878
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5879
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5880
+	 */
5881
+	public function valid_like_style_operators()
5882
+	{
5883
+		return array_intersect(
5884
+			$this->valid_operators(),
5885
+			$this->_like_style_operators
5886
+		);
5887
+	}
5888
+
5889
+	/**
5890
+	 * Gets the "in"-style operators
5891
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5892
+	 */
5893
+	public function valid_in_style_operators()
5894
+	{
5895
+		return array_intersect(
5896
+			$this->valid_operators(),
5897
+			$this->_in_style_operators
5898
+		);
5899
+	}
5900
+
5901
+	/**
5902
+	 * Gets the "null"-style operators (accept no arguments)
5903
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5904
+	 */
5905
+	public function valid_null_style_operators()
5906
+	{
5907
+		return array_intersect(
5908
+			$this->valid_operators(),
5909
+			$this->_null_style_operators
5910
+		);
5911
+	}
5912
+
5913
+	/**
5914
+	 * Gets an array where keys are the primary keys and values are their 'names'
5915
+	 * (as determined by the model object's name() function, which is often overridden)
5916
+	 *
5917
+	 * @param array $query_params like get_all's
5918
+	 * @return string[]
5919
+	 * @throws EE_Error
5920
+	 */
5921
+	public function get_all_names($query_params = array())
5922
+	{
5923
+		$objs = $this->get_all($query_params);
5924
+		$names = array();
5925
+		foreach ($objs as $obj) {
5926
+			$names[$obj->ID()] = $obj->name();
5927
+		}
5928
+		return $names;
5929
+	}
5930
+
5931
+
5932
+
5933
+	/**
5934
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5935
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5936
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5937
+	 * array_keys() on $model_objects.
5938
+	 *
5939
+	 * @param \EE_Base_Class[] $model_objects
5940
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5941
+	 *                                               in the returned array
5942
+	 * @return array
5943
+	 * @throws EE_Error
5944
+	 */
5945
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5946
+	{
5947
+		if (! $this->has_primary_key_field()) {
5948
+			if (WP_DEBUG) {
5949
+				EE_Error::add_error(
5950
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5951
+					__FILE__,
5952
+					__FUNCTION__,
5953
+					__LINE__
5954
+				);
5955
+			}
5956
+		}
5957
+		$IDs = array();
5958
+		foreach ($model_objects as $model_object) {
5959
+			$id = $model_object->ID();
5960
+			if (! $id) {
5961
+				if ($filter_out_empty_ids) {
5962
+					continue;
5963
+				}
5964
+				if (WP_DEBUG) {
5965
+					EE_Error::add_error(
5966
+						__(
5967
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5968
+							'event_espresso'
5969
+						),
5970
+						__FILE__,
5971
+						__FUNCTION__,
5972
+						__LINE__
5973
+					);
5974
+				}
5975
+			}
5976
+			$IDs[] = $id;
5977
+		}
5978
+		return $IDs;
5979
+	}
5980
+
5981
+
5982
+
5983
+	/**
5984
+	 * Returns the string used in capabilities relating to this model. If there
5985
+	 * are no capabilities that relate to this model returns false
5986
+	 *
5987
+	 * @return string|false
5988
+	 */
5989
+	public function cap_slug()
5990
+	{
5991
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5992
+	}
5993
+
5994
+
5995
+
5996
+	/**
5997
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5998
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5999
+	 * only returns the cap restrictions array in that context (ie, the array
6000
+	 * at that key)
6001
+	 *
6002
+	 * @param string $context
6003
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6004
+	 * @throws EE_Error
6005
+	 */
6006
+	public function cap_restrictions($context = EEM_Base::caps_read)
6007
+	{
6008
+		EEM_Base::verify_is_valid_cap_context($context);
6009
+		//check if we ought to run the restriction generator first
6010
+		if (
6011
+			isset($this->_cap_restriction_generators[$context])
6012
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6013
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6014
+		) {
6015
+			$this->_cap_restrictions[$context] = array_merge(
6016
+				$this->_cap_restrictions[$context],
6017
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
6018
+			);
6019
+		}
6020
+		//and make sure we've finalized the construction of each restriction
6021
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6022
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6023
+				$where_conditions_obj->_finalize_construct($this);
6024
+			}
6025
+		}
6026
+		return $this->_cap_restrictions[$context];
6027
+	}
6028
+
6029
+
6030
+
6031
+	/**
6032
+	 * Indicating whether or not this model thinks its a wp core model
6033
+	 *
6034
+	 * @return boolean
6035
+	 */
6036
+	public function is_wp_core_model()
6037
+	{
6038
+		return $this->_wp_core_model;
6039
+	}
6040
+
6041
+
6042
+
6043
+	/**
6044
+	 * Gets all the caps that are missing which impose a restriction on
6045
+	 * queries made in this context
6046
+	 *
6047
+	 * @param string $context one of EEM_Base::caps_ constants
6048
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6049
+	 * @throws EE_Error
6050
+	 */
6051
+	public function caps_missing($context = EEM_Base::caps_read)
6052
+	{
6053
+		$missing_caps = array();
6054
+		$cap_restrictions = $this->cap_restrictions($context);
6055
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6056
+			if (! EE_Capabilities::instance()
6057
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6058
+			) {
6059
+				$missing_caps[$cap] = $restriction_if_no_cap;
6060
+			}
6061
+		}
6062
+		return $missing_caps;
6063
+	}
6064
+
6065
+
6066
+
6067
+	/**
6068
+	 * Gets the mapping from capability contexts to action strings used in capability names
6069
+	 *
6070
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6071
+	 * one of 'read', 'edit', or 'delete'
6072
+	 */
6073
+	public function cap_contexts_to_cap_action_map()
6074
+	{
6075
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
6076
+			$this);
6077
+	}
6078
+
6079
+
6080
+
6081
+	/**
6082
+	 * Gets the action string for the specified capability context
6083
+	 *
6084
+	 * @param string $context
6085
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6086
+	 * @throws EE_Error
6087
+	 */
6088
+	public function cap_action_for_context($context)
6089
+	{
6090
+		$mapping = $this->cap_contexts_to_cap_action_map();
6091
+		if (isset($mapping[$context])) {
6092
+			return $mapping[$context];
6093
+		}
6094
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6095
+			return $action;
6096
+		}
6097
+		throw new EE_Error(
6098
+			sprintf(
6099
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6100
+				$context,
6101
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6102
+			)
6103
+		);
6104
+	}
6105
+
6106
+
6107
+
6108
+	/**
6109
+	 * Returns all the capability contexts which are valid when querying models
6110
+	 *
6111
+	 * @return array
6112
+	 */
6113
+	public static function valid_cap_contexts()
6114
+	{
6115
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6116
+			self::caps_read,
6117
+			self::caps_read_admin,
6118
+			self::caps_edit,
6119
+			self::caps_delete,
6120
+		));
6121
+	}
6122
+
6123
+
6124
+
6125
+	/**
6126
+	 * Returns all valid options for 'default_where_conditions'
6127
+	 *
6128
+	 * @return array
6129
+	 */
6130
+	public static function valid_default_where_conditions()
6131
+	{
6132
+		return array(
6133
+			EEM_Base::default_where_conditions_all,
6134
+			EEM_Base::default_where_conditions_this_only,
6135
+			EEM_Base::default_where_conditions_others_only,
6136
+			EEM_Base::default_where_conditions_minimum_all,
6137
+			EEM_Base::default_where_conditions_minimum_others,
6138
+			EEM_Base::default_where_conditions_none
6139
+		);
6140
+	}
6141
+
6142
+	// public static function default_where_conditions_full
6143
+	/**
6144
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6145
+	 *
6146
+	 * @param string $context
6147
+	 * @return bool
6148
+	 * @throws EE_Error
6149
+	 */
6150
+	static public function verify_is_valid_cap_context($context)
6151
+	{
6152
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6153
+		if (in_array($context, $valid_cap_contexts)) {
6154
+			return true;
6155
+		}
6156
+		throw new EE_Error(
6157
+			sprintf(
6158
+				__(
6159
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6160
+					'event_espresso'
6161
+				),
6162
+				$context,
6163
+				'EEM_Base',
6164
+				implode(',', $valid_cap_contexts)
6165
+			)
6166
+		);
6167
+	}
6168
+
6169
+
6170
+
6171
+	/**
6172
+	 * Clears all the models field caches. This is only useful when a sub-class
6173
+	 * might have added a field or something and these caches might be invalidated
6174
+	 */
6175
+	protected function _invalidate_field_caches()
6176
+	{
6177
+		$this->_cache_foreign_key_to_fields = array();
6178
+		$this->_cached_fields = null;
6179
+		$this->_cached_fields_non_db_only = null;
6180
+	}
6181
+
6182
+
6183
+
6184
+	/**
6185
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6186
+	 * (eg "and", "or", "not").
6187
+	 *
6188
+	 * @return array
6189
+	 */
6190
+	public function logic_query_param_keys()
6191
+	{
6192
+		return $this->_logic_query_param_keys;
6193
+	}
6194
+
6195
+
6196
+
6197
+	/**
6198
+	 * Determines whether or not the where query param array key is for a logic query param.
6199
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6200
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6201
+	 *
6202
+	 * @param $query_param_key
6203
+	 * @return bool
6204
+	 */
6205
+	public function is_logic_query_param_key($query_param_key)
6206
+	{
6207
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6208
+			if ($query_param_key === $logic_query_param_key
6209
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6210
+			) {
6211
+				return true;
6212
+			}
6213
+		}
6214
+		return false;
6215
+	}
6216 6216
 
6217 6217
 
6218 6218
 
Please login to merge, or discard this patch.
core/services/request/middleware/RecommendedVersions.php 1 patch
Indentation   +176 added lines, -176 removed lines patch added patch discarded remove patch
@@ -23,187 +23,187 @@
 block discarded – undo
23 23
 class RecommendedVersions extends Middleware
24 24
 {
25 25
 
26
-    /**
27
-     * converts a Request to a Response
28
-     *
29
-     * @param RequestInterface $request
30
-     * @param ResponseInterface      $response
31
-     * @return ResponseInterface
32
-     * @throws InvalidDataTypeException
33
-     */
34
-    public function handleRequest(RequestInterface $request, ResponseInterface $response)
35
-    {
36
-        $this->request  = $request;
37
-        $this->response = $response;
38
-        // check required WP version
39
-        if (! $this->minimumWordPressVersionRequired()) {
40
-            $this->request->unSetRequestParam('activate', true);
41
-            add_action('admin_notices', array($this, 'minimum_wp_version_error'), 1);
42
-            $this->response->terminateRequest();
43
-            $this->response->deactivatePlugin();
44
-        }
45
-        // check recommended PHP version
46
-        if (! $this->minimumPhpVersionRecommended()) {
47
-            $this->displayMinimumRecommendedPhpVersionNotice();
48
-        }
49
-        //upcoming required version
50
-        if (! $this->upcomingRequiredPhpVersion()) {
51
-            $this->displayUpcomingRequiredVersion();
52
-        }
53
-        $this->response = $this->processRequestStack($this->request, $this->response);
54
-        return $this->response;
55
-    }
56
-
57
-
58
-    /**
59
-     * Helper method to assess installed wp version against given values.
60
-     * By default this compares the required minimum version of WP for EE against the installed version of WP
61
-     * Note, $wp_version is the first parameter sent into the PHP version_compare function (what is being checked
62
-     * against) so consider that when sending in your values.
63
-     *
64
-     * @param string $version_to_check
65
-     * @param string $operator
66
-     * @return bool
67
-     */
68
-    public static function compareWordPressVersion($version_to_check = EE_MIN_WP_VER_REQUIRED, $operator = '>=')
69
-    {
70
-        global $wp_version;
71
-        return version_compare(
72
-        // first account for wp_version being pre-release
73
-        // (like RC, beta etc) which are usually in the format like 4.7-RC3-39519
74
-            strpos($wp_version, '-') > 0
75
-                ? substr($wp_version, 0, strpos($wp_version, '-'))
76
-                : $wp_version,
77
-            $version_to_check,
78
-            $operator
79
-        );
80
-    }
81
-
82
-
83
-
84
-    /**
85
-     * @return boolean
86
-     */
87
-    private function minimumWordPressVersionRequired()
88
-    {
89
-        return RecommendedVersions::compareWordPressVersion();
90
-    }
91
-
92
-
93
-
94
-    /**
95
-     * @param string $min_version
96
-     * @return boolean
97
-     */
98
-    private function checkPhpVersion($min_version = EE_MIN_PHP_VER_RECOMMENDED)
99
-    {
100
-        return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
101
-    }
102
-
103
-
104
-
105
-    /**
106
-     * @return boolean
107
-     */
108
-    private function minimumPhpVersionRecommended()
109
-    {
110
-        return $this->checkPhpVersion();
111
-    }
112
-
113
-
114
-
115
-    /**
116
-     * @return void
117
-     */
118
-    public function minimumWpVersionError()
119
-    {
120
-        global $wp_version;
121
-        ?>
26
+	/**
27
+	 * converts a Request to a Response
28
+	 *
29
+	 * @param RequestInterface $request
30
+	 * @param ResponseInterface      $response
31
+	 * @return ResponseInterface
32
+	 * @throws InvalidDataTypeException
33
+	 */
34
+	public function handleRequest(RequestInterface $request, ResponseInterface $response)
35
+	{
36
+		$this->request  = $request;
37
+		$this->response = $response;
38
+		// check required WP version
39
+		if (! $this->minimumWordPressVersionRequired()) {
40
+			$this->request->unSetRequestParam('activate', true);
41
+			add_action('admin_notices', array($this, 'minimum_wp_version_error'), 1);
42
+			$this->response->terminateRequest();
43
+			$this->response->deactivatePlugin();
44
+		}
45
+		// check recommended PHP version
46
+		if (! $this->minimumPhpVersionRecommended()) {
47
+			$this->displayMinimumRecommendedPhpVersionNotice();
48
+		}
49
+		//upcoming required version
50
+		if (! $this->upcomingRequiredPhpVersion()) {
51
+			$this->displayUpcomingRequiredVersion();
52
+		}
53
+		$this->response = $this->processRequestStack($this->request, $this->response);
54
+		return $this->response;
55
+	}
56
+
57
+
58
+	/**
59
+	 * Helper method to assess installed wp version against given values.
60
+	 * By default this compares the required minimum version of WP for EE against the installed version of WP
61
+	 * Note, $wp_version is the first parameter sent into the PHP version_compare function (what is being checked
62
+	 * against) so consider that when sending in your values.
63
+	 *
64
+	 * @param string $version_to_check
65
+	 * @param string $operator
66
+	 * @return bool
67
+	 */
68
+	public static function compareWordPressVersion($version_to_check = EE_MIN_WP_VER_REQUIRED, $operator = '>=')
69
+	{
70
+		global $wp_version;
71
+		return version_compare(
72
+		// first account for wp_version being pre-release
73
+		// (like RC, beta etc) which are usually in the format like 4.7-RC3-39519
74
+			strpos($wp_version, '-') > 0
75
+				? substr($wp_version, 0, strpos($wp_version, '-'))
76
+				: $wp_version,
77
+			$version_to_check,
78
+			$operator
79
+		);
80
+	}
81
+
82
+
83
+
84
+	/**
85
+	 * @return boolean
86
+	 */
87
+	private function minimumWordPressVersionRequired()
88
+	{
89
+		return RecommendedVersions::compareWordPressVersion();
90
+	}
91
+
92
+
93
+
94
+	/**
95
+	 * @param string $min_version
96
+	 * @return boolean
97
+	 */
98
+	private function checkPhpVersion($min_version = EE_MIN_PHP_VER_RECOMMENDED)
99
+	{
100
+		return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
101
+	}
102
+
103
+
104
+
105
+	/**
106
+	 * @return boolean
107
+	 */
108
+	private function minimumPhpVersionRecommended()
109
+	{
110
+		return $this->checkPhpVersion();
111
+	}
112
+
113
+
114
+
115
+	/**
116
+	 * @return void
117
+	 */
118
+	public function minimumWpVersionError()
119
+	{
120
+		global $wp_version;
121
+		?>
122 122
         <div class="error">
123 123
             <p>
124 124
                 <?php
125
-                printf(
126
-                    __('We\'re sorry, but Event Espresso requires WordPress version %1$s or greater in order to operate. You are currently running version %2$s.%3$sFor information on how to update your version of WordPress, please go to %4$s.',
127
-                        'event_espresso'),
128
-                    EE_MIN_WP_VER_REQUIRED,
129
-                    $wp_version,
130
-                    '<br/>',
131
-                    '<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
132
-                );
133
-                ?>
125
+				printf(
126
+					__('We\'re sorry, but Event Espresso requires WordPress version %1$s or greater in order to operate. You are currently running version %2$s.%3$sFor information on how to update your version of WordPress, please go to %4$s.',
127
+						'event_espresso'),
128
+					EE_MIN_WP_VER_REQUIRED,
129
+					$wp_version,
130
+					'<br/>',
131
+					'<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
132
+				);
133
+				?>
134 134
             </p>
135 135
         </div>
136 136
         <?php
137
-    }
138
-
139
-
140
-
141
-    /**
142
-     *    _display_minimum_recommended_php_version_notice
143
-     *
144
-     * @access private
145
-     * @return void
146
-     * @throws InvalidDataTypeException
147
-     */
148
-    private function displayMinimumRecommendedPhpVersionNotice()
149
-    {
150
-        if ($this->request->isAdmin()) {
151
-            new PersistentAdminNotice(
152
-                'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
153
-                sprintf(
154
-                    esc_html__(
155
-                        'Event Espresso recommends PHP version %1$s or greater for optimal performance. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
156
-                        'event_espresso'
157
-                    ),
158
-                    EE_MIN_PHP_VER_RECOMMENDED,
159
-                    PHP_VERSION,
160
-                    '<br/>',
161
-                    '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
162
-                )
163
-            );
164
-        }
165
-    }
166
-
167
-
168
-    /**
169
-     * Returns whether the provided php version number is less than the current version of php installed on the server.
170
-     *
171
-     * @param string $version_required
172
-     * @return bool
173
-     */
174
-    private function upcomingRequiredPhpVersion($version_required = '5.5')
175
-    {
176
-        return true;
177
-        //return $this->checkPhpVersion($version_required);
178
-    }
179
-
180
-
181
-    /**
182
-     *  Sets a notice for an upcoming required version of PHP in the next update of EE core.
183
-     */
184
-    private function displayUpcomingRequiredVersion()
185
-    {
186
-        if ($this->request->isAdmin()
187
-            && apply_filters('FHEE__EE_Recommended_Versions__displayUpcomingRequiredVersion', true, $this->request)
188
-            && current_user_can('update_plugins')
189
-        ) {
190
-            add_action('admin_notices', function ()
191
-            {
192
-                echo '<div class="notice event-espresso-admin-notice notice-warning"><p>'
193
-                     . sprintf(
194
-                         esc_html__(
195
-                             'Please note: The next update of Event Espresso 4 will %1$srequire%2$s PHP 5.4.45 or greater.  Your web server\'s PHP version is %3$s.  You can contact your host and ask them to update your PHP version to at least PHP 5.6.  Please do not update to the new version of Event Espresso 4 until the PHP update is completed. Read about why keeping your server on the latest version of PHP is a good idea %4$shere%5$s',
196
-                             'event_espresso'
197
-                         ),
198
-                         '<strong>',
199
-                         '</strong>',
200
-                         PHP_VERSION,
201
-                         '<a href="https://wordpress.org/support/upgrade-php/">',
202
-                         '</a>'
203
-                     )
204
-                     . '</p></div>';
205
-            });
206
-        }
207
-    }
137
+	}
138
+
139
+
140
+
141
+	/**
142
+	 *    _display_minimum_recommended_php_version_notice
143
+	 *
144
+	 * @access private
145
+	 * @return void
146
+	 * @throws InvalidDataTypeException
147
+	 */
148
+	private function displayMinimumRecommendedPhpVersionNotice()
149
+	{
150
+		if ($this->request->isAdmin()) {
151
+			new PersistentAdminNotice(
152
+				'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
153
+				sprintf(
154
+					esc_html__(
155
+						'Event Espresso recommends PHP version %1$s or greater for optimal performance. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
156
+						'event_espresso'
157
+					),
158
+					EE_MIN_PHP_VER_RECOMMENDED,
159
+					PHP_VERSION,
160
+					'<br/>',
161
+					'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
162
+				)
163
+			);
164
+		}
165
+	}
166
+
167
+
168
+	/**
169
+	 * Returns whether the provided php version number is less than the current version of php installed on the server.
170
+	 *
171
+	 * @param string $version_required
172
+	 * @return bool
173
+	 */
174
+	private function upcomingRequiredPhpVersion($version_required = '5.5')
175
+	{
176
+		return true;
177
+		//return $this->checkPhpVersion($version_required);
178
+	}
179
+
180
+
181
+	/**
182
+	 *  Sets a notice for an upcoming required version of PHP in the next update of EE core.
183
+	 */
184
+	private function displayUpcomingRequiredVersion()
185
+	{
186
+		if ($this->request->isAdmin()
187
+			&& apply_filters('FHEE__EE_Recommended_Versions__displayUpcomingRequiredVersion', true, $this->request)
188
+			&& current_user_can('update_plugins')
189
+		) {
190
+			add_action('admin_notices', function ()
191
+			{
192
+				echo '<div class="notice event-espresso-admin-notice notice-warning"><p>'
193
+					 . sprintf(
194
+						 esc_html__(
195
+							 'Please note: The next update of Event Espresso 4 will %1$srequire%2$s PHP 5.4.45 or greater.  Your web server\'s PHP version is %3$s.  You can contact your host and ask them to update your PHP version to at least PHP 5.6.  Please do not update to the new version of Event Espresso 4 until the PHP update is completed. Read about why keeping your server on the latest version of PHP is a good idea %4$shere%5$s',
196
+							 'event_espresso'
197
+						 ),
198
+						 '<strong>',
199
+						 '</strong>',
200
+						 PHP_VERSION,
201
+						 '<a href="https://wordpress.org/support/upgrade-php/">',
202
+						 '</a>'
203
+					 )
204
+					 . '</p></div>';
205
+			});
206
+		}
207
+	}
208 208
 }
209 209
 // Location: RecommendedVersions.php
Please login to merge, or discard this patch.
core/request_stack/EE_Request.core.php 1 patch
Indentation   +325 added lines, -325 removed lines patch added patch discarded remove patch
@@ -22,331 +22,331 @@
 block discarded – undo
22 22
 class EE_Request implements LegacyRequestInterface, InterminableInterface
23 23
 {
24 24
 
25
-    /**
26
-     * @var RequestInterface $request
27
-     */
28
-    private $request;
29
-
30
-    /**
31
-     * whether current request is for the admin but NOT via AJAX
32
-     *
33
-     * @var boolean $admin
34
-     */
35
-    public $admin = false;
36
-
37
-    /**
38
-     * whether current request is via AJAX
39
-     *
40
-     * @var boolean $ajax
41
-     */
42
-    public $ajax = false;
43
-
44
-    /**
45
-     * whether current request is via AJAX from the frontend of the site
46
-     *
47
-     * @var boolean $front_ajax
48
-     */
49
-    public $front_ajax = false;
50
-
51
-
52
-    /**
53
-     * @deprecated 4.9.53
54
-     * @param array $get
55
-     * @param array $post
56
-     * @param array $cookie
57
-     * @param array $server
58
-     */
59
-    public function __construct(
60
-        array $get = array(),
61
-        array $post = array(),
62
-        array $cookie = array(),
63
-        array $server = array()
64
-    ) {
65
-    }
66
-
67
-
68
-    /**
69
-     * @return RequestInterface
70
-     * @throws InvalidArgumentException
71
-     * @throws InvalidInterfaceException
72
-     * @throws InvalidDataTypeException
73
-     */
74
-    private function request()
75
-    {
76
-        if($this->request instanceof RequestInterface){
77
-            return $this->request;
78
-        }
79
-        $loader = LoaderFactory::getLoader();
80
-        $this->request = $loader->getShared('EventEspresso\core\services\request\RequestInterface');
81
-        return $this->request;
82
-    }
83
-
84
-
85
-    /**
86
-     * @param RequestInterface $request
87
-     */
88
-    public function setRequest(RequestInterface $request)
89
-    {
90
-        $this->request = $request;
91
-    }
92
-
93
-
94
-
95
-    /**
96
-     * @deprecated 4.9.53
97
-     * @return array
98
-     * @throws InvalidArgumentException
99
-     * @throws InvalidDataTypeException
100
-     * @throws InvalidInterfaceException
101
-     */
102
-    public function get_params()
103
-    {
104
-        return $this->request()->getParams();
105
-    }
106
-
107
-
108
-
109
-    /**
110
-     * @deprecated 4.9.53
111
-     * @return array
112
-     * @throws InvalidArgumentException
113
-     * @throws InvalidDataTypeException
114
-     * @throws InvalidInterfaceException
115
-     */
116
-    public function post_params()
117
-    {
118
-        return $this->request()->postParams();
119
-    }
120
-
121
-
122
-
123
-    /**
124
-     * @deprecated 4.9.53
125
-     * @return array
126
-     * @throws InvalidArgumentException
127
-     * @throws InvalidDataTypeException
128
-     * @throws InvalidInterfaceException
129
-     */
130
-    public function cookie_params()
131
-    {
132
-        return $this->request()->cookieParams();
133
-    }
134
-
135
-
136
-    /**
137
-     * @deprecated 4.9.53
138
-     * @return array
139
-     * @throws InvalidArgumentException
140
-     * @throws InvalidDataTypeException
141
-     * @throws InvalidInterfaceException
142
-     */
143
-    public function server_params()
144
-    {
145
-        return $this->request()->serverParams();
146
-    }
147
-
148
-
149
-
150
-    /**
151
-     * returns contents of $_REQUEST
152
-     *
153
-     * @deprecated 4.9.53
154
-     * @return array
155
-     * @throws InvalidArgumentException
156
-     * @throws InvalidDataTypeException
157
-     * @throws InvalidInterfaceException
158
-     */
159
-    public function params()
160
-    {
161
-        return $this->request()->requestParams();
162
-    }
163
-
164
-
165
-
166
-    /**
167
-     * @deprecated 4.9.53
168
-     * @param      $key
169
-     * @param      $value
170
-     * @param bool $override_ee
171
-     * @return void
172
-     * @throws InvalidArgumentException
173
-     * @throws InvalidDataTypeException
174
-     * @throws InvalidInterfaceException
175
-     */
176
-    public function set($key, $value, $override_ee = false)
177
-    {
178
-        $this->request()->setRequestParam($key, $value, $override_ee);
179
-    }
180
-
181
-
182
-
183
-    /**
184
-     * returns   the value for a request param if the given key exists
185
-     *
186
-     * @deprecated 4.9.53
187
-     * @param      $key
188
-     * @param null $default
189
-     * @return mixed
190
-     * @throws InvalidArgumentException
191
-     * @throws InvalidDataTypeException
192
-     * @throws InvalidInterfaceException
193
-     */
194
-    public function get($key, $default = null)
195
-    {
196
-        return $this->request()->getRequestParam($key, $default);
197
-    }
198
-
199
-
200
-
201
-    /**
202
-     * check if param exists
203
-     *
204
-     * @deprecated 4.9.53
205
-     * @param $key
206
-     * @return bool
207
-     * @throws InvalidArgumentException
208
-     * @throws InvalidDataTypeException
209
-     * @throws InvalidInterfaceException
210
-     */
211
-    public function is_set($key)
212
-    {
213
-        return $this->request()->requestParamIsSet($key);
214
-    }
215
-
216
-
217
-
218
-    /**
219
-     * remove param
220
-     *
221
-     * @deprecated 4.9.53
222
-     * @param      $key
223
-     * @param bool $unset_from_global_too
224
-     * @throws InvalidArgumentException
225
-     * @throws InvalidDataTypeException
226
-     * @throws InvalidInterfaceException
227
-     */
228
-    public function un_set($key, $unset_from_global_too = false)
229
-    {
230
-        $this->request()->unSetRequestParam($key, $unset_from_global_too);
231
-    }
232
-
233
-
234
-
235
-    /**
236
-     * @deprecated 4.9.53
237
-     * @return string
238
-     * @throws InvalidArgumentException
239
-     * @throws InvalidDataTypeException
240
-     * @throws InvalidInterfaceException
241
-     */
242
-    public function ip_address()
243
-    {
244
-        return $this->request()->ipAddress();
245
-    }
246
-
247
-
248
-    /**
249
-     * @deprecated 4.9.53
250
-     * @return bool
251
-     * @throws InvalidArgumentException
252
-     * @throws InvalidDataTypeException
253
-     * @throws InvalidInterfaceException
254
-     */
255
-    public function isAdmin()
256
-    {
257
-        return $this->request()->isAdmin();
258
-    }
259
-
260
-
261
-    /**
262
-     * @deprecated 4.9.53
263
-     * @return mixed
264
-     * @throws InvalidArgumentException
265
-     * @throws InvalidDataTypeException
266
-     * @throws InvalidInterfaceException
267
-     */
268
-    public function isAjax()
269
-    {
270
-        return $this->request()->isAjax();
271
-    }
272
-
273
-
274
-    /**
275
-     * @deprecated 4.9.53
276
-     * @return mixed
277
-     * @throws InvalidArgumentException
278
-     * @throws InvalidDataTypeException
279
-     * @throws InvalidInterfaceException
280
-     */
281
-    public function isFrontAjax()
282
-    {
283
-        return $this->request()->isFrontAjax();
284
-    }
285
-
286
-
287
-    /**
288
-     * @deprecated 4.9.53
289
-     * @return mixed|string
290
-     * @throws InvalidArgumentException
291
-     * @throws InvalidDataTypeException
292
-     * @throws InvalidInterfaceException
293
-     */
294
-    public function requestUri()
295
-    {
296
-        return $this->request()->requestUri();
297
-    }
298
-
299
-
300
-    /**
301
-     * @deprecated 4.9.53
302
-     * @return string
303
-     * @throws InvalidArgumentException
304
-     * @throws InvalidDataTypeException
305
-     * @throws InvalidInterfaceException
306
-     */
307
-    public function userAgent()
308
-    {
309
-        return $this->request()->userAgent();
310
-    }
311
-
312
-
313
-    /**
314
-     * @deprecated 4.9.53
315
-     * @param string $user_agent
316
-     * @throws InvalidArgumentException
317
-     * @throws InvalidDataTypeException
318
-     * @throws InvalidInterfaceException
319
-     */
320
-    public function setUserAgent($user_agent = '')
321
-    {
322
-        $this->request()->setUserAgent($user_agent);
323
-    }
324
-
325
-
326
-    /**
327
-     * @deprecated 4.9.53
328
-     * @return bool
329
-     * @throws InvalidArgumentException
330
-     * @throws InvalidDataTypeException
331
-     * @throws InvalidInterfaceException
332
-     */
333
-    public function isBot()
334
-    {
335
-        return $this->request()->isBot();
336
-    }
337
-
338
-
339
-    /**
340
-     * @deprecated 4.9.53
341
-     * @param bool $is_bot
342
-     * @throws InvalidArgumentException
343
-     * @throws InvalidDataTypeException
344
-     * @throws InvalidInterfaceException
345
-     */
346
-    public function setIsBot($is_bot)
347
-    {
348
-        $this->request()->setIsBot($is_bot);
349
-    }
25
+	/**
26
+	 * @var RequestInterface $request
27
+	 */
28
+	private $request;
29
+
30
+	/**
31
+	 * whether current request is for the admin but NOT via AJAX
32
+	 *
33
+	 * @var boolean $admin
34
+	 */
35
+	public $admin = false;
36
+
37
+	/**
38
+	 * whether current request is via AJAX
39
+	 *
40
+	 * @var boolean $ajax
41
+	 */
42
+	public $ajax = false;
43
+
44
+	/**
45
+	 * whether current request is via AJAX from the frontend of the site
46
+	 *
47
+	 * @var boolean $front_ajax
48
+	 */
49
+	public $front_ajax = false;
50
+
51
+
52
+	/**
53
+	 * @deprecated 4.9.53
54
+	 * @param array $get
55
+	 * @param array $post
56
+	 * @param array $cookie
57
+	 * @param array $server
58
+	 */
59
+	public function __construct(
60
+		array $get = array(),
61
+		array $post = array(),
62
+		array $cookie = array(),
63
+		array $server = array()
64
+	) {
65
+	}
66
+
67
+
68
+	/**
69
+	 * @return RequestInterface
70
+	 * @throws InvalidArgumentException
71
+	 * @throws InvalidInterfaceException
72
+	 * @throws InvalidDataTypeException
73
+	 */
74
+	private function request()
75
+	{
76
+		if($this->request instanceof RequestInterface){
77
+			return $this->request;
78
+		}
79
+		$loader = LoaderFactory::getLoader();
80
+		$this->request = $loader->getShared('EventEspresso\core\services\request\RequestInterface');
81
+		return $this->request;
82
+	}
83
+
84
+
85
+	/**
86
+	 * @param RequestInterface $request
87
+	 */
88
+	public function setRequest(RequestInterface $request)
89
+	{
90
+		$this->request = $request;
91
+	}
92
+
93
+
94
+
95
+	/**
96
+	 * @deprecated 4.9.53
97
+	 * @return array
98
+	 * @throws InvalidArgumentException
99
+	 * @throws InvalidDataTypeException
100
+	 * @throws InvalidInterfaceException
101
+	 */
102
+	public function get_params()
103
+	{
104
+		return $this->request()->getParams();
105
+	}
106
+
107
+
108
+
109
+	/**
110
+	 * @deprecated 4.9.53
111
+	 * @return array
112
+	 * @throws InvalidArgumentException
113
+	 * @throws InvalidDataTypeException
114
+	 * @throws InvalidInterfaceException
115
+	 */
116
+	public function post_params()
117
+	{
118
+		return $this->request()->postParams();
119
+	}
120
+
121
+
122
+
123
+	/**
124
+	 * @deprecated 4.9.53
125
+	 * @return array
126
+	 * @throws InvalidArgumentException
127
+	 * @throws InvalidDataTypeException
128
+	 * @throws InvalidInterfaceException
129
+	 */
130
+	public function cookie_params()
131
+	{
132
+		return $this->request()->cookieParams();
133
+	}
134
+
135
+
136
+	/**
137
+	 * @deprecated 4.9.53
138
+	 * @return array
139
+	 * @throws InvalidArgumentException
140
+	 * @throws InvalidDataTypeException
141
+	 * @throws InvalidInterfaceException
142
+	 */
143
+	public function server_params()
144
+	{
145
+		return $this->request()->serverParams();
146
+	}
147
+
148
+
149
+
150
+	/**
151
+	 * returns contents of $_REQUEST
152
+	 *
153
+	 * @deprecated 4.9.53
154
+	 * @return array
155
+	 * @throws InvalidArgumentException
156
+	 * @throws InvalidDataTypeException
157
+	 * @throws InvalidInterfaceException
158
+	 */
159
+	public function params()
160
+	{
161
+		return $this->request()->requestParams();
162
+	}
163
+
164
+
165
+
166
+	/**
167
+	 * @deprecated 4.9.53
168
+	 * @param      $key
169
+	 * @param      $value
170
+	 * @param bool $override_ee
171
+	 * @return void
172
+	 * @throws InvalidArgumentException
173
+	 * @throws InvalidDataTypeException
174
+	 * @throws InvalidInterfaceException
175
+	 */
176
+	public function set($key, $value, $override_ee = false)
177
+	{
178
+		$this->request()->setRequestParam($key, $value, $override_ee);
179
+	}
180
+
181
+
182
+
183
+	/**
184
+	 * returns   the value for a request param if the given key exists
185
+	 *
186
+	 * @deprecated 4.9.53
187
+	 * @param      $key
188
+	 * @param null $default
189
+	 * @return mixed
190
+	 * @throws InvalidArgumentException
191
+	 * @throws InvalidDataTypeException
192
+	 * @throws InvalidInterfaceException
193
+	 */
194
+	public function get($key, $default = null)
195
+	{
196
+		return $this->request()->getRequestParam($key, $default);
197
+	}
198
+
199
+
200
+
201
+	/**
202
+	 * check if param exists
203
+	 *
204
+	 * @deprecated 4.9.53
205
+	 * @param $key
206
+	 * @return bool
207
+	 * @throws InvalidArgumentException
208
+	 * @throws InvalidDataTypeException
209
+	 * @throws InvalidInterfaceException
210
+	 */
211
+	public function is_set($key)
212
+	{
213
+		return $this->request()->requestParamIsSet($key);
214
+	}
215
+
216
+
217
+
218
+	/**
219
+	 * remove param
220
+	 *
221
+	 * @deprecated 4.9.53
222
+	 * @param      $key
223
+	 * @param bool $unset_from_global_too
224
+	 * @throws InvalidArgumentException
225
+	 * @throws InvalidDataTypeException
226
+	 * @throws InvalidInterfaceException
227
+	 */
228
+	public function un_set($key, $unset_from_global_too = false)
229
+	{
230
+		$this->request()->unSetRequestParam($key, $unset_from_global_too);
231
+	}
232
+
233
+
234
+
235
+	/**
236
+	 * @deprecated 4.9.53
237
+	 * @return string
238
+	 * @throws InvalidArgumentException
239
+	 * @throws InvalidDataTypeException
240
+	 * @throws InvalidInterfaceException
241
+	 */
242
+	public function ip_address()
243
+	{
244
+		return $this->request()->ipAddress();
245
+	}
246
+
247
+
248
+	/**
249
+	 * @deprecated 4.9.53
250
+	 * @return bool
251
+	 * @throws InvalidArgumentException
252
+	 * @throws InvalidDataTypeException
253
+	 * @throws InvalidInterfaceException
254
+	 */
255
+	public function isAdmin()
256
+	{
257
+		return $this->request()->isAdmin();
258
+	}
259
+
260
+
261
+	/**
262
+	 * @deprecated 4.9.53
263
+	 * @return mixed
264
+	 * @throws InvalidArgumentException
265
+	 * @throws InvalidDataTypeException
266
+	 * @throws InvalidInterfaceException
267
+	 */
268
+	public function isAjax()
269
+	{
270
+		return $this->request()->isAjax();
271
+	}
272
+
273
+
274
+	/**
275
+	 * @deprecated 4.9.53
276
+	 * @return mixed
277
+	 * @throws InvalidArgumentException
278
+	 * @throws InvalidDataTypeException
279
+	 * @throws InvalidInterfaceException
280
+	 */
281
+	public function isFrontAjax()
282
+	{
283
+		return $this->request()->isFrontAjax();
284
+	}
285
+
286
+
287
+	/**
288
+	 * @deprecated 4.9.53
289
+	 * @return mixed|string
290
+	 * @throws InvalidArgumentException
291
+	 * @throws InvalidDataTypeException
292
+	 * @throws InvalidInterfaceException
293
+	 */
294
+	public function requestUri()
295
+	{
296
+		return $this->request()->requestUri();
297
+	}
298
+
299
+
300
+	/**
301
+	 * @deprecated 4.9.53
302
+	 * @return string
303
+	 * @throws InvalidArgumentException
304
+	 * @throws InvalidDataTypeException
305
+	 * @throws InvalidInterfaceException
306
+	 */
307
+	public function userAgent()
308
+	{
309
+		return $this->request()->userAgent();
310
+	}
311
+
312
+
313
+	/**
314
+	 * @deprecated 4.9.53
315
+	 * @param string $user_agent
316
+	 * @throws InvalidArgumentException
317
+	 * @throws InvalidDataTypeException
318
+	 * @throws InvalidInterfaceException
319
+	 */
320
+	public function setUserAgent($user_agent = '')
321
+	{
322
+		$this->request()->setUserAgent($user_agent);
323
+	}
324
+
325
+
326
+	/**
327
+	 * @deprecated 4.9.53
328
+	 * @return bool
329
+	 * @throws InvalidArgumentException
330
+	 * @throws InvalidDataTypeException
331
+	 * @throws InvalidInterfaceException
332
+	 */
333
+	public function isBot()
334
+	{
335
+		return $this->request()->isBot();
336
+	}
337
+
338
+
339
+	/**
340
+	 * @deprecated 4.9.53
341
+	 * @param bool $is_bot
342
+	 * @throws InvalidArgumentException
343
+	 * @throws InvalidDataTypeException
344
+	 * @throws InvalidInterfaceException
345
+	 */
346
+	public function setIsBot($is_bot)
347
+	{
348
+		$this->request()->setIsBot($is_bot);
349
+	}
350 350
 
351 351
 
352 352
 
Please login to merge, or discard this patch.
espresso.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
  * @since       4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
41
+    if ( ! function_exists('espresso_duplicate_plugin_error')) {
42 42
         /**
43 43
          *    espresso_duplicate_plugin_error
44 44
          *    displays if more than one version of EE is activated at the same time
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
 
64 64
 } else {
65 65
     define('EE_MIN_PHP_VER_REQUIRED', '5.4.0');
66
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+    if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
67 67
         /**
68 68
          * espresso_minimum_php_version_error
69 69
          * @return void
@@ -116,11 +116,11 @@  discard block
 block discarded – undo
116 116
 
117 117
         register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
118 118
 
119
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
119
+        require_once __DIR__.'/core/bootstrap_espresso.php';
120 120
         bootstrap_espresso();
121 121
     }
122 122
 }
123
-if (! function_exists('espresso_deactivate_plugin')) {
123
+if ( ! function_exists('espresso_deactivate_plugin')) {
124 124
     /**
125 125
      *    deactivate_plugin
126 126
      * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
@@ -131,8 +131,8 @@  discard block
 block discarded – undo
131 131
      */
132 132
     function espresso_deactivate_plugin($plugin_basename = '')
133 133
     {
134
-        if (! function_exists('deactivate_plugins')) {
135
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
134
+        if ( ! function_exists('deactivate_plugins')) {
135
+            require_once ABSPATH.'wp-admin/includes/plugin.php';
136 136
         }
137 137
         unset($_GET['activate'], $_REQUEST['activate']);
138 138
         deactivate_plugins($plugin_basename);
Please login to merge, or discard this patch.
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -38,103 +38,103 @@
 block discarded – undo
38 38
  * @since       4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
42
-        /**
43
-         *    espresso_duplicate_plugin_error
44
-         *    displays if more than one version of EE is activated at the same time
45
-         */
46
-        function espresso_duplicate_plugin_error()
47
-        {
48
-            ?>
41
+	if (! function_exists('espresso_duplicate_plugin_error')) {
42
+		/**
43
+		 *    espresso_duplicate_plugin_error
44
+		 *    displays if more than one version of EE is activated at the same time
45
+		 */
46
+		function espresso_duplicate_plugin_error()
47
+		{
48
+			?>
49 49
             <div class="error">
50 50
                 <p>
51 51
                     <?php
52
-                    echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                    ); ?>
52
+					echo esc_html__(
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+					); ?>
56 56
                 </p>
57 57
             </div>
58 58
             <?php
59
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-        }
61
-    }
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
59
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+		}
61
+	}
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 
64 64
 } else {
65
-    define('EE_MIN_PHP_VER_REQUIRED', '5.4.0');
66
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
67
-        /**
68
-         * espresso_minimum_php_version_error
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
65
+	define('EE_MIN_PHP_VER_REQUIRED', '5.4.0');
66
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
67
+		/**
68
+		 * espresso_minimum_php_version_error
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                        esc_html__(
79
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                            'event_espresso'
81
-                        ),
82
-                        EE_MIN_PHP_VER_REQUIRED,
83
-                        PHP_VERSION,
84
-                        '<br/>',
85
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+						esc_html__(
79
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+							'event_espresso'
81
+						),
82
+						EE_MIN_PHP_VER_REQUIRED,
83
+						PHP_VERSION,
84
+						'<br/>',
85
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
-        /**
98
-         * espresso_version
99
-         * Returns the plugin version
100
-         *
101
-         * @return string
102
-         */
103
-        function espresso_version()
104
-        {
105
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.59.rc.049');
106
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
+		/**
98
+		 * espresso_version
99
+		 * Returns the plugin version
100
+		 *
101
+		 * @return string
102
+		 */
103
+		function espresso_version()
104
+		{
105
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.59.rc.049');
106
+		}
107 107
 
108
-        /**
109
-         * espresso_plugin_activation
110
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
-         */
112
-        function espresso_plugin_activation()
113
-        {
114
-            update_option('ee_espresso_activation', true);
115
-        }
108
+		/**
109
+		 * espresso_plugin_activation
110
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
+		 */
112
+		function espresso_plugin_activation()
113
+		{
114
+			update_option('ee_espresso_activation', true);
115
+		}
116 116
 
117
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
117
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
118 118
 
119
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
120
-        bootstrap_espresso();
121
-    }
119
+		require_once __DIR__ . '/core/bootstrap_espresso.php';
120
+		bootstrap_espresso();
121
+	}
122 122
 }
123 123
 if (! function_exists('espresso_deactivate_plugin')) {
124
-    /**
125
-     *    deactivate_plugin
126
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
-     *
128
-     * @access public
129
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
-     * @return    void
131
-     */
132
-    function espresso_deactivate_plugin($plugin_basename = '')
133
-    {
134
-        if (! function_exists('deactivate_plugins')) {
135
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
-        }
137
-        unset($_GET['activate'], $_REQUEST['activate']);
138
-        deactivate_plugins($plugin_basename);
139
-    }
124
+	/**
125
+	 *    deactivate_plugin
126
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
+	 *
128
+	 * @access public
129
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
+	 * @return    void
131
+	 */
132
+	function espresso_deactivate_plugin($plugin_basename = '')
133
+	{
134
+		if (! function_exists('deactivate_plugins')) {
135
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
+		}
137
+		unset($_GET['activate'], $_REQUEST['activate']);
138
+		deactivate_plugins($plugin_basename);
139
+	}
140 140
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Payment.model.php 1 patch
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@  discard block
 block discarded – undo
8 8
  * @author				Michael Nelson, Brent Christensen
9 9
  *
10 10
  */
11
-class EEM_Payment extends EEM_Base implements EEMI_Payment{
11
+class EEM_Payment extends EEM_Base implements EEMI_Payment {
12 12
 
13 13
   	// private instance of the Payment object
14 14
 	protected static $_instance = NULL;
@@ -56,28 +56,28 @@  discard block
 block discarded – undo
56 56
 	 *		@param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any incoming timezone data that gets saved).  Note this just sends the timezone info to the date time model field objects.  Default is NULL (and will be assumed using the set timezone in the 'timezone_string' wp option)
57 57
 	 *		@return EEM_Payment
58 58
 	 */
59
-	protected function __construct( $timezone ) {
59
+	protected function __construct($timezone) {
60 60
 
61
-		$this->singular_item = __('Payment','event_espresso');
62
-		$this->plural_item = __('Payments','event_espresso');
61
+		$this->singular_item = __('Payment', 'event_espresso');
62
+		$this->plural_item = __('Payments', 'event_espresso');
63 63
 
64 64
 		$this->_tables = array(
65
-			'Payment'=>new EE_Primary_Table('esp_payment','PAY_ID')
65
+			'Payment'=>new EE_Primary_Table('esp_payment', 'PAY_ID')
66 66
 		);
67 67
 		$this->_fields = array(
68 68
 			'Payment'=>array(
69
-				'PAY_ID'=>new EE_Primary_Key_Int_Field('PAY_ID', __('Payment ID','event_espresso')),
70
-				'TXN_ID'=>new EE_Foreign_Key_Int_Field('TXN_ID', __('Transaction ID','event_espresso'), false, 0, 'Transaction'),
71
-				'STS_ID'=>new EE_Foreign_Key_String_Field('STS_ID', __('Status ID','event_espresso'), false, EEM_Payment::status_id_failed, 'Status'),
72
-				'PAY_timestamp'=> new EE_Datetime_Field('PAY_timestamp', __('Timestamp of when payment was attempted','event_espresso'), false, EE_Datetime_Field::now, $timezone ),
73
-				'PAY_source'=>new EE_All_Caps_Text_Field('PAY_source', __('User-friendly description of payment','event_espresso'), false, 'CART'),
74
-				'PAY_amount'=>new EE_Money_Field('PAY_amount', __('Amount Payment should be for','event_espresso'), false, 0),
69
+				'PAY_ID'=>new EE_Primary_Key_Int_Field('PAY_ID', __('Payment ID', 'event_espresso')),
70
+				'TXN_ID'=>new EE_Foreign_Key_Int_Field('TXN_ID', __('Transaction ID', 'event_espresso'), false, 0, 'Transaction'),
71
+				'STS_ID'=>new EE_Foreign_Key_String_Field('STS_ID', __('Status ID', 'event_espresso'), false, EEM_Payment::status_id_failed, 'Status'),
72
+				'PAY_timestamp'=> new EE_Datetime_Field('PAY_timestamp', __('Timestamp of when payment was attempted', 'event_espresso'), false, EE_Datetime_Field::now, $timezone),
73
+				'PAY_source'=>new EE_All_Caps_Text_Field('PAY_source', __('User-friendly description of payment', 'event_espresso'), false, 'CART'),
74
+				'PAY_amount'=>new EE_Money_Field('PAY_amount', __('Amount Payment should be for', 'event_espresso'), false, 0),
75 75
 				'PMD_ID'=>new EE_Foreign_Key_Int_Field('PMD_ID', __("Payment Method ID", 'event_espresso'), false, NULL, 'Payment_Method'),
76
-				'PAY_gateway_response'=>new EE_Plain_Text_Field('PAY_gateway_response', __('Response from Gateway about the payment','event_espresso'), false, ''),
77
-				'PAY_txn_id_chq_nmbr'=>new EE_Plain_Text_Field('PAY_txn_id_chq_nmbr', __('Gateway Transaction ID or Cheque Number','event_espresso'), true, ''),
78
-				'PAY_po_number'=>new EE_Plain_Text_Field('PAY_po_number', __('Purchase or Sales Number','event_espresso'), true, ''),
79
-				'PAY_extra_accntng'=>new EE_Simple_HTML_Field('PAY_extra_accntng', __('Extra Account Info','event_espresso'), true, ''),
80
-				'PAY_details'=>new EE_Serialized_Text_Field('PAY_details', __('Full Gateway response about payment','event_espresso'), true, ''),
76
+				'PAY_gateway_response'=>new EE_Plain_Text_Field('PAY_gateway_response', __('Response from Gateway about the payment', 'event_espresso'), false, ''),
77
+				'PAY_txn_id_chq_nmbr'=>new EE_Plain_Text_Field('PAY_txn_id_chq_nmbr', __('Gateway Transaction ID or Cheque Number', 'event_espresso'), true, ''),
78
+				'PAY_po_number'=>new EE_Plain_Text_Field('PAY_po_number', __('Purchase or Sales Number', 'event_espresso'), true, ''),
79
+				'PAY_extra_accntng'=>new EE_Simple_HTML_Field('PAY_extra_accntng', __('Extra Account Info', 'event_espresso'), true, ''),
80
+				'PAY_details'=>new EE_Serialized_Text_Field('PAY_details', __('Full Gateway response about payment', 'event_espresso'), true, ''),
81 81
 				'PAY_redirect_url'=>new EE_Plain_Text_Field('PAY_redirect_url', __("Redirect URL", 'event_espresso'), true),
82 82
 				'PAY_redirect_args'=>new EE_Serialized_Text_Field('PAY_redirect_args', __("Key-Value POST vars to send along with redirect", 'event_espresso'), true)
83 83
 			)
@@ -87,11 +87,11 @@  discard block
 block discarded – undo
87 87
 			'Status'=> new EE_Belongs_To_Relation(),
88 88
 			'Payment_Method'=>new EE_Belongs_To_Relation(),
89 89
 			'Registration_Payment' => new EE_Has_Many_Relation(),
90
-			'Registration' => new EE_HABTM_Relation( 'Registration_Payment' ),
90
+			'Registration' => new EE_HABTM_Relation('Registration_Payment'),
91 91
 		);
92 92
 		$this->_model_chain_to_wp_user = 'Payment_Method';
93 93
 		$this->_caps_slug = 'transactions';
94
-		parent::__construct( $timezone );
94
+		parent::__construct($timezone);
95 95
 	}
96 96
 
97 97
 
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 	 * @param string $PAY_txn_id_chq_nmbr
104 104
 	 * @return EE_Payment
105 105
 	 */
106
-	public function get_payment_by_txn_id_chq_nmbr( $PAY_txn_id_chq_nmbr ){
106
+	public function get_payment_by_txn_id_chq_nmbr($PAY_txn_id_chq_nmbr) {
107 107
 		return $this->get_one(array(array('PAY_txn_id_chq_nmbr'=>$PAY_txn_id_chq_nmbr)));
108 108
 	}
109 109
 
@@ -119,15 +119,15 @@  discard block
 block discarded – undo
119 119
 	 *		@param	string	$status_of_payment one of EEM_Payment::status_id_*, like 'PAP','PCN',etc. If none is provided, gets payments with any status
120 120
 	*		@return		EE_Payment[]
121 121
 	*/
122
-	public function get_payments_for_transaction( $TXN_ID = FALSE, $status_of_payment = null ) {
122
+	public function get_payments_for_transaction($TXN_ID = FALSE, $status_of_payment = null) {
123 123
 		// all payments for a TXN ordered chronologically
124
-		$query_params = array( array( 'TXN_ID' => $TXN_ID ), 'order_by' => array( 'PAY_timestamp' => 'ASC' ));
124
+		$query_params = array(array('TXN_ID' => $TXN_ID), 'order_by' => array('PAY_timestamp' => 'ASC'));
125 125
 		// if provided with a status, search specifically for that status. Otherwise get them all
126
-		if ( $status_of_payment ){
126
+		if ($status_of_payment) {
127 127
 			$query_params[0]['STS_ID'] = $status_of_payment;
128 128
 		}
129 129
 		// retrieve payments
130
-		return $this->get_all ( $query_params );
130
+		return $this->get_all($query_params);
131 131
 	}
132 132
 
133 133
 
@@ -137,8 +137,8 @@  discard block
 block discarded – undo
137 137
 	 * @param int $TXN_ID
138 138
 	 * @return EE_Payment[]
139 139
 	 */
140
-	public function get_approved_payments_for_transaction( $TXN_ID = 0 ) {
141
-		return $this->get_payments_for_transaction( $TXN_ID, EEM_Payment::status_id_approved );
140
+	public function get_approved_payments_for_transaction($TXN_ID = 0) {
141
+		return $this->get_payments_for_transaction($TXN_ID, EEM_Payment::status_id_approved);
142 142
 
143 143
 	}
144 144
 
@@ -159,36 +159,36 @@  discard block
 block discarded – undo
159 159
 	 *
160 160
 	 * @return EE_Payment[]
161 161
 	 */
162
-	public function get_payments_made_between_dates( $start_date = '', $end_date = '', $format = '', $timezone = '' ) {
163
-		$timezone = empty( $timezone ) ? EEH_DTT_Helper::get_timezone() : $timezone;
162
+	public function get_payments_made_between_dates($start_date = '', $end_date = '', $format = '', $timezone = '') {
163
+		$timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
164 164
 		//if $start_date or $end date, verify $format is included.
165
-		if ( ( ! empty( $start_date ) || ! empty( $end_date ) ) && empty( $format ) ) {
166
-			throw new EE_Error( __('You included a start date and/or a end date for this method but did not include a format string.  The format string is needed for setting up the query', 'event_espresso' ) );
165
+		if (( ! empty($start_date) || ! empty($end_date)) && empty($format)) {
166
+			throw new EE_Error(__('You included a start date and/or a end date for this method but did not include a format string.  The format string is needed for setting up the query', 'event_espresso'));
167 167
 		}
168
-		$now = new DateTime( 'now' );
168
+		$now = new DateTime('now');
169 169
 		// setup timezone objects once
170
-		$modelDateTimeZone = new DateTimeZone( $this->_timezone );
171
-		$passedDateTimeZone = new DateTimeZone( $timezone );
170
+		$modelDateTimeZone = new DateTimeZone($this->_timezone);
171
+		$passedDateTimeZone = new DateTimeZone($timezone);
172 172
 		// setup start date
173
-		$start_date = ! empty( $start_date ) ? date_create_from_format( $format, $start_date, $passedDateTimeZone ) : $now;
173
+		$start_date = ! empty($start_date) ? date_create_from_format($format, $start_date, $passedDateTimeZone) : $now;
174 174
 		EEH_DTT_Helper::setTimezone($start_date, $modelDateTimeZone);
175
-		$start_date = $start_date->format( 'Y-m-d' ) . ' 00:00:00';
176
-		$start_date = strtotime( $start_date );
175
+		$start_date = $start_date->format('Y-m-d').' 00:00:00';
176
+		$start_date = strtotime($start_date);
177 177
 		// setup end date
178
-		$end_date = ! empty( $end_date ) ? date_create_from_format( $format, $end_date, $passedDateTimeZone ) : $now;
178
+		$end_date = ! empty($end_date) ? date_create_from_format($format, $end_date, $passedDateTimeZone) : $now;
179 179
 		EEH_DTT_Helper::setTimezone($end_date, $modelDateTimeZone);
180
-		$end_date = $end_date->format('Y-m-d') . ' 23:59:59';
181
-		$end_date = strtotime( $end_date );
180
+		$end_date = $end_date->format('Y-m-d').' 23:59:59';
181
+		$end_date = strtotime($end_date);
182 182
 
183 183
 		// make sure our start date is the lowest value and vice versa
184
-		$start = min( $start_date, $end_date );
185
-		$end = max( $start_date, $end_date );
184
+		$start = min($start_date, $end_date);
185
+		$end = max($start_date, $end_date);
186 186
 
187 187
 		//yes we generated the date and time string in utc but we WANT this start date and time used in the set timezone on the model.
188
-		$start_date = $this->convert_datetime_for_query( 'PAY_timestamp', date( 'Y-m-d', $start ) . ' 00:00:00', 'Y-m-d H:i:s', $this->get_timezone() );
189
-		$end_date = $this->convert_datetime_for_query( 'PAY_timestamp', date( 'Y-m-d', $end) . ' 23:59:59' , 'Y-m-d H:i:s', $this->get_timezone() );
188
+		$start_date = $this->convert_datetime_for_query('PAY_timestamp', date('Y-m-d', $start).' 00:00:00', 'Y-m-d H:i:s', $this->get_timezone());
189
+		$end_date = $this->convert_datetime_for_query('PAY_timestamp', date('Y-m-d', $end).' 23:59:59', 'Y-m-d H:i:s', $this->get_timezone());
190 190
 
191
-		return $this->get_all(array(array('PAY_timestamp'=>array('>=',$start_date),'PAY_timestamp*'=>array('<=',$end_date))));
191
+		return $this->get_all(array(array('PAY_timestamp'=>array('>=', $start_date), 'PAY_timestamp*'=>array('<=', $end_date))));
192 192
 	}
193 193
 
194 194
 	/**
@@ -198,35 +198,35 @@  discard block
 block discarded – undo
198 198
 	 * returns a string for the approved status
199 199
 	 * @return 	string
200 200
 	 */
201
-	function approved_status(){
201
+	function approved_status() {
202 202
 		return self::status_id_approved;
203 203
 	}
204 204
 	/**
205 205
 	 * returns a string for the pending status
206 206
 	 * @return 	string
207 207
 	 */
208
-	function pending_status(){
208
+	function pending_status() {
209 209
 		return self::status_id_pending;
210 210
 	}
211 211
 	/**
212 212
 	 * returns a string for the cancelled status
213 213
 	 * @return 	string
214 214
 	 */
215
-	function cancelled_status(){
215
+	function cancelled_status() {
216 216
 		return self::status_id_cancelled;
217 217
 	}
218 218
 	/**
219 219
 	 * returns a string for the failed status
220 220
 	 * @return 	string
221 221
 	 */
222
-	function failed_status(){
222
+	function failed_status() {
223 223
 		return self::status_id_failed;
224 224
 	}
225 225
 	/**
226 226
 	 * returns a string for the declined status
227 227
 	 * @return 	string
228 228
 	 */
229
-	function declined_status(){
229
+	function declined_status() {
230 230
 		return self::status_id_declined;
231 231
 	}
232 232
 
Please login to merge, or discard this patch.
core/db_models/fields/EE_Datetime_Field.php 2 patches
Indentation   +742 added lines, -742 removed lines patch added patch discarded remove patch
@@ -17,747 +17,747 @@
 block discarded – undo
17 17
 class EE_Datetime_Field extends EE_Model_Field_Base
18 18
 {
19 19
 
20
-    /**
21
-     * The pattern we're looking for is if only the characters 0-9 are found and there are only
22
-     * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
23
-     *
24
-     * @type string unix_timestamp_regex
25
-     */
26
-    const unix_timestamp_regex = '/[0-9]{10,}/';
27
-
28
-    /**
29
-     * @type string mysql_timestamp_format
30
-     */
31
-    const mysql_timestamp_format = 'Y-m-d H:i:s';
32
-
33
-    /**
34
-     * @type string mysql_date_format
35
-     */
36
-    const mysql_date_format = 'Y-m-d';
37
-
38
-    /**
39
-     * @type string mysql_time_format
40
-     */
41
-    const mysql_time_format = 'H:i:s';
42
-
43
-    /**
44
-     * Const for using in the default value. If the field's default is set to this,
45
-     * then we will return the time of calling `get_default_value()`, not
46
-     * just the current time at construction
47
-     */
48
-    const now = 'now';
49
-
50
-    /**
51
-     * The following properties hold the default formats for date and time.
52
-     * Defaults are set via the constructor and can be overridden on class instantiation.
53
-     * However they can also be overridden later by the set_format() method
54
-     * (and corresponding set_date_format, set_time_format methods);
55
-     */
56
-    /**
57
-     * @type string $_date_format
58
-     */
59
-    protected $_date_format = '';
60
-
61
-    /**
62
-     * @type string $_time_format
63
-     */
64
-    protected $_time_format = '';
65
-
66
-    /**
67
-     * @type string $_pretty_date_format
68
-     */
69
-    protected $_pretty_date_format = '';
70
-
71
-    /**
72
-     * @type string $_pretty_time_format
73
-     */
74
-    protected $_pretty_time_format = '';
75
-
76
-    /**
77
-     * @type DateTimeZone $_DateTimeZone
78
-     */
79
-    protected $_DateTimeZone;
80
-
81
-    /**
82
-     * @type DateTimeZone $_UTC_DateTimeZone
83
-     */
84
-    protected $_UTC_DateTimeZone;
85
-
86
-    /**
87
-     * @type DateTimeZone $_blog_DateTimeZone
88
-     */
89
-    protected $_blog_DateTimeZone;
90
-
91
-
92
-    /**
93
-     * This property holds how we want the output returned when getting a datetime string.  It is set for the
94
-     * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
95
-     * and time returned via getters.
96
-     *
97
-     * @var mixed (null|string)
98
-     */
99
-    protected $_date_time_output;
100
-
101
-
102
-    /**
103
-     * timezone string
104
-     * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
105
-     * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
106
-     * coming out of the object to be in.  Default timezone is the current WP timezone option setting
107
-     *
108
-     * @var string
109
-     */
110
-    protected $_timezone_string;
111
-
112
-
113
-    /**
114
-     * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
115
-     * offsets for comparison purposes).
116
-     *
117
-     * @var int
118
-     */
119
-    protected $_blog_offset;
120
-
121
-
122
-
123
-    /**
124
-     * @param string $table_column
125
-     * @param string $nice_name
126
-     * @param bool   $nullable
127
-     * @param string $default_value
128
-     * @param string $timezone_string
129
-     * @param string $date_format
130
-     * @param string $time_format
131
-     * @param string $pretty_date_format
132
-     * @param string $pretty_time_format
133
-     * @throws EE_Error
134
-     * @throws InvalidArgumentException
135
-     */
136
-    public function __construct(
137
-        $table_column,
138
-        $nice_name,
139
-        $nullable,
140
-        $default_value,
141
-        $timezone_string = '',
142
-        $date_format = '',
143
-        $time_format = '',
144
-        $pretty_date_format = '',
145
-        $pretty_time_format = ''
146
-    ) {
147
-
148
-        $this->_date_format        = ! empty($date_format) ? $date_format : get_option('date_format');
149
-        $this->_time_format        = ! empty($time_format) ? $time_format : get_option('time_format');
150
-        $this->_pretty_date_format = ! empty($pretty_date_format) ? $pretty_date_format : get_option('date_format');
151
-        $this->_pretty_time_format = ! empty($pretty_time_format) ? $pretty_time_format : get_option('time_format');
152
-
153
-        parent::__construct($table_column, $nice_name, $nullable, $default_value);
154
-        $this->set_timezone($timezone_string);
155
-        $this->setSchemaFormat('date-time');
156
-    }
157
-
158
-
159
-    /**
160
-     * @return DateTimeZone
161
-     * @throws \EE_Error
162
-     */
163
-    public function get_UTC_DateTimeZone()
164
-    {
165
-        return $this->_UTC_DateTimeZone instanceof DateTimeZone
166
-            ? $this->_UTC_DateTimeZone
167
-            : $this->_create_timezone_object_from_timezone_string('UTC');
168
-    }
169
-
170
-
171
-    /**
172
-     * @return DateTimeZone
173
-     * @throws \EE_Error
174
-     */
175
-    public function get_blog_DateTimeZone()
176
-    {
177
-        return $this->_blog_DateTimeZone instanceof DateTimeZone
178
-            ? $this->_blog_DateTimeZone
179
-            : $this->_create_timezone_object_from_timezone_string('');
180
-    }
181
-
182
-
183
-    /**
184
-     * this prepares any incoming date data and make sure its converted to a utc unix timestamp
185
-     *
186
-     * @param  string|int $value_inputted_for_field_on_model_object could be a string formatted date time or int unix
187
-     *                                                              timestamp
188
-     * @return DateTime
189
-     */
190
-    public function prepare_for_set($value_inputted_for_field_on_model_object)
191
-    {
192
-        return $this->_get_date_object($value_inputted_for_field_on_model_object);
193
-    }
194
-
195
-
196
-    /**
197
-     * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
198
-     * getters need to know whether we're just returning the date or the time or both.  By default we return both.
199
-     *
200
-     * @param bool $pretty If we're returning the pretty formats or standard format string.
201
-     * @return string    The final assembled format string.
202
-     */
203
-    protected function _get_date_time_output($pretty = false)
204
-    {
205
-
206
-        switch ($this->_date_time_output) {
207
-            case 'time' :
208
-                return $pretty ? $this->_pretty_time_format : $this->_time_format;
209
-                break;
210
-
211
-            case 'date' :
212
-                return $pretty ? $this->_pretty_date_format : $this->_date_format;
213
-                break;
214
-
215
-            default :
216
-                return $pretty
217
-                    ? $this->_pretty_date_format . ' ' . $this->_pretty_time_format
218
-                    : $this->_date_format . ' ' . $this->_time_format;
219
-        }
220
-    }
221
-
222
-
223
-    /**
224
-     * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
225
-     * returned (using the format properties)
226
-     *
227
-     * @param string $what acceptable values are 'time' or 'date'.
228
-     *                     Any other value will be set but will always result
229
-     *                     in both 'date' and 'time' being returned.
230
-     * @return void
231
-     */
232
-    public function set_date_time_output($what = null)
233
-    {
234
-        $this->_date_time_output = $what;
235
-    }
236
-
237
-
238
-    /**
239
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
240
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
241
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
242
-     * We also set some other properties in this method.
243
-     *
244
-     * @param string $timezone_string A valid timezone string as described by @link
245
-     *                                http://www.php.net/manual/en/timezones.php
246
-     * @return void
247
-     * @throws InvalidArgumentException
248
-     * @throws InvalidDataTypeException
249
-     * @throws InvalidInterfaceException
250
-     */
251
-    public function set_timezone($timezone_string)
252
-    {
253
-        if (empty($timezone_string) && $this->_timezone_string !== null) {
254
-            // leave the timezone AS-IS if we already have one and
255
-            // the function arg didn't provide one
256
-            return;
257
-        }
258
-        $timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
259
-        $this->_timezone_string = ! empty($timezone_string) ? $timezone_string : 'UTC';
260
-        $this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
261
-    }
262
-
263
-
264
-    /**
265
-     * _create_timezone_object_from_timezone_name
266
-     *
267
-     * @access protected
268
-     * @param string $timezone_string
269
-     * @return \DateTimeZone
270
-     * @throws InvalidArgumentException
271
-     * @throws InvalidDataTypeException
272
-     * @throws InvalidInterfaceException
273
-     */
274
-    protected function _create_timezone_object_from_timezone_string($timezone_string = '')
275
-    {
276
-        return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
277
-    }
278
-
279
-
280
-    /**
281
-     * This just returns whatever is set for the current timezone.
282
-     *
283
-     * @access public
284
-     * @return string timezone string
285
-     */
286
-    public function get_timezone()
287
-    {
288
-        return $this->_timezone_string;
289
-    }
290
-
291
-
292
-    /**
293
-     * set the $_date_format property
294
-     *
295
-     * @access public
296
-     * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
297
-     * @param bool   $pretty Whether to set pretty format or not.
298
-     * @return void
299
-     */
300
-    public function set_date_format($format, $pretty = false)
301
-    {
302
-        if ($pretty) {
303
-            $this->_pretty_date_format = $format;
304
-        } else {
305
-            $this->_date_format = $format;
306
-        }
307
-    }
308
-
309
-
310
-    /**
311
-     * return the $_date_format property value.
312
-     *
313
-     * @param bool $pretty Whether to get pretty format or not.
314
-     * @return string
315
-     */
316
-    public function get_date_format($pretty = false)
317
-    {
318
-        return $pretty ? $this->_pretty_date_format : $this->_date_format;
319
-    }
320
-
321
-
322
-    /**
323
-     * set the $_time_format property
324
-     *
325
-     * @access public
326
-     * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
327
-     * @param bool   $pretty Whether to set pretty format or not.
328
-     * @return void
329
-     */
330
-    public function set_time_format($format, $pretty = false)
331
-    {
332
-        if ($pretty) {
333
-            $this->_pretty_time_format = $format;
334
-        } else {
335
-            $this->_time_format = $format;
336
-        }
337
-    }
338
-
339
-
340
-    /**
341
-     * return the $_time_format property value.
342
-     *
343
-     * @param bool $pretty Whether to get pretty format or not.
344
-     * @return string
345
-     */
346
-    public function get_time_format($pretty = false)
347
-    {
348
-        return $pretty ? $this->_pretty_time_format : $this->_time_format;
349
-    }
350
-
351
-
352
-    /**
353
-     * set the $_pretty_date_format property
354
-     *
355
-     * @access public
356
-     * @param string $format a new pretty date format (corresponding to formats accepted by PHP date() function)
357
-     * @return void
358
-     */
359
-    public function set_pretty_date_format($format)
360
-    {
361
-        $this->_pretty_date_format = $format;
362
-    }
363
-
364
-
365
-    /**
366
-     * set the $_pretty_time_format property
367
-     *
368
-     * @access public
369
-     * @param string $format a new pretty time format (corresponding to formats accepted by PHP date() function)
370
-     * @return void
371
-     */
372
-    public function set_pretty_time_format($format)
373
-    {
374
-        $this->_pretty_time_format = $format;
375
-    }
376
-
377
-
378
-    /**
379
-     * Only sets the time portion of the datetime.
380
-     *
381
-     * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
382
-     * @param DateTime        $current            current DateTime object for the datetime field
383
-     * @return DateTime
384
-     */
385
-    public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current)
386
-    {
387
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
388
-        // Otherwise parse the string.
389
-        if ($time_to_set_string instanceof DateTime) {
390
-            $parsed = array(
391
-                'hour'   => $time_to_set_string->format('H'),
392
-                'minute' => $time_to_set_string->format('i'),
393
-                'second' => $time_to_set_string->format('s'),
394
-            );
395
-        } else {
396
-            //parse incoming string
397
-            $parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
398
-        }
399
-        EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
400
-        return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
401
-    }
402
-
403
-
404
-    /**
405
-     * Only sets the date portion of the datetime.
406
-     *
407
-     * @param string|DateTime $date_to_set_string like Friday, January 8th or a DateTime object.
408
-     * @param DateTime        $current            current DateTime object for the datetime field
409
-     * @return DateTime
410
-     */
411
-    public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current)
412
-    {
413
-        // if $time_to_set_string is datetime object, then let's use it to set the parse array.
414
-        // Otherwise parse the string.
415
-        if ($date_to_set_string instanceof DateTime) {
416
-            $parsed = array(
417
-                'year'  => $date_to_set_string->format('Y'),
418
-                'month' => $date_to_set_string->format('m'),
419
-                'day'   => $date_to_set_string->format('d'),
420
-            );
421
-        } else {
422
-            //parse incoming string
423
-            $parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
424
-        }
425
-        EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
426
-        return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
427
-    }
428
-
429
-
430
-    /**
431
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).  When the
432
-     * datetime gets to this stage it should ALREADY be in UTC time
433
-     *
434
-     * @param  DateTime $DateTime
435
-     * @return string formatted date time for given timezone
436
-     * @throws \EE_Error
437
-     */
438
-    public function prepare_for_get($DateTime)
439
-    {
440
-        return $this->_prepare_for_display($DateTime);
441
-    }
442
-
443
-
444
-    /**
445
-     * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
446
-     * from the set wp timezone.  If so, then it returns the datetime string formatted via
447
-     * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
448
-     * abbreviation to the date_string.
449
-     *
450
-     * @param mixed $DateTime
451
-     * @param null  $schema
452
-     * @return string
453
-     * @throws \EE_Error
454
-     */
455
-    public function prepare_for_pretty_echoing($DateTime, $schema = null)
456
-    {
457
-        return $this->_prepare_for_display($DateTime, $schema ? $schema : true);
458
-    }
459
-
460
-
461
-    /**
462
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
463
-     * timezone).
464
-     *
465
-     * @param DateTime    $DateTime
466
-     * @param bool|string $schema
467
-     * @return string
468
-     * @throws \EE_Error
469
-     */
470
-    protected function _prepare_for_display($DateTime, $schema = false)
471
-    {
472
-        if (! $DateTime instanceof DateTime) {
473
-            if ($this->_nullable) {
474
-                return '';
475
-            } else {
476
-                if (WP_DEBUG) {
477
-                    throw new EE_Error(
478
-                        sprintf(
479
-                            __(
480
-                                'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.',
481
-                                'event_espresso'
482
-                            ),
483
-                            $this->_nicename
484
-                        )
485
-                    );
486
-                } else {
487
-                    $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now);
488
-                    EE_Error::add_error(
489
-                        sprintf(
490
-                            __(
491
-                                'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.  When WP_DEBUG is false, the value is set to "now" instead of throwing an exception.',
492
-                                'event_espresso'
493
-                            ),
494
-                            $this->_nicename
495
-                        )
496
-                    );
497
-                }
498
-            }
499
-        }
500
-        $format_string = $this->_get_date_time_output($schema);
501
-        EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
502
-        if ($schema) {
503
-            if ($this->_display_timezone()) {
504
-                //must be explicit because schema could equal true.
505
-                if ($schema === 'no_html') {
506
-                    $timezone_string = ' (' . $DateTime->format('T') . ')';
507
-                } else {
508
-                    $timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
509
-                }
510
-            } else {
511
-                $timezone_string = '';
512
-            }
513
-
514
-            return $DateTime->format($format_string) . $timezone_string;
515
-        }
516
-        return $DateTime->format($format_string);
517
-    }
518
-
519
-
520
-    /**
521
-     * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
522
-     * timezone).
523
-     *
524
-     * @param  mixed $datetime_value u
525
-     * @return string mysql timestamp in UTC
526
-     * @throws \EE_Error
527
-     */
528
-    public function prepare_for_use_in_db($datetime_value)
529
-    {
530
-        //we allow an empty value or DateTime object, but nothing else.
531
-        if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
532
-            throw new EE_Error(
533
-            	sprintf(
534
-            	    __(
535
-            		    'The incoming value being prepared for setting in the database must either be empty or a php 
20
+	/**
21
+	 * The pattern we're looking for is if only the characters 0-9 are found and there are only
22
+	 * 10 or more numbers (because 9 numbers even with all 9's would be sometime in 2001 )
23
+	 *
24
+	 * @type string unix_timestamp_regex
25
+	 */
26
+	const unix_timestamp_regex = '/[0-9]{10,}/';
27
+
28
+	/**
29
+	 * @type string mysql_timestamp_format
30
+	 */
31
+	const mysql_timestamp_format = 'Y-m-d H:i:s';
32
+
33
+	/**
34
+	 * @type string mysql_date_format
35
+	 */
36
+	const mysql_date_format = 'Y-m-d';
37
+
38
+	/**
39
+	 * @type string mysql_time_format
40
+	 */
41
+	const mysql_time_format = 'H:i:s';
42
+
43
+	/**
44
+	 * Const for using in the default value. If the field's default is set to this,
45
+	 * then we will return the time of calling `get_default_value()`, not
46
+	 * just the current time at construction
47
+	 */
48
+	const now = 'now';
49
+
50
+	/**
51
+	 * The following properties hold the default formats for date and time.
52
+	 * Defaults are set via the constructor and can be overridden on class instantiation.
53
+	 * However they can also be overridden later by the set_format() method
54
+	 * (and corresponding set_date_format, set_time_format methods);
55
+	 */
56
+	/**
57
+	 * @type string $_date_format
58
+	 */
59
+	protected $_date_format = '';
60
+
61
+	/**
62
+	 * @type string $_time_format
63
+	 */
64
+	protected $_time_format = '';
65
+
66
+	/**
67
+	 * @type string $_pretty_date_format
68
+	 */
69
+	protected $_pretty_date_format = '';
70
+
71
+	/**
72
+	 * @type string $_pretty_time_format
73
+	 */
74
+	protected $_pretty_time_format = '';
75
+
76
+	/**
77
+	 * @type DateTimeZone $_DateTimeZone
78
+	 */
79
+	protected $_DateTimeZone;
80
+
81
+	/**
82
+	 * @type DateTimeZone $_UTC_DateTimeZone
83
+	 */
84
+	protected $_UTC_DateTimeZone;
85
+
86
+	/**
87
+	 * @type DateTimeZone $_blog_DateTimeZone
88
+	 */
89
+	protected $_blog_DateTimeZone;
90
+
91
+
92
+	/**
93
+	 * This property holds how we want the output returned when getting a datetime string.  It is set for the
94
+	 * set_date_time_output() method.  By default this is empty.  When empty, we are assuming that we want both date
95
+	 * and time returned via getters.
96
+	 *
97
+	 * @var mixed (null|string)
98
+	 */
99
+	protected $_date_time_output;
100
+
101
+
102
+	/**
103
+	 * timezone string
104
+	 * This gets set by the constructor and can be changed by the "set_timezone()" method so that we know what timezone
105
+	 * incoming strings|timestamps are in.  This can also be used before a get to set what timezone you want strings
106
+	 * coming out of the object to be in.  Default timezone is the current WP timezone option setting
107
+	 *
108
+	 * @var string
109
+	 */
110
+	protected $_timezone_string;
111
+
112
+
113
+	/**
114
+	 * This holds whatever UTC offset for the blog (we automatically convert timezone strings into their related
115
+	 * offsets for comparison purposes).
116
+	 *
117
+	 * @var int
118
+	 */
119
+	protected $_blog_offset;
120
+
121
+
122
+
123
+	/**
124
+	 * @param string $table_column
125
+	 * @param string $nice_name
126
+	 * @param bool   $nullable
127
+	 * @param string $default_value
128
+	 * @param string $timezone_string
129
+	 * @param string $date_format
130
+	 * @param string $time_format
131
+	 * @param string $pretty_date_format
132
+	 * @param string $pretty_time_format
133
+	 * @throws EE_Error
134
+	 * @throws InvalidArgumentException
135
+	 */
136
+	public function __construct(
137
+		$table_column,
138
+		$nice_name,
139
+		$nullable,
140
+		$default_value,
141
+		$timezone_string = '',
142
+		$date_format = '',
143
+		$time_format = '',
144
+		$pretty_date_format = '',
145
+		$pretty_time_format = ''
146
+	) {
147
+
148
+		$this->_date_format        = ! empty($date_format) ? $date_format : get_option('date_format');
149
+		$this->_time_format        = ! empty($time_format) ? $time_format : get_option('time_format');
150
+		$this->_pretty_date_format = ! empty($pretty_date_format) ? $pretty_date_format : get_option('date_format');
151
+		$this->_pretty_time_format = ! empty($pretty_time_format) ? $pretty_time_format : get_option('time_format');
152
+
153
+		parent::__construct($table_column, $nice_name, $nullable, $default_value);
154
+		$this->set_timezone($timezone_string);
155
+		$this->setSchemaFormat('date-time');
156
+	}
157
+
158
+
159
+	/**
160
+	 * @return DateTimeZone
161
+	 * @throws \EE_Error
162
+	 */
163
+	public function get_UTC_DateTimeZone()
164
+	{
165
+		return $this->_UTC_DateTimeZone instanceof DateTimeZone
166
+			? $this->_UTC_DateTimeZone
167
+			: $this->_create_timezone_object_from_timezone_string('UTC');
168
+	}
169
+
170
+
171
+	/**
172
+	 * @return DateTimeZone
173
+	 * @throws \EE_Error
174
+	 */
175
+	public function get_blog_DateTimeZone()
176
+	{
177
+		return $this->_blog_DateTimeZone instanceof DateTimeZone
178
+			? $this->_blog_DateTimeZone
179
+			: $this->_create_timezone_object_from_timezone_string('');
180
+	}
181
+
182
+
183
+	/**
184
+	 * this prepares any incoming date data and make sure its converted to a utc unix timestamp
185
+	 *
186
+	 * @param  string|int $value_inputted_for_field_on_model_object could be a string formatted date time or int unix
187
+	 *                                                              timestamp
188
+	 * @return DateTime
189
+	 */
190
+	public function prepare_for_set($value_inputted_for_field_on_model_object)
191
+	{
192
+		return $this->_get_date_object($value_inputted_for_field_on_model_object);
193
+	}
194
+
195
+
196
+	/**
197
+	 * This returns the format string to be used by getters depending on what the $_date_time_output property is set at.
198
+	 * getters need to know whether we're just returning the date or the time or both.  By default we return both.
199
+	 *
200
+	 * @param bool $pretty If we're returning the pretty formats or standard format string.
201
+	 * @return string    The final assembled format string.
202
+	 */
203
+	protected function _get_date_time_output($pretty = false)
204
+	{
205
+
206
+		switch ($this->_date_time_output) {
207
+			case 'time' :
208
+				return $pretty ? $this->_pretty_time_format : $this->_time_format;
209
+				break;
210
+
211
+			case 'date' :
212
+				return $pretty ? $this->_pretty_date_format : $this->_date_format;
213
+				break;
214
+
215
+			default :
216
+				return $pretty
217
+					? $this->_pretty_date_format . ' ' . $this->_pretty_time_format
218
+					: $this->_date_format . ' ' . $this->_time_format;
219
+		}
220
+	}
221
+
222
+
223
+	/**
224
+	 * This just sets the $_date_time_output property so we can flag how date and times are formatted before being
225
+	 * returned (using the format properties)
226
+	 *
227
+	 * @param string $what acceptable values are 'time' or 'date'.
228
+	 *                     Any other value will be set but will always result
229
+	 *                     in both 'date' and 'time' being returned.
230
+	 * @return void
231
+	 */
232
+	public function set_date_time_output($what = null)
233
+	{
234
+		$this->_date_time_output = $what;
235
+	}
236
+
237
+
238
+	/**
239
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
240
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
241
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp).
242
+	 * We also set some other properties in this method.
243
+	 *
244
+	 * @param string $timezone_string A valid timezone string as described by @link
245
+	 *                                http://www.php.net/manual/en/timezones.php
246
+	 * @return void
247
+	 * @throws InvalidArgumentException
248
+	 * @throws InvalidDataTypeException
249
+	 * @throws InvalidInterfaceException
250
+	 */
251
+	public function set_timezone($timezone_string)
252
+	{
253
+		if (empty($timezone_string) && $this->_timezone_string !== null) {
254
+			// leave the timezone AS-IS if we already have one and
255
+			// the function arg didn't provide one
256
+			return;
257
+		}
258
+		$timezone_string        = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
259
+		$this->_timezone_string = ! empty($timezone_string) ? $timezone_string : 'UTC';
260
+		$this->_DateTimeZone    = $this->_create_timezone_object_from_timezone_string($this->_timezone_string);
261
+	}
262
+
263
+
264
+	/**
265
+	 * _create_timezone_object_from_timezone_name
266
+	 *
267
+	 * @access protected
268
+	 * @param string $timezone_string
269
+	 * @return \DateTimeZone
270
+	 * @throws InvalidArgumentException
271
+	 * @throws InvalidDataTypeException
272
+	 * @throws InvalidInterfaceException
273
+	 */
274
+	protected function _create_timezone_object_from_timezone_string($timezone_string = '')
275
+	{
276
+		return new DateTimeZone(EEH_DTT_Helper::get_valid_timezone_string($timezone_string));
277
+	}
278
+
279
+
280
+	/**
281
+	 * This just returns whatever is set for the current timezone.
282
+	 *
283
+	 * @access public
284
+	 * @return string timezone string
285
+	 */
286
+	public function get_timezone()
287
+	{
288
+		return $this->_timezone_string;
289
+	}
290
+
291
+
292
+	/**
293
+	 * set the $_date_format property
294
+	 *
295
+	 * @access public
296
+	 * @param string $format a new date format (corresponding to formats accepted by PHP date() function)
297
+	 * @param bool   $pretty Whether to set pretty format or not.
298
+	 * @return void
299
+	 */
300
+	public function set_date_format($format, $pretty = false)
301
+	{
302
+		if ($pretty) {
303
+			$this->_pretty_date_format = $format;
304
+		} else {
305
+			$this->_date_format = $format;
306
+		}
307
+	}
308
+
309
+
310
+	/**
311
+	 * return the $_date_format property value.
312
+	 *
313
+	 * @param bool $pretty Whether to get pretty format or not.
314
+	 * @return string
315
+	 */
316
+	public function get_date_format($pretty = false)
317
+	{
318
+		return $pretty ? $this->_pretty_date_format : $this->_date_format;
319
+	}
320
+
321
+
322
+	/**
323
+	 * set the $_time_format property
324
+	 *
325
+	 * @access public
326
+	 * @param string $format a new time format (corresponding to formats accepted by PHP date() function)
327
+	 * @param bool   $pretty Whether to set pretty format or not.
328
+	 * @return void
329
+	 */
330
+	public function set_time_format($format, $pretty = false)
331
+	{
332
+		if ($pretty) {
333
+			$this->_pretty_time_format = $format;
334
+		} else {
335
+			$this->_time_format = $format;
336
+		}
337
+	}
338
+
339
+
340
+	/**
341
+	 * return the $_time_format property value.
342
+	 *
343
+	 * @param bool $pretty Whether to get pretty format or not.
344
+	 * @return string
345
+	 */
346
+	public function get_time_format($pretty = false)
347
+	{
348
+		return $pretty ? $this->_pretty_time_format : $this->_time_format;
349
+	}
350
+
351
+
352
+	/**
353
+	 * set the $_pretty_date_format property
354
+	 *
355
+	 * @access public
356
+	 * @param string $format a new pretty date format (corresponding to formats accepted by PHP date() function)
357
+	 * @return void
358
+	 */
359
+	public function set_pretty_date_format($format)
360
+	{
361
+		$this->_pretty_date_format = $format;
362
+	}
363
+
364
+
365
+	/**
366
+	 * set the $_pretty_time_format property
367
+	 *
368
+	 * @access public
369
+	 * @param string $format a new pretty time format (corresponding to formats accepted by PHP date() function)
370
+	 * @return void
371
+	 */
372
+	public function set_pretty_time_format($format)
373
+	{
374
+		$this->_pretty_time_format = $format;
375
+	}
376
+
377
+
378
+	/**
379
+	 * Only sets the time portion of the datetime.
380
+	 *
381
+	 * @param string|DateTime $time_to_set_string like 8am OR a DateTime object.
382
+	 * @param DateTime        $current            current DateTime object for the datetime field
383
+	 * @return DateTime
384
+	 */
385
+	public function prepare_for_set_with_new_time($time_to_set_string, DateTime $current)
386
+	{
387
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
388
+		// Otherwise parse the string.
389
+		if ($time_to_set_string instanceof DateTime) {
390
+			$parsed = array(
391
+				'hour'   => $time_to_set_string->format('H'),
392
+				'minute' => $time_to_set_string->format('i'),
393
+				'second' => $time_to_set_string->format('s'),
394
+			);
395
+		} else {
396
+			//parse incoming string
397
+			$parsed = date_parse_from_format($this->_time_format, $time_to_set_string);
398
+		}
399
+		EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
400
+		return $current->setTime($parsed['hour'], $parsed['minute'], $parsed['second']);
401
+	}
402
+
403
+
404
+	/**
405
+	 * Only sets the date portion of the datetime.
406
+	 *
407
+	 * @param string|DateTime $date_to_set_string like Friday, January 8th or a DateTime object.
408
+	 * @param DateTime        $current            current DateTime object for the datetime field
409
+	 * @return DateTime
410
+	 */
411
+	public function prepare_for_set_with_new_date($date_to_set_string, DateTime $current)
412
+	{
413
+		// if $time_to_set_string is datetime object, then let's use it to set the parse array.
414
+		// Otherwise parse the string.
415
+		if ($date_to_set_string instanceof DateTime) {
416
+			$parsed = array(
417
+				'year'  => $date_to_set_string->format('Y'),
418
+				'month' => $date_to_set_string->format('m'),
419
+				'day'   => $date_to_set_string->format('d'),
420
+			);
421
+		} else {
422
+			//parse incoming string
423
+			$parsed = date_parse_from_format($this->_date_format, $date_to_set_string);
424
+		}
425
+		EEH_DTT_Helper::setTimezone($current, $this->_DateTimeZone);
426
+		return $current->setDate($parsed['year'], $parsed['month'], $parsed['day']);
427
+	}
428
+
429
+
430
+	/**
431
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0 timezone).  When the
432
+	 * datetime gets to this stage it should ALREADY be in UTC time
433
+	 *
434
+	 * @param  DateTime $DateTime
435
+	 * @return string formatted date time for given timezone
436
+	 * @throws \EE_Error
437
+	 */
438
+	public function prepare_for_get($DateTime)
439
+	{
440
+		return $this->_prepare_for_display($DateTime);
441
+	}
442
+
443
+
444
+	/**
445
+	 * This differs from prepare_for_get in that it considers whether the internal $_timezone differs
446
+	 * from the set wp timezone.  If so, then it returns the datetime string formatted via
447
+	 * _pretty_date_format, and _pretty_time_format.  However, it also appends a timezone
448
+	 * abbreviation to the date_string.
449
+	 *
450
+	 * @param mixed $DateTime
451
+	 * @param null  $schema
452
+	 * @return string
453
+	 * @throws \EE_Error
454
+	 */
455
+	public function prepare_for_pretty_echoing($DateTime, $schema = null)
456
+	{
457
+		return $this->_prepare_for_display($DateTime, $schema ? $schema : true);
458
+	}
459
+
460
+
461
+	/**
462
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
463
+	 * timezone).
464
+	 *
465
+	 * @param DateTime    $DateTime
466
+	 * @param bool|string $schema
467
+	 * @return string
468
+	 * @throws \EE_Error
469
+	 */
470
+	protected function _prepare_for_display($DateTime, $schema = false)
471
+	{
472
+		if (! $DateTime instanceof DateTime) {
473
+			if ($this->_nullable) {
474
+				return '';
475
+			} else {
476
+				if (WP_DEBUG) {
477
+					throw new EE_Error(
478
+						sprintf(
479
+							__(
480
+								'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.',
481
+								'event_espresso'
482
+							),
483
+							$this->_nicename
484
+						)
485
+					);
486
+				} else {
487
+					$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now);
488
+					EE_Error::add_error(
489
+						sprintf(
490
+							__(
491
+								'EE_Datetime_Field::_prepare_for_display requires a DateTime class to be the value for the $DateTime argument because the %s field is not nullable.  When WP_DEBUG is false, the value is set to "now" instead of throwing an exception.',
492
+								'event_espresso'
493
+							),
494
+							$this->_nicename
495
+						)
496
+					);
497
+				}
498
+			}
499
+		}
500
+		$format_string = $this->_get_date_time_output($schema);
501
+		EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
502
+		if ($schema) {
503
+			if ($this->_display_timezone()) {
504
+				//must be explicit because schema could equal true.
505
+				if ($schema === 'no_html') {
506
+					$timezone_string = ' (' . $DateTime->format('T') . ')';
507
+				} else {
508
+					$timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
509
+				}
510
+			} else {
511
+				$timezone_string = '';
512
+			}
513
+
514
+			return $DateTime->format($format_string) . $timezone_string;
515
+		}
516
+		return $DateTime->format($format_string);
517
+	}
518
+
519
+
520
+	/**
521
+	 * This prepares the EE_DateTime value to be saved to the db as mysql timestamp (UTC +0
522
+	 * timezone).
523
+	 *
524
+	 * @param  mixed $datetime_value u
525
+	 * @return string mysql timestamp in UTC
526
+	 * @throws \EE_Error
527
+	 */
528
+	public function prepare_for_use_in_db($datetime_value)
529
+	{
530
+		//we allow an empty value or DateTime object, but nothing else.
531
+		if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
532
+			throw new EE_Error(
533
+				sprintf(
534
+					__(
535
+						'The incoming value being prepared for setting in the database must either be empty or a php 
536 536
             		    DateTime object, instead of: %1$s %2$s',
537
-                        'event_espresso'
538
-	                ),
539
-                    '<br />',
540
-                    print_r($datetime_value, true)
541
-                )
542
-            );
543
-        }
544
-
545
-        if ($datetime_value instanceof DateTime) {
546
-            if (! $datetime_value instanceof DbSafeDateTime) {
547
-                $datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
548
-            }
549
-            EEH_DTT_Helper::setTimezone($datetime_value, $this->get_UTC_DateTimeZone());
550
-            return $datetime_value->format(
551
-                EE_Datetime_Field::mysql_timestamp_format
552
-            );
553
-        }
554
-
555
-        // if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
556
-        return ! $this->_nullable && empty($datetime_value) ? current_time('mysql', true) : null;
557
-    }
558
-
559
-
560
-    /**
561
-     * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
562
-     * allowed)
563
-     *
564
-     * @param string $datetime_string mysql timestamp in UTC
565
-     * @return  mixed null | DateTime
566
-     * @throws \EE_Error
567
-     */
568
-    public function prepare_for_set_from_db($datetime_string)
569
-    {
570
-        //if $datetime_value is empty, and ! $this->_nullable, just use time()
571
-        if (empty($datetime_string) && $this->_nullable) {
572
-            return null;
573
-        }
574
-        // datetime strings from the db should ALWAYS be in UTC+0, so use UTC_DateTimeZone when creating
575
-        if (empty($datetime_string)) {
576
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
577
-        } else {
578
-            $DateTime = DateTime::createFromFormat(
579
-                EE_Datetime_Field::mysql_timestamp_format,
580
-                $datetime_string,
581
-                $this->get_UTC_DateTimeZone()
582
-            );
583
-            if ($DateTime instanceof \DateTime) {
584
-                $DateTime = new DbSafeDateTime(
585
-                    $DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
586
-                    $this->get_UTC_DateTimeZone()
587
-                );
588
-            }
589
-        }
590
-
591
-        if (! $DateTime instanceof DbSafeDateTime) {
592
-            // if still no datetime object, then let's just use now
593
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
594
-        }
595
-        // THEN apply the field's set DateTimeZone
596
-        EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
597
-        return $DateTime;
598
-    }
599
-
600
-
601
-    /**
602
-     * All this method does is determine if we're going to display the timezone string or not on any output.
603
-     * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
604
-     * If so, then true.
605
-     *
606
-     * @return bool true for yes false for no
607
-     * @throws \EE_Error
608
-     */
609
-    protected function _display_timezone()
610
-    {
611
-
612
-        // first let's do a comparison of timezone strings.
613
-        // If they match then we can get out without any further calculations
614
-        $blog_string = get_option('timezone_string');
615
-        if ($blog_string === $this->_timezone_string) {
616
-            return false;
617
-        }
618
-        // now we need to calc the offset for the timezone string so we can compare with the blog offset.
619
-        $this_offset = $this->get_timezone_offset($this->_DateTimeZone);
620
-        $blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
621
-        // now compare
622
-        return $blog_offset !== $this_offset;
623
-    }
624
-
625
-
626
-    /**
627
-     * This method returns a php DateTime object for setting on the EE_Base_Class model.
628
-     * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
629
-     * with.
630
-     *
631
-     * @param int|string|DateTime $date_string            This should be the incoming date string.  It's assumed to be
632
-     *                                                    in the format that is set on the date_field (or DateTime
633
-     *                                                    object)!
634
-     * @return DateTime
635
-     */
636
-    protected function _get_date_object($date_string)
637
-    {
638
-        //first if this is an empty date_string and nullable is allowed, just return null.
639
-        if ($this->_nullable && empty($date_string)) {
640
-            return null;
641
-        }
642
-
643
-        // if incoming date
644
-        if ($date_string instanceof DateTime) {
645
-            EEH_DTT_Helper::setTimezone($date_string, $this->_DateTimeZone);
646
-            return $date_string;
647
-        }
648
-        // if empty date_string and made it here.
649
-        // Return a datetime object for now in the given timezone.
650
-        if (empty($date_string)) {
651
-            return new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
652
-        }
653
-        // if $date_string is matches something that looks like a Unix timestamp let's just use it.
654
-        if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
655
-            try {
656
-                // This is operating under the assumption that the incoming Unix timestamp
657
-                // is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
658
-                $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
659
-                $DateTime->setTimestamp($date_string);
660
-
661
-                return $DateTime;
662
-            } catch (Exception $e) {
663
-                // should be rare, but if things got fooled then let's just continue
664
-            }
665
-        }
666
-        //not a unix timestamp.  So we will use the set format on this object and set timezone to
667
-        //create the DateTime object.
668
-        $format = $this->_date_format . ' ' . $this->_time_format;
669
-        try {
670
-            $DateTime = DateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
671
-            if ($DateTime instanceof DateTime) {
672
-                $DateTime = new DbSafeDateTime(
673
-                    $DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
674
-                    $this->_DateTimeZone
675
-                );
676
-            }
677
-            if (! $DateTime instanceof DbSafeDateTime) {
678
-                throw new EE_Error(
679
-                    sprintf(
680
-                        __('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
681
-                        $date_string,
682
-                        $format
683
-                    )
684
-                );
685
-            }
686
-        } catch (Exception $e) {
687
-            // if we made it here then likely then something went really wrong.
688
-            // Instead of throwing an exception, let's just return a DateTime object for now, in the set timezone.
689
-            $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
690
-        }
691
-
692
-        return $DateTime;
693
-    }
694
-
695
-
696
-
697
-    /**
698
-     * get_timezone_transitions
699
-     *
700
-     * @param \DateTimeZone $DateTimeZone
701
-     * @param int           $time
702
-     * @param bool          $first_only
703
-     * @return mixed
704
-     */
705
-    public function get_timezone_transitions(DateTimeZone $DateTimeZone, $time = null, $first_only = true)
706
-    {
707
-        return EEH_DTT_Helper::get_timezone_transitions($DateTimeZone, $time, $first_only);
708
-    }
709
-
710
-
711
-
712
-    /**
713
-     * get_timezone_offset
714
-     *
715
-     * @param \DateTimeZone $DateTimeZone
716
-     * @param int           $time
717
-     * @return mixed
718
-     * @throws \DomainException
719
-     */
720
-    public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
721
-    {
722
-        return EEH_DTT_Helper::get_timezone_offset($DateTimeZone, $time);
723
-    }
724
-
725
-
726
-    /**
727
-     * This will take an incoming timezone string and return the abbreviation for that timezone
728
-     *
729
-     * @param  string $timezone_string
730
-     * @return string           abbreviation
731
-     * @throws \EE_Error
732
-     */
733
-    public function get_timezone_abbrev($timezone_string)
734
-    {
735
-        $timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
736
-        $dateTime        = new DateTime(\EE_Datetime_Field::now, new DateTimeZone($timezone_string));
737
-
738
-        return $dateTime->format('T');
739
-    }
740
-
741
-    /**
742
-     * Overrides the parent to allow for having a dynamic "now" value
743
-     *
744
-     * @return mixed
745
-     */
746
-    public function get_default_value()
747
-    {
748
-        if ($this->_default_value === EE_Datetime_Field::now) {
749
-            return time();
750
-        } else {
751
-            return parent::get_default_value();
752
-        }
753
-    }
754
-
755
-
756
-    public function getSchemaDescription()
757
-    {
758
-        return sprintf(
759
-            esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
760
-            $this->get_nicename()
761
-        );
762
-    }
537
+						'event_espresso'
538
+					),
539
+					'<br />',
540
+					print_r($datetime_value, true)
541
+				)
542
+			);
543
+		}
544
+
545
+		if ($datetime_value instanceof DateTime) {
546
+			if (! $datetime_value instanceof DbSafeDateTime) {
547
+				$datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
548
+			}
549
+			EEH_DTT_Helper::setTimezone($datetime_value, $this->get_UTC_DateTimeZone());
550
+			return $datetime_value->format(
551
+				EE_Datetime_Field::mysql_timestamp_format
552
+			);
553
+		}
554
+
555
+		// if $datetime_value is empty, and ! $this->_nullable, use current_time() but set the GMT flag to true
556
+		return ! $this->_nullable && empty($datetime_value) ? current_time('mysql', true) : null;
557
+	}
558
+
559
+
560
+	/**
561
+	 * This prepares the datetime for internal usage as a PHP DateTime object OR null (if nullable is
562
+	 * allowed)
563
+	 *
564
+	 * @param string $datetime_string mysql timestamp in UTC
565
+	 * @return  mixed null | DateTime
566
+	 * @throws \EE_Error
567
+	 */
568
+	public function prepare_for_set_from_db($datetime_string)
569
+	{
570
+		//if $datetime_value is empty, and ! $this->_nullable, just use time()
571
+		if (empty($datetime_string) && $this->_nullable) {
572
+			return null;
573
+		}
574
+		// datetime strings from the db should ALWAYS be in UTC+0, so use UTC_DateTimeZone when creating
575
+		if (empty($datetime_string)) {
576
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
577
+		} else {
578
+			$DateTime = DateTime::createFromFormat(
579
+				EE_Datetime_Field::mysql_timestamp_format,
580
+				$datetime_string,
581
+				$this->get_UTC_DateTimeZone()
582
+			);
583
+			if ($DateTime instanceof \DateTime) {
584
+				$DateTime = new DbSafeDateTime(
585
+					$DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
586
+					$this->get_UTC_DateTimeZone()
587
+				);
588
+			}
589
+		}
590
+
591
+		if (! $DateTime instanceof DbSafeDateTime) {
592
+			// if still no datetime object, then let's just use now
593
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
594
+		}
595
+		// THEN apply the field's set DateTimeZone
596
+		EEH_DTT_Helper::setTimezone($DateTime, $this->_DateTimeZone);
597
+		return $DateTime;
598
+	}
599
+
600
+
601
+	/**
602
+	 * All this method does is determine if we're going to display the timezone string or not on any output.
603
+	 * To determine this we check if the set timezone offset is different than the blog's set timezone offset.
604
+	 * If so, then true.
605
+	 *
606
+	 * @return bool true for yes false for no
607
+	 * @throws \EE_Error
608
+	 */
609
+	protected function _display_timezone()
610
+	{
611
+
612
+		// first let's do a comparison of timezone strings.
613
+		// If they match then we can get out without any further calculations
614
+		$blog_string = get_option('timezone_string');
615
+		if ($blog_string === $this->_timezone_string) {
616
+			return false;
617
+		}
618
+		// now we need to calc the offset for the timezone string so we can compare with the blog offset.
619
+		$this_offset = $this->get_timezone_offset($this->_DateTimeZone);
620
+		$blog_offset = $this->get_timezone_offset($this->get_blog_DateTimeZone());
621
+		// now compare
622
+		return $blog_offset !== $this_offset;
623
+	}
624
+
625
+
626
+	/**
627
+	 * This method returns a php DateTime object for setting on the EE_Base_Class model.
628
+	 * EE passes around DateTime objects because they are MUCH easier to manipulate and deal
629
+	 * with.
630
+	 *
631
+	 * @param int|string|DateTime $date_string            This should be the incoming date string.  It's assumed to be
632
+	 *                                                    in the format that is set on the date_field (or DateTime
633
+	 *                                                    object)!
634
+	 * @return DateTime
635
+	 */
636
+	protected function _get_date_object($date_string)
637
+	{
638
+		//first if this is an empty date_string and nullable is allowed, just return null.
639
+		if ($this->_nullable && empty($date_string)) {
640
+			return null;
641
+		}
642
+
643
+		// if incoming date
644
+		if ($date_string instanceof DateTime) {
645
+			EEH_DTT_Helper::setTimezone($date_string, $this->_DateTimeZone);
646
+			return $date_string;
647
+		}
648
+		// if empty date_string and made it here.
649
+		// Return a datetime object for now in the given timezone.
650
+		if (empty($date_string)) {
651
+			return new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
652
+		}
653
+		// if $date_string is matches something that looks like a Unix timestamp let's just use it.
654
+		if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $date_string)) {
655
+			try {
656
+				// This is operating under the assumption that the incoming Unix timestamp
657
+				// is an ACTUAL Unix timestamp and not the calculated one output by current_time('timestamp');
658
+				$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
659
+				$DateTime->setTimestamp($date_string);
660
+
661
+				return $DateTime;
662
+			} catch (Exception $e) {
663
+				// should be rare, but if things got fooled then let's just continue
664
+			}
665
+		}
666
+		//not a unix timestamp.  So we will use the set format on this object and set timezone to
667
+		//create the DateTime object.
668
+		$format = $this->_date_format . ' ' . $this->_time_format;
669
+		try {
670
+			$DateTime = DateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
671
+			if ($DateTime instanceof DateTime) {
672
+				$DateTime = new DbSafeDateTime(
673
+					$DateTime->format(\EE_Datetime_Field::mysql_timestamp_format),
674
+					$this->_DateTimeZone
675
+				);
676
+			}
677
+			if (! $DateTime instanceof DbSafeDateTime) {
678
+				throw new EE_Error(
679
+					sprintf(
680
+						__('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
681
+						$date_string,
682
+						$format
683
+					)
684
+				);
685
+			}
686
+		} catch (Exception $e) {
687
+			// if we made it here then likely then something went really wrong.
688
+			// Instead of throwing an exception, let's just return a DateTime object for now, in the set timezone.
689
+			$DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->_DateTimeZone);
690
+		}
691
+
692
+		return $DateTime;
693
+	}
694
+
695
+
696
+
697
+	/**
698
+	 * get_timezone_transitions
699
+	 *
700
+	 * @param \DateTimeZone $DateTimeZone
701
+	 * @param int           $time
702
+	 * @param bool          $first_only
703
+	 * @return mixed
704
+	 */
705
+	public function get_timezone_transitions(DateTimeZone $DateTimeZone, $time = null, $first_only = true)
706
+	{
707
+		return EEH_DTT_Helper::get_timezone_transitions($DateTimeZone, $time, $first_only);
708
+	}
709
+
710
+
711
+
712
+	/**
713
+	 * get_timezone_offset
714
+	 *
715
+	 * @param \DateTimeZone $DateTimeZone
716
+	 * @param int           $time
717
+	 * @return mixed
718
+	 * @throws \DomainException
719
+	 */
720
+	public function get_timezone_offset(DateTimeZone $DateTimeZone, $time = null)
721
+	{
722
+		return EEH_DTT_Helper::get_timezone_offset($DateTimeZone, $time);
723
+	}
724
+
725
+
726
+	/**
727
+	 * This will take an incoming timezone string and return the abbreviation for that timezone
728
+	 *
729
+	 * @param  string $timezone_string
730
+	 * @return string           abbreviation
731
+	 * @throws \EE_Error
732
+	 */
733
+	public function get_timezone_abbrev($timezone_string)
734
+	{
735
+		$timezone_string = EEH_DTT_Helper::get_valid_timezone_string($timezone_string);
736
+		$dateTime        = new DateTime(\EE_Datetime_Field::now, new DateTimeZone($timezone_string));
737
+
738
+		return $dateTime->format('T');
739
+	}
740
+
741
+	/**
742
+	 * Overrides the parent to allow for having a dynamic "now" value
743
+	 *
744
+	 * @return mixed
745
+	 */
746
+	public function get_default_value()
747
+	{
748
+		if ($this->_default_value === EE_Datetime_Field::now) {
749
+			return time();
750
+		} else {
751
+			return parent::get_default_value();
752
+		}
753
+	}
754
+
755
+
756
+	public function getSchemaDescription()
757
+	{
758
+		return sprintf(
759
+			esc_html__('%s - the value for this field is in the timezone of the site.', 'event_espresso'),
760
+			$this->get_nicename()
761
+		);
762
+	}
763 763
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -214,8 +214,8 @@  discard block
 block discarded – undo
214 214
 
215 215
             default :
216 216
                 return $pretty
217
-                    ? $this->_pretty_date_format . ' ' . $this->_pretty_time_format
218
-                    : $this->_date_format . ' ' . $this->_time_format;
217
+                    ? $this->_pretty_date_format.' '.$this->_pretty_time_format
218
+                    : $this->_date_format.' '.$this->_time_format;
219 219
         }
220 220
     }
221 221
 
@@ -469,7 +469,7 @@  discard block
 block discarded – undo
469 469
      */
470 470
     protected function _prepare_for_display($DateTime, $schema = false)
471 471
     {
472
-        if (! $DateTime instanceof DateTime) {
472
+        if ( ! $DateTime instanceof DateTime) {
473 473
             if ($this->_nullable) {
474 474
                 return '';
475 475
             } else {
@@ -503,15 +503,15 @@  discard block
 block discarded – undo
503 503
             if ($this->_display_timezone()) {
504 504
                 //must be explicit because schema could equal true.
505 505
                 if ($schema === 'no_html') {
506
-                    $timezone_string = ' (' . $DateTime->format('T') . ')';
506
+                    $timezone_string = ' ('.$DateTime->format('T').')';
507 507
                 } else {
508
-                    $timezone_string = ' <span class="ee_dtt_timezone_string">(' . $DateTime->format('T') . ')</span>';
508
+                    $timezone_string = ' <span class="ee_dtt_timezone_string">('.$DateTime->format('T').')</span>';
509 509
                 }
510 510
             } else {
511 511
                 $timezone_string = '';
512 512
             }
513 513
 
514
-            return $DateTime->format($format_string) . $timezone_string;
514
+            return $DateTime->format($format_string).$timezone_string;
515 515
         }
516 516
         return $DateTime->format($format_string);
517 517
     }
@@ -528,7 +528,7 @@  discard block
 block discarded – undo
528 528
     public function prepare_for_use_in_db($datetime_value)
529 529
     {
530 530
         //we allow an empty value or DateTime object, but nothing else.
531
-        if (! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
531
+        if ( ! empty($datetime_value) && ! $datetime_value instanceof DateTime) {
532 532
             throw new EE_Error(
533 533
             	sprintf(
534 534
             	    __(
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
         }
544 544
 
545 545
         if ($datetime_value instanceof DateTime) {
546
-            if (! $datetime_value instanceof DbSafeDateTime) {
546
+            if ( ! $datetime_value instanceof DbSafeDateTime) {
547 547
                 $datetime_value = DbSafeDateTime::createFromDateTime($datetime_value);
548 548
             }
549 549
             EEH_DTT_Helper::setTimezone($datetime_value, $this->get_UTC_DateTimeZone());
@@ -588,7 +588,7 @@  discard block
 block discarded – undo
588 588
             }
589 589
         }
590 590
 
591
-        if (! $DateTime instanceof DbSafeDateTime) {
591
+        if ( ! $DateTime instanceof DbSafeDateTime) {
592 592
             // if still no datetime object, then let's just use now
593 593
             $DateTime = new DbSafeDateTime(\EE_Datetime_Field::now, $this->get_UTC_DateTimeZone());
594 594
         }
@@ -665,7 +665,7 @@  discard block
 block discarded – undo
665 665
         }
666 666
         //not a unix timestamp.  So we will use the set format on this object and set timezone to
667 667
         //create the DateTime object.
668
-        $format = $this->_date_format . ' ' . $this->_time_format;
668
+        $format = $this->_date_format.' '.$this->_time_format;
669 669
         try {
670 670
             $DateTime = DateTime::createFromFormat($format, $date_string, $this->_DateTimeZone);
671 671
             if ($DateTime instanceof DateTime) {
@@ -674,7 +674,7 @@  discard block
 block discarded – undo
674 674
                     $this->_DateTimeZone
675 675
                 );
676 676
             }
677
-            if (! $DateTime instanceof DbSafeDateTime) {
677
+            if ( ! $DateTime instanceof DbSafeDateTime) {
678 678
                 throw new EE_Error(
679 679
                     sprintf(
680 680
                         __('"%1$s" does not represent a valid Date Time in the format "%2$s".', 'event_espresso'),
Please login to merge, or discard this patch.