Completed
Branch fix/kses-13 (26cb73)
by
unknown
15:41 queued 13:09
created
core/EE_Addon.core.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -580,7 +580,7 @@  discard block
 block discarded – undo
580 580
      */
581 581
     public function get_activation_indicator_option_name()
582 582
     {
583
-        return 'ee_activation_' . $this->name();
583
+        return 'ee_activation_'.$this->name();
584 584
     }
585 585
 
586 586
 
@@ -668,13 +668,13 @@  discard block
 block discarded – undo
668 668
      */
669 669
     public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
670 670
     {
671
-        if (! $version_history) {
671
+        if ( ! $version_history) {
672 672
             $version_history = $this->get_activation_history();
673 673
         }
674 674
         if ($current_version_to_add === null) {
675 675
             $current_version_to_add = $this->version();
676 676
         }
677
-        $version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
677
+        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
678 678
         // resave
679 679
         return update_option($this->get_activation_history_option_name(), $version_history);
680 680
     }
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
      */
688 688
     public function get_activation_history_option_name()
689 689
     {
690
-        return self::ee_addon_version_history_option_prefix . $this->name();
690
+        return self::ee_addon_version_history_option_prefix.$this->name();
691 691
     }
692 692
 
693 693
 
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
         // is admin and not in M-Mode ?
763 763
         if (is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
764 764
             add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
765
-            add_filter('after_plugin_row_' . $this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
765
+            add_filter('after_plugin_row_'.$this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
766 766
         }
767 767
     }
768 768
 
@@ -781,7 +781,7 @@  discard block
 block discarded – undo
781 781
             // before other links
782 782
             array_unshift(
783 783
                 $links,
784
-                '<a href="admin.php?page=' . $this->plugin_action_slug() . '">'
784
+                '<a href="admin.php?page='.$this->plugin_action_slug().'">'
785 785
                 . esc_html__('Settings', 'event_espresso')
786 786
                 . '</a>'
787 787
             );
@@ -804,19 +804,19 @@  discard block
 block discarded – undo
804 804
     {
805 805
         $after_plugin_row = '';
806 806
         $plugins_page_row = $this->get_plugins_page_row();
807
-        if (! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
807
+        if ( ! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
808 808
             $class = $status ? 'active' : 'inactive';
809 809
             $link_text = isset($plugins_page_row['link_text']) ? $plugins_page_row['link_text'] : '';
810 810
             $link_url = isset($plugins_page_row['link_url']) ? $plugins_page_row['link_url'] : '';
811 811
             $description = isset($plugins_page_row['description'])
812 812
                 ? $plugins_page_row['description']
813 813
                 : '';
814
-            if (! empty($link_text) && ! empty($link_url) && ! empty($description)) {
815
-                $after_plugin_row .= '<tr id="' . sanitize_title($plugin_file) . '-ee-addon" class="' . $class . '">';
814
+            if ( ! empty($link_text) && ! empty($link_url) && ! empty($description)) {
815
+                $after_plugin_row .= '<tr id="'.sanitize_title($plugin_file).'-ee-addon" class="'.$class.'">';
816 816
                 $after_plugin_row .= '<th class="check-column" scope="row"></th>';
817 817
                 $after_plugin_row .= '<td class="ee-addon-upsell-info-title-td plugin-title column-primary">';
818 818
                 $after_plugin_row .= '<p class="ee-addon-upsell-info-dv">
819
-	                <a class="ee-button" href="' . esc_url_raw($link_url) . '">'
819
+	                <a class="ee-button" href="' . esc_url_raw($link_url).'">'
820 820
                     . $link_text
821 821
                     . ' &nbsp;<span class="dashicons dashicons-arrow-right-alt2" style="margin:0;"></span>'
822 822
                     . '</a>
Please login to merge, or discard this patch.
Indentation   +848 added lines, -848 removed lines patch added patch discarded remove patch
@@ -20,859 +20,859 @@
 block discarded – undo
20 20
 {
21 21
 
22 22
 
23
-    /**
24
-     * prefix to be added onto an addon's plugin slug to make a wp option name
25
-     * which will be used to store the plugin's activation history
26
-     */
27
-    const ee_addon_version_history_option_prefix = 'ee_version_history_';
28
-
29
-    /**
30
-     * @var $_version
31
-     * @type string
32
-     */
33
-    protected $_version = '';
34
-
35
-    /**
36
-     * @var $_min_core_version
37
-     * @type string
38
-     */
39
-    protected $_min_core_version = '';
40
-
41
-    /**
42
-     * derived from plugin 'main_file_path using plugin_basename()
43
-     *
44
-     * @type string $_plugin_basename
45
-     */
46
-    protected $_plugin_basename = '';
47
-
48
-    /**
49
-     * A non-internationalized name to identify this addon for use in URLs, etc
50
-     *
51
-     * @type string $_plugin_slug
52
-     */
53
-    protected $_plugin_slug = '';
54
-
55
-    /**
56
-     * A non-internationalized name to identify this addon. Eg 'Calendar','MailChimp',etc/
57
-     *
58
-     * @type string _addon_name
59
-     */
60
-    protected $_addon_name = '';
61
-
62
-    /**
63
-     * one of the EE_System::req_type_* constants
64
-     *
65
-     * @type int $_req_type
66
-     */
67
-    protected $_req_type;
68
-
69
-    /**
70
-     * page slug to be used when generating the "Settings" link on the WP plugin page
71
-     *
72
-     * @type string $_plugin_action_slug
73
-     */
74
-    protected $_plugin_action_slug = '';
75
-
76
-    /**
77
-     * if not empty, inserts a new table row after this plugin's row on the WP Plugins page
78
-     * that can be used for adding upgrading/marketing info
79
-     *
80
-     * @type array $_plugins_page_row
81
-     */
82
-    protected $_plugins_page_row = array();
83
-
84
-
85
-    /**
86
-     *    filepath to the main file, which can be used for register_activation_hook, register_deactivation_hook, etc.
87
-     *
88
-     * @type string
89
-     */
90
-    protected $_main_plugin_file;
91
-
92
-    /**
93
-     *    This is the slug used to identify this add-on within the plugin update engine.
94
-     *
95
-     * @type string
96
-     */
97
-    protected $pue_slug;
98
-
99
-
100
-    /**
101
-     * @var EE_Dependency_Map $dependency_map
102
-     */
103
-    private $dependency_map;
104
-
105
-
106
-    /**
107
-     * @var DomainInterface $domain
108
-     */
109
-    private $domain;
110
-
111
-
112
-    /**
113
-     * @param EE_Dependency_Map $dependency_map [optional]
114
-     * @param DomainInterface   $domain         [optional]
115
-     */
116
-    public function __construct(EE_Dependency_Map $dependency_map = null, DomainInterface $domain = null)
117
-    {
118
-        if ($dependency_map instanceof EE_Dependency_Map) {
119
-            $this->setDependencyMap($dependency_map);
120
-        }
121
-        if ($domain instanceof DomainInterface) {
122
-            $this->setDomain($domain);
123
-        }
124
-        add_action('AHEE__EE_System__load_controllers__load_admin_controllers', array($this, 'admin_init'));
125
-    }
126
-
127
-
128
-    /**
129
-     * @param EE_Dependency_Map $dependency_map
130
-     */
131
-    public function setDependencyMap($dependency_map)
132
-    {
133
-        $this->dependency_map = $dependency_map;
134
-    }
135
-
136
-
137
-    /**
138
-     * @return EE_Dependency_Map
139
-     */
140
-    public function dependencyMap()
141
-    {
142
-        return $this->dependency_map;
143
-    }
144
-
145
-
146
-    /**
147
-     * @param DomainInterface $domain
148
-     */
149
-    public function setDomain(DomainInterface $domain)
150
-    {
151
-        $this->domain = $domain;
152
-    }
153
-
154
-    /**
155
-     * @return DomainInterface
156
-     */
157
-    public function domain()
158
-    {
159
-        return $this->domain;
160
-    }
161
-
162
-
163
-    /**
164
-     * @param mixed $version
165
-     */
166
-    public function set_version($version = null)
167
-    {
168
-        $this->_version = $version;
169
-    }
170
-
171
-
172
-    /**
173
-     * get__version
174
-     *
175
-     * @return string
176
-     */
177
-    public function version()
178
-    {
179
-        return $this->_version;
180
-    }
181
-
182
-
183
-    /**
184
-     * @param mixed $min_core_version
185
-     */
186
-    public function set_min_core_version($min_core_version = null)
187
-    {
188
-        $this->_min_core_version = $min_core_version;
189
-    }
190
-
191
-
192
-    /**
193
-     * get__min_core_version
194
-     *
195
-     * @return string
196
-     */
197
-    public function min_core_version()
198
-    {
199
-        return $this->_min_core_version;
200
-    }
201
-
202
-
203
-    /**
204
-     * Sets addon_name
205
-     *
206
-     * @param string $addon_name
207
-     * @return bool
208
-     */
209
-    public function set_name($addon_name)
210
-    {
211
-        return $this->_addon_name = $addon_name;
212
-    }
213
-
214
-
215
-    /**
216
-     * Gets addon_name
217
-     *
218
-     * @return string
219
-     */
220
-    public function name()
221
-    {
222
-        return $this->_addon_name;
223
-    }
224
-
225
-
226
-    /**
227
-     * @return string
228
-     */
229
-    public function plugin_basename()
230
-    {
231
-
232
-        return $this->_plugin_basename;
233
-    }
234
-
235
-
236
-    /**
237
-     * @param string $plugin_basename
238
-     */
239
-    public function set_plugin_basename($plugin_basename)
240
-    {
241
-
242
-        $this->_plugin_basename = $plugin_basename;
243
-    }
244
-
245
-
246
-    /**
247
-     * @return string
248
-     */
249
-    public function plugin_slug()
250
-    {
251
-
252
-        return $this->_plugin_slug;
253
-    }
254
-
255
-
256
-    /**
257
-     * @param string $plugin_slug
258
-     */
259
-    public function set_plugin_slug($plugin_slug)
260
-    {
261
-
262
-        $this->_plugin_slug = $plugin_slug;
263
-    }
264
-
265
-
266
-    /**
267
-     * @return string
268
-     */
269
-    public function plugin_action_slug()
270
-    {
271
-
272
-        return $this->_plugin_action_slug;
273
-    }
274
-
275
-
276
-    /**
277
-     * @param string $plugin_action_slug
278
-     */
279
-    public function set_plugin_action_slug($plugin_action_slug)
280
-    {
281
-
282
-        $this->_plugin_action_slug = $plugin_action_slug;
283
-    }
284
-
285
-
286
-    /**
287
-     * @return array
288
-     */
289
-    public function get_plugins_page_row()
290
-    {
291
-
292
-        return $this->_plugins_page_row;
293
-    }
294
-
295
-
296
-    /**
297
-     * @param array $plugins_page_row
298
-     */
299
-    public function set_plugins_page_row($plugins_page_row = array())
300
-    {
301
-        // sigh.... check for example content that I stupidly merged to master and remove it if found
302
-        if (
303
-            ! is_array($plugins_page_row)
304
-            && strpos($plugins_page_row, '<h3>Promotions Addon Upsell Info</h3>') !== false
305
-        ) {
306
-            $plugins_page_row = array();
307
-        }
308
-        $this->_plugins_page_row = (array) $plugins_page_row;
309
-    }
310
-
311
-
312
-    /**
313
-     * Called when EE core detects this addon has been activated for the first time.
314
-     * If the site isn't in maintenance mode, should setup the addon's database
315
-     *
316
-     * @return void
317
-     * @throws EE_Error
318
-     */
319
-    public function new_install()
320
-    {
321
-        $classname = get_class($this);
322
-        do_action("AHEE__{$classname}__new_install");
323
-        do_action('AHEE__EE_Addon__new_install', $this);
324
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
325
-        add_action(
326
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
327
-            array($this, 'initialize_db_if_no_migrations_required')
328
-        );
329
-    }
330
-
331
-
332
-    /**
333
-     * Called when EE core detects this addon has been reactivated. When this happens,
334
-     * it's good to just check that your data is still intact
335
-     *
336
-     * @return void
337
-     * @throws EE_Error
338
-     */
339
-    public function reactivation()
340
-    {
341
-        $classname = get_class($this);
342
-        do_action("AHEE__{$classname}__reactivation");
343
-        do_action('AHEE__EE_Addon__reactivation', $this);
344
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
345
-        add_action(
346
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
347
-            array($this, 'initialize_db_if_no_migrations_required')
348
-        );
349
-    }
350
-
351
-
352
-    /**
353
-     * Called when the registered deactivation hook for this addon fires.
354
-     *
355
-     * @throws EE_Error
356
-     */
357
-    public function deactivation()
358
-    {
359
-        $classname = get_class($this);
360
-        do_action("AHEE__{$classname}__deactivation");
361
-        do_action('AHEE__EE_Addon__deactivation', $this);
362
-        // check if the site no longer needs to be in maintenance mode
363
-        EE_Register_Addon::deregister($this->name());
364
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
365
-    }
366
-
367
-
368
-    /**
369
-     * Takes care of double-checking that we're not in maintenance mode, and then
370
-     * initializing this addon's necessary initial data. This is called by default on new activations
371
-     * and reactivations.
372
-     *
373
-     * @param bool $verify_schema whether to verify the database's schema for this addon, or just its data.
374
-     *                               This is a resource-intensive job so we prefer to only do it when necessary
375
-     * @return void
376
-     * @throws EE_Error
377
-     * @throws InvalidInterfaceException
378
-     * @throws InvalidDataTypeException
379
-     * @throws InvalidArgumentException
380
-     * @throws ReflectionException
381
-     */
382
-    public function initialize_db_if_no_migrations_required($verify_schema = true)
383
-    {
384
-        if ($verify_schema === '') {
385
-            // wp core bug imo: if no args are passed to `do_action('some_hook_name')` besides the hook's name
386
-            // (ie, no 2nd or 3rd arguments), instead of calling the registered callbacks with no arguments, it
387
-            // calls them with an argument of an empty string (ie ""), which evaluates to false
388
-            // so we need to treat the empty string as if nothing had been passed, and should instead use the default
389
-            $verify_schema = true;
390
-        }
391
-        if (EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
392
-            if ($verify_schema) {
393
-                $this->initialize_db();
394
-            }
395
-            $this->initialize_default_data();
396
-            // @todo: this will probably need to be adjusted in 4.4 as the array changed formats I believe
397
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to(
398
-                array(
399
-                    'slug'    => $this->name(),
400
-                    'version' => $this->version(),
401
-                )
402
-            );
403
-            /* make sure core's data is a-ok
23
+	/**
24
+	 * prefix to be added onto an addon's plugin slug to make a wp option name
25
+	 * which will be used to store the plugin's activation history
26
+	 */
27
+	const ee_addon_version_history_option_prefix = 'ee_version_history_';
28
+
29
+	/**
30
+	 * @var $_version
31
+	 * @type string
32
+	 */
33
+	protected $_version = '';
34
+
35
+	/**
36
+	 * @var $_min_core_version
37
+	 * @type string
38
+	 */
39
+	protected $_min_core_version = '';
40
+
41
+	/**
42
+	 * derived from plugin 'main_file_path using plugin_basename()
43
+	 *
44
+	 * @type string $_plugin_basename
45
+	 */
46
+	protected $_plugin_basename = '';
47
+
48
+	/**
49
+	 * A non-internationalized name to identify this addon for use in URLs, etc
50
+	 *
51
+	 * @type string $_plugin_slug
52
+	 */
53
+	protected $_plugin_slug = '';
54
+
55
+	/**
56
+	 * A non-internationalized name to identify this addon. Eg 'Calendar','MailChimp',etc/
57
+	 *
58
+	 * @type string _addon_name
59
+	 */
60
+	protected $_addon_name = '';
61
+
62
+	/**
63
+	 * one of the EE_System::req_type_* constants
64
+	 *
65
+	 * @type int $_req_type
66
+	 */
67
+	protected $_req_type;
68
+
69
+	/**
70
+	 * page slug to be used when generating the "Settings" link on the WP plugin page
71
+	 *
72
+	 * @type string $_plugin_action_slug
73
+	 */
74
+	protected $_plugin_action_slug = '';
75
+
76
+	/**
77
+	 * if not empty, inserts a new table row after this plugin's row on the WP Plugins page
78
+	 * that can be used for adding upgrading/marketing info
79
+	 *
80
+	 * @type array $_plugins_page_row
81
+	 */
82
+	protected $_plugins_page_row = array();
83
+
84
+
85
+	/**
86
+	 *    filepath to the main file, which can be used for register_activation_hook, register_deactivation_hook, etc.
87
+	 *
88
+	 * @type string
89
+	 */
90
+	protected $_main_plugin_file;
91
+
92
+	/**
93
+	 *    This is the slug used to identify this add-on within the plugin update engine.
94
+	 *
95
+	 * @type string
96
+	 */
97
+	protected $pue_slug;
98
+
99
+
100
+	/**
101
+	 * @var EE_Dependency_Map $dependency_map
102
+	 */
103
+	private $dependency_map;
104
+
105
+
106
+	/**
107
+	 * @var DomainInterface $domain
108
+	 */
109
+	private $domain;
110
+
111
+
112
+	/**
113
+	 * @param EE_Dependency_Map $dependency_map [optional]
114
+	 * @param DomainInterface   $domain         [optional]
115
+	 */
116
+	public function __construct(EE_Dependency_Map $dependency_map = null, DomainInterface $domain = null)
117
+	{
118
+		if ($dependency_map instanceof EE_Dependency_Map) {
119
+			$this->setDependencyMap($dependency_map);
120
+		}
121
+		if ($domain instanceof DomainInterface) {
122
+			$this->setDomain($domain);
123
+		}
124
+		add_action('AHEE__EE_System__load_controllers__load_admin_controllers', array($this, 'admin_init'));
125
+	}
126
+
127
+
128
+	/**
129
+	 * @param EE_Dependency_Map $dependency_map
130
+	 */
131
+	public function setDependencyMap($dependency_map)
132
+	{
133
+		$this->dependency_map = $dependency_map;
134
+	}
135
+
136
+
137
+	/**
138
+	 * @return EE_Dependency_Map
139
+	 */
140
+	public function dependencyMap()
141
+	{
142
+		return $this->dependency_map;
143
+	}
144
+
145
+
146
+	/**
147
+	 * @param DomainInterface $domain
148
+	 */
149
+	public function setDomain(DomainInterface $domain)
150
+	{
151
+		$this->domain = $domain;
152
+	}
153
+
154
+	/**
155
+	 * @return DomainInterface
156
+	 */
157
+	public function domain()
158
+	{
159
+		return $this->domain;
160
+	}
161
+
162
+
163
+	/**
164
+	 * @param mixed $version
165
+	 */
166
+	public function set_version($version = null)
167
+	{
168
+		$this->_version = $version;
169
+	}
170
+
171
+
172
+	/**
173
+	 * get__version
174
+	 *
175
+	 * @return string
176
+	 */
177
+	public function version()
178
+	{
179
+		return $this->_version;
180
+	}
181
+
182
+
183
+	/**
184
+	 * @param mixed $min_core_version
185
+	 */
186
+	public function set_min_core_version($min_core_version = null)
187
+	{
188
+		$this->_min_core_version = $min_core_version;
189
+	}
190
+
191
+
192
+	/**
193
+	 * get__min_core_version
194
+	 *
195
+	 * @return string
196
+	 */
197
+	public function min_core_version()
198
+	{
199
+		return $this->_min_core_version;
200
+	}
201
+
202
+
203
+	/**
204
+	 * Sets addon_name
205
+	 *
206
+	 * @param string $addon_name
207
+	 * @return bool
208
+	 */
209
+	public function set_name($addon_name)
210
+	{
211
+		return $this->_addon_name = $addon_name;
212
+	}
213
+
214
+
215
+	/**
216
+	 * Gets addon_name
217
+	 *
218
+	 * @return string
219
+	 */
220
+	public function name()
221
+	{
222
+		return $this->_addon_name;
223
+	}
224
+
225
+
226
+	/**
227
+	 * @return string
228
+	 */
229
+	public function plugin_basename()
230
+	{
231
+
232
+		return $this->_plugin_basename;
233
+	}
234
+
235
+
236
+	/**
237
+	 * @param string $plugin_basename
238
+	 */
239
+	public function set_plugin_basename($plugin_basename)
240
+	{
241
+
242
+		$this->_plugin_basename = $plugin_basename;
243
+	}
244
+
245
+
246
+	/**
247
+	 * @return string
248
+	 */
249
+	public function plugin_slug()
250
+	{
251
+
252
+		return $this->_plugin_slug;
253
+	}
254
+
255
+
256
+	/**
257
+	 * @param string $plugin_slug
258
+	 */
259
+	public function set_plugin_slug($plugin_slug)
260
+	{
261
+
262
+		$this->_plugin_slug = $plugin_slug;
263
+	}
264
+
265
+
266
+	/**
267
+	 * @return string
268
+	 */
269
+	public function plugin_action_slug()
270
+	{
271
+
272
+		return $this->_plugin_action_slug;
273
+	}
274
+
275
+
276
+	/**
277
+	 * @param string $plugin_action_slug
278
+	 */
279
+	public function set_plugin_action_slug($plugin_action_slug)
280
+	{
281
+
282
+		$this->_plugin_action_slug = $plugin_action_slug;
283
+	}
284
+
285
+
286
+	/**
287
+	 * @return array
288
+	 */
289
+	public function get_plugins_page_row()
290
+	{
291
+
292
+		return $this->_plugins_page_row;
293
+	}
294
+
295
+
296
+	/**
297
+	 * @param array $plugins_page_row
298
+	 */
299
+	public function set_plugins_page_row($plugins_page_row = array())
300
+	{
301
+		// sigh.... check for example content that I stupidly merged to master and remove it if found
302
+		if (
303
+			! is_array($plugins_page_row)
304
+			&& strpos($plugins_page_row, '<h3>Promotions Addon Upsell Info</h3>') !== false
305
+		) {
306
+			$plugins_page_row = array();
307
+		}
308
+		$this->_plugins_page_row = (array) $plugins_page_row;
309
+	}
310
+
311
+
312
+	/**
313
+	 * Called when EE core detects this addon has been activated for the first time.
314
+	 * If the site isn't in maintenance mode, should setup the addon's database
315
+	 *
316
+	 * @return void
317
+	 * @throws EE_Error
318
+	 */
319
+	public function new_install()
320
+	{
321
+		$classname = get_class($this);
322
+		do_action("AHEE__{$classname}__new_install");
323
+		do_action('AHEE__EE_Addon__new_install', $this);
324
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
325
+		add_action(
326
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
327
+			array($this, 'initialize_db_if_no_migrations_required')
328
+		);
329
+	}
330
+
331
+
332
+	/**
333
+	 * Called when EE core detects this addon has been reactivated. When this happens,
334
+	 * it's good to just check that your data is still intact
335
+	 *
336
+	 * @return void
337
+	 * @throws EE_Error
338
+	 */
339
+	public function reactivation()
340
+	{
341
+		$classname = get_class($this);
342
+		do_action("AHEE__{$classname}__reactivation");
343
+		do_action('AHEE__EE_Addon__reactivation', $this);
344
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
345
+		add_action(
346
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
347
+			array($this, 'initialize_db_if_no_migrations_required')
348
+		);
349
+	}
350
+
351
+
352
+	/**
353
+	 * Called when the registered deactivation hook for this addon fires.
354
+	 *
355
+	 * @throws EE_Error
356
+	 */
357
+	public function deactivation()
358
+	{
359
+		$classname = get_class($this);
360
+		do_action("AHEE__{$classname}__deactivation");
361
+		do_action('AHEE__EE_Addon__deactivation', $this);
362
+		// check if the site no longer needs to be in maintenance mode
363
+		EE_Register_Addon::deregister($this->name());
364
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
365
+	}
366
+
367
+
368
+	/**
369
+	 * Takes care of double-checking that we're not in maintenance mode, and then
370
+	 * initializing this addon's necessary initial data. This is called by default on new activations
371
+	 * and reactivations.
372
+	 *
373
+	 * @param bool $verify_schema whether to verify the database's schema for this addon, or just its data.
374
+	 *                               This is a resource-intensive job so we prefer to only do it when necessary
375
+	 * @return void
376
+	 * @throws EE_Error
377
+	 * @throws InvalidInterfaceException
378
+	 * @throws InvalidDataTypeException
379
+	 * @throws InvalidArgumentException
380
+	 * @throws ReflectionException
381
+	 */
382
+	public function initialize_db_if_no_migrations_required($verify_schema = true)
383
+	{
384
+		if ($verify_schema === '') {
385
+			// wp core bug imo: if no args are passed to `do_action('some_hook_name')` besides the hook's name
386
+			// (ie, no 2nd or 3rd arguments), instead of calling the registered callbacks with no arguments, it
387
+			// calls them with an argument of an empty string (ie ""), which evaluates to false
388
+			// so we need to treat the empty string as if nothing had been passed, and should instead use the default
389
+			$verify_schema = true;
390
+		}
391
+		if (EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
392
+			if ($verify_schema) {
393
+				$this->initialize_db();
394
+			}
395
+			$this->initialize_default_data();
396
+			// @todo: this will probably need to be adjusted in 4.4 as the array changed formats I believe
397
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to(
398
+				array(
399
+					'slug'    => $this->name(),
400
+					'version' => $this->version(),
401
+				)
402
+			);
403
+			/* make sure core's data is a-ok
404 404
              * (at the time of writing, we especially want to verify all the caps are present
405 405
              * because payment method type capabilities are added dynamically, and it's
406 406
              * possible this addon added a payment method. But it's also possible
407 407
              * other data needs to be verified)
408 408
              */
409
-            EEH_Activation::initialize_db_content();
410
-            /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
411
-            $rewrite_rules = LoaderFactory::getLoader()->getShared(
412
-                'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
413
-            );
414
-            $rewrite_rules->flushRewriteRules();
415
-            // in case there are lots of addons being activated at once, let's force garbage collection
416
-            // to help avoid memory limit errors
417
-            // EEH_Debug_Tools::instance()->measure_memory( 'db content initialized for ' . get_class( $this), true );
418
-            gc_collect_cycles();
419
-        } else {
420
-            // ask the data migration manager to init this addon's data
421
-            // when migrations are finished because we can't do it now
422
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for($this->name());
423
-        }
424
-    }
425
-
426
-
427
-    /**
428
-     * Used to setup this addon's database tables, but not necessarily any default
429
-     * data in them. The default is to actually use the most up-to-date data migration script
430
-     * for this addon, and just use its schema_changes_before_migration() and schema_changes_after_migration()
431
-     * methods to setup the db.
432
-     */
433
-    public function initialize_db()
434
-    {
435
-        // find the migration script that sets the database to be compatible with the code
436
-        $current_dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms($this->name());
437
-        if ($current_dms_name) {
438
-            $current_data_migration_script = EE_Registry::instance()->load_dms($current_dms_name);
439
-            $current_data_migration_script->set_migrating(false);
440
-            $current_data_migration_script->schema_changes_before_migration();
441
-            $current_data_migration_script->schema_changes_after_migration();
442
-            if ($current_data_migration_script->get_errors()) {
443
-                foreach ($current_data_migration_script->get_errors() as $error) {
444
-                    EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
445
-                }
446
-            }
447
-        }
448
-        // if not DMS was found that should be ok. This addon just doesn't require any database changes
449
-        EE_Data_Migration_Manager::instance()->update_current_database_state_to(
450
-            array(
451
-                'slug'    => $this->name(),
452
-                'version' => $this->version(),
453
-            )
454
-        );
455
-    }
456
-
457
-
458
-    /**
459
-     * If you want to setup default data for the addon, override this method, and call
460
-     * parent::initialize_default_data() from within it. This is normally called
461
-     * from EE_Addon::initialize_db_if_no_migrations_required(), just after EE_Addon::initialize_db()
462
-     * and should verify default data is present (but this is also called
463
-     * on reactivations and just after migrations, so please verify you actually want
464
-     * to ADD default data, because it may already be present).
465
-     * However, please call this parent (currently it just fires a hook which other
466
-     * addons may be depending on)
467
-     */
468
-    public function initialize_default_data()
469
-    {
470
-        /**
471
-         * Called when an addon is ensuring its default data is set (possibly called
472
-         * on a reactivation, so first check for the absence of other data before setting
473
-         * default data)
474
-         *
475
-         * @param EE_Addon $addon the addon that called this
476
-         */
477
-        do_action('AHEE__EE_Addon__initialize_default_data__begin', $this);
478
-        // override to insert default data. It is safe to use the models here
479
-        // because the site should not be in maintenance mode
480
-    }
481
-
482
-
483
-    /**
484
-     * EE Core detected that this addon has been upgraded. We should check if there
485
-     * are any new migration scripts, and if so put the site into maintenance mode until
486
-     * they're ran
487
-     *
488
-     * @return void
489
-     * @throws EE_Error
490
-     */
491
-    public function upgrade()
492
-    {
493
-        $classname = get_class($this);
494
-        do_action("AHEE__{$classname}__upgrade");
495
-        do_action('AHEE__EE_Addon__upgrade', $this);
496
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
497
-        // also it's possible there is new default data that needs to be added
498
-        add_action(
499
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
500
-            array($this, 'initialize_db_if_no_migrations_required')
501
-        );
502
-    }
503
-
504
-
505
-    /**
506
-     * If Core detects this addon has been downgraded, you may want to invoke some special logic here.
507
-     */
508
-    public function downgrade()
509
-    {
510
-        $classname = get_class($this);
511
-        do_action("AHEE__{$classname}__downgrade");
512
-        do_action('AHEE__EE_Addon__downgrade', $this);
513
-        // it's possible there's old default data that needs to be double-checked
514
-        add_action(
515
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
516
-            array($this, 'initialize_db_if_no_migrations_required')
517
-        );
518
-    }
519
-
520
-
521
-    /**
522
-     * set_db_update_option_name
523
-     * Until we do something better, we'll just check for migration scripts upon
524
-     * plugin activation only. In the future, we'll want to do it on plugin updates too
525
-     *
526
-     * @return bool
527
-     */
528
-    public function set_db_update_option_name()
529
-    {
530
-        EE_Error::doing_it_wrong(
531
-            __FUNCTION__,
532
-            esc_html__(
533
-                'EE_Addon::set_db_update_option_name was renamed to EE_Addon::set_activation_indicator_option',
534
-                'event_espresso'
535
-            ),
536
-            '4.3.0.alpha.016'
537
-        );
538
-        // let's just handle this on the next request, ok? right now we're just not really ready
539
-        return $this->set_activation_indicator_option();
540
-    }
541
-
542
-
543
-    /**
544
-     * Returns the name of the activation indicator option
545
-     * (an option which is set temporarily to indicate that this addon was just activated)
546
-     *
547
-     * @deprecated since version 4.3.0.alpha.016
548
-     * @return string
549
-     */
550
-    public function get_db_update_option_name()
551
-    {
552
-        EE_Error::doing_it_wrong(
553
-            __FUNCTION__,
554
-            esc_html__(
555
-                'EE_Addon::get_db_update_option was renamed to EE_Addon::get_activation_indicator_option_name',
556
-                'event_espresso'
557
-            ),
558
-            '4.3.0.alpha.016'
559
-        );
560
-        return $this->get_activation_indicator_option_name();
561
-    }
562
-
563
-
564
-    /**
565
-     * When the addon is activated, this should be called to set a wordpress option that
566
-     * indicates it was activated. This is especially useful for detecting reactivations.
567
-     *
568
-     * @return bool
569
-     */
570
-    public function set_activation_indicator_option()
571
-    {
572
-        // let's just handle this on the next request, ok? right now we're just not really ready
573
-        return update_option($this->get_activation_indicator_option_name(), true);
574
-    }
575
-
576
-
577
-    /**
578
-     * Gets the name of the wp option which is used to temporarily indicate that this addon was activated
579
-     *
580
-     * @return string
581
-     */
582
-    public function get_activation_indicator_option_name()
583
-    {
584
-        return 'ee_activation_' . $this->name();
585
-    }
586
-
587
-
588
-    /**
589
-     * Used by EE_System to set the request type of this addon. Should not be used by addon developers
590
-     *
591
-     * @param int $req_type
592
-     */
593
-    public function set_req_type($req_type)
594
-    {
595
-        $this->_req_type = $req_type;
596
-    }
597
-
598
-
599
-    /**
600
-     * Returns the request type of this addon (ie, EE_System::req_type_normal, EE_System::req_type_new_activation,
601
-     * EE_System::req_type_reactivation, EE_System::req_type_upgrade, or EE_System::req_type_downgrade). This is set by
602
-     * EE_System when it is checking for new install or upgrades of addons
603
-     */
604
-    public function detect_req_type($redetect = false)
605
-    {
606
-        if ($this->_req_type === null || $redetect) {
607
-            $this->detect_activation_or_upgrade();
608
-        }
609
-        return $this->_req_type;
610
-    }
611
-
612
-
613
-    /**
614
-     * Detects the request type for this addon (whether it was just activated, upgrades, a normal request, etc.)
615
-     * Should only be called once per request
616
-     *
617
-     * @return void
618
-     * @throws EE_Error
619
-     */
620
-    public function detect_activation_or_upgrade()
621
-    {
622
-        $activation_history_for_addon = $this->get_activation_history();
623
-        $request_type = EE_System::detect_req_type_given_activation_history(
624
-            $activation_history_for_addon,
625
-            $this->get_activation_indicator_option_name(),
626
-            $this->version()
627
-        );
628
-        $this->set_req_type($request_type);
629
-        $classname = get_class($this);
630
-        switch ($request_type) {
631
-            case EE_System::req_type_new_activation:
632
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__new_activation");
633
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__new_activation', $this);
634
-                $this->new_install();
635
-                $this->update_list_of_installed_versions($activation_history_for_addon);
636
-                break;
637
-            case EE_System::req_type_reactivation:
638
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__reactivation");
639
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__reactivation', $this);
640
-                $this->reactivation();
641
-                $this->update_list_of_installed_versions($activation_history_for_addon);
642
-                break;
643
-            case EE_System::req_type_upgrade:
644
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__upgrade");
645
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__upgrade', $this);
646
-                $this->upgrade();
647
-                $this->update_list_of_installed_versions($activation_history_for_addon);
648
-                break;
649
-            case EE_System::req_type_downgrade:
650
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__downgrade");
651
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__downgrade', $this);
652
-                $this->downgrade();
653
-                $this->update_list_of_installed_versions($activation_history_for_addon);
654
-                break;
655
-            case EE_System::req_type_normal:
656
-            default:
657
-                break;
658
-        }
659
-
660
-        do_action("AHEE__{$classname}__detect_if_activation_or_upgrade__complete");
661
-    }
662
-
663
-    /**
664
-     * Updates the version history for this addon
665
-     *
666
-     * @param array  $version_history
667
-     * @param string $current_version_to_add
668
-     * @return bool success
669
-     */
670
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
671
-    {
672
-        if (! $version_history) {
673
-            $version_history = $this->get_activation_history();
674
-        }
675
-        if ($current_version_to_add === null) {
676
-            $current_version_to_add = $this->version();
677
-        }
678
-        $version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
679
-        // resave
680
-        return update_option($this->get_activation_history_option_name(), $version_history);
681
-    }
682
-
683
-    /**
684
-     * Gets the name of the wp option that stores the activation history
685
-     * of this addon
686
-     *
687
-     * @return string
688
-     */
689
-    public function get_activation_history_option_name()
690
-    {
691
-        return self::ee_addon_version_history_option_prefix . $this->name();
692
-    }
693
-
694
-
695
-    /**
696
-     * Gets the wp option which stores the activation history for this addon
697
-     *
698
-     * @return array
699
-     */
700
-    public function get_activation_history()
701
-    {
702
-        return get_option($this->get_activation_history_option_name(), null);
703
-    }
704
-
705
-
706
-    /**
707
-     * @param string $config_section
708
-     */
709
-    public function set_config_section($config_section = '')
710
-    {
711
-        $this->_config_section = ! empty($config_section) ? $config_section : 'addons';
712
-    }
713
-
714
-    /**
715
-     * Sets the filepath to the main plugin file
716
-     *
717
-     * @param string $filepath
718
-     */
719
-    public function set_main_plugin_file($filepath)
720
-    {
721
-        $this->_main_plugin_file = $filepath;
722
-    }
723
-
724
-    /**
725
-     * gets the filepath to teh main file
726
-     *
727
-     * @return string
728
-     */
729
-    public function get_main_plugin_file()
730
-    {
731
-        return $this->_main_plugin_file;
732
-    }
733
-
734
-    /**
735
-     * Gets the filename (no path) of the main file (the main file loaded
736
-     * by WP)
737
-     *
738
-     * @return string
739
-     */
740
-    public function get_main_plugin_file_basename()
741
-    {
742
-        return plugin_basename($this->get_main_plugin_file());
743
-    }
744
-
745
-    /**
746
-     * Gets the folder name which contains the main plugin file
747
-     *
748
-     * @return string
749
-     */
750
-    public function get_main_plugin_file_dirname()
751
-    {
752
-        return dirname($this->get_main_plugin_file());
753
-    }
754
-
755
-
756
-    /**
757
-     * sets hooks used in the admin
758
-     *
759
-     * @return void
760
-     */
761
-    public function admin_init()
762
-    {
763
-        // is admin and not in M-Mode ?
764
-        if (is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
765
-            add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
766
-            add_filter('after_plugin_row_' . $this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
767
-        }
768
-    }
769
-
770
-
771
-    /**
772
-     * plugin_actions
773
-     * Add a settings link to the Plugins page, so people can go straight from the plugin page to the settings page.
774
-     *
775
-     * @param $links
776
-     * @param $file
777
-     * @return array
778
-     */
779
-    public function plugin_action_links($links, $file)
780
-    {
781
-        if ($file === $this->plugin_basename() && $this->plugin_action_slug() !== '') {
782
-            // before other links
783
-            array_unshift(
784
-                $links,
785
-                '<a href="admin.php?page=' . $this->plugin_action_slug() . '">'
786
-                . esc_html__('Settings', 'event_espresso')
787
-                . '</a>'
788
-            );
789
-        }
790
-        return $links;
791
-    }
792
-
793
-
794
-    /**
795
-     * after_plugin_row
796
-     * Add additional content to the plugins page plugin row
797
-     * Inserts another row
798
-     *
799
-     * @param $plugin_file
800
-     * @param $plugin_data
801
-     * @param $status
802
-     * @return void
803
-     */
804
-    public function after_plugin_row($plugin_file, $plugin_data, $status)
805
-    {
806
-        $after_plugin_row = '';
807
-        $plugins_page_row = $this->get_plugins_page_row();
808
-        if (! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
809
-            $class = $status ? 'active' : 'inactive';
810
-            $link_text = isset($plugins_page_row['link_text']) ? $plugins_page_row['link_text'] : '';
811
-            $link_url = isset($plugins_page_row['link_url']) ? $plugins_page_row['link_url'] : '';
812
-            $description = isset($plugins_page_row['description'])
813
-                ? $plugins_page_row['description']
814
-                : '';
815
-            if (! empty($link_text) && ! empty($link_url) && ! empty($description)) {
816
-                $after_plugin_row .= '<tr id="' . sanitize_title($plugin_file) . '-ee-addon" class="' . $class . '">';
817
-                $after_plugin_row .= '<th class="check-column" scope="row"></th>';
818
-                $after_plugin_row .= '<td class="ee-addon-upsell-info-title-td plugin-title column-primary">';
819
-                $after_plugin_row .= '<p class="ee-addon-upsell-info-dv">
409
+			EEH_Activation::initialize_db_content();
410
+			/** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
411
+			$rewrite_rules = LoaderFactory::getLoader()->getShared(
412
+				'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
413
+			);
414
+			$rewrite_rules->flushRewriteRules();
415
+			// in case there are lots of addons being activated at once, let's force garbage collection
416
+			// to help avoid memory limit errors
417
+			// EEH_Debug_Tools::instance()->measure_memory( 'db content initialized for ' . get_class( $this), true );
418
+			gc_collect_cycles();
419
+		} else {
420
+			// ask the data migration manager to init this addon's data
421
+			// when migrations are finished because we can't do it now
422
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for($this->name());
423
+		}
424
+	}
425
+
426
+
427
+	/**
428
+	 * Used to setup this addon's database tables, but not necessarily any default
429
+	 * data in them. The default is to actually use the most up-to-date data migration script
430
+	 * for this addon, and just use its schema_changes_before_migration() and schema_changes_after_migration()
431
+	 * methods to setup the db.
432
+	 */
433
+	public function initialize_db()
434
+	{
435
+		// find the migration script that sets the database to be compatible with the code
436
+		$current_dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms($this->name());
437
+		if ($current_dms_name) {
438
+			$current_data_migration_script = EE_Registry::instance()->load_dms($current_dms_name);
439
+			$current_data_migration_script->set_migrating(false);
440
+			$current_data_migration_script->schema_changes_before_migration();
441
+			$current_data_migration_script->schema_changes_after_migration();
442
+			if ($current_data_migration_script->get_errors()) {
443
+				foreach ($current_data_migration_script->get_errors() as $error) {
444
+					EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
445
+				}
446
+			}
447
+		}
448
+		// if not DMS was found that should be ok. This addon just doesn't require any database changes
449
+		EE_Data_Migration_Manager::instance()->update_current_database_state_to(
450
+			array(
451
+				'slug'    => $this->name(),
452
+				'version' => $this->version(),
453
+			)
454
+		);
455
+	}
456
+
457
+
458
+	/**
459
+	 * If you want to setup default data for the addon, override this method, and call
460
+	 * parent::initialize_default_data() from within it. This is normally called
461
+	 * from EE_Addon::initialize_db_if_no_migrations_required(), just after EE_Addon::initialize_db()
462
+	 * and should verify default data is present (but this is also called
463
+	 * on reactivations and just after migrations, so please verify you actually want
464
+	 * to ADD default data, because it may already be present).
465
+	 * However, please call this parent (currently it just fires a hook which other
466
+	 * addons may be depending on)
467
+	 */
468
+	public function initialize_default_data()
469
+	{
470
+		/**
471
+		 * Called when an addon is ensuring its default data is set (possibly called
472
+		 * on a reactivation, so first check for the absence of other data before setting
473
+		 * default data)
474
+		 *
475
+		 * @param EE_Addon $addon the addon that called this
476
+		 */
477
+		do_action('AHEE__EE_Addon__initialize_default_data__begin', $this);
478
+		// override to insert default data. It is safe to use the models here
479
+		// because the site should not be in maintenance mode
480
+	}
481
+
482
+
483
+	/**
484
+	 * EE Core detected that this addon has been upgraded. We should check if there
485
+	 * are any new migration scripts, and if so put the site into maintenance mode until
486
+	 * they're ran
487
+	 *
488
+	 * @return void
489
+	 * @throws EE_Error
490
+	 */
491
+	public function upgrade()
492
+	{
493
+		$classname = get_class($this);
494
+		do_action("AHEE__{$classname}__upgrade");
495
+		do_action('AHEE__EE_Addon__upgrade', $this);
496
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
497
+		// also it's possible there is new default data that needs to be added
498
+		add_action(
499
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
500
+			array($this, 'initialize_db_if_no_migrations_required')
501
+		);
502
+	}
503
+
504
+
505
+	/**
506
+	 * If Core detects this addon has been downgraded, you may want to invoke some special logic here.
507
+	 */
508
+	public function downgrade()
509
+	{
510
+		$classname = get_class($this);
511
+		do_action("AHEE__{$classname}__downgrade");
512
+		do_action('AHEE__EE_Addon__downgrade', $this);
513
+		// it's possible there's old default data that needs to be double-checked
514
+		add_action(
515
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
516
+			array($this, 'initialize_db_if_no_migrations_required')
517
+		);
518
+	}
519
+
520
+
521
+	/**
522
+	 * set_db_update_option_name
523
+	 * Until we do something better, we'll just check for migration scripts upon
524
+	 * plugin activation only. In the future, we'll want to do it on plugin updates too
525
+	 *
526
+	 * @return bool
527
+	 */
528
+	public function set_db_update_option_name()
529
+	{
530
+		EE_Error::doing_it_wrong(
531
+			__FUNCTION__,
532
+			esc_html__(
533
+				'EE_Addon::set_db_update_option_name was renamed to EE_Addon::set_activation_indicator_option',
534
+				'event_espresso'
535
+			),
536
+			'4.3.0.alpha.016'
537
+		);
538
+		// let's just handle this on the next request, ok? right now we're just not really ready
539
+		return $this->set_activation_indicator_option();
540
+	}
541
+
542
+
543
+	/**
544
+	 * Returns the name of the activation indicator option
545
+	 * (an option which is set temporarily to indicate that this addon was just activated)
546
+	 *
547
+	 * @deprecated since version 4.3.0.alpha.016
548
+	 * @return string
549
+	 */
550
+	public function get_db_update_option_name()
551
+	{
552
+		EE_Error::doing_it_wrong(
553
+			__FUNCTION__,
554
+			esc_html__(
555
+				'EE_Addon::get_db_update_option was renamed to EE_Addon::get_activation_indicator_option_name',
556
+				'event_espresso'
557
+			),
558
+			'4.3.0.alpha.016'
559
+		);
560
+		return $this->get_activation_indicator_option_name();
561
+	}
562
+
563
+
564
+	/**
565
+	 * When the addon is activated, this should be called to set a wordpress option that
566
+	 * indicates it was activated. This is especially useful for detecting reactivations.
567
+	 *
568
+	 * @return bool
569
+	 */
570
+	public function set_activation_indicator_option()
571
+	{
572
+		// let's just handle this on the next request, ok? right now we're just not really ready
573
+		return update_option($this->get_activation_indicator_option_name(), true);
574
+	}
575
+
576
+
577
+	/**
578
+	 * Gets the name of the wp option which is used to temporarily indicate that this addon was activated
579
+	 *
580
+	 * @return string
581
+	 */
582
+	public function get_activation_indicator_option_name()
583
+	{
584
+		return 'ee_activation_' . $this->name();
585
+	}
586
+
587
+
588
+	/**
589
+	 * Used by EE_System to set the request type of this addon. Should not be used by addon developers
590
+	 *
591
+	 * @param int $req_type
592
+	 */
593
+	public function set_req_type($req_type)
594
+	{
595
+		$this->_req_type = $req_type;
596
+	}
597
+
598
+
599
+	/**
600
+	 * Returns the request type of this addon (ie, EE_System::req_type_normal, EE_System::req_type_new_activation,
601
+	 * EE_System::req_type_reactivation, EE_System::req_type_upgrade, or EE_System::req_type_downgrade). This is set by
602
+	 * EE_System when it is checking for new install or upgrades of addons
603
+	 */
604
+	public function detect_req_type($redetect = false)
605
+	{
606
+		if ($this->_req_type === null || $redetect) {
607
+			$this->detect_activation_or_upgrade();
608
+		}
609
+		return $this->_req_type;
610
+	}
611
+
612
+
613
+	/**
614
+	 * Detects the request type for this addon (whether it was just activated, upgrades, a normal request, etc.)
615
+	 * Should only be called once per request
616
+	 *
617
+	 * @return void
618
+	 * @throws EE_Error
619
+	 */
620
+	public function detect_activation_or_upgrade()
621
+	{
622
+		$activation_history_for_addon = $this->get_activation_history();
623
+		$request_type = EE_System::detect_req_type_given_activation_history(
624
+			$activation_history_for_addon,
625
+			$this->get_activation_indicator_option_name(),
626
+			$this->version()
627
+		);
628
+		$this->set_req_type($request_type);
629
+		$classname = get_class($this);
630
+		switch ($request_type) {
631
+			case EE_System::req_type_new_activation:
632
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__new_activation");
633
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__new_activation', $this);
634
+				$this->new_install();
635
+				$this->update_list_of_installed_versions($activation_history_for_addon);
636
+				break;
637
+			case EE_System::req_type_reactivation:
638
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__reactivation");
639
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__reactivation', $this);
640
+				$this->reactivation();
641
+				$this->update_list_of_installed_versions($activation_history_for_addon);
642
+				break;
643
+			case EE_System::req_type_upgrade:
644
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__upgrade");
645
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__upgrade', $this);
646
+				$this->upgrade();
647
+				$this->update_list_of_installed_versions($activation_history_for_addon);
648
+				break;
649
+			case EE_System::req_type_downgrade:
650
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__downgrade");
651
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__downgrade', $this);
652
+				$this->downgrade();
653
+				$this->update_list_of_installed_versions($activation_history_for_addon);
654
+				break;
655
+			case EE_System::req_type_normal:
656
+			default:
657
+				break;
658
+		}
659
+
660
+		do_action("AHEE__{$classname}__detect_if_activation_or_upgrade__complete");
661
+	}
662
+
663
+	/**
664
+	 * Updates the version history for this addon
665
+	 *
666
+	 * @param array  $version_history
667
+	 * @param string $current_version_to_add
668
+	 * @return bool success
669
+	 */
670
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
671
+	{
672
+		if (! $version_history) {
673
+			$version_history = $this->get_activation_history();
674
+		}
675
+		if ($current_version_to_add === null) {
676
+			$current_version_to_add = $this->version();
677
+		}
678
+		$version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
679
+		// resave
680
+		return update_option($this->get_activation_history_option_name(), $version_history);
681
+	}
682
+
683
+	/**
684
+	 * Gets the name of the wp option that stores the activation history
685
+	 * of this addon
686
+	 *
687
+	 * @return string
688
+	 */
689
+	public function get_activation_history_option_name()
690
+	{
691
+		return self::ee_addon_version_history_option_prefix . $this->name();
692
+	}
693
+
694
+
695
+	/**
696
+	 * Gets the wp option which stores the activation history for this addon
697
+	 *
698
+	 * @return array
699
+	 */
700
+	public function get_activation_history()
701
+	{
702
+		return get_option($this->get_activation_history_option_name(), null);
703
+	}
704
+
705
+
706
+	/**
707
+	 * @param string $config_section
708
+	 */
709
+	public function set_config_section($config_section = '')
710
+	{
711
+		$this->_config_section = ! empty($config_section) ? $config_section : 'addons';
712
+	}
713
+
714
+	/**
715
+	 * Sets the filepath to the main plugin file
716
+	 *
717
+	 * @param string $filepath
718
+	 */
719
+	public function set_main_plugin_file($filepath)
720
+	{
721
+		$this->_main_plugin_file = $filepath;
722
+	}
723
+
724
+	/**
725
+	 * gets the filepath to teh main file
726
+	 *
727
+	 * @return string
728
+	 */
729
+	public function get_main_plugin_file()
730
+	{
731
+		return $this->_main_plugin_file;
732
+	}
733
+
734
+	/**
735
+	 * Gets the filename (no path) of the main file (the main file loaded
736
+	 * by WP)
737
+	 *
738
+	 * @return string
739
+	 */
740
+	public function get_main_plugin_file_basename()
741
+	{
742
+		return plugin_basename($this->get_main_plugin_file());
743
+	}
744
+
745
+	/**
746
+	 * Gets the folder name which contains the main plugin file
747
+	 *
748
+	 * @return string
749
+	 */
750
+	public function get_main_plugin_file_dirname()
751
+	{
752
+		return dirname($this->get_main_plugin_file());
753
+	}
754
+
755
+
756
+	/**
757
+	 * sets hooks used in the admin
758
+	 *
759
+	 * @return void
760
+	 */
761
+	public function admin_init()
762
+	{
763
+		// is admin and not in M-Mode ?
764
+		if (is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
765
+			add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
766
+			add_filter('after_plugin_row_' . $this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
767
+		}
768
+	}
769
+
770
+
771
+	/**
772
+	 * plugin_actions
773
+	 * Add a settings link to the Plugins page, so people can go straight from the plugin page to the settings page.
774
+	 *
775
+	 * @param $links
776
+	 * @param $file
777
+	 * @return array
778
+	 */
779
+	public function plugin_action_links($links, $file)
780
+	{
781
+		if ($file === $this->plugin_basename() && $this->plugin_action_slug() !== '') {
782
+			// before other links
783
+			array_unshift(
784
+				$links,
785
+				'<a href="admin.php?page=' . $this->plugin_action_slug() . '">'
786
+				. esc_html__('Settings', 'event_espresso')
787
+				. '</a>'
788
+			);
789
+		}
790
+		return $links;
791
+	}
792
+
793
+
794
+	/**
795
+	 * after_plugin_row
796
+	 * Add additional content to the plugins page plugin row
797
+	 * Inserts another row
798
+	 *
799
+	 * @param $plugin_file
800
+	 * @param $plugin_data
801
+	 * @param $status
802
+	 * @return void
803
+	 */
804
+	public function after_plugin_row($plugin_file, $plugin_data, $status)
805
+	{
806
+		$after_plugin_row = '';
807
+		$plugins_page_row = $this->get_plugins_page_row();
808
+		if (! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
809
+			$class = $status ? 'active' : 'inactive';
810
+			$link_text = isset($plugins_page_row['link_text']) ? $plugins_page_row['link_text'] : '';
811
+			$link_url = isset($plugins_page_row['link_url']) ? $plugins_page_row['link_url'] : '';
812
+			$description = isset($plugins_page_row['description'])
813
+				? $plugins_page_row['description']
814
+				: '';
815
+			if (! empty($link_text) && ! empty($link_url) && ! empty($description)) {
816
+				$after_plugin_row .= '<tr id="' . sanitize_title($plugin_file) . '-ee-addon" class="' . $class . '">';
817
+				$after_plugin_row .= '<th class="check-column" scope="row"></th>';
818
+				$after_plugin_row .= '<td class="ee-addon-upsell-info-title-td plugin-title column-primary">';
819
+				$after_plugin_row .= '<p class="ee-addon-upsell-info-dv">
820 820
 	                <a class="ee-button" href="' . esc_url_raw($link_url) . '">'
821
-                    . $link_text
822
-                    . ' &nbsp;<span class="dashicons dashicons-arrow-right-alt2" style="margin:0;"></span>'
823
-                    . '</a>
821
+					. $link_text
822
+					. ' &nbsp;<span class="dashicons dashicons-arrow-right-alt2" style="margin:0;"></span>'
823
+					. '</a>
824 824
                 </p>';
825
-                $after_plugin_row .= '</td>';
826
-                $after_plugin_row .= '<td class="ee-addon-upsell-info-desc-td column-description desc">';
827
-                $after_plugin_row .= $description;
828
-                $after_plugin_row .= '</td>';
829
-                $after_plugin_row .= '</tr>';
830
-            } else {
831
-                $after_plugin_row .= $description;
832
-            }
833
-        }
834
-
835
-        echo wp_kses($after_plugin_row, AllowedTags::getAllowedTags());
836
-    }
837
-
838
-
839
-    /**
840
-     * A safe space for addons to add additional logic like setting hooks that need to be set early in the request.
841
-     * Child classes that have logic like that to run can override this method declaration.  This was not made abstract
842
-     * for back compat reasons.
843
-     *
844
-     * This will fire on the `AHEE__EE_System__load_espresso_addons__complete` hook at priority 999.
845
-     *
846
-     * It is recommended, if client code is `de-registering` an add-on, then do it on the
847
-     * `AHEE__EE_System__load_espresso_addons__complete` hook before priority 999 so as to ensure any code logic in this
848
-     * callback does not get run/set in that request.
849
-     *
850
-     * Also, keep in mind that if a registered add-on happens to be deactivated via
851
-     * EE_System::_deactivate_incompatible_addons() because its incompatible, any code executed in this method
852
-     * (including setting hooks etc) will have executed before the plugin was deactivated.  If you use
853
-     * `after_registration` to set any filter and/or action hooks and want to ensure they are removed on this add-on's
854
-     * deactivation, you can override `EE_Addon::deactivation` and unset your hooks and filters there.  Just remember
855
-     * to call `parent::deactivation`.
856
-     *
857
-     * @since 4.9.26
858
-     */
859
-    public function after_registration()
860
-    {
861
-        // cricket chirp... cricket chirp...
862
-    }
863
-
864
-    /**
865
-     * @return string
866
-     */
867
-    public function getPueSlug()
868
-    {
869
-        return $this->pue_slug;
870
-    }
871
-    /**
872
-     * @param string $pue_slug
873
-     */
874
-    public function setPueSlug($pue_slug)
875
-    {
876
-        $this->pue_slug = $pue_slug;
877
-    }
825
+				$after_plugin_row .= '</td>';
826
+				$after_plugin_row .= '<td class="ee-addon-upsell-info-desc-td column-description desc">';
827
+				$after_plugin_row .= $description;
828
+				$after_plugin_row .= '</td>';
829
+				$after_plugin_row .= '</tr>';
830
+			} else {
831
+				$after_plugin_row .= $description;
832
+			}
833
+		}
834
+
835
+		echo wp_kses($after_plugin_row, AllowedTags::getAllowedTags());
836
+	}
837
+
838
+
839
+	/**
840
+	 * A safe space for addons to add additional logic like setting hooks that need to be set early in the request.
841
+	 * Child classes that have logic like that to run can override this method declaration.  This was not made abstract
842
+	 * for back compat reasons.
843
+	 *
844
+	 * This will fire on the `AHEE__EE_System__load_espresso_addons__complete` hook at priority 999.
845
+	 *
846
+	 * It is recommended, if client code is `de-registering` an add-on, then do it on the
847
+	 * `AHEE__EE_System__load_espresso_addons__complete` hook before priority 999 so as to ensure any code logic in this
848
+	 * callback does not get run/set in that request.
849
+	 *
850
+	 * Also, keep in mind that if a registered add-on happens to be deactivated via
851
+	 * EE_System::_deactivate_incompatible_addons() because its incompatible, any code executed in this method
852
+	 * (including setting hooks etc) will have executed before the plugin was deactivated.  If you use
853
+	 * `after_registration` to set any filter and/or action hooks and want to ensure they are removed on this add-on's
854
+	 * deactivation, you can override `EE_Addon::deactivation` and unset your hooks and filters there.  Just remember
855
+	 * to call `parent::deactivation`.
856
+	 *
857
+	 * @since 4.9.26
858
+	 */
859
+	public function after_registration()
860
+	{
861
+		// cricket chirp... cricket chirp...
862
+	}
863
+
864
+	/**
865
+	 * @return string
866
+	 */
867
+	public function getPueSlug()
868
+	{
869
+		return $this->pue_slug;
870
+	}
871
+	/**
872
+	 * @param string $pue_slug
873
+	 */
874
+	public function setPueSlug($pue_slug)
875
+	{
876
+		$this->pue_slug = $pue_slug;
877
+	}
878 878
 }
Please login to merge, or discard this patch.
core/bootstrap_espresso.php 2 patches
Indentation   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -14,22 +14,22 @@  discard block
 block discarded – undo
14 14
  */
15 15
 function espresso_load_error_handling()
16 16
 {
17
-    static $error_handling_loaded = false;
18
-    if ($error_handling_loaded) {
19
-        return;
20
-    }
21
-    // load debugging tools
22
-    if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
23
-        require_once EE_HELPERS . 'EEH_Debug_Tools.helper.php';
24
-        EEH_Debug_Tools::instance();
25
-    }
26
-    // load error handling
27
-    if (is_readable(EE_CORE . 'EE_Error.core.php')) {
28
-        require_once EE_CORE . 'EE_Error.core.php';
29
-    } else {
30
-        wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
31
-    }
32
-    $error_handling_loaded = true;
17
+	static $error_handling_loaded = false;
18
+	if ($error_handling_loaded) {
19
+		return;
20
+	}
21
+	// load debugging tools
22
+	if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
23
+		require_once EE_HELPERS . 'EEH_Debug_Tools.helper.php';
24
+		EEH_Debug_Tools::instance();
25
+	}
26
+	// load error handling
27
+	if (is_readable(EE_CORE . 'EE_Error.core.php')) {
28
+		require_once EE_CORE . 'EE_Error.core.php';
29
+	} else {
30
+		wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
31
+	}
32
+	$error_handling_loaded = true;
33 33
 }
34 34
 
35 35
 
@@ -43,19 +43,19 @@  discard block
 block discarded – undo
43 43
  */
44 44
 function espresso_load_required($classname, $full_path_to_file)
45 45
 {
46
-    if (is_readable($full_path_to_file)) {
47
-        require_once $full_path_to_file;
48
-    } else {
49
-        throw new EE_Error(
50
-            sprintf(
51
-                esc_html__(
52
-                    'The %s class file could not be located or is not readable due to file permissions.',
53
-                    'event_espresso'
54
-                ),
55
-                $classname
56
-            )
57
-        );
58
-    }
46
+	if (is_readable($full_path_to_file)) {
47
+		require_once $full_path_to_file;
48
+	} else {
49
+		throw new EE_Error(
50
+			sprintf(
51
+				esc_html__(
52
+					'The %s class file could not be located or is not readable due to file permissions.',
53
+					'event_espresso'
54
+				),
55
+				$classname
56
+			)
57
+		);
58
+	}
59 59
 }
60 60
 
61 61
 
@@ -73,52 +73,52 @@  discard block
 block discarded – undo
73 73
  */
74 74
 function bootstrap_espresso()
75 75
 {
76
-    require_once __DIR__ . '/espresso_definitions.php';
77
-    try {
78
-        espresso_load_error_handling();
79
-        // include WordPress shims for functions introduced in later versions of WordPress
80
-        espresso_load_required(
81
-            '',
82
-            EE_CORE . 'wordpress-shims.php'
83
-        );
84
-        espresso_load_required(
85
-            '',
86
-            EE_CORE . 'third-party-compatibility.php'
87
-        );
88
-        espresso_load_required(
89
-            'EEH_Base',
90
-            EE_CORE . 'helpers/EEH_Base.helper.php'
91
-        );
92
-        espresso_load_required(
93
-            'EEH_File',
94
-            EE_CORE . 'interfaces/EEHI_File.interface.php'
95
-        );
96
-        espresso_load_required(
97
-            'EEH_File',
98
-            EE_CORE . 'helpers/EEH_File.helper.php'
99
-        );
100
-        espresso_load_required(
101
-            'EEH_Array',
102
-            EE_CORE . 'helpers/EEH_Array.helper.php'
103
-        );
104
-        espresso_load_required(
105
-            'EE_Base',
106
-            EE_CORE . 'EE_Base.core.php'
107
-        );
108
-        // instantiate and configure PSR4 autoloader
109
-        espresso_load_required(
110
-            'Psr4Autoloader',
111
-            EE_CORE . 'Psr4Autoloader.php'
112
-        );
113
-        espresso_load_required(
114
-            'EE_Psr4AutoloaderInit',
115
-            EE_CORE . 'EE_Psr4AutoloaderInit.core.php'
116
-        );
117
-        $AutoloaderInit = new EE_Psr4AutoloaderInit();
118
-        $AutoloaderInit->initializeAutoloader();
119
-        new EventEspresso\core\services\bootstrap\BootstrapCore();
120
-    } catch (Exception $e) {
121
-        require_once EE_CORE . 'exceptions/ExceptionStackTraceDisplay.php';
122
-        new EventEspresso\core\exceptions\ExceptionStackTraceDisplay($e);
123
-    }
76
+	require_once __DIR__ . '/espresso_definitions.php';
77
+	try {
78
+		espresso_load_error_handling();
79
+		// include WordPress shims for functions introduced in later versions of WordPress
80
+		espresso_load_required(
81
+			'',
82
+			EE_CORE . 'wordpress-shims.php'
83
+		);
84
+		espresso_load_required(
85
+			'',
86
+			EE_CORE . 'third-party-compatibility.php'
87
+		);
88
+		espresso_load_required(
89
+			'EEH_Base',
90
+			EE_CORE . 'helpers/EEH_Base.helper.php'
91
+		);
92
+		espresso_load_required(
93
+			'EEH_File',
94
+			EE_CORE . 'interfaces/EEHI_File.interface.php'
95
+		);
96
+		espresso_load_required(
97
+			'EEH_File',
98
+			EE_CORE . 'helpers/EEH_File.helper.php'
99
+		);
100
+		espresso_load_required(
101
+			'EEH_Array',
102
+			EE_CORE . 'helpers/EEH_Array.helper.php'
103
+		);
104
+		espresso_load_required(
105
+			'EE_Base',
106
+			EE_CORE . 'EE_Base.core.php'
107
+		);
108
+		// instantiate and configure PSR4 autoloader
109
+		espresso_load_required(
110
+			'Psr4Autoloader',
111
+			EE_CORE . 'Psr4Autoloader.php'
112
+		);
113
+		espresso_load_required(
114
+			'EE_Psr4AutoloaderInit',
115
+			EE_CORE . 'EE_Psr4AutoloaderInit.core.php'
116
+		);
117
+		$AutoloaderInit = new EE_Psr4AutoloaderInit();
118
+		$AutoloaderInit->initializeAutoloader();
119
+		new EventEspresso\core\services\bootstrap\BootstrapCore();
120
+	} catch (Exception $e) {
121
+		require_once EE_CORE . 'exceptions/ExceptionStackTraceDisplay.php';
122
+		new EventEspresso\core\exceptions\ExceptionStackTraceDisplay($e);
123
+	}
124 124
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -19,13 +19,13 @@  discard block
 block discarded – undo
19 19
         return;
20 20
     }
21 21
     // load debugging tools
22
-    if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
23
-        require_once EE_HELPERS . 'EEH_Debug_Tools.helper.php';
22
+    if (WP_DEBUG === true && is_readable(EE_HELPERS.'EEH_Debug_Tools.helper.php')) {
23
+        require_once EE_HELPERS.'EEH_Debug_Tools.helper.php';
24 24
         EEH_Debug_Tools::instance();
25 25
     }
26 26
     // load error handling
27
-    if (is_readable(EE_CORE . 'EE_Error.core.php')) {
28
-        require_once EE_CORE . 'EE_Error.core.php';
27
+    if (is_readable(EE_CORE.'EE_Error.core.php')) {
28
+        require_once EE_CORE.'EE_Error.core.php';
29 29
     } else {
30 30
         wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
31 31
     }
@@ -73,52 +73,52 @@  discard block
 block discarded – undo
73 73
  */
74 74
 function bootstrap_espresso()
75 75
 {
76
-    require_once __DIR__ . '/espresso_definitions.php';
76
+    require_once __DIR__.'/espresso_definitions.php';
77 77
     try {
78 78
         espresso_load_error_handling();
79 79
         // include WordPress shims for functions introduced in later versions of WordPress
80 80
         espresso_load_required(
81 81
             '',
82
-            EE_CORE . 'wordpress-shims.php'
82
+            EE_CORE.'wordpress-shims.php'
83 83
         );
84 84
         espresso_load_required(
85 85
             '',
86
-            EE_CORE . 'third-party-compatibility.php'
86
+            EE_CORE.'third-party-compatibility.php'
87 87
         );
88 88
         espresso_load_required(
89 89
             'EEH_Base',
90
-            EE_CORE . 'helpers/EEH_Base.helper.php'
90
+            EE_CORE.'helpers/EEH_Base.helper.php'
91 91
         );
92 92
         espresso_load_required(
93 93
             'EEH_File',
94
-            EE_CORE . 'interfaces/EEHI_File.interface.php'
94
+            EE_CORE.'interfaces/EEHI_File.interface.php'
95 95
         );
96 96
         espresso_load_required(
97 97
             'EEH_File',
98
-            EE_CORE . 'helpers/EEH_File.helper.php'
98
+            EE_CORE.'helpers/EEH_File.helper.php'
99 99
         );
100 100
         espresso_load_required(
101 101
             'EEH_Array',
102
-            EE_CORE . 'helpers/EEH_Array.helper.php'
102
+            EE_CORE.'helpers/EEH_Array.helper.php'
103 103
         );
104 104
         espresso_load_required(
105 105
             'EE_Base',
106
-            EE_CORE . 'EE_Base.core.php'
106
+            EE_CORE.'EE_Base.core.php'
107 107
         );
108 108
         // instantiate and configure PSR4 autoloader
109 109
         espresso_load_required(
110 110
             'Psr4Autoloader',
111
-            EE_CORE . 'Psr4Autoloader.php'
111
+            EE_CORE.'Psr4Autoloader.php'
112 112
         );
113 113
         espresso_load_required(
114 114
             'EE_Psr4AutoloaderInit',
115
-            EE_CORE . 'EE_Psr4AutoloaderInit.core.php'
115
+            EE_CORE.'EE_Psr4AutoloaderInit.core.php'
116 116
         );
117 117
         $AutoloaderInit = new EE_Psr4AutoloaderInit();
118 118
         $AutoloaderInit->initializeAutoloader();
119 119
         new EventEspresso\core\services\bootstrap\BootstrapCore();
120 120
     } catch (Exception $e) {
121
-        require_once EE_CORE . 'exceptions/ExceptionStackTraceDisplay.php';
121
+        require_once EE_CORE.'exceptions/ExceptionStackTraceDisplay.php';
122 122
         new EventEspresso\core\exceptions\ExceptionStackTraceDisplay($e);
123 123
     }
124 124
 }
Please login to merge, or discard this patch.
core/exceptions/ExceptionStackTraceDisplay.php 2 patches
Indentation   +277 added lines, -277 removed lines patch added patch discarded remove patch
@@ -20,163 +20,163 @@  discard block
 block discarded – undo
20 20
 class ExceptionStackTraceDisplay
21 21
 {
22 22
 
23
-    /**
24
-     * @var   string
25
-     * @since 4.10.24.p
26
-     */
27
-    private $class_name = '';
23
+	/**
24
+	 * @var   string
25
+	 * @since 4.10.24.p
26
+	 */
27
+	private $class_name = '';
28 28
 
29
-    /**
30
-     * @var   string
31
-     * @since 4.10.24.p
32
-     */
33
-    private $error_code = '';
29
+	/**
30
+	 * @var   string
31
+	 * @since 4.10.24.p
32
+	 */
33
+	private $error_code = '';
34 34
 
35 35
 
36
-    /**
37
-     * @param Exception $exception
38
-     * @throws Exception
39
-     */
40
-    public function __construct(Exception $exception)
41
-    {
42
-        if (WP_DEBUG && ! defined('EE_TESTS_DIR')) {
43
-            $this->displayException($exception);
44
-        } else {
45
-            throw $exception;
46
-        }
47
-    }
36
+	/**
37
+	 * @param Exception $exception
38
+	 * @throws Exception
39
+	 */
40
+	public function __construct(Exception $exception)
41
+	{
42
+		if (WP_DEBUG && ! defined('EE_TESTS_DIR')) {
43
+			$this->displayException($exception);
44
+		} else {
45
+			throw $exception;
46
+		}
47
+	}
48 48
 
49 49
 
50
-    /**
51
-     * @access protected
52
-     * @param Exception $exception
53
-     * @throws ReflectionException
54
-     */
55
-    protected function displayException(Exception $exception)
56
-    {
57
-        // get separate user and developer messages if they exist
58
-        $msg = explode('||', $exception->getMessage());
59
-        $user_msg = $msg[0];
60
-        $dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
61
-        $msg = WP_DEBUG ? $dev_msg : $user_msg;
62
-        // process trace info
63
-        $trace_details = $this->traceDetails($exception);
64
-        $code          = $exception->getCode() ?: $this->error_code;
65
-        // add helpful developer messages if debugging is on
66
-        // or generic non-identifying messages for non-privileged users
67
-        $error_message = WP_DEBUG
68
-            ? $this->developerError($exception, $msg, $code, $trace_details)
69
-            : $this->genericError($msg, $code);
70
-        // start gathering output
71
-        $output = '
50
+	/**
51
+	 * @access protected
52
+	 * @param Exception $exception
53
+	 * @throws ReflectionException
54
+	 */
55
+	protected function displayException(Exception $exception)
56
+	{
57
+		// get separate user and developer messages if they exist
58
+		$msg = explode('||', $exception->getMessage());
59
+		$user_msg = $msg[0];
60
+		$dev_msg = isset($msg[1]) ? $msg[1] : $msg[0];
61
+		$msg = WP_DEBUG ? $dev_msg : $user_msg;
62
+		// process trace info
63
+		$trace_details = $this->traceDetails($exception);
64
+		$code          = $exception->getCode() ?: $this->error_code;
65
+		// add helpful developer messages if debugging is on
66
+		// or generic non-identifying messages for non-privileged users
67
+		$error_message = WP_DEBUG
68
+			? $this->developerError($exception, $msg, $code, $trace_details)
69
+			: $this->genericError($msg, $code);
70
+		// start gathering output
71
+		$output = '
72 72
         <div id="ee-error-message" class="error">
73 73
             ' . $error_message . '
74 74
         </div>';
75
-        $scripts = $this->printScripts(true);
76
-        if (defined('DOING_AJAX')) {
77
-            echo wp_json_encode(array('error' => $output . $scripts));
78
-            exit();
79
-        }
80
-        echo wp_kses($output . $scripts, AllowedTags::getWithScriptAndStyleTags());
81
-    }
75
+		$scripts = $this->printScripts(true);
76
+		if (defined('DOING_AJAX')) {
77
+			echo wp_json_encode(array('error' => $output . $scripts));
78
+			exit();
79
+		}
80
+		echo wp_kses($output . $scripts, AllowedTags::getWithScriptAndStyleTags());
81
+	}
82 82
 
83 83
 
84
-    private function genericError($msg, $code)
85
-    {
86
-        return '
84
+	private function genericError($msg, $code)
85
+	{
86
+		return '
87 87
         <p>
88 88
             <span class="ee-error-user-msg-spn">' . trim($msg) . '</span> &nbsp; <sup>' . $code . '</sup>
89 89
         </p>';
90
-    }
90
+	}
91 91
 
92 92
 
93
-    /**
94
-     * @param Exception $exception
95
-     * @param $msg
96
-     * @param $code
97
-     * @param $trace_details
98
-     * @return string
99
-     * @throws ReflectionException
100
-     */
101
-    private function developerError(Exception $exception, $msg, $code, $trace_details)
102
-    {
103
-        $time = time();
104
-        return '
93
+	/**
94
+	 * @param Exception $exception
95
+	 * @param $msg
96
+	 * @param $code
97
+	 * @param $trace_details
98
+	 * @return string
99
+	 * @throws ReflectionException
100
+	 */
101
+	private function developerError(Exception $exception, $msg, $code, $trace_details)
102
+	{
103
+		$time = time();
104
+		return '
105 105
         <div class="ee-error-dev-msg-dv">
106 106
             <p class="ee-error-dev-msg-pg">
107 107
                 '
108
-                . sprintf(
109
-                    esc_html__('%1$sAn %2$s was thrown!%3$s code: %4$s', 'event_espresso'),
110
-                    '<strong class="ee-error-dev-msg-str">',
111
-                    get_class($exception),
112
-                    '</strong>  &nbsp; <span>',
113
-                    $code . '</span>'
114
-                )
115
-                . '<br />
108
+				. sprintf(
109
+					esc_html__('%1$sAn %2$s was thrown!%3$s code: %4$s', 'event_espresso'),
110
+					'<strong class="ee-error-dev-msg-str">',
111
+					get_class($exception),
112
+					'</strong>  &nbsp; <span>',
113
+					$code . '</span>'
114
+				)
115
+				. '<br />
116 116
                 <span class="big-text">"' . trim($msg) . '"</span><br/>
117 117
                 <a id="display-ee-error-trace-1'
118
-                   . $time
119
-                   . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-1'
120
-                   . $time
121
-                   . '">
118
+				   . $time
119
+				   . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-1'
120
+				   . $time
121
+				   . '">
122 122
                     ' . esc_html__('click to view backtrace and class/method details', 'event_espresso') . '
123 123
                 </a><br />
124 124
                 '
125
-                . $exception->getFile()
126
-                . sprintf(
127
-                    esc_html__('%1$s( line no: %2$s )%3$s', 'event_espresso'),
128
-                    ' &nbsp; <span class="small-text lt-grey-text">',
129
-                    $exception->getLine(),
130
-                    '</span>'
131
-                )
132
-                . '
125
+				. $exception->getFile()
126
+				. sprintf(
127
+					esc_html__('%1$s( line no: %2$s )%3$s', 'event_espresso'),
128
+					' &nbsp; <span class="small-text lt-grey-text">',
129
+					$exception->getLine(),
130
+					'</span>'
131
+				)
132
+				. '
133 133
             </p>
134 134
             <div id="ee-error-trace-1'
135
-                   . $time
136
-                   . '-dv" class="ee-error-trace-dv ee-error-trace-dv--hidden">
135
+				   . $time
136
+				   . '-dv" class="ee-error-trace-dv ee-error-trace-dv--hidden">
137 137
                 '
138
-                   . $trace_details
139
-                   . $this->classDetails() . '
138
+				   . $trace_details
139
+				   . $this->classDetails() . '
140 140
             </div>
141 141
         </div>';
142
-    }
142
+	}
143 143
 
144 144
 
145
-    /**
146
-     * @throws ReflectionException
147
-     */
148
-    private function classDetails()
149
-    {
150
-        if (empty($this->class_name)) {
151
-            return '';
152
-        }
153
-        $a = new ReflectionClass($this->class_name);
154
-        return '
145
+	/**
146
+	 * @throws ReflectionException
147
+	 */
148
+	private function classDetails()
149
+	{
150
+		if (empty($this->class_name)) {
151
+			return '';
152
+		}
153
+		$a = new ReflectionClass($this->class_name);
154
+		return '
155 155
             <div style="padding:3px; margin:0 0 1em; border:1px solid #999; background:#fff; border-radius:3px;">
156 156
                 <div style="padding:1em 2em; border:1px solid #999; background:#fcfcfc;">
157 157
                     <h3>' . esc_html__('Class Details', 'event_espresso') . '</h3>
158 158
                     <pre>' . $a . '</pre>
159 159
                 </div>
160 160
             </div>';
161
-    }
161
+	}
162 162
 
163
-    /**
164
-     * @param Exception $exception
165
-     * @return string
166
-     * @throws ReflectionException
167
-     * @since 4.10.24.p
168
-     */
169
-    private function traceDetails(Exception $exception)
170
-    {
171
-        $trace = $exception->getTrace();
172
-        if (empty($trace)) {
173
-            return esc_html__(
174
-                'Sorry, but no trace information was available for this exception.',
175
-                'event_espresso'
176
-            );
177
-        }
163
+	/**
164
+	 * @param Exception $exception
165
+	 * @return string
166
+	 * @throws ReflectionException
167
+	 * @since 4.10.24.p
168
+	 */
169
+	private function traceDetails(Exception $exception)
170
+	{
171
+		$trace = $exception->getTrace();
172
+		if (empty($trace)) {
173
+			return esc_html__(
174
+				'Sorry, but no trace information was available for this exception.',
175
+				'event_espresso'
176
+			);
177
+		}
178 178
 
179
-        $trace_details = '
179
+		$trace_details = '
180 180
         <div id="ee-trace-details">
181 181
             <table>
182 182
                 <tr>
@@ -185,180 +185,180 @@  discard block
 block discarded – undo
185 185
                     <th scope="col" class="ee-align-left" style="width:40%;">File</th>
186 186
                     <th scope="col" class="ee-align-left">
187 187
                     ' . esc_html__('Class', 'event_espresso')
188
-                              . '->'
189
-                              . esc_html__('Method( arguments )', 'event_espresso') . '
188
+							  . '->'
189
+							  . esc_html__('Method( arguments )', 'event_espresso') . '
190 190
                     </th>
191 191
                 </tr>';
192
-        $last_on_stack = count($trace) - 1;
193
-        // reverse array so that stack is in proper chronological order
194
-        $sorted_trace = array_reverse($trace);
195
-        foreach ($sorted_trace as $nmbr => $trace) {
196
-            $this->class_name = isset($trace['class']) ? $trace['class'] : '';
197
-            $file     = isset($trace['file']) ? $trace['file'] : '';
198
-            $type     = isset($trace['type']) ? $trace['type'] : '';
199
-            $function = isset($trace['function']) ? $trace['function'] : '';
200
-            $args     = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
201
-            $args     = isset($trace['args']) && count($trace['args']) > 4 ? ' <br />' . $args . '<br />' : $args;
202
-            $line     = isset($trace['line']) ? $trace['line'] : '';
203
-            if (empty($file) && ! empty($this->class_name)) {
204
-                $a    = new ReflectionClass($this->class_name);
205
-                $file = $a->getFileName();
206
-                if (empty($line) && ! empty($function)) {
207
-                    try {
208
-                        // if $function is a closure, this throws an exception
209
-                        $b    = new ReflectionMethod($this->class_name, $function);
210
-                        $line = $b->getStartLine();
211
-                    } catch (Exception $closure_exception) {
212
-                        $line = 'unknown';
213
-                    }
214
-                }
215
-            }
216
-            if ($nmbr === $last_on_stack) {
217
-                $file       = $exception->getFile() ?: $file;
218
-                $line       = $exception->getLine() ?: $line;
219
-                $this->error_code = $this->generate_error_code($file, $trace['function'], $line);
220
-            }
221
-            $file          = EEH_File::standardise_directory_separators($file);
222
-            $nmbr          = ! empty($nmbr) ? $nmbr : '&nbsp;';
223
-            $line          = ! empty($line) ? $line : '&nbsp;';
224
-            $file          = ! empty($file) ? $file : '&nbsp;';
225
-            $type          = ! empty($type) ? $type : '';
226
-            $function      = ! empty($function) ? $function : '';
227
-            $args          = ! empty($args) ? '( ' . $args . ' )' : '()';
228
-            $trace_details .= '
192
+		$last_on_stack = count($trace) - 1;
193
+		// reverse array so that stack is in proper chronological order
194
+		$sorted_trace = array_reverse($trace);
195
+		foreach ($sorted_trace as $nmbr => $trace) {
196
+			$this->class_name = isset($trace['class']) ? $trace['class'] : '';
197
+			$file     = isset($trace['file']) ? $trace['file'] : '';
198
+			$type     = isset($trace['type']) ? $trace['type'] : '';
199
+			$function = isset($trace['function']) ? $trace['function'] : '';
200
+			$args     = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
201
+			$args     = isset($trace['args']) && count($trace['args']) > 4 ? ' <br />' . $args . '<br />' : $args;
202
+			$line     = isset($trace['line']) ? $trace['line'] : '';
203
+			if (empty($file) && ! empty($this->class_name)) {
204
+				$a    = new ReflectionClass($this->class_name);
205
+				$file = $a->getFileName();
206
+				if (empty($line) && ! empty($function)) {
207
+					try {
208
+						// if $function is a closure, this throws an exception
209
+						$b    = new ReflectionMethod($this->class_name, $function);
210
+						$line = $b->getStartLine();
211
+					} catch (Exception $closure_exception) {
212
+						$line = 'unknown';
213
+					}
214
+				}
215
+			}
216
+			if ($nmbr === $last_on_stack) {
217
+				$file       = $exception->getFile() ?: $file;
218
+				$line       = $exception->getLine() ?: $line;
219
+				$this->error_code = $this->generate_error_code($file, $trace['function'], $line);
220
+			}
221
+			$file          = EEH_File::standardise_directory_separators($file);
222
+			$nmbr          = ! empty($nmbr) ? $nmbr : '&nbsp;';
223
+			$line          = ! empty($line) ? $line : '&nbsp;';
224
+			$file          = ! empty($file) ? $file : '&nbsp;';
225
+			$type          = ! empty($type) ? $type : '';
226
+			$function      = ! empty($function) ? $function : '';
227
+			$args          = ! empty($args) ? '( ' . $args . ' )' : '()';
228
+			$trace_details .= '
229 229
                 <tr>
230 230
                     <td class="ee-align-right">' . $nmbr . '</td>
231 231
                     <td class="ee-align-right">' . $line . '</td>
232 232
                     <td class="ee-align-left">' . $file . '</td>
233 233
                     <td class="ee-align-left">' . $this->class_name . $type . $function . $args . '</td>
234 234
                 </tr>';
235
-        }
236
-        $trace_details .= '
235
+		}
236
+		$trace_details .= '
237 237
             </table>
238 238
         </div>';
239
-        return $trace_details;
240
-    }
239
+		return $trace_details;
240
+	}
241 241
 
242 242
 
243
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
244
-    // phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
243
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
244
+	// phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
245 245
 
246
-    /**
247
-     * generate string from exception trace args
248
-     *
249
-     * @param array $arguments
250
-     * @param int   $indent
251
-     * @param bool  $array
252
-     * @return string
253
-     */
254
-    private function _convert_args_to_string($arguments = array(), $indent = 0, $array = false)
255
-    {
256
-        $args = array();
257
-        $args_count = count($arguments);
258
-        if ($args_count > 2) {
259
-            $indent++;
260
-            $args[] = '<br />';
261
-        }
262
-        $x = 0;
263
-        foreach ($arguments as $arg) {
264
-            $x++;
265
-            for ($i = 0; $i < $indent; $i++) {
266
-                $args[] = ' &nbsp;&nbsp; ';
267
-            }
268
-            if (is_string($arg)) {
269
-                if (! $array && strlen($arg) > 75) {
270
-                    $args[] = '<br />';
271
-                    for ($i = 0; $i <= $indent; $i++) {
272
-                        $args[] = ' &nbsp;&nbsp; ';
273
-                    }
274
-                    $args[] = "'" . $arg . "'<br />";
275
-                } else {
276
-                    $args[] = " '" . $arg . "'";
277
-                }
278
-            } elseif (is_array($arg)) {
279
-                $arg_count = count($arg);
280
-                if ($arg_count > 2) {
281
-                    $indent++;
282
-                    $args[] = ' array(' . $this->_convert_args_to_string($arg, $indent, true) . ')';
283
-                    $indent--;
284
-                } elseif ($arg_count === 0) {
285
-                    $args[] = ' array()';
286
-                } else {
287
-                    $args[] = ' array( ' . $this->_convert_args_to_string($arg) . ' )';
288
-                }
289
-            } elseif ($arg === null) {
290
-                $args[] = ' null';
291
-            } elseif (is_bool($arg)) {
292
-                $args[] = $arg ? ' true' : ' false';
293
-            } elseif (is_object($arg)) {
294
-                $args[] = get_class($arg);
295
-            } elseif (is_resource($arg)) {
296
-                $args[] = get_resource_type($arg);
297
-            } else {
298
-                $args[] = $arg;
299
-            }
300
-            if ($x === $args_count) {
301
-                if ($args_count > 2) {
302
-                    $args[] = '<br />';
303
-                    $indent--;
304
-                    for ($i = 1; $i < $indent; $i++) {
305
-                        $args[] = ' &nbsp;&nbsp; ';
306
-                    }
307
-                }
308
-            } else {
309
-                $args[] = $args_count > 2 ? ',<br />' : ', ';
310
-            }
311
-        }
312
-        return implode('', $args);
313
-    }
246
+	/**
247
+	 * generate string from exception trace args
248
+	 *
249
+	 * @param array $arguments
250
+	 * @param int   $indent
251
+	 * @param bool  $array
252
+	 * @return string
253
+	 */
254
+	private function _convert_args_to_string($arguments = array(), $indent = 0, $array = false)
255
+	{
256
+		$args = array();
257
+		$args_count = count($arguments);
258
+		if ($args_count > 2) {
259
+			$indent++;
260
+			$args[] = '<br />';
261
+		}
262
+		$x = 0;
263
+		foreach ($arguments as $arg) {
264
+			$x++;
265
+			for ($i = 0; $i < $indent; $i++) {
266
+				$args[] = ' &nbsp;&nbsp; ';
267
+			}
268
+			if (is_string($arg)) {
269
+				if (! $array && strlen($arg) > 75) {
270
+					$args[] = '<br />';
271
+					for ($i = 0; $i <= $indent; $i++) {
272
+						$args[] = ' &nbsp;&nbsp; ';
273
+					}
274
+					$args[] = "'" . $arg . "'<br />";
275
+				} else {
276
+					$args[] = " '" . $arg . "'";
277
+				}
278
+			} elseif (is_array($arg)) {
279
+				$arg_count = count($arg);
280
+				if ($arg_count > 2) {
281
+					$indent++;
282
+					$args[] = ' array(' . $this->_convert_args_to_string($arg, $indent, true) . ')';
283
+					$indent--;
284
+				} elseif ($arg_count === 0) {
285
+					$args[] = ' array()';
286
+				} else {
287
+					$args[] = ' array( ' . $this->_convert_args_to_string($arg) . ' )';
288
+				}
289
+			} elseif ($arg === null) {
290
+				$args[] = ' null';
291
+			} elseif (is_bool($arg)) {
292
+				$args[] = $arg ? ' true' : ' false';
293
+			} elseif (is_object($arg)) {
294
+				$args[] = get_class($arg);
295
+			} elseif (is_resource($arg)) {
296
+				$args[] = get_resource_type($arg);
297
+			} else {
298
+				$args[] = $arg;
299
+			}
300
+			if ($x === $args_count) {
301
+				if ($args_count > 2) {
302
+					$args[] = '<br />';
303
+					$indent--;
304
+					for ($i = 1; $i < $indent; $i++) {
305
+						$args[] = ' &nbsp;&nbsp; ';
306
+					}
307
+				}
308
+			} else {
309
+				$args[] = $args_count > 2 ? ',<br />' : ', ';
310
+			}
311
+		}
312
+		return implode('', $args);
313
+	}
314 314
 
315 315
 
316
-    /**
317
-     * create error code from filepath, function name,
318
-     * and line number where exception or error was thrown
319
-     *
320
-     * @access protected
321
-     * @param string $file
322
-     * @param string $func
323
-     * @param string $line
324
-     * @return string
325
-     */
326
-    protected function generate_error_code($file = '', $func = '', $line = '')
327
-    {
328
-        $file_bits = explode('.', basename($file));
329
-        $error_code = ! empty($file_bits[0]) ? $file_bits[0] : '';
330
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
331
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
332
-        return $error_code;
333
-    }
316
+	/**
317
+	 * create error code from filepath, function name,
318
+	 * and line number where exception or error was thrown
319
+	 *
320
+	 * @access protected
321
+	 * @param string $file
322
+	 * @param string $func
323
+	 * @param string $line
324
+	 * @return string
325
+	 */
326
+	protected function generate_error_code($file = '', $func = '', $line = '')
327
+	{
328
+		$file_bits = explode('.', basename($file));
329
+		$error_code = ! empty($file_bits[0]) ? $file_bits[0] : '';
330
+		$error_code .= ! empty($func) ? ' - ' . $func : '';
331
+		$error_code .= ! empty($line) ? ' - ' . $line : '';
332
+		return $error_code;
333
+	}
334 334
 
335 335
 
336
-    /**
337
-     * _print_scripts
338
-     *
339
-     * @param bool $force_print
340
-     * @return string
341
-     */
342
-    private function printScripts($force_print = false)
343
-    {
344
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
345
-            //  if script is already enqueued then we can just get out
346
-            if (wp_script_is('ee_error_js')) {
347
-                return '';
348
-            }
349
-            if (wp_script_is('ee_error_js', 'registered')) {
350
-                wp_enqueue_style('espresso_default');
351
-                wp_enqueue_style('espresso_custom_css');
352
-                wp_enqueue_script('ee_error_js');
353
-                wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
354
-                return '';
355
-            }
356
-        }
357
-        $jquery = includes_url() . 'js/jquery/jquery.js';
358
-        $core = EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js?ver=' . espresso_version();
359
-        $ee_error = EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js?ver=' . espresso_version();
360
-        $style = EE_GLOBAL_ASSETS_URL . 'css/ee-exception-stack-display.css';
361
-        return '
336
+	/**
337
+	 * _print_scripts
338
+	 *
339
+	 * @param bool $force_print
340
+	 * @return string
341
+	 */
342
+	private function printScripts($force_print = false)
343
+	{
344
+		if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
345
+			//  if script is already enqueued then we can just get out
346
+			if (wp_script_is('ee_error_js')) {
347
+				return '';
348
+			}
349
+			if (wp_script_is('ee_error_js', 'registered')) {
350
+				wp_enqueue_style('espresso_default');
351
+				wp_enqueue_style('espresso_custom_css');
352
+				wp_enqueue_script('ee_error_js');
353
+				wp_localize_script('ee_error_js', 'ee_settings', array('wp_debug' => WP_DEBUG));
354
+				return '';
355
+			}
356
+		}
357
+		$jquery = includes_url() . 'js/jquery/jquery.js';
358
+		$core = EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js?ver=' . espresso_version();
359
+		$ee_error = EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js?ver=' . espresso_version();
360
+		$style = EE_GLOBAL_ASSETS_URL . 'css/ee-exception-stack-display.css';
361
+		return '
362 362
             <script>
363 363
             const ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
364 364
             </script>
@@ -367,5 +367,5 @@  discard block
 block discarded – undo
367 367
             <script src="' . esc_url_raw($ee_error) . '" type="text/javascript"></script>
368 368
             <link href="' . esc_url_raw($style) . '" rel="stylesheet" />
369 369
         ';
370
-    }
370
+	}
371 371
 }
Please login to merge, or discard this patch.
Spacing   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -70,14 +70,14 @@  discard block
 block discarded – undo
70 70
         // start gathering output
71 71
         $output = '
72 72
         <div id="ee-error-message" class="error">
73
-            ' . $error_message . '
73
+            ' . $error_message.'
74 74
         </div>';
75 75
         $scripts = $this->printScripts(true);
76 76
         if (defined('DOING_AJAX')) {
77
-            echo wp_json_encode(array('error' => $output . $scripts));
77
+            echo wp_json_encode(array('error' => $output.$scripts));
78 78
             exit();
79 79
         }
80
-        echo wp_kses($output . $scripts, AllowedTags::getWithScriptAndStyleTags());
80
+        echo wp_kses($output.$scripts, AllowedTags::getWithScriptAndStyleTags());
81 81
     }
82 82
 
83 83
 
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
     {
86 86
         return '
87 87
         <p>
88
-            <span class="ee-error-user-msg-spn">' . trim($msg) . '</span> &nbsp; <sup>' . $code . '</sup>
88
+            <span class="ee-error-user-msg-spn">' . trim($msg).'</span> &nbsp; <sup>'.$code.'</sup>
89 89
         </p>';
90 90
     }
91 91
 
@@ -110,16 +110,16 @@  discard block
 block discarded – undo
110 110
                     '<strong class="ee-error-dev-msg-str">',
111 111
                     get_class($exception),
112 112
                     '</strong>  &nbsp; <span>',
113
-                    $code . '</span>'
113
+                    $code.'</span>'
114 114
                 )
115 115
                 . '<br />
116
-                <span class="big-text">"' . trim($msg) . '"</span><br/>
116
+                <span class="big-text">"' . trim($msg).'"</span><br/>
117 117
                 <a id="display-ee-error-trace-1'
118 118
                    . $time
119 119
                    . '" class="display-ee-error-trace-lnk small-text" rel="ee-error-trace-1'
120 120
                    . $time
121 121
                    . '">
122
-                    ' . esc_html__('click to view backtrace and class/method details', 'event_espresso') . '
122
+                    ' . esc_html__('click to view backtrace and class/method details', 'event_espresso').'
123 123
                 </a><br />
124 124
                 '
125 125
                 . $exception->getFile()
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
                    . '-dv" class="ee-error-trace-dv ee-error-trace-dv--hidden">
137 137
                 '
138 138
                    . $trace_details
139
-                   . $this->classDetails() . '
139
+                   . $this->classDetails().'
140 140
             </div>
141 141
         </div>';
142 142
     }
@@ -154,8 +154,8 @@  discard block
 block discarded – undo
154 154
         return '
155 155
             <div style="padding:3px; margin:0 0 1em; border:1px solid #999; background:#fff; border-radius:3px;">
156 156
                 <div style="padding:1em 2em; border:1px solid #999; background:#fcfcfc;">
157
-                    <h3>' . esc_html__('Class Details', 'event_espresso') . '</h3>
158
-                    <pre>' . $a . '</pre>
157
+                    <h3>' . esc_html__('Class Details', 'event_espresso').'</h3>
158
+                    <pre>' . $a.'</pre>
159 159
                 </div>
160 160
             </div>';
161 161
     }
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
                     <th scope="col" class="ee-align-left">
187 187
                     ' . esc_html__('Class', 'event_espresso')
188 188
                               . '->'
189
-                              . esc_html__('Method( arguments )', 'event_espresso') . '
189
+                              . esc_html__('Method( arguments )', 'event_espresso').'
190 190
                     </th>
191 191
                 </tr>';
192 192
         $last_on_stack = count($trace) - 1;
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
             $type     = isset($trace['type']) ? $trace['type'] : '';
199 199
             $function = isset($trace['function']) ? $trace['function'] : '';
200 200
             $args     = isset($trace['args']) ? $this->_convert_args_to_string($trace['args']) : '';
201
-            $args     = isset($trace['args']) && count($trace['args']) > 4 ? ' <br />' . $args . '<br />' : $args;
201
+            $args     = isset($trace['args']) && count($trace['args']) > 4 ? ' <br />'.$args.'<br />' : $args;
202 202
             $line     = isset($trace['line']) ? $trace['line'] : '';
203 203
             if (empty($file) && ! empty($this->class_name)) {
204 204
                 $a    = new ReflectionClass($this->class_name);
@@ -224,13 +224,13 @@  discard block
 block discarded – undo
224 224
             $file          = ! empty($file) ? $file : '&nbsp;';
225 225
             $type          = ! empty($type) ? $type : '';
226 226
             $function      = ! empty($function) ? $function : '';
227
-            $args          = ! empty($args) ? '( ' . $args . ' )' : '()';
227
+            $args          = ! empty($args) ? '( '.$args.' )' : '()';
228 228
             $trace_details .= '
229 229
                 <tr>
230
-                    <td class="ee-align-right">' . $nmbr . '</td>
231
-                    <td class="ee-align-right">' . $line . '</td>
232
-                    <td class="ee-align-left">' . $file . '</td>
233
-                    <td class="ee-align-left">' . $this->class_name . $type . $function . $args . '</td>
230
+                    <td class="ee-align-right">' . $nmbr.'</td>
231
+                    <td class="ee-align-right">' . $line.'</td>
232
+                    <td class="ee-align-left">' . $file.'</td>
233
+                    <td class="ee-align-left">' . $this->class_name.$type.$function.$args.'</td>
234 234
                 </tr>';
235 235
         }
236 236
         $trace_details .= '
@@ -266,25 +266,25 @@  discard block
 block discarded – undo
266 266
                 $args[] = ' &nbsp;&nbsp; ';
267 267
             }
268 268
             if (is_string($arg)) {
269
-                if (! $array && strlen($arg) > 75) {
269
+                if ( ! $array && strlen($arg) > 75) {
270 270
                     $args[] = '<br />';
271 271
                     for ($i = 0; $i <= $indent; $i++) {
272 272
                         $args[] = ' &nbsp;&nbsp; ';
273 273
                     }
274
-                    $args[] = "'" . $arg . "'<br />";
274
+                    $args[] = "'".$arg."'<br />";
275 275
                 } else {
276
-                    $args[] = " '" . $arg . "'";
276
+                    $args[] = " '".$arg."'";
277 277
                 }
278 278
             } elseif (is_array($arg)) {
279 279
                 $arg_count = count($arg);
280 280
                 if ($arg_count > 2) {
281 281
                     $indent++;
282
-                    $args[] = ' array(' . $this->_convert_args_to_string($arg, $indent, true) . ')';
282
+                    $args[] = ' array('.$this->_convert_args_to_string($arg, $indent, true).')';
283 283
                     $indent--;
284 284
                 } elseif ($arg_count === 0) {
285 285
                     $args[] = ' array()';
286 286
                 } else {
287
-                    $args[] = ' array( ' . $this->_convert_args_to_string($arg) . ' )';
287
+                    $args[] = ' array( '.$this->_convert_args_to_string($arg).' )';
288 288
                 }
289 289
             } elseif ($arg === null) {
290 290
                 $args[] = ' null';
@@ -327,8 +327,8 @@  discard block
 block discarded – undo
327 327
     {
328 328
         $file_bits = explode('.', basename($file));
329 329
         $error_code = ! empty($file_bits[0]) ? $file_bits[0] : '';
330
-        $error_code .= ! empty($func) ? ' - ' . $func : '';
331
-        $error_code .= ! empty($line) ? ' - ' . $line : '';
330
+        $error_code .= ! empty($func) ? ' - '.$func : '';
331
+        $error_code .= ! empty($line) ? ' - '.$line : '';
332 332
         return $error_code;
333 333
     }
334 334
 
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
      */
342 342
     private function printScripts($force_print = false)
343 343
     {
344
-        if (! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
344
+        if ( ! $force_print && (did_action('admin_enqueue_scripts') || did_action('wp_enqueue_scripts'))) {
345 345
             //  if script is already enqueued then we can just get out
346 346
             if (wp_script_is('ee_error_js')) {
347 347
                 return '';
@@ -354,18 +354,18 @@  discard block
 block discarded – undo
354 354
                 return '';
355 355
             }
356 356
         }
357
-        $jquery = includes_url() . 'js/jquery/jquery.js';
358
-        $core = EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js?ver=' . espresso_version();
359
-        $ee_error = EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js?ver=' . espresso_version();
360
-        $style = EE_GLOBAL_ASSETS_URL . 'css/ee-exception-stack-display.css';
357
+        $jquery = includes_url().'js/jquery/jquery.js';
358
+        $core = EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js?ver='.espresso_version();
359
+        $ee_error = EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js?ver='.espresso_version();
360
+        $style = EE_GLOBAL_ASSETS_URL.'css/ee-exception-stack-display.css';
361 361
         return '
362 362
             <script>
363
-            const ee_settings = {"wp_debug":"' . WP_DEBUG . '"};
363
+            const ee_settings = {"wp_debug":"' . WP_DEBUG.'"};
364 364
             </script>
365
-            <script src="' . esc_url_raw($jquery) . '" type="text/javascript"></script>
366
-            <script src="' . esc_url_raw($core) . '" type="text/javascript"></script>
367
-            <script src="' . esc_url_raw($ee_error) . '" type="text/javascript"></script>
368
-            <link href="' . esc_url_raw($style) . '" rel="stylesheet" />
365
+            <script src="' . esc_url_raw($jquery).'" type="text/javascript"></script>
366
+            <script src="' . esc_url_raw($core).'" type="text/javascript"></script>
367
+            <script src="' . esc_url_raw($ee_error).'" type="text/javascript"></script>
368
+            <link href="' . esc_url_raw($style).'" rel="stylesheet" />
369 369
         ';
370 370
     }
371 371
 }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +80 added lines, -80 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
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.6.2');
65
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.6.2');
65
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                        esc_html__(
79
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                            'event_espresso'
81
-                        ),
82
-                        EE_MIN_PHP_VER_REQUIRED,
83
-                        PHP_VERSION,
84
-                        '<br/>',
85
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+						esc_html__(
79
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+							'event_espresso'
81
+						),
82
+						EE_MIN_PHP_VER_REQUIRED,
83
+						PHP_VERSION,
84
+						'<br/>',
85
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        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.10.31.rc.002');
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.10.31.rc.002');
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
 }
141 141
\ No newline at end of file
Please login to merge, or discard this patch.
core/services/request/sanitizers/AllowedTags.php 1 patch
Indentation   +277 added lines, -277 removed lines patch added patch discarded remove patch
@@ -13,281 +13,281 @@
 block discarded – undo
13 13
 class AllowedTags
14 14
 {
15 15
 
16
-    /**
17
-     * @var array[]
18
-     */
19
-    private static $attributes = [
20
-        'accept-charset'    => 1,
21
-        'action'            => 1,
22
-        'alt'               => 1,
23
-        'allow'             => 1,
24
-        'allowfullscreen'   => 1,
25
-        'align'             => 1,
26
-        'aria-*'            => 1,
27
-        'autocomplete'      => 1,
28
-        'checked'           => 1,
29
-        'class'             => 1,
30
-        'cols'              => 1,
31
-        'content'           => 1,
32
-        'data-*'            => 1,
33
-        'dir'               => 1,
34
-        'disabled'          => 1,
35
-        'enctype'           => 1,
36
-        'for'               => 1,
37
-        'frameborder'       => 1,
38
-        'height'            => 1,
39
-        'href'              => 1,
40
-        'id'                => 1,
41
-        'itemprop'          => 1,
42
-        'itemscope'         => 1,
43
-        'itemtype'          => 1,
44
-        'label'             => 1,
45
-        'lang'              => 1,
46
-        'max'               => 1,
47
-        'maxlength'         => 1,
48
-        'method'            => 1,
49
-        'min'               => 1,
50
-        'multiple'          => 1,
51
-        'name'              => 1,
52
-        'novalidate'        => 1,
53
-        'placeholder'       => 1,
54
-        'readonly'          => 1,
55
-        'rel'               => 1,
56
-        'required'          => 1,
57
-        'rows'              => 1,
58
-        'selected'          => 1,
59
-        'src'               => 1,
60
-        'size'              => 1,
61
-        'style'             => 1,
62
-        'step'              => 1,
63
-        'tabindex'          => 1,
64
-        'target'            => 1,
65
-        'title'             => 1,
66
-        'type'              => 1,
67
-        'value'             => 1,
68
-        'width'             => 1,
69
-        'topmargin'         => 1,
70
-        'leftmargin'        => 1,
71
-        'marginheight'      => 1,
72
-        'marginwidth'       => 1,
73
-        'property'          => 1,
74
-        'bgcolor'           => 1,
75
-        'media'             => 1,
76
-        'cellpadding'       => 1,
77
-        'cellspacing'       => 1,
78
-        'border'            => 1,
79
-    ];
80
-
81
-
82
-    /**
83
-     * @var array
84
-     */
85
-    private static $tags = [
86
-        'a',
87
-        'abbr',
88
-        'b',
89
-        'br',
90
-        'code',
91
-        'div',
92
-        'em',
93
-        'h1',
94
-        'h2',
95
-        'h3',
96
-        'h4',
97
-        'h5',
98
-        'h6',
99
-        'hr',
100
-        'i',
101
-        'img',
102
-        'li',
103
-        'ol',
104
-        'p',
105
-        'pre',
106
-        'small',
107
-        'span',
108
-        'strong',
109
-        'table',
110
-        'td',
111
-        'tr',
112
-        'ul',
113
-    ];
114
-
115
-
116
-    /**
117
-     * @var array
118
-     */
119
-    private static $allowed_tags;
120
-
121
-
122
-    /**
123
-     * @var array
124
-     */
125
-    private static $allowed_with_embed_tags;
126
-
127
-
128
-    /**
129
-     * @var array
130
-     */
131
-    private static $allowed_with_form_tags;
132
-
133
-
134
-    /**
135
-     * @var array
136
-     */
137
-    private static $allowed_with_script_and_style_tags;
138
-
139
-    /**
140
-     * @var array
141
-     */
142
-    private static $allowed_with_full_tags;
143
-
144
-
145
-    /**
146
-     * merges additional tags and attributes into the WP post tags
147
-     */
148
-    private static function initializeAllowedTags()
149
-    {
150
-        $allowed_post_tags = wp_kses_allowed_html('post');
151
-        $allowed_tags = [];
152
-        foreach (AllowedTags::$tags as $tag) {
153
-            $allowed_tags[ $tag ] = AllowedTags::$attributes;
154
-        }
155
-        AllowedTags::$allowed_tags = array_merge_recursive($allowed_post_tags, $allowed_tags);
156
-    }
157
-
158
-
159
-    /**
160
-     * merges embed tags and attributes into the EE all tags
161
-     */
162
-    private static function initializeWithEmbedTags()
163
-    {
164
-        $all_tags = AllowedTags::getAllowedTags();
165
-        $embed_tags = [
166
-            'iframe' => AllowedTags::$attributes
167
-        ];
168
-        AllowedTags::$allowed_with_embed_tags = array_merge_recursive($all_tags, $embed_tags);
169
-    }
170
-
171
-
172
-    /**
173
-     * merges form tags and attributes into the EE all tags
174
-     */
175
-    private static function initializeWithFormTags()
176
-    {
177
-        $all_tags = AllowedTags::getAllowedTags();
178
-        $form_tags = [
179
-            'form'     => AllowedTags::$attributes,
180
-            'label'    => AllowedTags::$attributes,
181
-            'input'    => AllowedTags::$attributes,
182
-            'select'   => AllowedTags::$attributes,
183
-            'option'   => AllowedTags::$attributes,
184
-            'optgroup' => AllowedTags::$attributes,
185
-            'textarea' => AllowedTags::$attributes,
186
-            'button'   => AllowedTags::$attributes,
187
-            'fieldset' => AllowedTags::$attributes,
188
-            'output'   => AllowedTags::$attributes,
189
-        ];
190
-        AllowedTags::$allowed_with_form_tags = array_merge_recursive($all_tags, $form_tags);
191
-    }
192
-
193
-
194
-    /**
195
-     * merges form script and style tags and attributes into the EE all tags
196
-     */
197
-    private static function initializeWithScriptAndStyleTags()
198
-    {
199
-        $all_tags = AllowedTags::getAllowedTags();
200
-        $script_and_style_tags = [
201
-            'script' => AllowedTags::$attributes,
202
-            'style'  => AllowedTags::$attributes,
203
-            'link'   => AllowedTags::$attributes,
204
-        ];
205
-        AllowedTags::$allowed_with_script_and_style_tags = array_merge_recursive($all_tags, $script_and_style_tags);
206
-    }
207
-
208
-    /**
209
-     * merges all head and body tags and attributes into the EE all tags
210
-     */
211
-    private static function initializeWithFullTags()
212
-    {
213
-        $all_tags = AllowedTags::getAllowedTags();
214
-        $full_tags = [
215
-            'script'    => AllowedTags::$attributes,
216
-            'style'     => AllowedTags::$attributes,
217
-            'link'      => AllowedTags::$attributes,
218
-            'title'     => AllowedTags::$attributes,
219
-            'meta'      => AllowedTags::$attributes,
220
-            'iframe'    => AllowedTags::$attributes,
221
-            'form'      => AllowedTags::$attributes,
222
-            'label'     => AllowedTags::$attributes,
223
-            'input'     => AllowedTags::$attributes,
224
-            'select'    => AllowedTags::$attributes,
225
-            'option'    => AllowedTags::$attributes,
226
-            'optgroup'  => AllowedTags::$attributes,
227
-            'textarea'  => AllowedTags::$attributes,
228
-            'button'    => AllowedTags::$attributes,
229
-            'fieldset'  => AllowedTags::$attributes,
230
-            'output'    => AllowedTags::$attributes,
231
-        ];
232
-        AllowedTags::$allowed_with_full_tags = array_merge_recursive($all_tags, $full_tags);
233
-    }
234
-
235
-
236
-    /**
237
-     * @return array[]
238
-     */
239
-    public static function getAllowedTags()
240
-    {
241
-        if (empty(AllowedTags::$allowed_tags)) {
242
-            AllowedTags::initializeAllowedTags();
243
-        }
244
-        return AllowedTags::$allowed_tags;
245
-    }
246
-
247
-
248
-    /**
249
-     * @return array[]
250
-     */
251
-    public static function getWithEmbedTags()
252
-    {
253
-        if (empty(AllowedTags::$allowed_with_embed_tags)) {
254
-            AllowedTags::initializeWithEmbedTags();
255
-        }
256
-        return AllowedTags::$allowed_with_embed_tags;
257
-    }
258
-
259
-
260
-    /**
261
-     * @return array[]
262
-     */
263
-    public static function getWithFormTags()
264
-    {
265
-        if (empty(AllowedTags::$allowed_with_form_tags)) {
266
-            AllowedTags::initializeWithFormTags();
267
-        }
268
-        return AllowedTags::$allowed_with_form_tags;
269
-    }
270
-
271
-
272
-    /**
273
-     * @return array[]
274
-     */
275
-    public static function getWithScriptAndStyleTags()
276
-    {
277
-        if (empty(AllowedTags::$allowed_with_script_and_style_tags)) {
278
-            AllowedTags::initializeWithScriptAndStyleTags();
279
-        }
280
-        return AllowedTags::$allowed_with_script_and_style_tags;
281
-    }
282
-
283
-    /**
284
-     * @return array[]
285
-     */
286
-    public static function getWithFullTags()
287
-    {
288
-        if (empty(AllowedTags::$allowed_with_full_tags)) {
289
-            AllowedTags::initializeWithFullTags();
290
-        }
291
-        return AllowedTags::$allowed_with_full_tags;
292
-    }
16
+	/**
17
+	 * @var array[]
18
+	 */
19
+	private static $attributes = [
20
+		'accept-charset'    => 1,
21
+		'action'            => 1,
22
+		'alt'               => 1,
23
+		'allow'             => 1,
24
+		'allowfullscreen'   => 1,
25
+		'align'             => 1,
26
+		'aria-*'            => 1,
27
+		'autocomplete'      => 1,
28
+		'checked'           => 1,
29
+		'class'             => 1,
30
+		'cols'              => 1,
31
+		'content'           => 1,
32
+		'data-*'            => 1,
33
+		'dir'               => 1,
34
+		'disabled'          => 1,
35
+		'enctype'           => 1,
36
+		'for'               => 1,
37
+		'frameborder'       => 1,
38
+		'height'            => 1,
39
+		'href'              => 1,
40
+		'id'                => 1,
41
+		'itemprop'          => 1,
42
+		'itemscope'         => 1,
43
+		'itemtype'          => 1,
44
+		'label'             => 1,
45
+		'lang'              => 1,
46
+		'max'               => 1,
47
+		'maxlength'         => 1,
48
+		'method'            => 1,
49
+		'min'               => 1,
50
+		'multiple'          => 1,
51
+		'name'              => 1,
52
+		'novalidate'        => 1,
53
+		'placeholder'       => 1,
54
+		'readonly'          => 1,
55
+		'rel'               => 1,
56
+		'required'          => 1,
57
+		'rows'              => 1,
58
+		'selected'          => 1,
59
+		'src'               => 1,
60
+		'size'              => 1,
61
+		'style'             => 1,
62
+		'step'              => 1,
63
+		'tabindex'          => 1,
64
+		'target'            => 1,
65
+		'title'             => 1,
66
+		'type'              => 1,
67
+		'value'             => 1,
68
+		'width'             => 1,
69
+		'topmargin'         => 1,
70
+		'leftmargin'        => 1,
71
+		'marginheight'      => 1,
72
+		'marginwidth'       => 1,
73
+		'property'          => 1,
74
+		'bgcolor'           => 1,
75
+		'media'             => 1,
76
+		'cellpadding'       => 1,
77
+		'cellspacing'       => 1,
78
+		'border'            => 1,
79
+	];
80
+
81
+
82
+	/**
83
+	 * @var array
84
+	 */
85
+	private static $tags = [
86
+		'a',
87
+		'abbr',
88
+		'b',
89
+		'br',
90
+		'code',
91
+		'div',
92
+		'em',
93
+		'h1',
94
+		'h2',
95
+		'h3',
96
+		'h4',
97
+		'h5',
98
+		'h6',
99
+		'hr',
100
+		'i',
101
+		'img',
102
+		'li',
103
+		'ol',
104
+		'p',
105
+		'pre',
106
+		'small',
107
+		'span',
108
+		'strong',
109
+		'table',
110
+		'td',
111
+		'tr',
112
+		'ul',
113
+	];
114
+
115
+
116
+	/**
117
+	 * @var array
118
+	 */
119
+	private static $allowed_tags;
120
+
121
+
122
+	/**
123
+	 * @var array
124
+	 */
125
+	private static $allowed_with_embed_tags;
126
+
127
+
128
+	/**
129
+	 * @var array
130
+	 */
131
+	private static $allowed_with_form_tags;
132
+
133
+
134
+	/**
135
+	 * @var array
136
+	 */
137
+	private static $allowed_with_script_and_style_tags;
138
+
139
+	/**
140
+	 * @var array
141
+	 */
142
+	private static $allowed_with_full_tags;
143
+
144
+
145
+	/**
146
+	 * merges additional tags and attributes into the WP post tags
147
+	 */
148
+	private static function initializeAllowedTags()
149
+	{
150
+		$allowed_post_tags = wp_kses_allowed_html('post');
151
+		$allowed_tags = [];
152
+		foreach (AllowedTags::$tags as $tag) {
153
+			$allowed_tags[ $tag ] = AllowedTags::$attributes;
154
+		}
155
+		AllowedTags::$allowed_tags = array_merge_recursive($allowed_post_tags, $allowed_tags);
156
+	}
157
+
158
+
159
+	/**
160
+	 * merges embed tags and attributes into the EE all tags
161
+	 */
162
+	private static function initializeWithEmbedTags()
163
+	{
164
+		$all_tags = AllowedTags::getAllowedTags();
165
+		$embed_tags = [
166
+			'iframe' => AllowedTags::$attributes
167
+		];
168
+		AllowedTags::$allowed_with_embed_tags = array_merge_recursive($all_tags, $embed_tags);
169
+	}
170
+
171
+
172
+	/**
173
+	 * merges form tags and attributes into the EE all tags
174
+	 */
175
+	private static function initializeWithFormTags()
176
+	{
177
+		$all_tags = AllowedTags::getAllowedTags();
178
+		$form_tags = [
179
+			'form'     => AllowedTags::$attributes,
180
+			'label'    => AllowedTags::$attributes,
181
+			'input'    => AllowedTags::$attributes,
182
+			'select'   => AllowedTags::$attributes,
183
+			'option'   => AllowedTags::$attributes,
184
+			'optgroup' => AllowedTags::$attributes,
185
+			'textarea' => AllowedTags::$attributes,
186
+			'button'   => AllowedTags::$attributes,
187
+			'fieldset' => AllowedTags::$attributes,
188
+			'output'   => AllowedTags::$attributes,
189
+		];
190
+		AllowedTags::$allowed_with_form_tags = array_merge_recursive($all_tags, $form_tags);
191
+	}
192
+
193
+
194
+	/**
195
+	 * merges form script and style tags and attributes into the EE all tags
196
+	 */
197
+	private static function initializeWithScriptAndStyleTags()
198
+	{
199
+		$all_tags = AllowedTags::getAllowedTags();
200
+		$script_and_style_tags = [
201
+			'script' => AllowedTags::$attributes,
202
+			'style'  => AllowedTags::$attributes,
203
+			'link'   => AllowedTags::$attributes,
204
+		];
205
+		AllowedTags::$allowed_with_script_and_style_tags = array_merge_recursive($all_tags, $script_and_style_tags);
206
+	}
207
+
208
+	/**
209
+	 * merges all head and body tags and attributes into the EE all tags
210
+	 */
211
+	private static function initializeWithFullTags()
212
+	{
213
+		$all_tags = AllowedTags::getAllowedTags();
214
+		$full_tags = [
215
+			'script'    => AllowedTags::$attributes,
216
+			'style'     => AllowedTags::$attributes,
217
+			'link'      => AllowedTags::$attributes,
218
+			'title'     => AllowedTags::$attributes,
219
+			'meta'      => AllowedTags::$attributes,
220
+			'iframe'    => AllowedTags::$attributes,
221
+			'form'      => AllowedTags::$attributes,
222
+			'label'     => AllowedTags::$attributes,
223
+			'input'     => AllowedTags::$attributes,
224
+			'select'    => AllowedTags::$attributes,
225
+			'option'    => AllowedTags::$attributes,
226
+			'optgroup'  => AllowedTags::$attributes,
227
+			'textarea'  => AllowedTags::$attributes,
228
+			'button'    => AllowedTags::$attributes,
229
+			'fieldset'  => AllowedTags::$attributes,
230
+			'output'    => AllowedTags::$attributes,
231
+		];
232
+		AllowedTags::$allowed_with_full_tags = array_merge_recursive($all_tags, $full_tags);
233
+	}
234
+
235
+
236
+	/**
237
+	 * @return array[]
238
+	 */
239
+	public static function getAllowedTags()
240
+	{
241
+		if (empty(AllowedTags::$allowed_tags)) {
242
+			AllowedTags::initializeAllowedTags();
243
+		}
244
+		return AllowedTags::$allowed_tags;
245
+	}
246
+
247
+
248
+	/**
249
+	 * @return array[]
250
+	 */
251
+	public static function getWithEmbedTags()
252
+	{
253
+		if (empty(AllowedTags::$allowed_with_embed_tags)) {
254
+			AllowedTags::initializeWithEmbedTags();
255
+		}
256
+		return AllowedTags::$allowed_with_embed_tags;
257
+	}
258
+
259
+
260
+	/**
261
+	 * @return array[]
262
+	 */
263
+	public static function getWithFormTags()
264
+	{
265
+		if (empty(AllowedTags::$allowed_with_form_tags)) {
266
+			AllowedTags::initializeWithFormTags();
267
+		}
268
+		return AllowedTags::$allowed_with_form_tags;
269
+	}
270
+
271
+
272
+	/**
273
+	 * @return array[]
274
+	 */
275
+	public static function getWithScriptAndStyleTags()
276
+	{
277
+		if (empty(AllowedTags::$allowed_with_script_and_style_tags)) {
278
+			AllowedTags::initializeWithScriptAndStyleTags();
279
+		}
280
+		return AllowedTags::$allowed_with_script_and_style_tags;
281
+	}
282
+
283
+	/**
284
+	 * @return array[]
285
+	 */
286
+	public static function getWithFullTags()
287
+	{
288
+		if (empty(AllowedTags::$allowed_with_full_tags)) {
289
+			AllowedTags::initializeWithFullTags();
290
+		}
291
+		return AllowedTags::$allowed_with_full_tags;
292
+	}
293 293
 }
Please login to merge, or discard this patch.
core/EE_Front_Controller.core.php 1 patch
Indentation   +509 added lines, -509 removed lines patch added patch discarded remove patch
@@ -18,513 +18,513 @@
 block discarded – undo
18 18
 final class EE_Front_Controller
19 19
 {
20 20
 
21
-    /**
22
-     * @var string
23
-     */
24
-    private $_template_path;
25
-
26
-    /**
27
-     * @var string
28
-     */
29
-    private $_template;
30
-
31
-    /**
32
-     * @type EE_Registry
33
-     */
34
-    protected $Registry;
35
-
36
-    /**
37
-     * @type EE_Request_Handler
38
-     */
39
-    protected $Request_Handler;
40
-
41
-    /**
42
-     * @type EE_Module_Request_Router
43
-     */
44
-    protected $Module_Request_Router;
45
-
46
-    /**
47
-     * @type CurrentPage
48
-     */
49
-    protected $current_page;
50
-
51
-
52
-    /**
53
-     *    class constructor
54
-     *    should fire after shortcode, module, addon, or other plugin's default priority init phases have run
55
-     *
56
-     * @access    public
57
-     * @param EE_Registry              $Registry
58
-     * @param CurrentPage              $EspressoPage
59
-     * @param EE_Module_Request_Router $Module_Request_Router
60
-     */
61
-    public function __construct(
62
-        EE_Registry $Registry,
63
-        CurrentPage $EspressoPage,
64
-        EE_Module_Request_Router $Module_Request_Router
65
-    ) {
66
-        $this->Registry              = $Registry;
67
-        $this->current_page          = $EspressoPage;
68
-        $this->Module_Request_Router = $Module_Request_Router;
69
-        // load other resources and begin to actually run shortcodes and modules
70
-        // analyse the incoming WP request
71
-        add_action('parse_request', array($this, 'get_request'), 1, 1);
72
-        // process request with module factory
73
-        add_action('pre_get_posts', array($this, 'pre_get_posts'), 10, 1);
74
-        // before headers sent
75
-        add_action('wp', array($this, 'wp'), 5);
76
-        // primarily used to process any content shortcodes
77
-        add_action('template_redirect', array($this, 'templateRedirect'), 999);
78
-        // header
79
-        add_action('wp_head', array($this, 'header_meta_tag'), 5);
80
-        add_action('wp_print_scripts', array($this, 'wp_print_scripts'), 10);
81
-        add_filter('template_include', array($this, 'template_include'), 1);
82
-        // display errors
83
-        add_action('loop_start', array($this, 'display_errors'), 2);
84
-        // the content
85
-        // add_filter( 'the_content', array( $this, 'the_content' ), 5, 1 );
86
-        // exclude our private cpt comments
87
-        add_filter('comments_clauses', array($this, 'filter_wp_comments'), 10, 1);
88
-        // make sure any ajax requests will respect the url schema when requests are made against admin-ajax.php (http:// or https://)
89
-        add_filter('admin_url', array($this, 'maybe_force_admin_ajax_ssl'), 200, 1);
90
-        // action hook EE
91
-        do_action('AHEE__EE_Front_Controller__construct__done', $this);
92
-    }
93
-
94
-
95
-    /**
96
-     * @return EE_Request_Handler
97
-     * @deprecated 4.10.14.p
98
-     */
99
-    public function Request_Handler()
100
-    {
101
-        if (! $this->Request_Handler instanceof EE_Request_Handler) {
102
-            $this->Request_Handler = LoaderFactory::getLoader()->getShared('EE_Request_Handler');
103
-        }
104
-        return $this->Request_Handler;
105
-    }
106
-
107
-
108
-    /**
109
-     * @return EE_Module_Request_Router
110
-     */
111
-    public function Module_Request_Router()
112
-    {
113
-        return $this->Module_Request_Router;
114
-    }
115
-
116
-
117
-    /**
118
-     * @return LegacyShortcodesManager
119
-     * @deprecated 4.10.14.p
120
-     */
121
-    public function getLegacyShortcodesManager()
122
-    {
123
-        return EE_Config::getLegacyShortcodesManager();
124
-    }
125
-
126
-
127
-
128
-
129
-
130
-    /***********************************************        INIT ACTION HOOK         ***********************************************/
131
-    /**
132
-     * filter_wp_comments
133
-     * This simply makes sure that any "private" EE CPTs do not have their comments show up in any wp comment
134
-     * widgets/queries done on frontend
135
-     *
136
-     * @param  array $clauses array of comment clauses setup by WP_Comment_Query
137
-     * @return array array of comment clauses with modifications.
138
-     * @throws InvalidArgumentException
139
-     * @throws InvalidDataTypeException
140
-     * @throws InvalidInterfaceException
141
-     */
142
-    public function filter_wp_comments($clauses)
143
-    {
144
-        global $wpdb;
145
-        if (strpos($clauses['join'], $wpdb->posts) !== false) {
146
-            /** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
147
-            $custom_post_types = LoaderFactory::getLoader()->getShared(
148
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
149
-            );
150
-            $cpts = $custom_post_types->getPrivateCustomPostTypes();
151
-            foreach ($cpts as $cpt => $details) {
152
-                $clauses['where'] .= $wpdb->prepare(" AND $wpdb->posts.post_type != %s", $cpt);
153
-            }
154
-        }
155
-        return $clauses;
156
-    }
157
-
158
-
159
-    /**
160
-     * this just makes sure that if the site is using ssl that we force that for any admin ajax calls from frontend
161
-     *
162
-     * @param  string $url incoming url
163
-     * @return string         final assembled url
164
-     */
165
-    public function maybe_force_admin_ajax_ssl($url)
166
-    {
167
-        if (is_ssl() && preg_match('/admin-ajax.php/', $url)) {
168
-            $url = str_replace('http://', 'https://', $url);
169
-        }
170
-        return $url;
171
-    }
172
-
173
-
174
-
175
-
176
-
177
-
178
-    /***********************************************        WP_LOADED ACTION HOOK         ***********************************************/
179
-
180
-
181
-    /**
182
-     *    wp_loaded - should fire after shortcode, module, addon, or other plugin's have been registered and their
183
-     *    default priority init phases have run
184
-     *
185
-     * @access    public
186
-     * @return    void
187
-     */
188
-    public function wp_loaded()
189
-    {
190
-    }
191
-
192
-
193
-
194
-
195
-
196
-    /***********************************************        PARSE_REQUEST HOOK         ***********************************************/
197
-    /**
198
-     *    _get_request
199
-     *
200
-     * @access public
201
-     * @param WP $WP
202
-     * @return void
203
-     */
204
-    public function get_request(WP $WP)
205
-    {
206
-        do_action('AHEE__EE_Front_Controller__get_request__start');
207
-        $this->current_page->parseQueryVars($WP);
208
-        do_action('AHEE__EE_Front_Controller__get_request__complete');
209
-        remove_action('parse_request', [$this, 'get_request'], 1);
210
-    }
211
-
212
-
213
-    /**
214
-     *    pre_get_posts - basically a module factory for instantiating modules and selecting the final view template
215
-     *
216
-     * @access    public
217
-     * @param WP_Query $WP_Query
218
-     * @return    void
219
-     * @throws EE_Error
220
-     * @throws ReflectionException
221
-     */
222
-    public function pre_get_posts($WP_Query)
223
-    {
224
-        // only load Module_Request_Router if this is the main query
225
-        if (
226
-            $this->Module_Request_Router instanceof EE_Module_Request_Router
227
-            && $WP_Query->is_main_query()
228
-        ) {
229
-            // cycle thru module routes
230
-            while ($route = $this->Module_Request_Router->get_route($WP_Query)) {
231
-                // determine module and method for route
232
-                $module = $this->Module_Request_Router->resolve_route($route[0], $route[1]);
233
-                if ($module instanceof EED_Module) {
234
-                    // get registered view for route
235
-                    $this->_template_path = $this->Module_Request_Router->get_view($route);
236
-                    // grab module name
237
-                    $module_name = $module->module_name();
238
-                    // map the module to the module objects
239
-                    $this->Registry->modules->{$module_name} = $module;
240
-                }
241
-            }
242
-        }
243
-    }
244
-
245
-
246
-
247
-
248
-
249
-    /***********************************************        WP HOOK         ***********************************************/
250
-
251
-
252
-    /**
253
-     *    wp - basically last chance to do stuff before headers sent
254
-     *
255
-     * @access    public
256
-     * @return    void
257
-     */
258
-    public function wp()
259
-    {
260
-    }
261
-
262
-
263
-
264
-    /***********************     GET_HEADER && WP_HEAD HOOK     ***********************/
265
-
266
-
267
-    /**
268
-     * callback for the "template_redirect" hook point
269
-     * checks sidebars for EE widgets
270
-     * loads resources and assets accordingly
271
-     *
272
-     * @return void
273
-     */
274
-    public function templateRedirect()
275
-    {
276
-        global $wp_query;
277
-        if (empty($wp_query->posts)) {
278
-            return;
279
-        }
280
-        // if we already know this is an espresso page, then load assets
281
-        $load_assets = $this->current_page->isEspressoPage();
282
-        // if we are already loading assets then just move along, otherwise check for widgets
283
-        $load_assets = $load_assets || $this->espresso_widgets_in_active_sidebars();
284
-        if ($load_assets) {
285
-            add_action('wp_enqueue_scripts', array($this, 'enqueueStyle'), 10);
286
-            add_action('wp_print_footer_scripts', array($this, 'enqueueScripts'), 10);
287
-        }
288
-    }
289
-
290
-
291
-    /**
292
-     * builds list of active widgets then scans active sidebars looking for them
293
-     * returns true is an EE widget is found in an active sidebar
294
-     * Please Note: this does NOT mean that the sidebar or widget
295
-     * is actually in use in a given template, as that is unfortunately not known
296
-     * until a sidebar and it's widgets are actually loaded
297
-     *
298
-     * @return boolean
299
-     */
300
-    private function espresso_widgets_in_active_sidebars()
301
-    {
302
-        $espresso_widgets = array();
303
-        foreach ($this->Registry->widgets as $widget_class => $widget) {
304
-            $id_base = EspressoWidget::getIdBase($widget_class);
305
-            if (is_active_widget(false, false, $id_base)) {
306
-                $espresso_widgets[] = $id_base;
307
-            }
308
-        }
309
-        $all_sidebar_widgets = wp_get_sidebars_widgets();
310
-        foreach ($all_sidebar_widgets as $sidebar_widgets) {
311
-            if (is_array($sidebar_widgets) && ! empty($sidebar_widgets)) {
312
-                foreach ($sidebar_widgets as $sidebar_widget) {
313
-                    foreach ($espresso_widgets as $espresso_widget) {
314
-                        if (strpos($sidebar_widget, $espresso_widget) !== false) {
315
-                            return true;
316
-                        }
317
-                    }
318
-                }
319
-            }
320
-        }
321
-        return false;
322
-    }
323
-
324
-
325
-    /**
326
-     *    header_meta_tag
327
-     *
328
-     * @access    public
329
-     * @return    void
330
-     */
331
-    public function header_meta_tag()
332
-    {
333
-        print(
334
-        apply_filters(
335
-            'FHEE__EE_Front_Controller__header_meta_tag',
336
-            '<meta name="generator" content="Event Espresso Version ' . EVENT_ESPRESSO_VERSION . "\" />\n"
337
-        )
338
-        );
339
-
340
-        // let's exclude all event type taxonomy term archive pages from search engine indexing
341
-        // @see https://events.codebasehq.com/projects/event-espresso/tickets/10249
342
-        // also exclude all critical pages from indexing
343
-        if (
344
-            (
345
-                is_tax('espresso_event_type')
346
-                && get_option('blog_public') !== '0'
347
-            )
348
-            || is_page(EE_Registry::instance()->CFG->core->get_critical_pages_array())
349
-        ) {
350
-            print(
351
-            apply_filters(
352
-                'FHEE__EE_Front_Controller__header_meta_tag__noindex_for_event_type',
353
-                '<meta name="robots" content="noindex,follow" />' . "\n"
354
-            )
355
-            );
356
-        }
357
-    }
358
-
359
-
360
-    /**
361
-     * wp_print_scripts
362
-     *
363
-     * @return void
364
-     * @throws EE_Error
365
-     */
366
-    public function wp_print_scripts()
367
-    {
368
-        global $post;
369
-        if (
370
-            isset($post->EE_Event)
371
-            && $post->EE_Event instanceof EE_Event
372
-            && get_post_type() === 'espresso_events'
373
-            && is_singular()
374
-        ) {
375
-            EEH_Schema::add_json_linked_data_for_event($post->EE_Event);
376
-        }
377
-    }
378
-
379
-
380
-    public function enqueueStyle()
381
-    {
382
-        wp_enqueue_style('espresso_default');
383
-        wp_enqueue_style('espresso_custom_css');
384
-    }
385
-
386
-
387
-
388
-    /***********************************************        WP_FOOTER         ***********************************************/
389
-
390
-
391
-    public function enqueueScripts()
392
-    {
393
-        wp_enqueue_script('espresso_core');
394
-    }
395
-
396
-
397
-    /**
398
-     * display_errors
399
-     *
400
-     * @access public
401
-     * @return void
402
-     * @throws DomainException
403
-     */
404
-    public function display_errors()
405
-    {
406
-        static $shown_already = false;
407
-        do_action('AHEE__EE_Front_Controller__display_errors__begin');
408
-        if (
409
-            ! $shown_already
410
-            && apply_filters('FHEE__EE_Front_Controller__display_errors', true)
411
-            && is_main_query()
412
-            && ! is_feed()
413
-            && in_the_loop()
414
-            && $this->current_page->isEspressoPage()
415
-        ) {
416
-            $shown_already = true;
417
-            if (did_action('wp_head')) {
418
-                echo wp_kses($this->printNotices(), AllowedTags::getAllowedTags());
419
-            } else {
420
-                // block enabled themes run their query loop before headers are sent
421
-                // so we need to add our notices onto the beginning of the content
422
-                add_filter('the_content', [$this, 'prependNotices'], 1, 1);
423
-            }
424
-        }
425
-        do_action('AHEE__EE_Front_Controller__display_errors__end');
426
-    }
427
-
428
-
429
-    /**
430
-     * @param string $the_content
431
-     * @return string
432
-     * @since 4.10.30.p
433
-     */
434
-    public function prependNotices($the_content)
435
-    {
436
-        $notices = $this->printNotices();
437
-        return $notices ? $notices . $the_content : $the_content;
438
-    }
439
-
440
-
441
-    /**
442
-     * @return false|string
443
-     * @since 4.10.30.p
444
-     */
445
-    public function printNotices()
446
-    {
447
-        ob_start();
448
-        echo wp_kses(EE_Error::get_notices(), AllowedTags::getWithFormTags());
449
-        EEH_Template::display_template(EE_TEMPLATES . 'espresso-ajax-notices.template.php');
450
-        return ob_get_clean();
451
-    }
452
-
453
-
454
-
455
-    /***********************************************        UTILITIES         ***********************************************/
456
-
457
-
458
-    /**
459
-     * @param string $template_include_path
460
-     * @return string
461
-     * @throws EE_Error
462
-     * @throws ReflectionException
463
-     */
464
-    public function template_include($template_include_path = null)
465
-    {
466
-        if ($this->current_page->isEspressoPage()) {
467
-            // despite all helpers having autoloaders set, we need to manually load the template loader
468
-            // because there are some side effects in that class for triggering template tag functions
469
-            $this->Registry->load_helper('EEH_Template');
470
-            $this->_template_path = ! empty($this->_template_path)
471
-                ? basename($this->_template_path)
472
-                : basename(
473
-                    $template_include_path
474
-                );
475
-            $template_path = EEH_Template::locate_template($this->_template_path, array(), false);
476
-            $this->_template_path = ! empty($template_path) ? $template_path : $template_include_path;
477
-            $this->_template = basename($this->_template_path);
478
-            return $this->_template_path;
479
-        }
480
-        return $template_include_path;
481
-    }
482
-
483
-
484
-    /**
485
-     * @param bool $with_path
486
-     * @return    string
487
-     */
488
-    public function get_selected_template($with_path = false)
489
-    {
490
-        return $with_path ? $this->_template_path : $this->_template;
491
-    }
492
-
493
-
494
-    /**
495
-     * @param string $shortcode_class
496
-     * @param WP     $wp
497
-     * @throws ReflectionException
498
-     * @deprecated 4.9.26
499
-     */
500
-    public function initialize_shortcode($shortcode_class = '', WP $wp = null)
501
-    {
502
-        EE_Error::doing_it_wrong(
503
-            __METHOD__,
504
-            esc_html__(
505
-                'Usage is deprecated. Please use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::initializeShortcode() instead.',
506
-                'event_espresso'
507
-            ),
508
-            '4.9.26'
509
-        );
510
-        $this->getLegacyShortcodesManager()->initializeShortcode($shortcode_class, $wp);
511
-    }
512
-
513
-
514
-    /**
515
-     * @return void
516
-     * @deprecated 4.9.57.p
517
-     */
518
-    public function loadPersistentAdminNoticeManager()
519
-    {
520
-    }
521
-
522
-
523
-    /**
524
-     * @return void
525
-     * @deprecated 4.9.64.p
526
-     */
527
-    public function employ_CPT_Strategy()
528
-    {
529
-    }
21
+	/**
22
+	 * @var string
23
+	 */
24
+	private $_template_path;
25
+
26
+	/**
27
+	 * @var string
28
+	 */
29
+	private $_template;
30
+
31
+	/**
32
+	 * @type EE_Registry
33
+	 */
34
+	protected $Registry;
35
+
36
+	/**
37
+	 * @type EE_Request_Handler
38
+	 */
39
+	protected $Request_Handler;
40
+
41
+	/**
42
+	 * @type EE_Module_Request_Router
43
+	 */
44
+	protected $Module_Request_Router;
45
+
46
+	/**
47
+	 * @type CurrentPage
48
+	 */
49
+	protected $current_page;
50
+
51
+
52
+	/**
53
+	 *    class constructor
54
+	 *    should fire after shortcode, module, addon, or other plugin's default priority init phases have run
55
+	 *
56
+	 * @access    public
57
+	 * @param EE_Registry              $Registry
58
+	 * @param CurrentPage              $EspressoPage
59
+	 * @param EE_Module_Request_Router $Module_Request_Router
60
+	 */
61
+	public function __construct(
62
+		EE_Registry $Registry,
63
+		CurrentPage $EspressoPage,
64
+		EE_Module_Request_Router $Module_Request_Router
65
+	) {
66
+		$this->Registry              = $Registry;
67
+		$this->current_page          = $EspressoPage;
68
+		$this->Module_Request_Router = $Module_Request_Router;
69
+		// load other resources and begin to actually run shortcodes and modules
70
+		// analyse the incoming WP request
71
+		add_action('parse_request', array($this, 'get_request'), 1, 1);
72
+		// process request with module factory
73
+		add_action('pre_get_posts', array($this, 'pre_get_posts'), 10, 1);
74
+		// before headers sent
75
+		add_action('wp', array($this, 'wp'), 5);
76
+		// primarily used to process any content shortcodes
77
+		add_action('template_redirect', array($this, 'templateRedirect'), 999);
78
+		// header
79
+		add_action('wp_head', array($this, 'header_meta_tag'), 5);
80
+		add_action('wp_print_scripts', array($this, 'wp_print_scripts'), 10);
81
+		add_filter('template_include', array($this, 'template_include'), 1);
82
+		// display errors
83
+		add_action('loop_start', array($this, 'display_errors'), 2);
84
+		// the content
85
+		// add_filter( 'the_content', array( $this, 'the_content' ), 5, 1 );
86
+		// exclude our private cpt comments
87
+		add_filter('comments_clauses', array($this, 'filter_wp_comments'), 10, 1);
88
+		// make sure any ajax requests will respect the url schema when requests are made against admin-ajax.php (http:// or https://)
89
+		add_filter('admin_url', array($this, 'maybe_force_admin_ajax_ssl'), 200, 1);
90
+		// action hook EE
91
+		do_action('AHEE__EE_Front_Controller__construct__done', $this);
92
+	}
93
+
94
+
95
+	/**
96
+	 * @return EE_Request_Handler
97
+	 * @deprecated 4.10.14.p
98
+	 */
99
+	public function Request_Handler()
100
+	{
101
+		if (! $this->Request_Handler instanceof EE_Request_Handler) {
102
+			$this->Request_Handler = LoaderFactory::getLoader()->getShared('EE_Request_Handler');
103
+		}
104
+		return $this->Request_Handler;
105
+	}
106
+
107
+
108
+	/**
109
+	 * @return EE_Module_Request_Router
110
+	 */
111
+	public function Module_Request_Router()
112
+	{
113
+		return $this->Module_Request_Router;
114
+	}
115
+
116
+
117
+	/**
118
+	 * @return LegacyShortcodesManager
119
+	 * @deprecated 4.10.14.p
120
+	 */
121
+	public function getLegacyShortcodesManager()
122
+	{
123
+		return EE_Config::getLegacyShortcodesManager();
124
+	}
125
+
126
+
127
+
128
+
129
+
130
+	/***********************************************        INIT ACTION HOOK         ***********************************************/
131
+	/**
132
+	 * filter_wp_comments
133
+	 * This simply makes sure that any "private" EE CPTs do not have their comments show up in any wp comment
134
+	 * widgets/queries done on frontend
135
+	 *
136
+	 * @param  array $clauses array of comment clauses setup by WP_Comment_Query
137
+	 * @return array array of comment clauses with modifications.
138
+	 * @throws InvalidArgumentException
139
+	 * @throws InvalidDataTypeException
140
+	 * @throws InvalidInterfaceException
141
+	 */
142
+	public function filter_wp_comments($clauses)
143
+	{
144
+		global $wpdb;
145
+		if (strpos($clauses['join'], $wpdb->posts) !== false) {
146
+			/** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
147
+			$custom_post_types = LoaderFactory::getLoader()->getShared(
148
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
149
+			);
150
+			$cpts = $custom_post_types->getPrivateCustomPostTypes();
151
+			foreach ($cpts as $cpt => $details) {
152
+				$clauses['where'] .= $wpdb->prepare(" AND $wpdb->posts.post_type != %s", $cpt);
153
+			}
154
+		}
155
+		return $clauses;
156
+	}
157
+
158
+
159
+	/**
160
+	 * this just makes sure that if the site is using ssl that we force that for any admin ajax calls from frontend
161
+	 *
162
+	 * @param  string $url incoming url
163
+	 * @return string         final assembled url
164
+	 */
165
+	public function maybe_force_admin_ajax_ssl($url)
166
+	{
167
+		if (is_ssl() && preg_match('/admin-ajax.php/', $url)) {
168
+			$url = str_replace('http://', 'https://', $url);
169
+		}
170
+		return $url;
171
+	}
172
+
173
+
174
+
175
+
176
+
177
+
178
+	/***********************************************        WP_LOADED ACTION HOOK         ***********************************************/
179
+
180
+
181
+	/**
182
+	 *    wp_loaded - should fire after shortcode, module, addon, or other plugin's have been registered and their
183
+	 *    default priority init phases have run
184
+	 *
185
+	 * @access    public
186
+	 * @return    void
187
+	 */
188
+	public function wp_loaded()
189
+	{
190
+	}
191
+
192
+
193
+
194
+
195
+
196
+	/***********************************************        PARSE_REQUEST HOOK         ***********************************************/
197
+	/**
198
+	 *    _get_request
199
+	 *
200
+	 * @access public
201
+	 * @param WP $WP
202
+	 * @return void
203
+	 */
204
+	public function get_request(WP $WP)
205
+	{
206
+		do_action('AHEE__EE_Front_Controller__get_request__start');
207
+		$this->current_page->parseQueryVars($WP);
208
+		do_action('AHEE__EE_Front_Controller__get_request__complete');
209
+		remove_action('parse_request', [$this, 'get_request'], 1);
210
+	}
211
+
212
+
213
+	/**
214
+	 *    pre_get_posts - basically a module factory for instantiating modules and selecting the final view template
215
+	 *
216
+	 * @access    public
217
+	 * @param WP_Query $WP_Query
218
+	 * @return    void
219
+	 * @throws EE_Error
220
+	 * @throws ReflectionException
221
+	 */
222
+	public function pre_get_posts($WP_Query)
223
+	{
224
+		// only load Module_Request_Router if this is the main query
225
+		if (
226
+			$this->Module_Request_Router instanceof EE_Module_Request_Router
227
+			&& $WP_Query->is_main_query()
228
+		) {
229
+			// cycle thru module routes
230
+			while ($route = $this->Module_Request_Router->get_route($WP_Query)) {
231
+				// determine module and method for route
232
+				$module = $this->Module_Request_Router->resolve_route($route[0], $route[1]);
233
+				if ($module instanceof EED_Module) {
234
+					// get registered view for route
235
+					$this->_template_path = $this->Module_Request_Router->get_view($route);
236
+					// grab module name
237
+					$module_name = $module->module_name();
238
+					// map the module to the module objects
239
+					$this->Registry->modules->{$module_name} = $module;
240
+				}
241
+			}
242
+		}
243
+	}
244
+
245
+
246
+
247
+
248
+
249
+	/***********************************************        WP HOOK         ***********************************************/
250
+
251
+
252
+	/**
253
+	 *    wp - basically last chance to do stuff before headers sent
254
+	 *
255
+	 * @access    public
256
+	 * @return    void
257
+	 */
258
+	public function wp()
259
+	{
260
+	}
261
+
262
+
263
+
264
+	/***********************     GET_HEADER && WP_HEAD HOOK     ***********************/
265
+
266
+
267
+	/**
268
+	 * callback for the "template_redirect" hook point
269
+	 * checks sidebars for EE widgets
270
+	 * loads resources and assets accordingly
271
+	 *
272
+	 * @return void
273
+	 */
274
+	public function templateRedirect()
275
+	{
276
+		global $wp_query;
277
+		if (empty($wp_query->posts)) {
278
+			return;
279
+		}
280
+		// if we already know this is an espresso page, then load assets
281
+		$load_assets = $this->current_page->isEspressoPage();
282
+		// if we are already loading assets then just move along, otherwise check for widgets
283
+		$load_assets = $load_assets || $this->espresso_widgets_in_active_sidebars();
284
+		if ($load_assets) {
285
+			add_action('wp_enqueue_scripts', array($this, 'enqueueStyle'), 10);
286
+			add_action('wp_print_footer_scripts', array($this, 'enqueueScripts'), 10);
287
+		}
288
+	}
289
+
290
+
291
+	/**
292
+	 * builds list of active widgets then scans active sidebars looking for them
293
+	 * returns true is an EE widget is found in an active sidebar
294
+	 * Please Note: this does NOT mean that the sidebar or widget
295
+	 * is actually in use in a given template, as that is unfortunately not known
296
+	 * until a sidebar and it's widgets are actually loaded
297
+	 *
298
+	 * @return boolean
299
+	 */
300
+	private function espresso_widgets_in_active_sidebars()
301
+	{
302
+		$espresso_widgets = array();
303
+		foreach ($this->Registry->widgets as $widget_class => $widget) {
304
+			$id_base = EspressoWidget::getIdBase($widget_class);
305
+			if (is_active_widget(false, false, $id_base)) {
306
+				$espresso_widgets[] = $id_base;
307
+			}
308
+		}
309
+		$all_sidebar_widgets = wp_get_sidebars_widgets();
310
+		foreach ($all_sidebar_widgets as $sidebar_widgets) {
311
+			if (is_array($sidebar_widgets) && ! empty($sidebar_widgets)) {
312
+				foreach ($sidebar_widgets as $sidebar_widget) {
313
+					foreach ($espresso_widgets as $espresso_widget) {
314
+						if (strpos($sidebar_widget, $espresso_widget) !== false) {
315
+							return true;
316
+						}
317
+					}
318
+				}
319
+			}
320
+		}
321
+		return false;
322
+	}
323
+
324
+
325
+	/**
326
+	 *    header_meta_tag
327
+	 *
328
+	 * @access    public
329
+	 * @return    void
330
+	 */
331
+	public function header_meta_tag()
332
+	{
333
+		print(
334
+		apply_filters(
335
+			'FHEE__EE_Front_Controller__header_meta_tag',
336
+			'<meta name="generator" content="Event Espresso Version ' . EVENT_ESPRESSO_VERSION . "\" />\n"
337
+		)
338
+		);
339
+
340
+		// let's exclude all event type taxonomy term archive pages from search engine indexing
341
+		// @see https://events.codebasehq.com/projects/event-espresso/tickets/10249
342
+		// also exclude all critical pages from indexing
343
+		if (
344
+			(
345
+				is_tax('espresso_event_type')
346
+				&& get_option('blog_public') !== '0'
347
+			)
348
+			|| is_page(EE_Registry::instance()->CFG->core->get_critical_pages_array())
349
+		) {
350
+			print(
351
+			apply_filters(
352
+				'FHEE__EE_Front_Controller__header_meta_tag__noindex_for_event_type',
353
+				'<meta name="robots" content="noindex,follow" />' . "\n"
354
+			)
355
+			);
356
+		}
357
+	}
358
+
359
+
360
+	/**
361
+	 * wp_print_scripts
362
+	 *
363
+	 * @return void
364
+	 * @throws EE_Error
365
+	 */
366
+	public function wp_print_scripts()
367
+	{
368
+		global $post;
369
+		if (
370
+			isset($post->EE_Event)
371
+			&& $post->EE_Event instanceof EE_Event
372
+			&& get_post_type() === 'espresso_events'
373
+			&& is_singular()
374
+		) {
375
+			EEH_Schema::add_json_linked_data_for_event($post->EE_Event);
376
+		}
377
+	}
378
+
379
+
380
+	public function enqueueStyle()
381
+	{
382
+		wp_enqueue_style('espresso_default');
383
+		wp_enqueue_style('espresso_custom_css');
384
+	}
385
+
386
+
387
+
388
+	/***********************************************        WP_FOOTER         ***********************************************/
389
+
390
+
391
+	public function enqueueScripts()
392
+	{
393
+		wp_enqueue_script('espresso_core');
394
+	}
395
+
396
+
397
+	/**
398
+	 * display_errors
399
+	 *
400
+	 * @access public
401
+	 * @return void
402
+	 * @throws DomainException
403
+	 */
404
+	public function display_errors()
405
+	{
406
+		static $shown_already = false;
407
+		do_action('AHEE__EE_Front_Controller__display_errors__begin');
408
+		if (
409
+			! $shown_already
410
+			&& apply_filters('FHEE__EE_Front_Controller__display_errors', true)
411
+			&& is_main_query()
412
+			&& ! is_feed()
413
+			&& in_the_loop()
414
+			&& $this->current_page->isEspressoPage()
415
+		) {
416
+			$shown_already = true;
417
+			if (did_action('wp_head')) {
418
+				echo wp_kses($this->printNotices(), AllowedTags::getAllowedTags());
419
+			} else {
420
+				// block enabled themes run their query loop before headers are sent
421
+				// so we need to add our notices onto the beginning of the content
422
+				add_filter('the_content', [$this, 'prependNotices'], 1, 1);
423
+			}
424
+		}
425
+		do_action('AHEE__EE_Front_Controller__display_errors__end');
426
+	}
427
+
428
+
429
+	/**
430
+	 * @param string $the_content
431
+	 * @return string
432
+	 * @since 4.10.30.p
433
+	 */
434
+	public function prependNotices($the_content)
435
+	{
436
+		$notices = $this->printNotices();
437
+		return $notices ? $notices . $the_content : $the_content;
438
+	}
439
+
440
+
441
+	/**
442
+	 * @return false|string
443
+	 * @since 4.10.30.p
444
+	 */
445
+	public function printNotices()
446
+	{
447
+		ob_start();
448
+		echo wp_kses(EE_Error::get_notices(), AllowedTags::getWithFormTags());
449
+		EEH_Template::display_template(EE_TEMPLATES . 'espresso-ajax-notices.template.php');
450
+		return ob_get_clean();
451
+	}
452
+
453
+
454
+
455
+	/***********************************************        UTILITIES         ***********************************************/
456
+
457
+
458
+	/**
459
+	 * @param string $template_include_path
460
+	 * @return string
461
+	 * @throws EE_Error
462
+	 * @throws ReflectionException
463
+	 */
464
+	public function template_include($template_include_path = null)
465
+	{
466
+		if ($this->current_page->isEspressoPage()) {
467
+			// despite all helpers having autoloaders set, we need to manually load the template loader
468
+			// because there are some side effects in that class for triggering template tag functions
469
+			$this->Registry->load_helper('EEH_Template');
470
+			$this->_template_path = ! empty($this->_template_path)
471
+				? basename($this->_template_path)
472
+				: basename(
473
+					$template_include_path
474
+				);
475
+			$template_path = EEH_Template::locate_template($this->_template_path, array(), false);
476
+			$this->_template_path = ! empty($template_path) ? $template_path : $template_include_path;
477
+			$this->_template = basename($this->_template_path);
478
+			return $this->_template_path;
479
+		}
480
+		return $template_include_path;
481
+	}
482
+
483
+
484
+	/**
485
+	 * @param bool $with_path
486
+	 * @return    string
487
+	 */
488
+	public function get_selected_template($with_path = false)
489
+	{
490
+		return $with_path ? $this->_template_path : $this->_template;
491
+	}
492
+
493
+
494
+	/**
495
+	 * @param string $shortcode_class
496
+	 * @param WP     $wp
497
+	 * @throws ReflectionException
498
+	 * @deprecated 4.9.26
499
+	 */
500
+	public function initialize_shortcode($shortcode_class = '', WP $wp = null)
501
+	{
502
+		EE_Error::doing_it_wrong(
503
+			__METHOD__,
504
+			esc_html__(
505
+				'Usage is deprecated. Please use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::initializeShortcode() instead.',
506
+				'event_espresso'
507
+			),
508
+			'4.9.26'
509
+		);
510
+		$this->getLegacyShortcodesManager()->initializeShortcode($shortcode_class, $wp);
511
+	}
512
+
513
+
514
+	/**
515
+	 * @return void
516
+	 * @deprecated 4.9.57.p
517
+	 */
518
+	public function loadPersistentAdminNoticeManager()
519
+	{
520
+	}
521
+
522
+
523
+	/**
524
+	 * @return void
525
+	 * @deprecated 4.9.64.p
526
+	 */
527
+	public function employ_CPT_Strategy()
528
+	{
529
+	}
530 530
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 1 patch
Indentation   +6470 added lines, -6470 removed lines patch added patch discarded remove patch
@@ -36,6476 +36,6476 @@
 block discarded – undo
36 36
 abstract class EEM_Base extends EE_Base implements ResettableInterface
37 37
 {
38 38
 
39
-    /**
40
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
41
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
42
-     * They almost always WILL NOT, but it's not necessarily a requirement.
43
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
44
-     *
45
-     * @var boolean
46
-     */
47
-    private $_values_already_prepared_by_model_object = 0;
48
-
49
-    /**
50
-     * when $_values_already_prepared_by_model_object equals this, we assume
51
-     * the data is just like form input that needs to have the model fields'
52
-     * prepare_for_set and prepare_for_use_in_db called on it
53
-     */
54
-    const not_prepared_by_model_object = 0;
55
-
56
-    /**
57
-     * when $_values_already_prepared_by_model_object equals this, we
58
-     * assume this value is coming from a model object and doesn't need to have
59
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
60
-     */
61
-    const prepared_by_model_object = 1;
62
-
63
-    /**
64
-     * when $_values_already_prepared_by_model_object equals this, we assume
65
-     * the values are already to be used in the database (ie no processing is done
66
-     * on them by the model's fields)
67
-     */
68
-    const prepared_for_use_in_db = 2;
69
-
70
-
71
-    protected $singular_item = 'Item';
72
-
73
-    protected $plural_item   = 'Items';
74
-
75
-    /**
76
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
77
-     */
78
-    protected $_tables;
79
-
80
-    /**
81
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
82
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
83
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
84
-     *
85
-     * @var \EE_Model_Field_Base[][] $_fields
86
-     */
87
-    protected $_fields;
88
-
89
-    /**
90
-     * array of different kinds of relations
91
-     *
92
-     * @var \EE_Model_Relation_Base[] $_model_relations
93
-     */
94
-    protected $_model_relations;
95
-
96
-    /**
97
-     * @var \EE_Index[] $_indexes
98
-     */
99
-    protected $_indexes = array();
100
-
101
-    /**
102
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
103
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
104
-     * by setting the same columns as used in these queries in the query yourself.
105
-     *
106
-     * @var EE_Default_Where_Conditions
107
-     */
108
-    protected $_default_where_conditions_strategy;
109
-
110
-    /**
111
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
112
-     * This is particularly useful when you want something between 'none' and 'default'
113
-     *
114
-     * @var EE_Default_Where_Conditions
115
-     */
116
-    protected $_minimum_where_conditions_strategy;
117
-
118
-    /**
119
-     * String describing how to find the "owner" of this model's objects.
120
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
121
-     * But when there isn't, this indicates which related model, or transiently-related model,
122
-     * has the foreign key to the wp_users table.
123
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
124
-     * related to events, and events have a foreign key to wp_users.
125
-     * On EEM_Transaction, this would be 'Transaction.Event'
126
-     *
127
-     * @var string
128
-     */
129
-    protected $_model_chain_to_wp_user = '';
130
-
131
-    /**
132
-     * String describing how to find the model with a password controlling access to this model. This property has the
133
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
134
-     * This value is the path of models to follow to arrive at the model with the password field.
135
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
136
-     * model with a password that should affect reading this on the front-end.
137
-     * Eg this is an empty string for the Event model because it has a password.
138
-     * This is null for the Registration model, because its event's password has no bearing on whether
139
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
140
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
141
-     * should hide tickets for datetimes for events that have a password set.
142
-     * @var string |null
143
-     */
144
-    protected $model_chain_to_password = null;
145
-
146
-    /**
147
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
148
-     * don't need it (particularly CPT models)
149
-     *
150
-     * @var bool
151
-     */
152
-    protected $_ignore_where_strategy = false;
153
-
154
-    /**
155
-     * String used in caps relating to this model. Eg, if the caps relating to this
156
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
157
-     *
158
-     * @var string. If null it hasn't been initialized yet. If false then we
159
-     * have indicated capabilities don't apply to this
160
-     */
161
-    protected $_caps_slug = null;
162
-
163
-    /**
164
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
165
-     * and next-level keys are capability names, and each's value is a
166
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
167
-     * they specify which context to use (ie, frontend, backend, edit or delete)
168
-     * and then each capability in the corresponding sub-array that they're missing
169
-     * adds the where conditions onto the query.
170
-     *
171
-     * @var array
172
-     */
173
-    protected $_cap_restrictions = array(
174
-        self::caps_read       => array(),
175
-        self::caps_read_admin => array(),
176
-        self::caps_edit       => array(),
177
-        self::caps_delete     => array(),
178
-    );
179
-
180
-    /**
181
-     * Array defining which cap restriction generators to use to create default
182
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
183
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
184
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
185
-     * automatically set this to false (not just null).
186
-     *
187
-     * @var EE_Restriction_Generator_Base[]
188
-     */
189
-    protected $_cap_restriction_generators = array();
190
-
191
-    /**
192
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
193
-     */
194
-    const caps_read       = 'read';
195
-
196
-    const caps_read_admin = 'read_admin';
197
-
198
-    const caps_edit       = 'edit';
199
-
200
-    const caps_delete     = 'delete';
201
-
202
-    /**
203
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
204
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
205
-     * maps to 'read' because when looking for relevant permissions we're going to use
206
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
207
-     *
208
-     * @var array
209
-     */
210
-    protected $_cap_contexts_to_cap_action_map = array(
211
-        self::caps_read       => 'read',
212
-        self::caps_read_admin => 'read',
213
-        self::caps_edit       => 'edit',
214
-        self::caps_delete     => 'delete',
215
-    );
216
-
217
-    /**
218
-     * Timezone
219
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
220
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
221
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
222
-     * EE_Datetime_Field data type will have access to it.
223
-     *
224
-     * @var string
225
-     */
226
-    protected $_timezone;
227
-
228
-
229
-    /**
230
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
231
-     * multisite.
232
-     *
233
-     * @var int
234
-     */
235
-    protected static $_model_query_blog_id;
236
-
237
-    /**
238
-     * A copy of _fields, except the array keys are the model names pointed to by
239
-     * the field
240
-     *
241
-     * @var EE_Model_Field_Base[]
242
-     */
243
-    private $_cache_foreign_key_to_fields = array();
244
-
245
-    /**
246
-     * Cached list of all the fields on the model, indexed by their name
247
-     *
248
-     * @var EE_Model_Field_Base[]
249
-     */
250
-    private $_cached_fields = null;
251
-
252
-    /**
253
-     * Cached list of all the fields on the model, except those that are
254
-     * marked as only pertinent to the database
255
-     *
256
-     * @var EE_Model_Field_Base[]
257
-     */
258
-    private $_cached_fields_non_db_only = null;
259
-
260
-    /**
261
-     * A cached reference to the primary key for quick lookup
262
-     *
263
-     * @var EE_Model_Field_Base
264
-     */
265
-    private $_primary_key_field = null;
266
-
267
-    /**
268
-     * Flag indicating whether this model has a primary key or not
269
-     *
270
-     * @var boolean
271
-     */
272
-    protected $_has_primary_key_field = null;
273
-
274
-    /**
275
-     * array in the format:  [ FK alias => full PK ]
276
-     * where keys are local column name aliases for foreign keys
277
-     * and values are the fully qualified column name for the primary key they represent
278
-     *  ex:
279
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
280
-     *
281
-     * @var array $foreign_key_aliases
282
-     */
283
-    protected $foreign_key_aliases = [];
284
-
285
-    /**
286
-     * Whether or not this model is based off a table in WP core only (CPTs should set
287
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
288
-     * This should be true for models that deal with data that should exist independent of EE.
289
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
290
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
291
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
292
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
293
-     * @var boolean
294
-     */
295
-    protected $_wp_core_model = false;
296
-
297
-    /**
298
-     * @var bool stores whether this model has a password field or not.
299
-     * null until initialized by hasPasswordField()
300
-     */
301
-    protected $has_password_field;
302
-
303
-    /**
304
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
305
-     */
306
-    protected $password_field;
307
-
308
-    /**
309
-     *    List of valid operators that can be used for querying.
310
-     * The keys are all operators we'll accept, the values are the real SQL
311
-     * operators used
312
-     *
313
-     * @var array
314
-     */
315
-    protected $_valid_operators = array(
316
-        '='           => '=',
317
-        '<='          => '<=',
318
-        '<'           => '<',
319
-        '>='          => '>=',
320
-        '>'           => '>',
321
-        '!='          => '!=',
322
-        'LIKE'        => 'LIKE',
323
-        'like'        => 'LIKE',
324
-        'NOT_LIKE'    => 'NOT LIKE',
325
-        'not_like'    => 'NOT LIKE',
326
-        'NOT LIKE'    => 'NOT LIKE',
327
-        'not like'    => 'NOT LIKE',
328
-        'IN'          => 'IN',
329
-        'in'          => 'IN',
330
-        'NOT_IN'      => 'NOT IN',
331
-        'not_in'      => 'NOT IN',
332
-        'NOT IN'      => 'NOT IN',
333
-        'not in'      => 'NOT IN',
334
-        'between'     => 'BETWEEN',
335
-        'BETWEEN'     => 'BETWEEN',
336
-        'IS_NOT_NULL' => 'IS NOT NULL',
337
-        'is_not_null' => 'IS NOT NULL',
338
-        'IS NOT NULL' => 'IS NOT NULL',
339
-        'is not null' => 'IS NOT NULL',
340
-        'IS_NULL'     => 'IS NULL',
341
-        'is_null'     => 'IS NULL',
342
-        'IS NULL'     => 'IS NULL',
343
-        'is null'     => 'IS NULL',
344
-        'REGEXP'      => 'REGEXP',
345
-        'regexp'      => 'REGEXP',
346
-        'NOT_REGEXP'  => 'NOT REGEXP',
347
-        'not_regexp'  => 'NOT REGEXP',
348
-        'NOT REGEXP'  => 'NOT REGEXP',
349
-        'not regexp'  => 'NOT REGEXP',
350
-    );
351
-
352
-    /**
353
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
354
-     *
355
-     * @var array
356
-     */
357
-    protected $_in_style_operators = array('IN', 'NOT IN');
358
-
359
-    /**
360
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
361
-     * '12-31-2012'"
362
-     *
363
-     * @var array
364
-     */
365
-    protected $_between_style_operators = array('BETWEEN');
366
-
367
-    /**
368
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
369
-     * @var array
370
-     */
371
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
372
-    /**
373
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
374
-     * on a join table.
375
-     *
376
-     * @var array
377
-     */
378
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
379
-
380
-    /**
381
-     * Allowed values for $query_params['order'] for ordering in queries
382
-     *
383
-     * @var array
384
-     */
385
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
386
-
387
-    /**
388
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
389
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
390
-     *
391
-     * @var array
392
-     */
393
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
394
-
395
-    /**
396
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
397
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
398
-     *
399
-     * @var array
400
-     */
401
-    private $_allowed_query_params = array(
402
-        0,
403
-        'limit',
404
-        'order_by',
405
-        'group_by',
406
-        'having',
407
-        'force_join',
408
-        'order',
409
-        'on_join_limit',
410
-        'default_where_conditions',
411
-        'caps',
412
-        'extra_selects',
413
-        'exclude_protected',
414
-    );
415
-
416
-    /**
417
-     * All the data types that can be used in $wpdb->prepare statements.
418
-     *
419
-     * @var array
420
-     */
421
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
422
-
423
-    /**
424
-     * @var EE_Registry $EE
425
-     */
426
-    protected $EE = null;
427
-
428
-
429
-    /**
430
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
431
-     *
432
-     * @var int
433
-     */
434
-    protected $_show_next_x_db_queries = 0;
435
-
436
-    /**
437
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
438
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
439
-     * WHERE, GROUP_BY, etc.
440
-     *
441
-     * @var CustomSelects
442
-     */
443
-    protected $_custom_selections = array();
444
-
445
-    /**
446
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
447
-     * caches every model object we've fetched from the DB on this request
448
-     *
449
-     * @var array
450
-     */
451
-    protected $_entity_map;
452
-
453
-    /**
454
-     * @var LoaderInterface $loader
455
-     */
456
-    protected static $loader;
457
-
458
-
459
-    /**
460
-     * constant used to show EEM_Base has not yet verified the db on this http request
461
-     */
462
-    const db_verified_none = 0;
463
-
464
-    /**
465
-     * constant used to show EEM_Base has verified the EE core db on this http request,
466
-     * but not the addons' dbs
467
-     */
468
-    const db_verified_core = 1;
469
-
470
-    /**
471
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
472
-     * the EE core db too)
473
-     */
474
-    const db_verified_addons = 2;
475
-
476
-    /**
477
-     * indicates whether an EEM_Base child has already re-verified the DB
478
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
479
-     * looking like EEM_Base::db_verified_*
480
-     *
481
-     * @var int - 0 = none, 1 = core, 2 = addons
482
-     */
483
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
484
-
485
-    /**
486
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
487
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
488
-     *        registrations for non-trashed tickets for non-trashed datetimes)
489
-     */
490
-    const default_where_conditions_all = 'all';
491
-
492
-    /**
493
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
494
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
495
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
496
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
497
-     *        models which share tables with other models, this can return data for the wrong model.
498
-     */
499
-    const default_where_conditions_this_only = 'this_model_only';
500
-
501
-    /**
502
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
503
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
504
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
505
-     */
506
-    const default_where_conditions_others_only = 'other_models_only';
507
-
508
-    /**
509
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
510
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
511
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
512
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
513
-     *        (regardless of whether those events and venues are trashed)
514
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
515
-     *        events.
516
-     */
517
-    const default_where_conditions_minimum_all = 'minimum';
518
-
519
-    /**
520
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
521
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
522
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
523
-     *        not)
524
-     */
525
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
526
-
527
-    /**
528
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
529
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
530
-     *        it's possible it will return table entries for other models. You should use
531
-     *        EEM_Base::default_where_conditions_minimum_all instead.
532
-     */
533
-    const default_where_conditions_none = 'none';
534
-
535
-
536
-
537
-    /**
538
-     * About all child constructors:
539
-     * they should define the _tables, _fields and _model_relations arrays.
540
-     * Should ALWAYS be called after child constructor.
541
-     * In order to make the child constructors to be as simple as possible, this parent constructor
542
-     * finalizes constructing all the object's attributes.
543
-     * Generally, rather than requiring a child to code
544
-     * $this->_tables = array(
545
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
546
-     *        ...);
547
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
548
-     * each EE_Table has a function to set the table's alias after the constructor, using
549
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
550
-     * do something similar.
551
-     *
552
-     * @param null $timezone
553
-     * @throws EE_Error
554
-     */
555
-    protected function __construct($timezone = null)
556
-    {
557
-        // check that the model has not been loaded too soon
558
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
559
-            throw new EE_Error(
560
-                sprintf(
561
-                    esc_html__(
562
-                        '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.',
563
-                        'event_espresso'
564
-                    ),
565
-                    get_class($this)
566
-                )
567
-            );
568
-        }
569
-        /**
570
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
571
-         */
572
-        if (empty(EEM_Base::$_model_query_blog_id)) {
573
-            EEM_Base::set_model_query_blog_id();
574
-        }
575
-        /**
576
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
577
-         * just use EE_Register_Model_Extension
578
-         *
579
-         * @var EE_Table_Base[] $_tables
580
-         */
581
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
582
-        foreach ($this->_tables as $table_alias => $table_obj) {
583
-            /** @var $table_obj EE_Table_Base */
584
-            $table_obj->_construct_finalize_with_alias($table_alias);
585
-            if ($table_obj instanceof EE_Secondary_Table) {
586
-                /** @var $table_obj EE_Secondary_Table */
587
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
588
-            }
589
-        }
590
-        /**
591
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
592
-         * EE_Register_Model_Extension
593
-         *
594
-         * @param EE_Model_Field_Base[] $_fields
595
-         */
596
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
597
-        $this->_invalidate_field_caches();
598
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
599
-            if (! array_key_exists($table_alias, $this->_tables)) {
600
-                throw new EE_Error(sprintf(esc_html__(
601
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
602
-                    'event_espresso'
603
-                ), $table_alias, implode(",", $this->_fields)));
604
-            }
605
-            foreach ($fields_for_table as $field_name => $field_obj) {
606
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
607
-                // primary key field base has a slightly different _construct_finalize
608
-                /** @var $field_obj EE_Model_Field_Base */
609
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
610
-            }
611
-        }
612
-        // everything is related to Extra_Meta
613
-        if (get_class($this) !== 'EEM_Extra_Meta') {
614
-            // make extra meta related to everything, but don't block deleting things just
615
-            // because they have related extra meta info. For now just orphan those extra meta
616
-            // in the future we should automatically delete them
617
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
618
-        }
619
-        // and change logs
620
-        if (get_class($this) !== 'EEM_Change_Log') {
621
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
622
-        }
623
-        /**
624
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
625
-         * EE_Register_Model_Extension
626
-         *
627
-         * @param EE_Model_Relation_Base[] $_model_relations
628
-         */
629
-        $this->_model_relations = (array) apply_filters(
630
-            'FHEE__' . get_class($this) . '__construct__model_relations',
631
-            $this->_model_relations
632
-        );
633
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
634
-            /** @var $relation_obj EE_Model_Relation_Base */
635
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
636
-        }
637
-        foreach ($this->_indexes as $index_name => $index_obj) {
638
-            /** @var $index_obj EE_Index */
639
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
640
-        }
641
-        $this->set_timezone($timezone);
642
-        // finalize default where condition strategy, or set default
643
-        if (! $this->_default_where_conditions_strategy) {
644
-            // nothing was set during child constructor, so set default
645
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
646
-        }
647
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
648
-        if (! $this->_minimum_where_conditions_strategy) {
649
-            // nothing was set during child constructor, so set default
650
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
651
-        }
652
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
653
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
654
-        // to indicate to NOT set it, set it to the logical default
655
-        if ($this->_caps_slug === null) {
656
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
657
-        }
658
-        // initialize the standard cap restriction generators if none were specified by the child constructor
659
-        if ($this->_cap_restriction_generators !== false) {
660
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
661
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
662
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
663
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
664
-                        new EE_Restriction_Generator_Protected(),
665
-                        $cap_context,
666
-                        $this
667
-                    );
668
-                }
669
-            }
670
-        }
671
-        // if there are cap restriction generators, use them to make the default cap restrictions
672
-        if ($this->_cap_restriction_generators !== false) {
673
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
674
-                if (! $generator_object) {
675
-                    continue;
676
-                }
677
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
678
-                    throw new EE_Error(
679
-                        sprintf(
680
-                            esc_html__(
681
-                                '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.',
682
-                                'event_espresso'
683
-                            ),
684
-                            $context,
685
-                            $this->get_this_model_name()
686
-                        )
687
-                    );
688
-                }
689
-                $action = $this->cap_action_for_context($context);
690
-                if (! $generator_object->construction_finalized()) {
691
-                    $generator_object->_construct_finalize($this, $action);
692
-                }
693
-            }
694
-        }
695
-        do_action('AHEE__' . get_class($this) . '__construct__end');
696
-    }
697
-
698
-
699
-
700
-    /**
701
-     * Used to set the $_model_query_blog_id static property.
702
-     *
703
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
704
-     *                      value for get_current_blog_id() will be used.
705
-     */
706
-    public static function set_model_query_blog_id($blog_id = 0)
707
-    {
708
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
709
-    }
710
-
711
-
712
-
713
-    /**
714
-     * Returns whatever is set as the internal $model_query_blog_id.
715
-     *
716
-     * @return int
717
-     */
718
-    public static function get_model_query_blog_id()
719
-    {
720
-        return EEM_Base::$_model_query_blog_id;
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * This function is a singleton method used to instantiate the Espresso_model object
727
-     *
728
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
729
-     *                                (and any incoming timezone data that gets saved).
730
-     *                                Note this just sends the timezone info to the date time model field objects.
731
-     *                                Default is NULL
732
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
733
-     * @return static (as in the concrete child class)
734
-     * @throws EE_Error
735
-     * @throws InvalidArgumentException
736
-     * @throws InvalidDataTypeException
737
-     * @throws InvalidInterfaceException
738
-     */
739
-    public static function instance($timezone = null)
740
-    {
741
-        // check if instance of Espresso_model already exists
742
-        if (! static::$_instance instanceof static) {
743
-            // instantiate Espresso_model
744
-            static::$_instance = new static(
745
-                $timezone,
746
-                EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
747
-            );
748
-        }
749
-        // we might have a timezone set, let set_timezone decide what to do with it
750
-        static::$_instance->set_timezone($timezone);
751
-        // Espresso_model object
752
-        return static::$_instance;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * resets the model and returns it
759
-     *
760
-     * @param null | string $timezone
761
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
762
-     * all its properties reset; if it wasn't instantiated, returns null)
763
-     * @throws EE_Error
764
-     * @throws ReflectionException
765
-     * @throws InvalidArgumentException
766
-     * @throws InvalidDataTypeException
767
-     * @throws InvalidInterfaceException
768
-     */
769
-    public static function reset($timezone = null)
770
-    {
771
-        if (static::$_instance instanceof EEM_Base) {
772
-            // let's try to NOT swap out the current instance for a new one
773
-            // because if someone has a reference to it, we can't remove their reference
774
-            // so it's best to keep using the same reference, but change the original object
775
-            // reset all its properties to their original values as defined in the class
776
-            $r = new ReflectionClass(get_class(static::$_instance));
777
-            $static_properties = $r->getStaticProperties();
778
-            foreach ($r->getDefaultProperties() as $property => $value) {
779
-                // don't set instance to null like it was originally,
780
-                // but it's static anyways, and we're ignoring static properties (for now at least)
781
-                if (! isset($static_properties[ $property ])) {
782
-                    static::$_instance->{$property} = $value;
783
-                }
784
-            }
785
-            // and then directly call its constructor again, like we would if we were creating a new one
786
-            static::$_instance->__construct(
787
-                $timezone,
788
-                EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
789
-            );
790
-            return self::instance();
791
-        }
792
-        return null;
793
-    }
794
-
795
-
796
-
797
-    /**
798
-     * @return LoaderInterface
799
-     * @throws InvalidArgumentException
800
-     * @throws InvalidDataTypeException
801
-     * @throws InvalidInterfaceException
802
-     */
803
-    private static function getLoader()
804
-    {
805
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
806
-            EEM_Base::$loader = LoaderFactory::getLoader();
807
-        }
808
-        return EEM_Base::$loader;
809
-    }
810
-
811
-
812
-
813
-    /**
814
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
815
-     *
816
-     * @param  boolean $translated return localized strings or JUST the array.
817
-     * @return array
818
-     * @throws EE_Error
819
-     * @throws InvalidArgumentException
820
-     * @throws InvalidDataTypeException
821
-     * @throws InvalidInterfaceException
822
-     */
823
-    public function status_array($translated = false)
824
-    {
825
-        if (! array_key_exists('Status', $this->_model_relations)) {
826
-            return array();
827
-        }
828
-        $model_name = $this->get_this_model_name();
829
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
830
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
831
-        $status_array = array();
832
-        foreach ($stati as $status) {
833
-            $status_array[ $status->ID() ] = $status->get('STS_code');
834
-        }
835
-        return $translated
836
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
837
-            : $status_array;
838
-    }
839
-
840
-
841
-
842
-    /**
843
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
844
-     *
845
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
846
-     *                             or if you have the development copy of EE you can view this at the path:
847
-     *                             /docs/G--Model-System/model-query-params.md
848
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
849
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
-     *                                        array( array(
853
-     *                                        'OR'=>array(
854
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
-     *                                        )
857
-     *                                        ),
858
-     *                                        'limit'=>10,
859
-     *                                        'group_by'=>'TXN_ID'
860
-     *                                        ));
861
-     *                                        get all the answers to the question titled "shirt size" for event with id
862
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
-     *                                        'Question.QST_display_text'=>'shirt size',
864
-     *                                        'Registration.Event.EVT_ID'=>12
865
-     *                                        ),
866
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
867
-     *                                        ));
868
-     * @throws EE_Error
869
-     */
870
-    public function get_all($query_params = array())
871
-    {
872
-        if (
873
-            isset($query_params['limit'])
874
-            && ! isset($query_params['group_by'])
875
-        ) {
876
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
877
-        }
878
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
879
-    }
880
-
881
-
882
-
883
-    /**
884
-     * Modifies the query parameters so we only get back model objects
885
-     * that "belong" to the current user
886
-     *
887
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
889
-     */
890
-    public function alter_query_params_to_only_include_mine($query_params = array())
891
-    {
892
-        $wp_user_field_name = $this->wp_user_field_name();
893
-        if ($wp_user_field_name) {
894
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
895
-        }
896
-        return $query_params;
897
-    }
898
-
899
-
900
-
901
-    /**
902
-     * Returns the name of the field's name that points to the WP_User table
903
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
904
-     * foreign key to the WP_User table)
905
-     *
906
-     * @return string|boolean string on success, boolean false when there is no
907
-     * foreign key to the WP_User table
908
-     */
909
-    public function wp_user_field_name()
910
-    {
911
-        try {
912
-            if (! empty($this->_model_chain_to_wp_user)) {
913
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914
-                $last_model_name = end($models_to_follow_to_wp_users);
915
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
917
-            } else {
918
-                $model_with_fk_to_wp_users = $this;
919
-                $model_chain_to_wp_user = '';
920
-            }
921
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
923
-        } catch (EE_Error $e) {
924
-            return false;
925
-        }
926
-    }
927
-
928
-
929
-
930
-    /**
931
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
932
-     * (or transiently-related model) has a foreign key to the wp_users table;
933
-     * useful for finding if model objects of this type are 'owned' by the current user.
934
-     * This is an empty string when the foreign key is on this model and when it isn't,
935
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
936
-     * (or transiently-related model)
937
-     *
938
-     * @return string
939
-     */
940
-    public function model_chain_to_wp_user()
941
-    {
942
-        return $this->_model_chain_to_wp_user;
943
-    }
944
-
945
-
946
-
947
-    /**
948
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
949
-     * like how registrations don't have a foreign key to wp_users, but the
950
-     * events they are for are), or is unrelated to wp users.
951
-     * generally available
952
-     *
953
-     * @return boolean
954
-     */
955
-    public function is_owned()
956
-    {
957
-        if ($this->model_chain_to_wp_user()) {
958
-            return true;
959
-        }
960
-        try {
961
-            $this->get_foreign_key_to('WP_User');
962
-            return true;
963
-        } catch (EE_Error $e) {
964
-            return false;
965
-        }
966
-    }
967
-
968
-
969
-    /**
970
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
971
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
972
-     * the model)
973
-     *
974
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
975
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
976
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
977
-     *                                  fields on the model, and the models we joined to in the query. However, you can
978
-     *                                  override this and set the select to "*", or a specific column name, like
979
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
980
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
981
-     *                                  the aliases used to refer to this selection, and values are to be
982
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
983
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
984
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
985
-     * @throws EE_Error
986
-     * @throws InvalidArgumentException
987
-     */
988
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
989
-    {
990
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
991
-        ;
992
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
993
-        $select_expressions = $columns_to_select === null
994
-            ? $this->_construct_default_select_sql($model_query_info)
995
-            : '';
996
-        if ($this->_custom_selections instanceof CustomSelects) {
997
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998
-            $select_expressions .= $select_expressions
999
-                ? ', ' . $custom_expressions
1000
-                : $custom_expressions;
1001
-        }
1002
-
1003
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1004
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1010
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1011
-     * method of including extra select information.
1012
-     *
1013
-     * @param array             $query_params
1014
-     * @param null|array|string $columns_to_select
1015
-     * @return null|CustomSelects
1016
-     * @throws InvalidArgumentException
1017
-     */
1018
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019
-    {
1020
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021
-            return null;
1022
-        }
1023
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1024
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1025
-        return new CustomSelects($selects);
1026
-    }
1027
-
1028
-
1029
-
1030
-    /**
1031
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1032
-     * but you can use the model query params to more easily
1033
-     * take care of joins, field preparation etc.
1034
-     *
1035
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1036
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1039
-     *                                  override this and set the select to "*", or a specific column name, like
1040
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
-     *                                  the aliases used to refer to this selection, and values are to be
1043
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
-     * @throws EE_Error
1047
-     */
1048
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
-    {
1050
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
-    }
1052
-
1053
-
1054
-
1055
-    /**
1056
-     * For creating a custom select statement
1057
-     *
1058
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
-     *                                 SQL, and 1=>is the datatype
1061
-     * @throws EE_Error
1062
-     * @return string
1063
-     */
1064
-    private function _construct_select_from_input($columns_to_select)
1065
-    {
1066
-        if (is_array($columns_to_select)) {
1067
-            $select_sql_array = array();
1068
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
-                    throw new EE_Error(
1071
-                        sprintf(
1072
-                            esc_html__(
1073
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
-                                'event_espresso'
1075
-                            ),
1076
-                            $selection_and_datatype,
1077
-                            $alias
1078
-                        )
1079
-                    );
1080
-                }
1081
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082
-                    throw new EE_Error(
1083
-                        sprintf(
1084
-                            esc_html__(
1085
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
-                                'event_espresso'
1087
-                            ),
1088
-                            $selection_and_datatype[1],
1089
-                            $selection_and_datatype[0],
1090
-                            $alias,
1091
-                            implode(', ', $this->_valid_wpdb_data_types)
1092
-                        )
1093
-                    );
1094
-                }
1095
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
-            }
1097
-            $columns_to_select_string = implode(', ', $select_sql_array);
1098
-        } else {
1099
-            $columns_to_select_string = $columns_to_select;
1100
-        }
1101
-        return $columns_to_select_string;
1102
-    }
1103
-
1104
-
1105
-
1106
-    /**
1107
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
-     *
1109
-     * @return string
1110
-     * @throws EE_Error
1111
-     */
1112
-    public function primary_key_name()
1113
-    {
1114
-        return $this->get_primary_key_field()->get_name();
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1120
-     * If there is no primary key on this model, $id is treated as primary key string
1121
-     *
1122
-     * @param mixed $id int or string, depending on the type of the model's primary key
1123
-     * @return EE_Base_Class
1124
-     * @throws EE_Error
1125
-     */
1126
-    public function get_one_by_ID($id)
1127
-    {
1128
-        if ($this->get_from_entity_map($id)) {
1129
-            return $this->get_from_entity_map($id);
1130
-        }
1131
-        $model_object = $this->get_one(
1132
-            $this->alter_query_params_to_restrict_by_ID(
1133
-                $id,
1134
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
-            )
1136
-        );
1137
-        $className = $this->_get_class_name();
1138
-        if ($model_object instanceof $className) {
1139
-            // make sure valid objects get added to the entity map
1140
-            // so that the next call to this method doesn't trigger another trip to the db
1141
-            $this->add_to_entity_map($model_object);
1142
-        }
1143
-        return $model_object;
1144
-    }
1145
-
1146
-
1147
-
1148
-    /**
1149
-     * Alters query parameters to only get items with this ID are returned.
1150
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1151
-     * or could just be a simple primary key ID
1152
-     *
1153
-     * @param int   $id
1154
-     * @param array $query_params
1155
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1156
-     * @throws EE_Error
1157
-     */
1158
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159
-    {
1160
-        if (! isset($query_params[0])) {
1161
-            $query_params[0] = array();
1162
-        }
1163
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1164
-        if ($conditions_from_id === null) {
1165
-            $query_params[0][ $this->primary_key_name() ] = $id;
1166
-        } else {
1167
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1168
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1169
-        }
1170
-        return $query_params;
1171
-    }
1172
-
1173
-
1174
-
1175
-    /**
1176
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1177
-     * array. If no item is found, null is returned.
1178
-     *
1179
-     * @param array $query_params like EEM_Base's $query_params variable.
1180
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1181
-     * @throws EE_Error
1182
-     */
1183
-    public function get_one($query_params = array())
1184
-    {
1185
-        if (! is_array($query_params)) {
1186
-            EE_Error::doing_it_wrong(
1187
-                'EEM_Base::get_one',
1188
-                sprintf(
1189
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1190
-                    gettype($query_params)
1191
-                ),
1192
-                '4.6.0'
1193
-            );
1194
-            $query_params = array();
1195
-        }
1196
-        $query_params['limit'] = 1;
1197
-        $items = $this->get_all($query_params);
1198
-        if (empty($items)) {
1199
-            return null;
1200
-        }
1201
-        return array_shift($items);
1202
-    }
1203
-
1204
-
1205
-
1206
-    /**
1207
-     * Returns the next x number of items in sequence from the given value as
1208
-     * found in the database matching the given query conditions.
1209
-     *
1210
-     * @param mixed $current_field_value    Value used for the reference point.
1211
-     * @param null  $field_to_order_by      What field is used for the
1212
-     *                                      reference point.
1213
-     * @param int   $limit                  How many to return.
1214
-     * @param array $query_params           Extra conditions on the query.
1215
-     * @param null  $columns_to_select      If left null, then an array of
1216
-     *                                      EE_Base_Class objects is returned,
1217
-     *                                      otherwise you can indicate just the
1218
-     *                                      columns you want returned.
1219
-     * @return EE_Base_Class[]|array
1220
-     * @throws EE_Error
1221
-     */
1222
-    public function next_x(
1223
-        $current_field_value,
1224
-        $field_to_order_by = null,
1225
-        $limit = 1,
1226
-        $query_params = array(),
1227
-        $columns_to_select = null
1228
-    ) {
1229
-        return $this->_get_consecutive(
1230
-            $current_field_value,
1231
-            '>',
1232
-            $field_to_order_by,
1233
-            $limit,
1234
-            $query_params,
1235
-            $columns_to_select
1236
-        );
1237
-    }
1238
-
1239
-
1240
-
1241
-    /**
1242
-     * Returns the previous x number of items in sequence from the given value
1243
-     * as found in the database matching the given query conditions.
1244
-     *
1245
-     * @param mixed $current_field_value    Value used for the reference point.
1246
-     * @param null  $field_to_order_by      What field is used for the
1247
-     *                                      reference point.
1248
-     * @param int   $limit                  How many to return.
1249
-     * @param array $query_params           Extra conditions on the query.
1250
-     * @param null  $columns_to_select      If left null, then an array of
1251
-     *                                      EE_Base_Class objects is returned,
1252
-     *                                      otherwise you can indicate just the
1253
-     *                                      columns you want returned.
1254
-     * @return EE_Base_Class[]|array
1255
-     * @throws EE_Error
1256
-     */
1257
-    public function previous_x(
1258
-        $current_field_value,
1259
-        $field_to_order_by = null,
1260
-        $limit = 1,
1261
-        $query_params = array(),
1262
-        $columns_to_select = null
1263
-    ) {
1264
-        return $this->_get_consecutive(
1265
-            $current_field_value,
1266
-            '<',
1267
-            $field_to_order_by,
1268
-            $limit,
1269
-            $query_params,
1270
-            $columns_to_select
1271
-        );
1272
-    }
1273
-
1274
-
1275
-
1276
-    /**
1277
-     * Returns the next item in sequence from the given value as found in the
1278
-     * database matching the given query conditions.
1279
-     *
1280
-     * @param mixed $current_field_value    Value used for the reference point.
1281
-     * @param null  $field_to_order_by      What field is used for the
1282
-     *                                      reference point.
1283
-     * @param array $query_params           Extra conditions on the query.
1284
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1285
-     *                                      object is returned, otherwise you
1286
-     *                                      can indicate just the columns you
1287
-     *                                      want and a single array indexed by
1288
-     *                                      the columns will be returned.
1289
-     * @return EE_Base_Class|null|array()
1290
-     * @throws EE_Error
1291
-     */
1292
-    public function next(
1293
-        $current_field_value,
1294
-        $field_to_order_by = null,
1295
-        $query_params = array(),
1296
-        $columns_to_select = null
1297
-    ) {
1298
-        $results = $this->_get_consecutive(
1299
-            $current_field_value,
1300
-            '>',
1301
-            $field_to_order_by,
1302
-            1,
1303
-            $query_params,
1304
-            $columns_to_select
1305
-        );
1306
-        return empty($results) ? null : reset($results);
1307
-    }
1308
-
1309
-
1310
-
1311
-    /**
1312
-     * Returns the previous item in sequence from the given value as found in
1313
-     * the database matching the given query conditions.
1314
-     *
1315
-     * @param mixed $current_field_value    Value used for the reference point.
1316
-     * @param null  $field_to_order_by      What field is used for the
1317
-     *                                      reference point.
1318
-     * @param array $query_params           Extra conditions on the query.
1319
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1320
-     *                                      object is returned, otherwise you
1321
-     *                                      can indicate just the columns you
1322
-     *                                      want and a single array indexed by
1323
-     *                                      the columns will be returned.
1324
-     * @return EE_Base_Class|null|array()
1325
-     * @throws EE_Error
1326
-     */
1327
-    public function previous(
1328
-        $current_field_value,
1329
-        $field_to_order_by = null,
1330
-        $query_params = array(),
1331
-        $columns_to_select = null
1332
-    ) {
1333
-        $results = $this->_get_consecutive(
1334
-            $current_field_value,
1335
-            '<',
1336
-            $field_to_order_by,
1337
-            1,
1338
-            $query_params,
1339
-            $columns_to_select
1340
-        );
1341
-        return empty($results) ? null : reset($results);
1342
-    }
1343
-
1344
-
1345
-
1346
-    /**
1347
-     * Returns the a consecutive number of items in sequence from the given
1348
-     * value as found in the database matching the given query conditions.
1349
-     *
1350
-     * @param mixed  $current_field_value   Value used for the reference point.
1351
-     * @param string $operand               What operand is used for the sequence.
1352
-     * @param string $field_to_order_by     What field is used for the reference point.
1353
-     * @param int    $limit                 How many to return.
1354
-     * @param array  $query_params          Extra conditions on the query.
1355
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1356
-     *                                      otherwise you can indicate just the columns you want returned.
1357
-     * @return EE_Base_Class[]|array
1358
-     * @throws EE_Error
1359
-     */
1360
-    protected function _get_consecutive(
1361
-        $current_field_value,
1362
-        $operand = '>',
1363
-        $field_to_order_by = null,
1364
-        $limit = 1,
1365
-        $query_params = array(),
1366
-        $columns_to_select = null
1367
-    ) {
1368
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1369
-        if (empty($field_to_order_by)) {
1370
-            if ($this->has_primary_key_field()) {
1371
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1372
-            } else {
1373
-                if (WP_DEBUG) {
1374
-                    throw new EE_Error(esc_html__(
1375
-                        '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).',
1376
-                        'event_espresso'
1377
-                    ));
1378
-                }
1379
-                EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1380
-                return array();
1381
-            }
1382
-        }
1383
-        if (! is_array($query_params)) {
1384
-            EE_Error::doing_it_wrong(
1385
-                'EEM_Base::_get_consecutive',
1386
-                sprintf(
1387
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1388
-                    gettype($query_params)
1389
-                ),
1390
-                '4.6.0'
1391
-            );
1392
-            $query_params = array();
1393
-        }
1394
-        // let's add the where query param for consecutive look up.
1395
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1396
-        $query_params['limit'] = $limit;
1397
-        // set direction
1398
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1399
-        $query_params['order_by'] = $operand === '>'
1400
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1401
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1402
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1403
-        if (empty($columns_to_select)) {
1404
-            return $this->get_all($query_params);
1405
-        }
1406
-        // getting just the fields
1407
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1408
-    }
1409
-
1410
-
1411
-
1412
-    /**
1413
-     * This sets the _timezone property after model object has been instantiated.
1414
-     *
1415
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1416
-     */
1417
-    public function set_timezone($timezone)
1418
-    {
1419
-        if ($timezone !== null) {
1420
-            $this->_timezone = $timezone;
1421
-        }
1422
-        // note we need to loop through relations and set the timezone on those objects as well.
1423
-        foreach ($this->_model_relations as $relation) {
1424
-            $relation->set_timezone($timezone);
1425
-        }
1426
-        // and finally we do the same for any datetime fields
1427
-        foreach ($this->_fields as $field) {
1428
-            if ($field instanceof EE_Datetime_Field) {
1429
-                $field->set_timezone($timezone);
1430
-            }
1431
-        }
1432
-    }
1433
-
1434
-
1435
-
1436
-    /**
1437
-     * This just returns whatever is set for the current timezone.
1438
-     *
1439
-     * @access public
1440
-     * @return string
1441
-     */
1442
-    public function get_timezone()
1443
-    {
1444
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1445
-        if (empty($this->_timezone)) {
1446
-            foreach ($this->_fields as $field) {
1447
-                if ($field instanceof EE_Datetime_Field) {
1448
-                    $this->set_timezone($field->get_timezone());
1449
-                    break;
1450
-                }
1451
-            }
1452
-        }
1453
-        // if timezone STILL empty then return the default timezone for the site.
1454
-        if (empty($this->_timezone)) {
1455
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1456
-        }
1457
-        return $this->_timezone;
1458
-    }
1459
-
1460
-
1461
-
1462
-    /**
1463
-     * This returns the date formats set for the given field name and also ensures that
1464
-     * $this->_timezone property is set correctly.
1465
-     *
1466
-     * @since 4.6.x
1467
-     * @param string $field_name The name of the field the formats are being retrieved for.
1468
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1469
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1470
-     * @return array formats in an array with the date format first, and the time format last.
1471
-     */
1472
-    public function get_formats_for($field_name, $pretty = false)
1473
-    {
1474
-        $field_settings = $this->field_settings_for($field_name);
1475
-        // if not a valid EE_Datetime_Field then throw error
1476
-        if (! $field_settings instanceof EE_Datetime_Field) {
1477
-            throw new EE_Error(sprintf(esc_html__(
1478
-                '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.',
1479
-                'event_espresso'
1480
-            ), $field_name));
1481
-        }
1482
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1483
-        // the field.
1484
-        $this->_timezone = $field_settings->get_timezone();
1485
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1486
-    }
1487
-
1488
-
1489
-
1490
-    /**
1491
-     * This returns the current time in a format setup for a query on this model.
1492
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1493
-     * it will return:
1494
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1495
-     *  NOW
1496
-     *  - or a unix timestamp (equivalent to time())
1497
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1498
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1499
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1500
-     * @since 4.6.x
1501
-     * @param string $field_name       The field the current time is needed for.
1502
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1503
-     *                                 formatted string matching the set format for the field in the set timezone will
1504
-     *                                 be returned.
1505
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1506
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1507
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1508
-     *                                 exception is triggered.
1509
-     */
1510
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1511
-    {
1512
-        $formats = $this->get_formats_for($field_name);
1513
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1514
-        if ($timestamp) {
1515
-            return $DateTime->format('U');
1516
-        }
1517
-        // not returning timestamp, so return formatted string in timezone.
1518
-        switch ($what) {
1519
-            case 'time':
1520
-                return $DateTime->format($formats[1]);
1521
-                break;
1522
-            case 'date':
1523
-                return $DateTime->format($formats[0]);
1524
-                break;
1525
-            default:
1526
-                return $DateTime->format(implode(' ', $formats));
1527
-                break;
1528
-        }
1529
-    }
1530
-
1531
-
1532
-
1533
-    /**
1534
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1535
-     * for the model are.  Returns a DateTime object.
1536
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1537
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1538
-     * ignored.
1539
-     *
1540
-     * @param string $field_name      The field being setup.
1541
-     * @param string $timestring      The date time string being used.
1542
-     * @param string $incoming_format The format for the time string.
1543
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1544
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1545
-     *                                format is
1546
-     *                                'U', this is ignored.
1547
-     * @return DateTime
1548
-     * @throws EE_Error
1549
-     */
1550
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1551
-    {
1552
-        // just using this to ensure the timezone is set correctly internally
1553
-        $this->get_formats_for($field_name);
1554
-        // load EEH_DTT_Helper
1555
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1556
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1557
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1558
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1559
-    }
1560
-
1561
-
1562
-
1563
-    /**
1564
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1565
-     *
1566
-     * @return EE_Table_Base[]
1567
-     */
1568
-    public function get_tables()
1569
-    {
1570
-        return $this->_tables;
1571
-    }
1572
-
1573
-
1574
-
1575
-    /**
1576
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1577
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1578
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1579
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1580
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1581
-     * model object with EVT_ID = 1
1582
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1583
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1584
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1585
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1586
-     * are not specified)
1587
-     *
1588
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1589
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1590
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1591
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1592
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1593
-     *                                         ID=34, we'd use this method as follows:
1594
-     *                                         EEM_Transaction::instance()->update(
1595
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1596
-     *                                         array(array('TXN_ID'=>34)));
1597
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1598
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1599
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1600
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1601
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1602
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1603
-     *                                         TRUE, it is assumed that you've already called
1604
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1605
-     *                                         malicious javascript. However, if
1606
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1607
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1608
-     *                                         and every other field, before insertion. We provide this parameter
1609
-     *                                         because model objects perform their prepare_for_set function on all
1610
-     *                                         their values, and so don't need to be called again (and in many cases,
1611
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1612
-     *                                         prepare_for_set method...)
1613
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1614
-     *                                         in this model's entity map according to $fields_n_values that match
1615
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1616
-     *                                         by setting this to FALSE, but be aware that model objects being used
1617
-     *                                         could get out-of-sync with the database
1618
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1619
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1620
-     *                                         bad)
1621
-     * @throws EE_Error
1622
-     */
1623
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624
-    {
1625
-        if (! is_array($query_params)) {
1626
-            EE_Error::doing_it_wrong(
1627
-                'EEM_Base::update',
1628
-                sprintf(
1629
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1630
-                    gettype($query_params)
1631
-                ),
1632
-                '4.6.0'
1633
-            );
1634
-            $query_params = array();
1635
-        }
1636
-        /**
1637
-         * Action called before a model update call has been made.
1638
-         *
1639
-         * @param EEM_Base $model
1640
-         * @param array    $fields_n_values the updated fields and their new values
1641
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
-         */
1643
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1644
-        /**
1645
-         * Filters the fields about to be updated given the query parameters. You can provide the
1646
-         * $query_params to $this->get_all() to find exactly which records will be updated
1647
-         *
1648
-         * @param array    $fields_n_values fields and their new values
1649
-         * @param EEM_Base $model           the model being queried
1650
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1651
-         */
1652
-        $fields_n_values = (array) apply_filters(
1653
-            'FHEE__EEM_Base__update__fields_n_values',
1654
-            $fields_n_values,
1655
-            $this,
1656
-            $query_params
1657
-        );
1658
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1659
-        // to do that, for each table, verify that it's PK isn't null.
1660
-        $tables = $this->get_tables();
1661
-        // 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
1662
-        // NOTE: we should make this code more efficient by NOT querying twice
1663
-        // before the real update, but that needs to first go through ALPHA testing
1664
-        // as it's dangerous. says Mike August 8 2014
1665
-        // we want to make sure the default_where strategy is ignored
1666
-        $this->_ignore_where_strategy = true;
1667
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1668
-        foreach ($wpdb_select_results as $wpdb_result) {
1669
-            // type cast stdClass as array
1670
-            $wpdb_result = (array) $wpdb_result;
1671
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672
-            if ($this->has_primary_key_field()) {
1673
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1674
-            } else {
1675
-                // 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)
1676
-                $main_table_pk_value = null;
1677
-            }
1678
-            // 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
1679
-            // 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
1680
-            if (count($tables) > 1) {
1681
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1682
-                // in that table, and so we'll want to insert one
1683
-                foreach ($tables as $table_obj) {
1684
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1685
-                    // if there is no private key for this table on the results, it means there's no entry
1686
-                    // in this table, right? so insert a row in the current table, using any fields available
1687
-                    if (
1688
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
-                           && $wpdb_result[ $this_table_pk_column ])
1690
-                    ) {
1691
-                        $success = $this->_insert_into_specific_table(
1692
-                            $table_obj,
1693
-                            $fields_n_values,
1694
-                            $main_table_pk_value
1695
-                        );
1696
-                        // if we died here, report the error
1697
-                        if (! $success) {
1698
-                            return false;
1699
-                        }
1700
-                    }
1701
-                }
1702
-            }
1703
-            //              //and now check that if we have cached any models by that ID on the model, that
1704
-            //              //they also get updated properly
1705
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1706
-            //              if( $model_object ){
1707
-            //                  foreach( $fields_n_values as $field => $value ){
1708
-            //                      $model_object->set($field, $value);
1709
-            // let's make sure default_where strategy is followed now
1710
-            $this->_ignore_where_strategy = false;
1711
-        }
1712
-        // if we want to keep model objects in sync, AND
1713
-        // if this wasn't called from a model object (to update itself)
1714
-        // then we want to make sure we keep all the existing
1715
-        // model objects in sync with the db
1716
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1717
-            if ($this->has_primary_key_field()) {
1718
-                $model_objs_affected_ids = $this->get_col($query_params);
1719
-            } else {
1720
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1721
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1722
-                $model_objs_affected_ids = array();
1723
-                foreach ($models_affected_key_columns as $row) {
1724
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1725
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1726
-                }
1727
-            }
1728
-            if (! $model_objs_affected_ids) {
1729
-                // wait wait wait- if nothing was affected let's stop here
1730
-                return 0;
1731
-            }
1732
-            foreach ($model_objs_affected_ids as $id) {
1733
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1734
-                if ($model_obj_in_entity_map) {
1735
-                    foreach ($fields_n_values as $field => $new_value) {
1736
-                        $model_obj_in_entity_map->set($field, $new_value);
1737
-                    }
1738
-                }
1739
-            }
1740
-            // if there is a primary key on this model, we can now do a slight optimization
1741
-            if ($this->has_primary_key_field()) {
1742
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1743
-                $query_params = array(
1744
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1745
-                    'limit'                    => count($model_objs_affected_ids),
1746
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1747
-                );
1748
-            }
1749
-        }
1750
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1751
-        $SQL = "UPDATE "
1752
-               . $model_query_info->get_full_join_sql()
1753
-               . " SET "
1754
-               . $this->_construct_update_sql($fields_n_values)
1755
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757
-        /**
1758
-         * Action called after a model update call has been made.
1759
-         *
1760
-         * @param EEM_Base $model
1761
-         * @param array    $fields_n_values the updated fields and their new values
1762
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1763
-         * @param int      $rows_affected
1764
-         */
1765
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
-        return $rows_affected;// how many supposedly got updated
1767
-    }
1768
-
1769
-
1770
-
1771
-    /**
1772
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1773
-     * are teh values of the field specified (or by default the primary key field)
1774
-     * that matched the query params. Note that you should pass the name of the
1775
-     * model FIELD, not the database table's column name.
1776
-     *
1777
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1778
-     * @param string $field_to_select
1779
-     * @return array just like $wpdb->get_col()
1780
-     * @throws EE_Error
1781
-     */
1782
-    public function get_col($query_params = array(), $field_to_select = null)
1783
-    {
1784
-        if ($field_to_select) {
1785
-            $field = $this->field_settings_for($field_to_select);
1786
-        } elseif ($this->has_primary_key_field()) {
1787
-            $field = $this->get_primary_key_field();
1788
-        } else {
1789
-            // no primary key, just grab the first column
1790
-            $field = reset($this->field_settings());
1791
-        }
1792
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1793
-        $select_expressions = $field->get_qualified_column();
1794
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1795
-        return $this->_do_wpdb_query('get_col', array($SQL));
1796
-    }
1797
-
1798
-
1799
-
1800
-    /**
1801
-     * Returns a single column value for a single row from the database
1802
-     *
1803
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1804
-     * @param string $field_to_select @see EEM_Base::get_col()
1805
-     * @return string
1806
-     * @throws EE_Error
1807
-     */
1808
-    public function get_var($query_params = array(), $field_to_select = null)
1809
-    {
1810
-        $query_params['limit'] = 1;
1811
-        $col = $this->get_col($query_params, $field_to_select);
1812
-        if (! empty($col)) {
1813
-            return reset($col);
1814
-        }
1815
-        return null;
1816
-    }
1817
-
1818
-
1819
-
1820
-    /**
1821
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1822
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1823
-     * injection, but currently no further filtering is done
1824
-     *
1825
-     * @global      $wpdb
1826
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1827
-     *                               be updated to in the DB
1828
-     * @return string of SQL
1829
-     * @throws EE_Error
1830
-     */
1831
-    public function _construct_update_sql($fields_n_values)
1832
-    {
1833
-        /** @type WPDB $wpdb */
1834
-        global $wpdb;
1835
-        $cols_n_values = array();
1836
-        foreach ($fields_n_values as $field_name => $value) {
1837
-            $field_obj = $this->field_settings_for($field_name);
1838
-            // if the value is NULL, we want to assign the value to that.
1839
-            // wpdb->prepare doesn't really handle that properly
1840
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1841
-            $value_sql = $prepared_value === null ? 'NULL'
1842
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1843
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1844
-        }
1845
-        return implode(",", $cols_n_values);
1846
-    }
1847
-
1848
-
1849
-
1850
-    /**
1851
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1852
-     * Performs a HARD delete, meaning the database row should always be removed,
1853
-     * not just have a flag field on it switched
1854
-     * Wrapper for EEM_Base::delete_permanently()
1855
-     *
1856
-     * @param mixed $id
1857
-     * @param boolean $allow_blocking
1858
-     * @return int the number of rows deleted
1859
-     * @throws EE_Error
1860
-     */
1861
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1862
-    {
1863
-        return $this->delete_permanently(
1864
-            array(
1865
-                array($this->get_primary_key_field()->get_name() => $id),
1866
-                'limit' => 1,
1867
-            ),
1868
-            $allow_blocking
1869
-        );
1870
-    }
1871
-
1872
-
1873
-
1874
-    /**
1875
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1876
-     * Wrapper for EEM_Base::delete()
1877
-     *
1878
-     * @param mixed $id
1879
-     * @param boolean $allow_blocking
1880
-     * @return int the number of rows deleted
1881
-     * @throws EE_Error
1882
-     */
1883
-    public function delete_by_ID($id, $allow_blocking = true)
1884
-    {
1885
-        return $this->delete(
1886
-            array(
1887
-                array($this->get_primary_key_field()->get_name() => $id),
1888
-                'limit' => 1,
1889
-            ),
1890
-            $allow_blocking
1891
-        );
1892
-    }
1893
-
1894
-
1895
-
1896
-    /**
1897
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1898
-     * meaning if the model has a field that indicates its been "trashed" or
1899
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1900
-     *
1901
-     * @see EEM_Base::delete_permanently
1902
-     * @param array   $query_params
1903
-     * @param boolean $allow_blocking
1904
-     * @return int how many rows got deleted
1905
-     * @throws EE_Error
1906
-     */
1907
-    public function delete($query_params, $allow_blocking = true)
1908
-    {
1909
-        return $this->delete_permanently($query_params, $allow_blocking);
1910
-    }
1911
-
1912
-
1913
-
1914
-    /**
1915
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1916
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1917
-     * as archived, not actually deleted
1918
-     *
1919
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1920
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1921
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1922
-     *                                deletes regardless of other objects which may depend on it. Its generally
1923
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1924
-     *                                DB
1925
-     * @return int how many rows got deleted
1926
-     * @throws EE_Error
1927
-     */
1928
-    public function delete_permanently($query_params, $allow_blocking = true)
1929
-    {
1930
-        /**
1931
-         * Action called just before performing a real deletion query. You can use the
1932
-         * model and its $query_params to find exactly which items will be deleted
1933
-         *
1934
-         * @param EEM_Base $model
1935
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1936
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1937
-         *                                 to block (prevent) this deletion
1938
-         */
1939
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1940
-        // some MySQL databases may be running safe mode, which may restrict
1941
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1942
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1943
-        // to delete them
1944
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1945
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1946
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1947
-            $columns_and_ids_for_deleting
1948
-        );
1949
-        /**
1950
-         * Allows client code to act on the items being deleted before the query is actually executed.
1951
-         *
1952
-         * @param EEM_Base $this  The model instance being acted on.
1953
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1954
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1955
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1956
-         *                                                  derived from the incoming query parameters.
1957
-         *                                                  @see details on the structure of this array in the phpdocs
1958
-         *                                                  for the `_get_ids_for_delete_method`
1959
-         *
1960
-         */
1961
-        do_action(
1962
-            'AHEE__EEM_Base__delete__before_query',
1963
-            $this,
1964
-            $query_params,
1965
-            $allow_blocking,
1966
-            $columns_and_ids_for_deleting
1967
-        );
1968
-        if ($deletion_where_query_part) {
1969
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1970
-            $table_aliases = array_keys($this->_tables);
1971
-            $SQL = "DELETE "
1972
-                   . implode(", ", $table_aliases)
1973
-                   . " FROM "
1974
-                   . $model_query_info->get_full_join_sql()
1975
-                   . " WHERE "
1976
-                   . $deletion_where_query_part;
1977
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1978
-        } else {
1979
-            $rows_deleted = 0;
1980
-        }
1981
-
1982
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1983
-        // there was no error with the delete query.
1984
-        if (
1985
-            $this->has_primary_key_field()
1986
-            && $rows_deleted !== false
1987
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1988
-        ) {
1989
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1990
-            foreach ($ids_for_removal as $id) {
1991
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1992
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1993
-                }
1994
-            }
1995
-
1996
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1997
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1998
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1999
-            // (although it is possible).
2000
-            // Note this can be skipped by using the provided filter and returning false.
2001
-            if (
2002
-                apply_filters(
2003
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2004
-                    ! $this instanceof EEM_Extra_Meta,
2005
-                    $this
2006
-                )
2007
-            ) {
2008
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2009
-                    0 => array(
2010
-                        'EXM_type' => $this->get_this_model_name(),
2011
-                        'OBJ_ID'   => array(
2012
-                            'IN',
2013
-                            $ids_for_removal
2014
-                        )
2015
-                    )
2016
-                ));
2017
-            }
2018
-        }
2019
-
2020
-        /**
2021
-         * Action called just after performing a real deletion query. Although at this point the
2022
-         * items should have been deleted
2023
-         *
2024
-         * @param EEM_Base $model
2025
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2026
-         * @param int      $rows_deleted
2027
-         */
2028
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
-        return $rows_deleted;// how many supposedly got deleted
2030
-    }
2031
-
2032
-
2033
-
2034
-    /**
2035
-     * Checks all the relations that throw error messages when there are blocking related objects
2036
-     * for related model objects. If there are any related model objects on those relations,
2037
-     * adds an EE_Error, and return true
2038
-     *
2039
-     * @param EE_Base_Class|int $this_model_obj_or_id
2040
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2041
-     *                                                 should be ignored when determining whether there are related
2042
-     *                                                 model objects which block this model object's deletion. Useful
2043
-     *                                                 if you know A is related to B and are considering deleting A,
2044
-     *                                                 but want to see if A has any other objects blocking its deletion
2045
-     *                                                 before removing the relation between A and B
2046
-     * @return boolean
2047
-     * @throws EE_Error
2048
-     */
2049
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2050
-    {
2051
-        // first, if $ignore_this_model_obj was supplied, get its model
2052
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2053
-            $ignored_model = $ignore_this_model_obj->get_model();
2054
-        } else {
2055
-            $ignored_model = null;
2056
-        }
2057
-        // now check all the relations of $this_model_obj_or_id and see if there
2058
-        // are any related model objects blocking it?
2059
-        $is_blocked = false;
2060
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2061
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2062
-                // if $ignore_this_model_obj was supplied, then for the query
2063
-                // on that model needs to be told to ignore $ignore_this_model_obj
2064
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2065
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2066
-                        array(
2067
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2068
-                                '!=',
2069
-                                $ignore_this_model_obj->ID(),
2070
-                            ),
2071
-                        ),
2072
-                    ));
2073
-                } else {
2074
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2075
-                }
2076
-                if ($related_model_objects) {
2077
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2078
-                    $is_blocked = true;
2079
-                }
2080
-            }
2081
-        }
2082
-        return $is_blocked;
2083
-    }
2084
-
2085
-
2086
-    /**
2087
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2088
-     * @param array $row_results_for_deleting
2089
-     * @param bool  $allow_blocking
2090
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2091
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2092
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2093
-     *                 deleted. Example:
2094
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2095
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2096
-     *                 where each element is a group of columns and values that get deleted. Example:
2097
-     *                      array(
2098
-     *                          0 => array(
2099
-     *                              'Term_Relationship.object_id' => 1
2100
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2101
-     *                          ),
2102
-     *                          1 => array(
2103
-     *                              'Term_Relationship.object_id' => 1
2104
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2105
-     *                          )
2106
-     *                      )
2107
-     * @throws EE_Error
2108
-     */
2109
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2110
-    {
2111
-        $ids_to_delete_indexed_by_column = array();
2112
-        if ($this->has_primary_key_field()) {
2113
-            $primary_table = $this->_get_main_table();
2114
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2115
-            $other_tables = $this->_get_other_tables();
2116
-            $ids_to_delete_indexed_by_column = $query = array();
2117
-            foreach ($row_results_for_deleting as $item_to_delete) {
2118
-                // before we mark this item for deletion,
2119
-                // make sure there's no related entities blocking its deletion (if we're checking)
2120
-                if (
2121
-                    $allow_blocking
2122
-                    && $this->delete_is_blocked_by_related_models(
2123
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2124
-                    )
2125
-                ) {
2126
-                    continue;
2127
-                }
2128
-                // primary table deletes
2129
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2130
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2131
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2132
-                }
2133
-            }
2134
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2135
-            $fields = $this->get_combined_primary_key_fields();
2136
-            foreach ($row_results_for_deleting as $item_to_delete) {
2137
-                $ids_to_delete_indexed_by_column_for_row = array();
2138
-                foreach ($fields as $cpk_field) {
2139
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2140
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2141
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2142
-                    }
2143
-                }
2144
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2145
-            }
2146
-        } else {
2147
-            // so there's no primary key and no combined key...
2148
-            // sorry, can't help you
2149
-            throw new EE_Error(
2150
-                sprintf(
2151
-                    esc_html__(
2152
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2153
-                        "event_espresso"
2154
-                    ),
2155
-                    get_class($this)
2156
-                )
2157
-            );
2158
-        }
2159
-        return $ids_to_delete_indexed_by_column;
2160
-    }
2161
-
2162
-
2163
-    /**
2164
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2165
-     * the corresponding query_part for the query performing the delete.
2166
-     *
2167
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2168
-     * @return string
2169
-     * @throws EE_Error
2170
-     */
2171
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2172
-    {
2173
-        $query_part = '';
2174
-        if (empty($ids_to_delete_indexed_by_column)) {
2175
-            return $query_part;
2176
-        } elseif ($this->has_primary_key_field()) {
2177
-            $query = array();
2178
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2179
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2180
-            }
2181
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2182
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2183
-            $ways_to_identify_a_row = array();
2184
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2185
-                $values_for_each_combined_primary_key_for_a_row = array();
2186
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2187
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2188
-                }
2189
-                $ways_to_identify_a_row[] = '('
2190
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2191
-                                            . ')';
2192
-            }
2193
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2194
-        }
2195
-        return $query_part;
2196
-    }
2197
-
2198
-
2199
-
2200
-    /**
2201
-     * Gets the model field by the fully qualified name
2202
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2203
-     * @return EE_Model_Field_Base
2204
-     */
2205
-    public function get_field_by_column($qualified_column_name)
2206
-    {
2207
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2208
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2209
-                return $field_obj;
2210
-            }
2211
-        }
2212
-        throw new EE_Error(
2213
-            sprintf(
2214
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2215
-                $this->get_this_model_name(),
2216
-                $qualified_column_name
2217
-            )
2218
-        );
2219
-    }
2220
-
2221
-
2222
-
2223
-    /**
2224
-     * Count all the rows that match criteria the model query params.
2225
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2226
-     * column
2227
-     *
2228
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2229
-     * @param string $field_to_count field on model to count by (not column name)
2230
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2231
-     *                               that by the setting $distinct to TRUE;
2232
-     * @return int
2233
-     * @throws EE_Error
2234
-     */
2235
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2236
-    {
2237
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2238
-        if ($field_to_count) {
2239
-            $field_obj = $this->field_settings_for($field_to_count);
2240
-            $column_to_count = $field_obj->get_qualified_column();
2241
-        } elseif ($this->has_primary_key_field()) {
2242
-            $pk_field_obj = $this->get_primary_key_field();
2243
-            $column_to_count = $pk_field_obj->get_qualified_column();
2244
-        } else {
2245
-            // there's no primary key
2246
-            // if we're counting distinct items, and there's no primary key,
2247
-            // we need to list out the columns for distinction;
2248
-            // otherwise we can just use star
2249
-            if ($distinct) {
2250
-                $columns_to_use = array();
2251
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2252
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2253
-                }
2254
-                $column_to_count = implode(',', $columns_to_use);
2255
-            } else {
2256
-                $column_to_count = '*';
2257
-            }
2258
-        }
2259
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2260
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2262
-    }
2263
-
2264
-
2265
-
2266
-    /**
2267
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2268
-     *
2269
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2270
-     * @param string $field_to_sum name of field (array key in $_fields array)
2271
-     * @return float
2272
-     * @throws EE_Error
2273
-     */
2274
-    public function sum($query_params, $field_to_sum = null)
2275
-    {
2276
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2277
-        if ($field_to_sum) {
2278
-            $field_obj = $this->field_settings_for($field_to_sum);
2279
-        } else {
2280
-            $field_obj = $this->get_primary_key_field();
2281
-        }
2282
-        $column_to_count = $field_obj->get_qualified_column();
2283
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2284
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2285
-        $data_type = $field_obj->get_wpdb_data_type();
2286
-        if ($data_type === '%d' || $data_type === '%s') {
2287
-            return (float) $return_value;
2288
-        }
2289
-        // must be %f
2290
-        return (float) $return_value;
2291
-    }
2292
-
2293
-
2294
-
2295
-    /**
2296
-     * Just calls the specified method on $wpdb with the given arguments
2297
-     * Consolidates a little extra error handling code
2298
-     *
2299
-     * @param string $wpdb_method
2300
-     * @param array  $arguments_to_provide
2301
-     * @throws EE_Error
2302
-     * @global wpdb  $wpdb
2303
-     * @return mixed
2304
-     */
2305
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2306
-    {
2307
-        // if we're in maintenance mode level 2, DON'T run any queries
2308
-        // because level 2 indicates the database needs updating and
2309
-        // is probably out of sync with the code
2310
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2311
-            throw new EE_Error(sprintf(esc_html__(
2312
-                "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.",
2313
-                "event_espresso"
2314
-            )));
2315
-        }
2316
-        /** @type WPDB $wpdb */
2317
-        global $wpdb;
2318
-        if (! method_exists($wpdb, $wpdb_method)) {
2319
-            throw new EE_Error(sprintf(esc_html__(
2320
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2321
-                'event_espresso'
2322
-            ), $wpdb_method));
2323
-        }
2324
-        if (WP_DEBUG) {
2325
-            $old_show_errors_value = $wpdb->show_errors;
2326
-            $wpdb->show_errors(false);
2327
-        }
2328
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2329
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2330
-        if (WP_DEBUG) {
2331
-            $wpdb->show_errors($old_show_errors_value);
2332
-            if (! empty($wpdb->last_error)) {
2333
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2334
-            }
2335
-            if ($result === false) {
2336
-                throw new EE_Error(sprintf(esc_html__(
2337
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2338
-                    'event_espresso'
2339
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2340
-            }
2341
-        } elseif ($result === false) {
2342
-            EE_Error::add_error(
2343
-                sprintf(
2344
-                    esc_html__(
2345
-                        '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"',
2346
-                        'event_espresso'
2347
-                    ),
2348
-                    $wpdb_method,
2349
-                    var_export($arguments_to_provide, true),
2350
-                    $wpdb->last_error
2351
-                ),
2352
-                __FILE__,
2353
-                __FUNCTION__,
2354
-                __LINE__
2355
-            );
2356
-        }
2357
-        return $result;
2358
-    }
2359
-
2360
-
2361
-
2362
-    /**
2363
-     * Attempts to run the indicated WPDB method with the provided arguments,
2364
-     * and if there's an error tries to verify the DB is correct. Uses
2365
-     * the static property EEM_Base::$_db_verification_level to determine whether
2366
-     * we should try to fix the EE core db, the addons, or just give up
2367
-     *
2368
-     * @param string $wpdb_method
2369
-     * @param array  $arguments_to_provide
2370
-     * @return mixed
2371
-     */
2372
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2373
-    {
2374
-        /** @type WPDB $wpdb */
2375
-        global $wpdb;
2376
-        $wpdb->last_error = null;
2377
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2378
-        // was there an error running the query? but we don't care on new activations
2379
-        // (we're going to setup the DB anyway on new activations)
2380
-        if (
2381
-            ($result === false || ! empty($wpdb->last_error))
2382
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2383
-        ) {
2384
-            switch (EEM_Base::$_db_verification_level) {
2385
-                case EEM_Base::db_verified_none:
2386
-                    // let's double-check core's DB
2387
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2388
-                    break;
2389
-                case EEM_Base::db_verified_core:
2390
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2391
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2392
-                    break;
2393
-                case EEM_Base::db_verified_addons:
2394
-                    // ummmm... you in trouble
2395
-                    return $result;
2396
-                    break;
2397
-            }
2398
-            if (! empty($error_message)) {
2399
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2400
-                trigger_error($error_message);
2401
-            }
2402
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2403
-        }
2404
-        return $result;
2405
-    }
2406
-
2407
-
2408
-
2409
-    /**
2410
-     * Verifies the EE core database is up-to-date and records that we've done it on
2411
-     * EEM_Base::$_db_verification_level
2412
-     *
2413
-     * @param string $wpdb_method
2414
-     * @param array  $arguments_to_provide
2415
-     * @return string
2416
-     */
2417
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2418
-    {
2419
-        /** @type WPDB $wpdb */
2420
-        global $wpdb;
2421
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2422
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2423
-        $error_message = sprintf(
2424
-            esc_html__(
2425
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2426
-                'event_espresso'
2427
-            ),
2428
-            $wpdb->last_error,
2429
-            $wpdb_method,
2430
-            wp_json_encode($arguments_to_provide)
2431
-        );
2432
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2433
-        return $error_message;
2434
-    }
2435
-
2436
-
2437
-
2438
-    /**
2439
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2440
-     * EEM_Base::$_db_verification_level
2441
-     *
2442
-     * @param $wpdb_method
2443
-     * @param $arguments_to_provide
2444
-     * @return string
2445
-     */
2446
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2447
-    {
2448
-        /** @type WPDB $wpdb */
2449
-        global $wpdb;
2450
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2451
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2452
-        $error_message = sprintf(
2453
-            esc_html__(
2454
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2455
-                'event_espresso'
2456
-            ),
2457
-            $wpdb->last_error,
2458
-            $wpdb_method,
2459
-            wp_json_encode($arguments_to_provide)
2460
-        );
2461
-        EE_System::instance()->initialize_addons();
2462
-        return $error_message;
2463
-    }
2464
-
2465
-
2466
-
2467
-    /**
2468
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2469
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2470
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2471
-     * ..."
2472
-     *
2473
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2474
-     * @return string
2475
-     */
2476
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2477
-    {
2478
-        return " FROM " . $model_query_info->get_full_join_sql() .
2479
-               $model_query_info->get_where_sql() .
2480
-               $model_query_info->get_group_by_sql() .
2481
-               $model_query_info->get_having_sql() .
2482
-               $model_query_info->get_order_by_sql() .
2483
-               $model_query_info->get_limit_sql();
2484
-    }
2485
-
2486
-
2487
-
2488
-    /**
2489
-     * Set to easily debug the next X queries ran from this model.
2490
-     *
2491
-     * @param int $count
2492
-     */
2493
-    public function show_next_x_db_queries($count = 1)
2494
-    {
2495
-        $this->_show_next_x_db_queries = $count;
2496
-    }
2497
-
2498
-
2499
-
2500
-    /**
2501
-     * @param $sql_query
2502
-     */
2503
-    public function show_db_query_if_previously_requested($sql_query)
2504
-    {
2505
-        if ($this->_show_next_x_db_queries > 0) {
2506
-            echo esc_html($sql_query);
2507
-            $this->_show_next_x_db_queries--;
2508
-        }
2509
-    }
2510
-
2511
-
2512
-
2513
-    /**
2514
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2515
-     * There are the 3 cases:
2516
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2517
-     * $otherModelObject has no ID, it is first saved.
2518
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2519
-     * has no ID, it is first saved.
2520
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2521
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2522
-     * join table
2523
-     *
2524
-     * @param        EE_Base_Class                     /int $thisModelObject
2525
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2526
-     * @param string $relationName                     , key in EEM_Base::_relations
2527
-     *                                                 an attendee to a group, you also want to specify which role they
2528
-     *                                                 will have in that group. So you would use this parameter to
2529
-     *                                                 specify array('role-column-name'=>'role-id')
2530
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2531
-     *                                                 to for relation to methods that allow you to further specify
2532
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2533
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2534
-     *                                                 because these will be inserted in any new rows created as well.
2535
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2536
-     * @throws EE_Error
2537
-     */
2538
-    public function add_relationship_to(
2539
-        $id_or_obj,
2540
-        $other_model_id_or_obj,
2541
-        $relationName,
2542
-        $extra_join_model_fields_n_values = array()
2543
-    ) {
2544
-        $relation_obj = $this->related_settings_for($relationName);
2545
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2546
-    }
2547
-
2548
-
2549
-
2550
-    /**
2551
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2552
-     * There are the 3 cases:
2553
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2554
-     * error
2555
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2556
-     * an error
2557
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2558
-     *
2559
-     * @param        EE_Base_Class /int $id_or_obj
2560
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2561
-     * @param string $relationName key in EEM_Base::_relations
2562
-     * @return boolean of success
2563
-     * @throws EE_Error
2564
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2565
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2566
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2567
-     *                             because these will be inserted in any new rows created as well.
2568
-     */
2569
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2570
-    {
2571
-        $relation_obj = $this->related_settings_for($relationName);
2572
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2573
-    }
2574
-
2575
-
2576
-
2577
-    /**
2578
-     * @param mixed           $id_or_obj
2579
-     * @param string          $relationName
2580
-     * @param array           $where_query_params
2581
-     * @param EE_Base_Class[] objects to which relations were removed
2582
-     * @return \EE_Base_Class[]
2583
-     * @throws EE_Error
2584
-     */
2585
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2586
-    {
2587
-        $relation_obj = $this->related_settings_for($relationName);
2588
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2589
-    }
2590
-
2591
-
2592
-
2593
-    /**
2594
-     * Gets all the related items of the specified $model_name, using $query_params.
2595
-     * Note: by default, we remove the "default query params"
2596
-     * because we want to get even deleted items etc.
2597
-     *
2598
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2599
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2600
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2601
-     * @return EE_Base_Class[]
2602
-     * @throws EE_Error
2603
-     */
2604
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2605
-    {
2606
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2607
-        $relation_settings = $this->related_settings_for($model_name);
2608
-        return $relation_settings->get_all_related($model_obj, $query_params);
2609
-    }
2610
-
2611
-
2612
-
2613
-    /**
2614
-     * Deletes all the model objects across the relation indicated by $model_name
2615
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2616
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2617
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2618
-     *
2619
-     * @param EE_Base_Class|int|string $id_or_obj
2620
-     * @param string                   $model_name
2621
-     * @param array                    $query_params
2622
-     * @return int how many deleted
2623
-     * @throws EE_Error
2624
-     */
2625
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2626
-    {
2627
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2628
-        $relation_settings = $this->related_settings_for($model_name);
2629
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2630
-    }
2631
-
2632
-
2633
-
2634
-    /**
2635
-     * Hard deletes all the model objects across the relation indicated by $model_name
2636
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2637
-     * the model objects can't be hard deleted because of blocking related model objects,
2638
-     * just does a soft-delete on them instead.
2639
-     *
2640
-     * @param EE_Base_Class|int|string $id_or_obj
2641
-     * @param string                   $model_name
2642
-     * @param array                    $query_params
2643
-     * @return int how many deleted
2644
-     * @throws EE_Error
2645
-     */
2646
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2647
-    {
2648
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2649
-        $relation_settings = $this->related_settings_for($model_name);
2650
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2651
-    }
2652
-
2653
-
2654
-
2655
-    /**
2656
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2657
-     * unless otherwise specified in the $query_params
2658
-     *
2659
-     * @param        int             /EE_Base_Class $id_or_obj
2660
-     * @param string $model_name     like 'Event', or 'Registration'
2661
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2662
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2663
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2664
-     *                               that by the setting $distinct to TRUE;
2665
-     * @return int
2666
-     * @throws EE_Error
2667
-     */
2668
-    public function count_related(
2669
-        $id_or_obj,
2670
-        $model_name,
2671
-        $query_params = array(),
2672
-        $field_to_count = null,
2673
-        $distinct = false
2674
-    ) {
2675
-        $related_model = $this->get_related_model_obj($model_name);
2676
-        // we're just going to use the query params on the related model's normal get_all query,
2677
-        // except add a condition to say to match the current mod
2678
-        if (! isset($query_params['default_where_conditions'])) {
2679
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2680
-        }
2681
-        $this_model_name = $this->get_this_model_name();
2682
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2683
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2684
-        return $related_model->count($query_params, $field_to_count, $distinct);
2685
-    }
2686
-
2687
-
2688
-
2689
-    /**
2690
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2691
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2692
-     *
2693
-     * @param        int           /EE_Base_Class $id_or_obj
2694
-     * @param string $model_name   like 'Event', or 'Registration'
2695
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2696
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2697
-     * @return float
2698
-     * @throws EE_Error
2699
-     */
2700
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2701
-    {
2702
-        $related_model = $this->get_related_model_obj($model_name);
2703
-        if (! is_array($query_params)) {
2704
-            EE_Error::doing_it_wrong(
2705
-                'EEM_Base::sum_related',
2706
-                sprintf(
2707
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2708
-                    gettype($query_params)
2709
-                ),
2710
-                '4.6.0'
2711
-            );
2712
-            $query_params = array();
2713
-        }
2714
-        // we're just going to use the query params on the related model's normal get_all query,
2715
-        // except add a condition to say to match the current mod
2716
-        if (! isset($query_params['default_where_conditions'])) {
2717
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2718
-        }
2719
-        $this_model_name = $this->get_this_model_name();
2720
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2721
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2722
-        return $related_model->sum($query_params, $field_to_sum);
2723
-    }
2724
-
2725
-
2726
-
2727
-    /**
2728
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2729
-     * $modelObject
2730
-     *
2731
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2732
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2733
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2734
-     * @return EE_Base_Class
2735
-     * @throws EE_Error
2736
-     */
2737
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2738
-    {
2739
-        $query_params['limit'] = 1;
2740
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2741
-        if ($results) {
2742
-            return array_shift($results);
2743
-        }
2744
-        return null;
2745
-    }
2746
-
2747
-
2748
-
2749
-    /**
2750
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2751
-     *
2752
-     * @return string
2753
-     */
2754
-    public function get_this_model_name()
2755
-    {
2756
-        return str_replace("EEM_", "", get_class($this));
2757
-    }
2758
-
2759
-
2760
-
2761
-    /**
2762
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2763
-     *
2764
-     * @return EE_Any_Foreign_Model_Name_Field
2765
-     * @throws EE_Error
2766
-     */
2767
-    public function get_field_containing_related_model_name()
2768
-    {
2769
-        foreach ($this->field_settings(true) as $field) {
2770
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2771
-                $field_with_model_name = $field;
2772
-            }
2773
-        }
2774
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2775
-            throw new EE_Error(sprintf(
2776
-                esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2777
-                $this->get_this_model_name()
2778
-            ));
2779
-        }
2780
-        return $field_with_model_name;
2781
-    }
2782
-
2783
-
2784
-
2785
-    /**
2786
-     * Inserts a new entry into the database, for each table.
2787
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2788
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2789
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2790
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2791
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2792
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2793
-     *
2794
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2795
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2796
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2797
-     *                              of EEM_Base)
2798
-     * @return int|string new primary key on main table that got inserted
2799
-     * @throws EE_Error
2800
-     */
2801
-    public function insert($field_n_values)
2802
-    {
2803
-        /**
2804
-         * Filters the fields and their values before inserting an item using the models
2805
-         *
2806
-         * @param array    $fields_n_values keys are the fields and values are their new values
2807
-         * @param EEM_Base $model           the model used
2808
-         */
2809
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2810
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2811
-            $main_table = $this->_get_main_table();
2812
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2813
-            if ($new_id !== false) {
2814
-                foreach ($this->_get_other_tables() as $other_table) {
2815
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2816
-                }
2817
-            }
2818
-            /**
2819
-             * Done just after attempting to insert a new model object
2820
-             *
2821
-             * @param EEM_Base   $model           used
2822
-             * @param array      $fields_n_values fields and their values
2823
-             * @param int|string the              ID of the newly-inserted model object
2824
-             */
2825
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2826
-            return $new_id;
2827
-        }
2828
-        return false;
2829
-    }
2830
-
2831
-
2832
-
2833
-    /**
2834
-     * Checks that the result would satisfy the unique indexes on this model
2835
-     *
2836
-     * @param array  $field_n_values
2837
-     * @param string $action
2838
-     * @return boolean
2839
-     * @throws EE_Error
2840
-     */
2841
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2842
-    {
2843
-        foreach ($this->unique_indexes() as $index_name => $index) {
2844
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2845
-            if ($this->exists(array($uniqueness_where_params))) {
2846
-                EE_Error::add_error(
2847
-                    sprintf(
2848
-                        esc_html__(
2849
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2850
-                            "event_espresso"
2851
-                        ),
2852
-                        $action,
2853
-                        $this->_get_class_name(),
2854
-                        $index_name,
2855
-                        implode(",", $index->field_names()),
2856
-                        http_build_query($uniqueness_where_params)
2857
-                    ),
2858
-                    __FILE__,
2859
-                    __FUNCTION__,
2860
-                    __LINE__
2861
-                );
2862
-                return false;
2863
-            }
2864
-        }
2865
-        return true;
2866
-    }
2867
-
2868
-
2869
-
2870
-    /**
2871
-     * Checks the database for an item that conflicts (ie, if this item were
2872
-     * saved to the DB would break some uniqueness requirement, like a primary key
2873
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2874
-     * can be either an EE_Base_Class or an array of fields n values
2875
-     *
2876
-     * @param EE_Base_Class|array $obj_or_fields_array
2877
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2878
-     *                                                 when looking for conflicts
2879
-     *                                                 (ie, if false, we ignore the model object's primary key
2880
-     *                                                 when finding "conflicts". If true, it's also considered).
2881
-     *                                                 Only works for INT primary key,
2882
-     *                                                 STRING primary keys cannot be ignored
2883
-     * @throws EE_Error
2884
-     * @return EE_Base_Class|array
2885
-     */
2886
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2887
-    {
2888
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2889
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2890
-        } elseif (is_array($obj_or_fields_array)) {
2891
-            $fields_n_values = $obj_or_fields_array;
2892
-        } else {
2893
-            throw new EE_Error(
2894
-                sprintf(
2895
-                    esc_html__(
2896
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2897
-                        "event_espresso"
2898
-                    ),
2899
-                    get_class($this),
2900
-                    $obj_or_fields_array
2901
-                )
2902
-            );
2903
-        }
2904
-        $query_params = array();
2905
-        if (
2906
-            $this->has_primary_key_field()
2907
-            && ($include_primary_key
2908
-                || $this->get_primary_key_field()
2909
-                   instanceof
2910
-                   EE_Primary_Key_String_Field)
2911
-            && isset($fields_n_values[ $this->primary_key_name() ])
2912
-        ) {
2913
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2914
-        }
2915
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2916
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2917
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2918
-        }
2919
-        // if there is nothing to base this search on, then we shouldn't find anything
2920
-        if (empty($query_params)) {
2921
-            return array();
2922
-        }
2923
-        return $this->get_one($query_params);
2924
-    }
2925
-
2926
-
2927
-
2928
-    /**
2929
-     * Like count, but is optimized and returns a boolean instead of an int
2930
-     *
2931
-     * @param array $query_params
2932
-     * @return boolean
2933
-     * @throws EE_Error
2934
-     */
2935
-    public function exists($query_params)
2936
-    {
2937
-        $query_params['limit'] = 1;
2938
-        return $this->count($query_params) > 0;
2939
-    }
2940
-
2941
-
2942
-
2943
-    /**
2944
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2945
-     *
2946
-     * @param int|string $id
2947
-     * @return boolean
2948
-     * @throws EE_Error
2949
-     */
2950
-    public function exists_by_ID($id)
2951
-    {
2952
-        return $this->exists(
2953
-            array(
2954
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2955
-                array(
2956
-                    $this->primary_key_name() => $id,
2957
-                ),
2958
-            )
2959
-        );
2960
-    }
2961
-
2962
-
2963
-
2964
-    /**
2965
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2966
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2967
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2968
-     * on the main table)
2969
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2970
-     * cases where we want to call it directly rather than via insert().
2971
-     *
2972
-     * @access   protected
2973
-     * @param EE_Table_Base $table
2974
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2975
-     *                                       float
2976
-     * @param int           $new_id          for now we assume only int keys
2977
-     * @throws EE_Error
2978
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2979
-     * @return int ID of new row inserted, or FALSE on failure
2980
-     */
2981
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2982
-    {
2983
-        global $wpdb;
2984
-        $insertion_col_n_values = array();
2985
-        $format_for_insertion = array();
2986
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2987
-        foreach ($fields_on_table as $field_name => $field_obj) {
2988
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2989
-            if ($field_obj->is_auto_increment()) {
2990
-                continue;
2991
-            }
2992
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2993
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2994
-            if ($prepared_value !== null) {
2995
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2996
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2997
-            }
2998
-        }
2999
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3000
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3001
-            // so add the fk to the main table as a column
3002
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3003
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3004
-        }
3005
-        // insert the new entry
3006
-        $result = $this->_do_wpdb_query(
3007
-            'insert',
3008
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3009
-        );
3010
-        if ($result === false) {
3011
-            return false;
3012
-        }
3013
-        // ok, now what do we return for the ID of the newly-inserted thing?
3014
-        if ($this->has_primary_key_field()) {
3015
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3016
-                return $wpdb->insert_id;
3017
-            }
3018
-            // it's not an auto-increment primary key, so
3019
-            // it must have been supplied
3020
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3021
-        }
3022
-        // we can't return a  primary key because there is none. instead return
3023
-        // a unique string indicating this model
3024
-        return $this->get_index_primary_key_string($fields_n_values);
3025
-    }
3026
-
3027
-
3028
-
3029
-    /**
3030
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3031
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3032
-     * and there is no default, we pass it along. WPDB will take care of it)
3033
-     *
3034
-     * @param EE_Model_Field_Base $field_obj
3035
-     * @param array               $fields_n_values
3036
-     * @return mixed string|int|float depending on what the table column will be expecting
3037
-     * @throws EE_Error
3038
-     */
3039
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3040
-    {
3041
-        // if this field doesn't allow nullable, don't allow it
3042
-        if (
3043
-            ! $field_obj->is_nullable()
3044
-            && (
3045
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3046
-                || $fields_n_values[ $field_obj->get_name() ] === null
3047
-            )
3048
-        ) {
3049
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3050
-        }
3051
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3052
-            ? $fields_n_values[ $field_obj->get_name() ]
3053
-            : null;
3054
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3055
-    }
3056
-
3057
-
3058
-
3059
-    /**
3060
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3061
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3062
-     * the field's prepare_for_set() method.
3063
-     *
3064
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3065
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3066
-     *                                   top of file)
3067
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3068
-     *                                   $value is a custom selection
3069
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3070
-     */
3071
-    private function _prepare_value_for_use_in_db($value, $field)
3072
-    {
3073
-        if ($field && $field instanceof EE_Model_Field_Base) {
3074
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3075
-            switch ($this->_values_already_prepared_by_model_object) {
3076
-                /** @noinspection PhpMissingBreakStatementInspection */
3077
-                case self::not_prepared_by_model_object:
3078
-                    $value = $field->prepare_for_set($value);
3079
-                // purposefully left out "return"
3080
-                case self::prepared_by_model_object:
3081
-                    /** @noinspection SuspiciousAssignmentsInspection */
3082
-                    $value = $field->prepare_for_use_in_db($value);
3083
-                case self::prepared_for_use_in_db:
3084
-                    // leave the value alone
3085
-            }
3086
-            return $value;
3087
-            // phpcs:enable
3088
-        }
3089
-        return $value;
3090
-    }
3091
-
3092
-
3093
-
3094
-    /**
3095
-     * Returns the main table on this model
3096
-     *
3097
-     * @return EE_Primary_Table
3098
-     * @throws EE_Error
3099
-     */
3100
-    protected function _get_main_table()
3101
-    {
3102
-        foreach ($this->_tables as $table) {
3103
-            if ($table instanceof EE_Primary_Table) {
3104
-                return $table;
3105
-            }
3106
-        }
3107
-        throw new EE_Error(sprintf(esc_html__(
3108
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3109
-            'event_espresso'
3110
-        ), get_class($this)));
3111
-    }
3112
-
3113
-
3114
-
3115
-    /**
3116
-     * table
3117
-     * returns EE_Primary_Table table name
3118
-     *
3119
-     * @return string
3120
-     * @throws EE_Error
3121
-     */
3122
-    public function table()
3123
-    {
3124
-        return $this->_get_main_table()->get_table_name();
3125
-    }
3126
-
3127
-
3128
-
3129
-    /**
3130
-     * table
3131
-     * returns first EE_Secondary_Table table name
3132
-     *
3133
-     * @return string
3134
-     */
3135
-    public function second_table()
3136
-    {
3137
-        // grab second table from tables array
3138
-        $second_table = end($this->_tables);
3139
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3140
-    }
3141
-
3142
-
3143
-
3144
-    /**
3145
-     * get_table_obj_by_alias
3146
-     * returns table name given it's alias
3147
-     *
3148
-     * @param string $table_alias
3149
-     * @return EE_Primary_Table | EE_Secondary_Table
3150
-     */
3151
-    public function get_table_obj_by_alias($table_alias = '')
3152
-    {
3153
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3154
-    }
3155
-
3156
-
3157
-
3158
-    /**
3159
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3160
-     *
3161
-     * @return EE_Secondary_Table[]
3162
-     */
3163
-    protected function _get_other_tables()
3164
-    {
3165
-        $other_tables = array();
3166
-        foreach ($this->_tables as $table_alias => $table) {
3167
-            if ($table instanceof EE_Secondary_Table) {
3168
-                $other_tables[ $table_alias ] = $table;
3169
-            }
3170
-        }
3171
-        return $other_tables;
3172
-    }
3173
-
3174
-
3175
-
3176
-    /**
3177
-     * Finds all the fields that correspond to the given table
3178
-     *
3179
-     * @param string $table_alias , array key in EEM_Base::_tables
3180
-     * @return EE_Model_Field_Base[]
3181
-     */
3182
-    public function _get_fields_for_table($table_alias)
3183
-    {
3184
-        return $this->_fields[ $table_alias ];
3185
-    }
3186
-
3187
-
3188
-
3189
-    /**
3190
-     * Recurses through all the where parameters, and finds all the related models we'll need
3191
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3192
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3193
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3194
-     * related Registration, Transaction, and Payment models.
3195
-     *
3196
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3197
-     * @return EE_Model_Query_Info_Carrier
3198
-     * @throws EE_Error
3199
-     */
3200
-    public function _extract_related_models_from_query($query_params)
3201
-    {
3202
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3203
-        if (array_key_exists(0, $query_params)) {
3204
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3205
-        }
3206
-        if (array_key_exists('group_by', $query_params)) {
3207
-            if (is_array($query_params['group_by'])) {
3208
-                $this->_extract_related_models_from_sub_params_array_values(
3209
-                    $query_params['group_by'],
3210
-                    $query_info_carrier,
3211
-                    'group_by'
3212
-                );
3213
-            } elseif (! empty($query_params['group_by'])) {
3214
-                $this->_extract_related_model_info_from_query_param(
3215
-                    $query_params['group_by'],
3216
-                    $query_info_carrier,
3217
-                    'group_by'
3218
-                );
3219
-            }
3220
-        }
3221
-        if (array_key_exists('having', $query_params)) {
3222
-            $this->_extract_related_models_from_sub_params_array_keys(
3223
-                $query_params[0],
3224
-                $query_info_carrier,
3225
-                'having'
3226
-            );
3227
-        }
3228
-        if (array_key_exists('order_by', $query_params)) {
3229
-            if (is_array($query_params['order_by'])) {
3230
-                $this->_extract_related_models_from_sub_params_array_keys(
3231
-                    $query_params['order_by'],
3232
-                    $query_info_carrier,
3233
-                    'order_by'
3234
-                );
3235
-            } elseif (! empty($query_params['order_by'])) {
3236
-                $this->_extract_related_model_info_from_query_param(
3237
-                    $query_params['order_by'],
3238
-                    $query_info_carrier,
3239
-                    'order_by'
3240
-                );
3241
-            }
3242
-        }
3243
-        if (array_key_exists('force_join', $query_params)) {
3244
-            $this->_extract_related_models_from_sub_params_array_values(
3245
-                $query_params['force_join'],
3246
-                $query_info_carrier,
3247
-                'force_join'
3248
-            );
3249
-        }
3250
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3251
-        return $query_info_carrier;
3252
-    }
3253
-
3254
-
3255
-
3256
-    /**
3257
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3258
-     *
3259
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3260
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3261
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3262
-     * @throws EE_Error
3263
-     * @return \EE_Model_Query_Info_Carrier
3264
-     */
3265
-    private function _extract_related_models_from_sub_params_array_keys(
3266
-        $sub_query_params,
3267
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3268
-        $query_param_type
3269
-    ) {
3270
-        if (! empty($sub_query_params)) {
3271
-            $sub_query_params = (array) $sub_query_params;
3272
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3273
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3274
-                $this->_extract_related_model_info_from_query_param(
3275
-                    $param,
3276
-                    $model_query_info_carrier,
3277
-                    $query_param_type
3278
-                );
3279
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3280
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3281
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3282
-                // of array('Registration.TXN_ID'=>23)
3283
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
-                    if (! is_array($possibly_array_of_params)) {
3286
-                        throw new EE_Error(sprintf(
3287
-                            esc_html__(
3288
-                                "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'))",
3289
-                                "event_espresso"
3290
-                            ),
3291
-                            $param,
3292
-                            $possibly_array_of_params
3293
-                        ));
3294
-                    }
3295
-                    $this->_extract_related_models_from_sub_params_array_keys(
3296
-                        $possibly_array_of_params,
3297
-                        $model_query_info_carrier,
3298
-                        $query_param_type
3299
-                    );
3300
-                } elseif (
3301
-                    $query_param_type === 0 // ie WHERE
3302
-                          && is_array($possibly_array_of_params)
3303
-                          && isset($possibly_array_of_params[2])
3304
-                          && $possibly_array_of_params[2] == true
3305
-                ) {
3306
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3307
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3308
-                    // from which we should extract query parameters!
3309
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3310
-                        throw new EE_Error(sprintf(esc_html__(
3311
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3312
-                            "event_espresso"
3313
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3314
-                    }
3315
-                    $this->_extract_related_model_info_from_query_param(
3316
-                        $possibly_array_of_params[1],
3317
-                        $model_query_info_carrier,
3318
-                        $query_param_type
3319
-                    );
3320
-                }
3321
-            }
3322
-        }
3323
-        return $model_query_info_carrier;
3324
-    }
3325
-
3326
-
3327
-
3328
-    /**
3329
-     * For extracting related models from forced_joins, where the array values contain the info about what
3330
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3331
-     *
3332
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3333
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3334
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3335
-     * @throws EE_Error
3336
-     * @return \EE_Model_Query_Info_Carrier
3337
-     */
3338
-    private function _extract_related_models_from_sub_params_array_values(
3339
-        $sub_query_params,
3340
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3341
-        $query_param_type
3342
-    ) {
3343
-        if (! empty($sub_query_params)) {
3344
-            if (! is_array($sub_query_params)) {
3345
-                throw new EE_Error(sprintf(
3346
-                    esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3347
-                    $sub_query_params
3348
-                ));
3349
-            }
3350
-            foreach ($sub_query_params as $param) {
3351
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3352
-                $this->_extract_related_model_info_from_query_param(
3353
-                    $param,
3354
-                    $model_query_info_carrier,
3355
-                    $query_param_type
3356
-                );
3357
-            }
3358
-        }
3359
-        return $model_query_info_carrier;
3360
-    }
3361
-
3362
-
3363
-    /**
3364
-     * Extract all the query parts from  model query params
3365
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3366
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3367
-     * but use them in a different order. Eg, we need to know what models we are querying
3368
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3369
-     * other models before we can finalize the where clause SQL.
3370
-     *
3371
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3372
-     * @throws EE_Error
3373
-     * @return EE_Model_Query_Info_Carrier
3374
-     * @throws ModelConfigurationException
3375
-     */
3376
-    public function _create_model_query_info_carrier($query_params)
3377
-    {
3378
-        if (! is_array($query_params)) {
3379
-            EE_Error::doing_it_wrong(
3380
-                'EEM_Base::_create_model_query_info_carrier',
3381
-                sprintf(
3382
-                    esc_html__(
3383
-                        '$query_params should be an array, you passed a variable of type %s',
3384
-                        'event_espresso'
3385
-                    ),
3386
-                    gettype($query_params)
3387
-                ),
3388
-                '4.6.0'
3389
-            );
3390
-            $query_params = array();
3391
-        }
3392
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3393
-        // first check if we should alter the query to account for caps or not
3394
-        // because the caps might require us to do extra joins
3395
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3396
-            $query_params[0] = array_replace_recursive(
3397
-                $query_params[0],
3398
-                $this->caps_where_conditions(
3399
-                    $query_params['caps']
3400
-                )
3401
-            );
3402
-        }
3403
-
3404
-        // check if we should alter the query to remove data related to protected
3405
-        // custom post types
3406
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3407
-            $where_param_key_for_password = $this->modelChainAndPassword();
3408
-            // only include if related to a cpt where no password has been set
3409
-            $query_params[0]['OR*nopassword'] = array(
3410
-                $where_param_key_for_password => '',
3411
-                $where_param_key_for_password . '*' => array('IS_NULL')
3412
-            );
3413
-        }
3414
-        $query_object = $this->_extract_related_models_from_query($query_params);
3415
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3416
-        foreach ($query_params[0] as $key => $value) {
3417
-            if (is_int($key)) {
3418
-                throw new EE_Error(
3419
-                    sprintf(
3420
-                        esc_html__(
3421
-                            "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.",
3422
-                            "event_espresso"
3423
-                        ),
3424
-                        $key,
3425
-                        var_export($value, true),
3426
-                        var_export($query_params, true),
3427
-                        get_class($this)
3428
-                    )
3429
-                );
3430
-            }
3431
-        }
3432
-        if (
3433
-            array_key_exists('default_where_conditions', $query_params)
3434
-            && ! empty($query_params['default_where_conditions'])
3435
-        ) {
3436
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3437
-        } else {
3438
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3439
-        }
3440
-        $query_params[0] = array_merge(
3441
-            $this->_get_default_where_conditions_for_models_in_query(
3442
-                $query_object,
3443
-                $use_default_where_conditions,
3444
-                $query_params[0]
3445
-            ),
3446
-            $query_params[0]
3447
-        );
3448
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3449
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3450
-        // So we need to setup a subquery and use that for the main join.
3451
-        // Note for now this only works on the primary table for the model.
3452
-        // So for instance, you could set the limit array like this:
3453
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3454
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3455
-            $query_object->set_main_model_join_sql(
3456
-                $this->_construct_limit_join_select(
3457
-                    $query_params['on_join_limit'][0],
3458
-                    $query_params['on_join_limit'][1]
3459
-                )
3460
-            );
3461
-        }
3462
-        // set limit
3463
-        if (array_key_exists('limit', $query_params)) {
3464
-            if (is_array($query_params['limit'])) {
3465
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3466
-                    $e = sprintf(
3467
-                        esc_html__(
3468
-                            "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)",
3469
-                            "event_espresso"
3470
-                        ),
3471
-                        http_build_query($query_params['limit'])
3472
-                    );
3473
-                    throw new EE_Error($e . "|" . $e);
3474
-                }
3475
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3476
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3477
-            } elseif (! empty($query_params['limit'])) {
3478
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3479
-            }
3480
-        }
3481
-        // set order by
3482
-        if (array_key_exists('order_by', $query_params)) {
3483
-            if (is_array($query_params['order_by'])) {
3484
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3485
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3486
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3487
-                if (array_key_exists('order', $query_params)) {
3488
-                    throw new EE_Error(
3489
-                        sprintf(
3490
-                            esc_html__(
3491
-                                "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 ",
3492
-                                "event_espresso"
3493
-                            ),
3494
-                            get_class($this),
3495
-                            implode(", ", array_keys($query_params['order_by'])),
3496
-                            implode(", ", $query_params['order_by']),
3497
-                            $query_params['order']
3498
-                        )
3499
-                    );
3500
-                }
3501
-                $this->_extract_related_models_from_sub_params_array_keys(
3502
-                    $query_params['order_by'],
3503
-                    $query_object,
3504
-                    'order_by'
3505
-                );
3506
-                // assume it's an array of fields to order by
3507
-                $order_array = array();
3508
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3509
-                    $order = $this->_extract_order($order);
3510
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3511
-                }
3512
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3513
-            } elseif (! empty($query_params['order_by'])) {
3514
-                $this->_extract_related_model_info_from_query_param(
3515
-                    $query_params['order_by'],
3516
-                    $query_object,
3517
-                    'order',
3518
-                    $query_params['order_by']
3519
-                );
3520
-                $order = isset($query_params['order'])
3521
-                    ? $this->_extract_order($query_params['order'])
3522
-                    : 'DESC';
3523
-                $query_object->set_order_by_sql(
3524
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3525
-                );
3526
-            }
3527
-        }
3528
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3529
-        if (
3530
-            ! array_key_exists('order_by', $query_params)
3531
-            && array_key_exists('order', $query_params)
3532
-            && ! empty($query_params['order'])
3533
-        ) {
3534
-            $pk_field = $this->get_primary_key_field();
3535
-            $order = $this->_extract_order($query_params['order']);
3536
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3537
-        }
3538
-        // set group by
3539
-        if (array_key_exists('group_by', $query_params)) {
3540
-            if (is_array($query_params['group_by'])) {
3541
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3542
-                $group_by_array = array();
3543
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3544
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3545
-                }
3546
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3547
-            } elseif (! empty($query_params['group_by'])) {
3548
-                $query_object->set_group_by_sql(
3549
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3550
-                );
3551
-            }
3552
-        }
3553
-        // set having
3554
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3555
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3556
-        }
3557
-        // now, just verify they didn't pass anything wack
3558
-        foreach ($query_params as $query_key => $query_value) {
3559
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3560
-                throw new EE_Error(
3561
-                    sprintf(
3562
-                        esc_html__(
3563
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3564
-                            'event_espresso'
3565
-                        ),
3566
-                        $query_key,
3567
-                        get_class($this),
3568
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3569
-                        implode(',', $this->_allowed_query_params)
3570
-                    )
3571
-                );
3572
-            }
3573
-        }
3574
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3575
-        if (empty($main_model_join_sql)) {
3576
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3577
-        }
3578
-        return $query_object;
3579
-    }
3580
-
3581
-
3582
-
3583
-    /**
3584
-     * Gets the where conditions that should be imposed on the query based on the
3585
-     * context (eg reading frontend, backend, edit or delete).
3586
-     *
3587
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3588
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3589
-     * @throws EE_Error
3590
-     */
3591
-    public function caps_where_conditions($context = self::caps_read)
3592
-    {
3593
-        EEM_Base::verify_is_valid_cap_context($context);
3594
-        $cap_where_conditions = array();
3595
-        $cap_restrictions = $this->caps_missing($context);
3596
-        /**
3597
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3598
-         */
3599
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3600
-            $cap_where_conditions = array_replace_recursive(
3601
-                $cap_where_conditions,
3602
-                $restriction_if_no_cap->get_default_where_conditions()
3603
-            );
3604
-        }
3605
-        return apply_filters(
3606
-            'FHEE__EEM_Base__caps_where_conditions__return',
3607
-            $cap_where_conditions,
3608
-            $this,
3609
-            $context,
3610
-            $cap_restrictions
3611
-        );
3612
-    }
3613
-
3614
-
3615
-
3616
-    /**
3617
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3618
-     * otherwise throws an exception
3619
-     *
3620
-     * @param string $should_be_order_string
3621
-     * @return string either ASC, asc, DESC or desc
3622
-     * @throws EE_Error
3623
-     */
3624
-    private function _extract_order($should_be_order_string)
3625
-    {
3626
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3627
-            return $should_be_order_string;
3628
-        }
3629
-        throw new EE_Error(
3630
-            sprintf(
3631
-                esc_html__(
3632
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3633
-                    "event_espresso"
3634
-                ),
3635
-                get_class($this),
3636
-                $should_be_order_string
3637
-            )
3638
-        );
3639
-    }
3640
-
3641
-
3642
-
3643
-    /**
3644
-     * Looks at all the models which are included in this query, and asks each
3645
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3646
-     * so they can be merged
3647
-     *
3648
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3649
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3650
-     *                                                                  'none' means NO default where conditions will
3651
-     *                                                                  be used AT ALL during this query.
3652
-     *                                                                  'other_models_only' means default where
3653
-     *                                                                  conditions from other models will be used, but
3654
-     *                                                                  not for this primary model. 'all', the default,
3655
-     *                                                                  means default where conditions will apply as
3656
-     *                                                                  normal
3657
-     * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3658
-     * @throws EE_Error
3659
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3660
-     */
3661
-    private function _get_default_where_conditions_for_models_in_query(
3662
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3663
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3664
-        $where_query_params = array()
3665
-    ) {
3666
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3667
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3668
-            throw new EE_Error(sprintf(
3669
-                esc_html__(
3670
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3671
-                    "event_espresso"
3672
-                ),
3673
-                $use_default_where_conditions,
3674
-                implode(", ", $allowed_used_default_where_conditions_values)
3675
-            ));
3676
-        }
3677
-        $universal_query_params = array();
3678
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3679
-            $universal_query_params = $this->_get_default_where_conditions();
3680
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3681
-            $universal_query_params = $this->_get_minimum_where_conditions();
3682
-        }
3683
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3684
-            $related_model = $this->get_related_model_obj($model_name);
3685
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3686
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3687
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3688
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3689
-            } else {
3690
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3691
-                continue;
3692
-            }
3693
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3694
-                $related_model_universal_where_params,
3695
-                $where_query_params,
3696
-                $related_model,
3697
-                $model_relation_path
3698
-            );
3699
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3700
-                $universal_query_params,
3701
-                $overrides
3702
-            );
3703
-        }
3704
-        return $universal_query_params;
3705
-    }
3706
-
3707
-
3708
-
3709
-    /**
3710
-     * Determines whether or not we should use default where conditions for the model in question
3711
-     * (this model, or other related models).
3712
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3713
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3714
-     * We should use default where conditions on related models when they requested to use default where conditions
3715
-     * on all models, or specifically just on other related models
3716
-     * @param      $default_where_conditions_value
3717
-     * @param bool $for_this_model false means this is for OTHER related models
3718
-     * @return bool
3719
-     */
3720
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3721
-    {
3722
-        return (
3723
-                   $for_this_model
3724
-                   && in_array(
3725
-                       $default_where_conditions_value,
3726
-                       array(
3727
-                           EEM_Base::default_where_conditions_all,
3728
-                           EEM_Base::default_where_conditions_this_only,
3729
-                           EEM_Base::default_where_conditions_minimum_others,
3730
-                       ),
3731
-                       true
3732
-                   )
3733
-               )
3734
-               || (
3735
-                   ! $for_this_model
3736
-                   && in_array(
3737
-                       $default_where_conditions_value,
3738
-                       array(
3739
-                           EEM_Base::default_where_conditions_all,
3740
-                           EEM_Base::default_where_conditions_others_only,
3741
-                       ),
3742
-                       true
3743
-                   )
3744
-               );
3745
-    }
3746
-
3747
-    /**
3748
-     * Determines whether or not we should use default minimum conditions for the model in question
3749
-     * (this model, or other related models).
3750
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3751
-     * where conditions.
3752
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3753
-     * on this model or others
3754
-     * @param      $default_where_conditions_value
3755
-     * @param bool $for_this_model false means this is for OTHER related models
3756
-     * @return bool
3757
-     */
3758
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3759
-    {
3760
-        return (
3761
-                   $for_this_model
3762
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3763
-               )
3764
-               || (
3765
-                   ! $for_this_model
3766
-                   && in_array(
3767
-                       $default_where_conditions_value,
3768
-                       array(
3769
-                           EEM_Base::default_where_conditions_minimum_others,
3770
-                           EEM_Base::default_where_conditions_minimum_all,
3771
-                       ),
3772
-                       true
3773
-                   )
3774
-               );
3775
-    }
3776
-
3777
-
3778
-    /**
3779
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3780
-     * then we also add a special where condition which allows for that model's primary key
3781
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3782
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3783
-     *
3784
-     * @param array    $default_where_conditions
3785
-     * @param array    $provided_where_conditions
3786
-     * @param EEM_Base $model
3787
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3788
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3789
-     * @throws EE_Error
3790
-     */
3791
-    private function _override_defaults_or_make_null_friendly(
3792
-        $default_where_conditions,
3793
-        $provided_where_conditions,
3794
-        $model,
3795
-        $model_relation_path
3796
-    ) {
3797
-        $null_friendly_where_conditions = array();
3798
-        $none_overridden = true;
3799
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3800
-        foreach ($default_where_conditions as $key => $val) {
3801
-            if (isset($provided_where_conditions[ $key ])) {
3802
-                $none_overridden = false;
3803
-            } else {
3804
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3805
-            }
3806
-        }
3807
-        if ($none_overridden && $default_where_conditions) {
3808
-            if ($model->has_primary_key_field()) {
3809
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3810
-                                                                                . "."
3811
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3812
-            }/*else{
39
+	/**
40
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
41
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
42
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
43
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
44
+	 *
45
+	 * @var boolean
46
+	 */
47
+	private $_values_already_prepared_by_model_object = 0;
48
+
49
+	/**
50
+	 * when $_values_already_prepared_by_model_object equals this, we assume
51
+	 * the data is just like form input that needs to have the model fields'
52
+	 * prepare_for_set and prepare_for_use_in_db called on it
53
+	 */
54
+	const not_prepared_by_model_object = 0;
55
+
56
+	/**
57
+	 * when $_values_already_prepared_by_model_object equals this, we
58
+	 * assume this value is coming from a model object and doesn't need to have
59
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
60
+	 */
61
+	const prepared_by_model_object = 1;
62
+
63
+	/**
64
+	 * when $_values_already_prepared_by_model_object equals this, we assume
65
+	 * the values are already to be used in the database (ie no processing is done
66
+	 * on them by the model's fields)
67
+	 */
68
+	const prepared_for_use_in_db = 2;
69
+
70
+
71
+	protected $singular_item = 'Item';
72
+
73
+	protected $plural_item   = 'Items';
74
+
75
+	/**
76
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
77
+	 */
78
+	protected $_tables;
79
+
80
+	/**
81
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
82
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
83
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
84
+	 *
85
+	 * @var \EE_Model_Field_Base[][] $_fields
86
+	 */
87
+	protected $_fields;
88
+
89
+	/**
90
+	 * array of different kinds of relations
91
+	 *
92
+	 * @var \EE_Model_Relation_Base[] $_model_relations
93
+	 */
94
+	protected $_model_relations;
95
+
96
+	/**
97
+	 * @var \EE_Index[] $_indexes
98
+	 */
99
+	protected $_indexes = array();
100
+
101
+	/**
102
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
103
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
104
+	 * by setting the same columns as used in these queries in the query yourself.
105
+	 *
106
+	 * @var EE_Default_Where_Conditions
107
+	 */
108
+	protected $_default_where_conditions_strategy;
109
+
110
+	/**
111
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
112
+	 * This is particularly useful when you want something between 'none' and 'default'
113
+	 *
114
+	 * @var EE_Default_Where_Conditions
115
+	 */
116
+	protected $_minimum_where_conditions_strategy;
117
+
118
+	/**
119
+	 * String describing how to find the "owner" of this model's objects.
120
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
121
+	 * But when there isn't, this indicates which related model, or transiently-related model,
122
+	 * has the foreign key to the wp_users table.
123
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
124
+	 * related to events, and events have a foreign key to wp_users.
125
+	 * On EEM_Transaction, this would be 'Transaction.Event'
126
+	 *
127
+	 * @var string
128
+	 */
129
+	protected $_model_chain_to_wp_user = '';
130
+
131
+	/**
132
+	 * String describing how to find the model with a password controlling access to this model. This property has the
133
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
134
+	 * This value is the path of models to follow to arrive at the model with the password field.
135
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
136
+	 * model with a password that should affect reading this on the front-end.
137
+	 * Eg this is an empty string for the Event model because it has a password.
138
+	 * This is null for the Registration model, because its event's password has no bearing on whether
139
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
140
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
141
+	 * should hide tickets for datetimes for events that have a password set.
142
+	 * @var string |null
143
+	 */
144
+	protected $model_chain_to_password = null;
145
+
146
+	/**
147
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
148
+	 * don't need it (particularly CPT models)
149
+	 *
150
+	 * @var bool
151
+	 */
152
+	protected $_ignore_where_strategy = false;
153
+
154
+	/**
155
+	 * String used in caps relating to this model. Eg, if the caps relating to this
156
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
157
+	 *
158
+	 * @var string. If null it hasn't been initialized yet. If false then we
159
+	 * have indicated capabilities don't apply to this
160
+	 */
161
+	protected $_caps_slug = null;
162
+
163
+	/**
164
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
165
+	 * and next-level keys are capability names, and each's value is a
166
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
167
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
168
+	 * and then each capability in the corresponding sub-array that they're missing
169
+	 * adds the where conditions onto the query.
170
+	 *
171
+	 * @var array
172
+	 */
173
+	protected $_cap_restrictions = array(
174
+		self::caps_read       => array(),
175
+		self::caps_read_admin => array(),
176
+		self::caps_edit       => array(),
177
+		self::caps_delete     => array(),
178
+	);
179
+
180
+	/**
181
+	 * Array defining which cap restriction generators to use to create default
182
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
183
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
184
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
185
+	 * automatically set this to false (not just null).
186
+	 *
187
+	 * @var EE_Restriction_Generator_Base[]
188
+	 */
189
+	protected $_cap_restriction_generators = array();
190
+
191
+	/**
192
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
193
+	 */
194
+	const caps_read       = 'read';
195
+
196
+	const caps_read_admin = 'read_admin';
197
+
198
+	const caps_edit       = 'edit';
199
+
200
+	const caps_delete     = 'delete';
201
+
202
+	/**
203
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
204
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
205
+	 * maps to 'read' because when looking for relevant permissions we're going to use
206
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
207
+	 *
208
+	 * @var array
209
+	 */
210
+	protected $_cap_contexts_to_cap_action_map = array(
211
+		self::caps_read       => 'read',
212
+		self::caps_read_admin => 'read',
213
+		self::caps_edit       => 'edit',
214
+		self::caps_delete     => 'delete',
215
+	);
216
+
217
+	/**
218
+	 * Timezone
219
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
220
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
221
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
222
+	 * EE_Datetime_Field data type will have access to it.
223
+	 *
224
+	 * @var string
225
+	 */
226
+	protected $_timezone;
227
+
228
+
229
+	/**
230
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
231
+	 * multisite.
232
+	 *
233
+	 * @var int
234
+	 */
235
+	protected static $_model_query_blog_id;
236
+
237
+	/**
238
+	 * A copy of _fields, except the array keys are the model names pointed to by
239
+	 * the field
240
+	 *
241
+	 * @var EE_Model_Field_Base[]
242
+	 */
243
+	private $_cache_foreign_key_to_fields = array();
244
+
245
+	/**
246
+	 * Cached list of all the fields on the model, indexed by their name
247
+	 *
248
+	 * @var EE_Model_Field_Base[]
249
+	 */
250
+	private $_cached_fields = null;
251
+
252
+	/**
253
+	 * Cached list of all the fields on the model, except those that are
254
+	 * marked as only pertinent to the database
255
+	 *
256
+	 * @var EE_Model_Field_Base[]
257
+	 */
258
+	private $_cached_fields_non_db_only = null;
259
+
260
+	/**
261
+	 * A cached reference to the primary key for quick lookup
262
+	 *
263
+	 * @var EE_Model_Field_Base
264
+	 */
265
+	private $_primary_key_field = null;
266
+
267
+	/**
268
+	 * Flag indicating whether this model has a primary key or not
269
+	 *
270
+	 * @var boolean
271
+	 */
272
+	protected $_has_primary_key_field = null;
273
+
274
+	/**
275
+	 * array in the format:  [ FK alias => full PK ]
276
+	 * where keys are local column name aliases for foreign keys
277
+	 * and values are the fully qualified column name for the primary key they represent
278
+	 *  ex:
279
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
280
+	 *
281
+	 * @var array $foreign_key_aliases
282
+	 */
283
+	protected $foreign_key_aliases = [];
284
+
285
+	/**
286
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
287
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
288
+	 * This should be true for models that deal with data that should exist independent of EE.
289
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
290
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
291
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
292
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
293
+	 * @var boolean
294
+	 */
295
+	protected $_wp_core_model = false;
296
+
297
+	/**
298
+	 * @var bool stores whether this model has a password field or not.
299
+	 * null until initialized by hasPasswordField()
300
+	 */
301
+	protected $has_password_field;
302
+
303
+	/**
304
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
305
+	 */
306
+	protected $password_field;
307
+
308
+	/**
309
+	 *    List of valid operators that can be used for querying.
310
+	 * The keys are all operators we'll accept, the values are the real SQL
311
+	 * operators used
312
+	 *
313
+	 * @var array
314
+	 */
315
+	protected $_valid_operators = array(
316
+		'='           => '=',
317
+		'<='          => '<=',
318
+		'<'           => '<',
319
+		'>='          => '>=',
320
+		'>'           => '>',
321
+		'!='          => '!=',
322
+		'LIKE'        => 'LIKE',
323
+		'like'        => 'LIKE',
324
+		'NOT_LIKE'    => 'NOT LIKE',
325
+		'not_like'    => 'NOT LIKE',
326
+		'NOT LIKE'    => 'NOT LIKE',
327
+		'not like'    => 'NOT LIKE',
328
+		'IN'          => 'IN',
329
+		'in'          => 'IN',
330
+		'NOT_IN'      => 'NOT IN',
331
+		'not_in'      => 'NOT IN',
332
+		'NOT IN'      => 'NOT IN',
333
+		'not in'      => 'NOT IN',
334
+		'between'     => 'BETWEEN',
335
+		'BETWEEN'     => 'BETWEEN',
336
+		'IS_NOT_NULL' => 'IS NOT NULL',
337
+		'is_not_null' => 'IS NOT NULL',
338
+		'IS NOT NULL' => 'IS NOT NULL',
339
+		'is not null' => 'IS NOT NULL',
340
+		'IS_NULL'     => 'IS NULL',
341
+		'is_null'     => 'IS NULL',
342
+		'IS NULL'     => 'IS NULL',
343
+		'is null'     => 'IS NULL',
344
+		'REGEXP'      => 'REGEXP',
345
+		'regexp'      => 'REGEXP',
346
+		'NOT_REGEXP'  => 'NOT REGEXP',
347
+		'not_regexp'  => 'NOT REGEXP',
348
+		'NOT REGEXP'  => 'NOT REGEXP',
349
+		'not regexp'  => 'NOT REGEXP',
350
+	);
351
+
352
+	/**
353
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
354
+	 *
355
+	 * @var array
356
+	 */
357
+	protected $_in_style_operators = array('IN', 'NOT IN');
358
+
359
+	/**
360
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
361
+	 * '12-31-2012'"
362
+	 *
363
+	 * @var array
364
+	 */
365
+	protected $_between_style_operators = array('BETWEEN');
366
+
367
+	/**
368
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
369
+	 * @var array
370
+	 */
371
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
372
+	/**
373
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
374
+	 * on a join table.
375
+	 *
376
+	 * @var array
377
+	 */
378
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
379
+
380
+	/**
381
+	 * Allowed values for $query_params['order'] for ordering in queries
382
+	 *
383
+	 * @var array
384
+	 */
385
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
386
+
387
+	/**
388
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
389
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
390
+	 *
391
+	 * @var array
392
+	 */
393
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
394
+
395
+	/**
396
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
397
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
398
+	 *
399
+	 * @var array
400
+	 */
401
+	private $_allowed_query_params = array(
402
+		0,
403
+		'limit',
404
+		'order_by',
405
+		'group_by',
406
+		'having',
407
+		'force_join',
408
+		'order',
409
+		'on_join_limit',
410
+		'default_where_conditions',
411
+		'caps',
412
+		'extra_selects',
413
+		'exclude_protected',
414
+	);
415
+
416
+	/**
417
+	 * All the data types that can be used in $wpdb->prepare statements.
418
+	 *
419
+	 * @var array
420
+	 */
421
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
422
+
423
+	/**
424
+	 * @var EE_Registry $EE
425
+	 */
426
+	protected $EE = null;
427
+
428
+
429
+	/**
430
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
431
+	 *
432
+	 * @var int
433
+	 */
434
+	protected $_show_next_x_db_queries = 0;
435
+
436
+	/**
437
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
438
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
439
+	 * WHERE, GROUP_BY, etc.
440
+	 *
441
+	 * @var CustomSelects
442
+	 */
443
+	protected $_custom_selections = array();
444
+
445
+	/**
446
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
447
+	 * caches every model object we've fetched from the DB on this request
448
+	 *
449
+	 * @var array
450
+	 */
451
+	protected $_entity_map;
452
+
453
+	/**
454
+	 * @var LoaderInterface $loader
455
+	 */
456
+	protected static $loader;
457
+
458
+
459
+	/**
460
+	 * constant used to show EEM_Base has not yet verified the db on this http request
461
+	 */
462
+	const db_verified_none = 0;
463
+
464
+	/**
465
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
466
+	 * but not the addons' dbs
467
+	 */
468
+	const db_verified_core = 1;
469
+
470
+	/**
471
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
472
+	 * the EE core db too)
473
+	 */
474
+	const db_verified_addons = 2;
475
+
476
+	/**
477
+	 * indicates whether an EEM_Base child has already re-verified the DB
478
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
479
+	 * looking like EEM_Base::db_verified_*
480
+	 *
481
+	 * @var int - 0 = none, 1 = core, 2 = addons
482
+	 */
483
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
484
+
485
+	/**
486
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
487
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
488
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
489
+	 */
490
+	const default_where_conditions_all = 'all';
491
+
492
+	/**
493
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
494
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
495
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
496
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
497
+	 *        models which share tables with other models, this can return data for the wrong model.
498
+	 */
499
+	const default_where_conditions_this_only = 'this_model_only';
500
+
501
+	/**
502
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
503
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
504
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
505
+	 */
506
+	const default_where_conditions_others_only = 'other_models_only';
507
+
508
+	/**
509
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
510
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
511
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
512
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
513
+	 *        (regardless of whether those events and venues are trashed)
514
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
515
+	 *        events.
516
+	 */
517
+	const default_where_conditions_minimum_all = 'minimum';
518
+
519
+	/**
520
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
521
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
522
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
523
+	 *        not)
524
+	 */
525
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
526
+
527
+	/**
528
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
529
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
530
+	 *        it's possible it will return table entries for other models. You should use
531
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
532
+	 */
533
+	const default_where_conditions_none = 'none';
534
+
535
+
536
+
537
+	/**
538
+	 * About all child constructors:
539
+	 * they should define the _tables, _fields and _model_relations arrays.
540
+	 * Should ALWAYS be called after child constructor.
541
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
542
+	 * finalizes constructing all the object's attributes.
543
+	 * Generally, rather than requiring a child to code
544
+	 * $this->_tables = array(
545
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
546
+	 *        ...);
547
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
548
+	 * each EE_Table has a function to set the table's alias after the constructor, using
549
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
550
+	 * do something similar.
551
+	 *
552
+	 * @param null $timezone
553
+	 * @throws EE_Error
554
+	 */
555
+	protected function __construct($timezone = null)
556
+	{
557
+		// check that the model has not been loaded too soon
558
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
559
+			throw new EE_Error(
560
+				sprintf(
561
+					esc_html__(
562
+						'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.',
563
+						'event_espresso'
564
+					),
565
+					get_class($this)
566
+				)
567
+			);
568
+		}
569
+		/**
570
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
571
+		 */
572
+		if (empty(EEM_Base::$_model_query_blog_id)) {
573
+			EEM_Base::set_model_query_blog_id();
574
+		}
575
+		/**
576
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
577
+		 * just use EE_Register_Model_Extension
578
+		 *
579
+		 * @var EE_Table_Base[] $_tables
580
+		 */
581
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
582
+		foreach ($this->_tables as $table_alias => $table_obj) {
583
+			/** @var $table_obj EE_Table_Base */
584
+			$table_obj->_construct_finalize_with_alias($table_alias);
585
+			if ($table_obj instanceof EE_Secondary_Table) {
586
+				/** @var $table_obj EE_Secondary_Table */
587
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
588
+			}
589
+		}
590
+		/**
591
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
592
+		 * EE_Register_Model_Extension
593
+		 *
594
+		 * @param EE_Model_Field_Base[] $_fields
595
+		 */
596
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
597
+		$this->_invalidate_field_caches();
598
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
599
+			if (! array_key_exists($table_alias, $this->_tables)) {
600
+				throw new EE_Error(sprintf(esc_html__(
601
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
602
+					'event_espresso'
603
+				), $table_alias, implode(",", $this->_fields)));
604
+			}
605
+			foreach ($fields_for_table as $field_name => $field_obj) {
606
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
607
+				// primary key field base has a slightly different _construct_finalize
608
+				/** @var $field_obj EE_Model_Field_Base */
609
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
610
+			}
611
+		}
612
+		// everything is related to Extra_Meta
613
+		if (get_class($this) !== 'EEM_Extra_Meta') {
614
+			// make extra meta related to everything, but don't block deleting things just
615
+			// because they have related extra meta info. For now just orphan those extra meta
616
+			// in the future we should automatically delete them
617
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
618
+		}
619
+		// and change logs
620
+		if (get_class($this) !== 'EEM_Change_Log') {
621
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
622
+		}
623
+		/**
624
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
625
+		 * EE_Register_Model_Extension
626
+		 *
627
+		 * @param EE_Model_Relation_Base[] $_model_relations
628
+		 */
629
+		$this->_model_relations = (array) apply_filters(
630
+			'FHEE__' . get_class($this) . '__construct__model_relations',
631
+			$this->_model_relations
632
+		);
633
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
634
+			/** @var $relation_obj EE_Model_Relation_Base */
635
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
636
+		}
637
+		foreach ($this->_indexes as $index_name => $index_obj) {
638
+			/** @var $index_obj EE_Index */
639
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
640
+		}
641
+		$this->set_timezone($timezone);
642
+		// finalize default where condition strategy, or set default
643
+		if (! $this->_default_where_conditions_strategy) {
644
+			// nothing was set during child constructor, so set default
645
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
646
+		}
647
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
648
+		if (! $this->_minimum_where_conditions_strategy) {
649
+			// nothing was set during child constructor, so set default
650
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
651
+		}
652
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
653
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
654
+		// to indicate to NOT set it, set it to the logical default
655
+		if ($this->_caps_slug === null) {
656
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
657
+		}
658
+		// initialize the standard cap restriction generators if none were specified by the child constructor
659
+		if ($this->_cap_restriction_generators !== false) {
660
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
661
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
662
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
663
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
664
+						new EE_Restriction_Generator_Protected(),
665
+						$cap_context,
666
+						$this
667
+					);
668
+				}
669
+			}
670
+		}
671
+		// if there are cap restriction generators, use them to make the default cap restrictions
672
+		if ($this->_cap_restriction_generators !== false) {
673
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
674
+				if (! $generator_object) {
675
+					continue;
676
+				}
677
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
678
+					throw new EE_Error(
679
+						sprintf(
680
+							esc_html__(
681
+								'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.',
682
+								'event_espresso'
683
+							),
684
+							$context,
685
+							$this->get_this_model_name()
686
+						)
687
+					);
688
+				}
689
+				$action = $this->cap_action_for_context($context);
690
+				if (! $generator_object->construction_finalized()) {
691
+					$generator_object->_construct_finalize($this, $action);
692
+				}
693
+			}
694
+		}
695
+		do_action('AHEE__' . get_class($this) . '__construct__end');
696
+	}
697
+
698
+
699
+
700
+	/**
701
+	 * Used to set the $_model_query_blog_id static property.
702
+	 *
703
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
704
+	 *                      value for get_current_blog_id() will be used.
705
+	 */
706
+	public static function set_model_query_blog_id($blog_id = 0)
707
+	{
708
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
709
+	}
710
+
711
+
712
+
713
+	/**
714
+	 * Returns whatever is set as the internal $model_query_blog_id.
715
+	 *
716
+	 * @return int
717
+	 */
718
+	public static function get_model_query_blog_id()
719
+	{
720
+		return EEM_Base::$_model_query_blog_id;
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * This function is a singleton method used to instantiate the Espresso_model object
727
+	 *
728
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
729
+	 *                                (and any incoming timezone data that gets saved).
730
+	 *                                Note this just sends the timezone info to the date time model field objects.
731
+	 *                                Default is NULL
732
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
733
+	 * @return static (as in the concrete child class)
734
+	 * @throws EE_Error
735
+	 * @throws InvalidArgumentException
736
+	 * @throws InvalidDataTypeException
737
+	 * @throws InvalidInterfaceException
738
+	 */
739
+	public static function instance($timezone = null)
740
+	{
741
+		// check if instance of Espresso_model already exists
742
+		if (! static::$_instance instanceof static) {
743
+			// instantiate Espresso_model
744
+			static::$_instance = new static(
745
+				$timezone,
746
+				EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
747
+			);
748
+		}
749
+		// we might have a timezone set, let set_timezone decide what to do with it
750
+		static::$_instance->set_timezone($timezone);
751
+		// Espresso_model object
752
+		return static::$_instance;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * resets the model and returns it
759
+	 *
760
+	 * @param null | string $timezone
761
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
762
+	 * all its properties reset; if it wasn't instantiated, returns null)
763
+	 * @throws EE_Error
764
+	 * @throws ReflectionException
765
+	 * @throws InvalidArgumentException
766
+	 * @throws InvalidDataTypeException
767
+	 * @throws InvalidInterfaceException
768
+	 */
769
+	public static function reset($timezone = null)
770
+	{
771
+		if (static::$_instance instanceof EEM_Base) {
772
+			// let's try to NOT swap out the current instance for a new one
773
+			// because if someone has a reference to it, we can't remove their reference
774
+			// so it's best to keep using the same reference, but change the original object
775
+			// reset all its properties to their original values as defined in the class
776
+			$r = new ReflectionClass(get_class(static::$_instance));
777
+			$static_properties = $r->getStaticProperties();
778
+			foreach ($r->getDefaultProperties() as $property => $value) {
779
+				// don't set instance to null like it was originally,
780
+				// but it's static anyways, and we're ignoring static properties (for now at least)
781
+				if (! isset($static_properties[ $property ])) {
782
+					static::$_instance->{$property} = $value;
783
+				}
784
+			}
785
+			// and then directly call its constructor again, like we would if we were creating a new one
786
+			static::$_instance->__construct(
787
+				$timezone,
788
+				EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
789
+			);
790
+			return self::instance();
791
+		}
792
+		return null;
793
+	}
794
+
795
+
796
+
797
+	/**
798
+	 * @return LoaderInterface
799
+	 * @throws InvalidArgumentException
800
+	 * @throws InvalidDataTypeException
801
+	 * @throws InvalidInterfaceException
802
+	 */
803
+	private static function getLoader()
804
+	{
805
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
806
+			EEM_Base::$loader = LoaderFactory::getLoader();
807
+		}
808
+		return EEM_Base::$loader;
809
+	}
810
+
811
+
812
+
813
+	/**
814
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
815
+	 *
816
+	 * @param  boolean $translated return localized strings or JUST the array.
817
+	 * @return array
818
+	 * @throws EE_Error
819
+	 * @throws InvalidArgumentException
820
+	 * @throws InvalidDataTypeException
821
+	 * @throws InvalidInterfaceException
822
+	 */
823
+	public function status_array($translated = false)
824
+	{
825
+		if (! array_key_exists('Status', $this->_model_relations)) {
826
+			return array();
827
+		}
828
+		$model_name = $this->get_this_model_name();
829
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
830
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
831
+		$status_array = array();
832
+		foreach ($stati as $status) {
833
+			$status_array[ $status->ID() ] = $status->get('STS_code');
834
+		}
835
+		return $translated
836
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
837
+			: $status_array;
838
+	}
839
+
840
+
841
+
842
+	/**
843
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
844
+	 *
845
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
846
+	 *                             or if you have the development copy of EE you can view this at the path:
847
+	 *                             /docs/G--Model-System/model-query-params.md
848
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
849
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
+	 *                                        array( array(
853
+	 *                                        'OR'=>array(
854
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
+	 *                                        )
857
+	 *                                        ),
858
+	 *                                        'limit'=>10,
859
+	 *                                        'group_by'=>'TXN_ID'
860
+	 *                                        ));
861
+	 *                                        get all the answers to the question titled "shirt size" for event with id
862
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
+	 *                                        'Question.QST_display_text'=>'shirt size',
864
+	 *                                        'Registration.Event.EVT_ID'=>12
865
+	 *                                        ),
866
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
867
+	 *                                        ));
868
+	 * @throws EE_Error
869
+	 */
870
+	public function get_all($query_params = array())
871
+	{
872
+		if (
873
+			isset($query_params['limit'])
874
+			&& ! isset($query_params['group_by'])
875
+		) {
876
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
877
+		}
878
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
879
+	}
880
+
881
+
882
+
883
+	/**
884
+	 * Modifies the query parameters so we only get back model objects
885
+	 * that "belong" to the current user
886
+	 *
887
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
889
+	 */
890
+	public function alter_query_params_to_only_include_mine($query_params = array())
891
+	{
892
+		$wp_user_field_name = $this->wp_user_field_name();
893
+		if ($wp_user_field_name) {
894
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
895
+		}
896
+		return $query_params;
897
+	}
898
+
899
+
900
+
901
+	/**
902
+	 * Returns the name of the field's name that points to the WP_User table
903
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
904
+	 * foreign key to the WP_User table)
905
+	 *
906
+	 * @return string|boolean string on success, boolean false when there is no
907
+	 * foreign key to the WP_User table
908
+	 */
909
+	public function wp_user_field_name()
910
+	{
911
+		try {
912
+			if (! empty($this->_model_chain_to_wp_user)) {
913
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
914
+				$last_model_name = end($models_to_follow_to_wp_users);
915
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
916
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
917
+			} else {
918
+				$model_with_fk_to_wp_users = $this;
919
+				$model_chain_to_wp_user = '';
920
+			}
921
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
922
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
923
+		} catch (EE_Error $e) {
924
+			return false;
925
+		}
926
+	}
927
+
928
+
929
+
930
+	/**
931
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
932
+	 * (or transiently-related model) has a foreign key to the wp_users table;
933
+	 * useful for finding if model objects of this type are 'owned' by the current user.
934
+	 * This is an empty string when the foreign key is on this model and when it isn't,
935
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
936
+	 * (or transiently-related model)
937
+	 *
938
+	 * @return string
939
+	 */
940
+	public function model_chain_to_wp_user()
941
+	{
942
+		return $this->_model_chain_to_wp_user;
943
+	}
944
+
945
+
946
+
947
+	/**
948
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
949
+	 * like how registrations don't have a foreign key to wp_users, but the
950
+	 * events they are for are), or is unrelated to wp users.
951
+	 * generally available
952
+	 *
953
+	 * @return boolean
954
+	 */
955
+	public function is_owned()
956
+	{
957
+		if ($this->model_chain_to_wp_user()) {
958
+			return true;
959
+		}
960
+		try {
961
+			$this->get_foreign_key_to('WP_User');
962
+			return true;
963
+		} catch (EE_Error $e) {
964
+			return false;
965
+		}
966
+	}
967
+
968
+
969
+	/**
970
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
971
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
972
+	 * the model)
973
+	 *
974
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
975
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
976
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
977
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
978
+	 *                                  override this and set the select to "*", or a specific column name, like
979
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
980
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
981
+	 *                                  the aliases used to refer to this selection, and values are to be
982
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
983
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
984
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
985
+	 * @throws EE_Error
986
+	 * @throws InvalidArgumentException
987
+	 */
988
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
989
+	{
990
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
991
+		;
992
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
993
+		$select_expressions = $columns_to_select === null
994
+			? $this->_construct_default_select_sql($model_query_info)
995
+			: '';
996
+		if ($this->_custom_selections instanceof CustomSelects) {
997
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
998
+			$select_expressions .= $select_expressions
999
+				? ', ' . $custom_expressions
1000
+				: $custom_expressions;
1001
+		}
1002
+
1003
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1004
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1010
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1011
+	 * method of including extra select information.
1012
+	 *
1013
+	 * @param array             $query_params
1014
+	 * @param null|array|string $columns_to_select
1015
+	 * @return null|CustomSelects
1016
+	 * @throws InvalidArgumentException
1017
+	 */
1018
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1019
+	{
1020
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1021
+			return null;
1022
+		}
1023
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1024
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1025
+		return new CustomSelects($selects);
1026
+	}
1027
+
1028
+
1029
+
1030
+	/**
1031
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1032
+	 * but you can use the model query params to more easily
1033
+	 * take care of joins, field preparation etc.
1034
+	 *
1035
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1036
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1039
+	 *                                  override this and set the select to "*", or a specific column name, like
1040
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
+	 *                                  the aliases used to refer to this selection, and values are to be
1043
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
+	 * @throws EE_Error
1047
+	 */
1048
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
+	{
1050
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
+	}
1052
+
1053
+
1054
+
1055
+	/**
1056
+	 * For creating a custom select statement
1057
+	 *
1058
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
+	 *                                 SQL, and 1=>is the datatype
1061
+	 * @throws EE_Error
1062
+	 * @return string
1063
+	 */
1064
+	private function _construct_select_from_input($columns_to_select)
1065
+	{
1066
+		if (is_array($columns_to_select)) {
1067
+			$select_sql_array = array();
1068
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
+					throw new EE_Error(
1071
+						sprintf(
1072
+							esc_html__(
1073
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
+								'event_espresso'
1075
+							),
1076
+							$selection_and_datatype,
1077
+							$alias
1078
+						)
1079
+					);
1080
+				}
1081
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1082
+					throw new EE_Error(
1083
+						sprintf(
1084
+							esc_html__(
1085
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
+								'event_espresso'
1087
+							),
1088
+							$selection_and_datatype[1],
1089
+							$selection_and_datatype[0],
1090
+							$alias,
1091
+							implode(', ', $this->_valid_wpdb_data_types)
1092
+						)
1093
+					);
1094
+				}
1095
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
+			}
1097
+			$columns_to_select_string = implode(', ', $select_sql_array);
1098
+		} else {
1099
+			$columns_to_select_string = $columns_to_select;
1100
+		}
1101
+		return $columns_to_select_string;
1102
+	}
1103
+
1104
+
1105
+
1106
+	/**
1107
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
+	 *
1109
+	 * @return string
1110
+	 * @throws EE_Error
1111
+	 */
1112
+	public function primary_key_name()
1113
+	{
1114
+		return $this->get_primary_key_field()->get_name();
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1120
+	 * If there is no primary key on this model, $id is treated as primary key string
1121
+	 *
1122
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1123
+	 * @return EE_Base_Class
1124
+	 * @throws EE_Error
1125
+	 */
1126
+	public function get_one_by_ID($id)
1127
+	{
1128
+		if ($this->get_from_entity_map($id)) {
1129
+			return $this->get_from_entity_map($id);
1130
+		}
1131
+		$model_object = $this->get_one(
1132
+			$this->alter_query_params_to_restrict_by_ID(
1133
+				$id,
1134
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
+			)
1136
+		);
1137
+		$className = $this->_get_class_name();
1138
+		if ($model_object instanceof $className) {
1139
+			// make sure valid objects get added to the entity map
1140
+			// so that the next call to this method doesn't trigger another trip to the db
1141
+			$this->add_to_entity_map($model_object);
1142
+		}
1143
+		return $model_object;
1144
+	}
1145
+
1146
+
1147
+
1148
+	/**
1149
+	 * Alters query parameters to only get items with this ID are returned.
1150
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1151
+	 * or could just be a simple primary key ID
1152
+	 *
1153
+	 * @param int   $id
1154
+	 * @param array $query_params
1155
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1156
+	 * @throws EE_Error
1157
+	 */
1158
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1159
+	{
1160
+		if (! isset($query_params[0])) {
1161
+			$query_params[0] = array();
1162
+		}
1163
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1164
+		if ($conditions_from_id === null) {
1165
+			$query_params[0][ $this->primary_key_name() ] = $id;
1166
+		} else {
1167
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1168
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1169
+		}
1170
+		return $query_params;
1171
+	}
1172
+
1173
+
1174
+
1175
+	/**
1176
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1177
+	 * array. If no item is found, null is returned.
1178
+	 *
1179
+	 * @param array $query_params like EEM_Base's $query_params variable.
1180
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1181
+	 * @throws EE_Error
1182
+	 */
1183
+	public function get_one($query_params = array())
1184
+	{
1185
+		if (! is_array($query_params)) {
1186
+			EE_Error::doing_it_wrong(
1187
+				'EEM_Base::get_one',
1188
+				sprintf(
1189
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1190
+					gettype($query_params)
1191
+				),
1192
+				'4.6.0'
1193
+			);
1194
+			$query_params = array();
1195
+		}
1196
+		$query_params['limit'] = 1;
1197
+		$items = $this->get_all($query_params);
1198
+		if (empty($items)) {
1199
+			return null;
1200
+		}
1201
+		return array_shift($items);
1202
+	}
1203
+
1204
+
1205
+
1206
+	/**
1207
+	 * Returns the next x number of items in sequence from the given value as
1208
+	 * found in the database matching the given query conditions.
1209
+	 *
1210
+	 * @param mixed $current_field_value    Value used for the reference point.
1211
+	 * @param null  $field_to_order_by      What field is used for the
1212
+	 *                                      reference point.
1213
+	 * @param int   $limit                  How many to return.
1214
+	 * @param array $query_params           Extra conditions on the query.
1215
+	 * @param null  $columns_to_select      If left null, then an array of
1216
+	 *                                      EE_Base_Class objects is returned,
1217
+	 *                                      otherwise you can indicate just the
1218
+	 *                                      columns you want returned.
1219
+	 * @return EE_Base_Class[]|array
1220
+	 * @throws EE_Error
1221
+	 */
1222
+	public function next_x(
1223
+		$current_field_value,
1224
+		$field_to_order_by = null,
1225
+		$limit = 1,
1226
+		$query_params = array(),
1227
+		$columns_to_select = null
1228
+	) {
1229
+		return $this->_get_consecutive(
1230
+			$current_field_value,
1231
+			'>',
1232
+			$field_to_order_by,
1233
+			$limit,
1234
+			$query_params,
1235
+			$columns_to_select
1236
+		);
1237
+	}
1238
+
1239
+
1240
+
1241
+	/**
1242
+	 * Returns the previous x number of items in sequence from the given value
1243
+	 * as found in the database matching the given query conditions.
1244
+	 *
1245
+	 * @param mixed $current_field_value    Value used for the reference point.
1246
+	 * @param null  $field_to_order_by      What field is used for the
1247
+	 *                                      reference point.
1248
+	 * @param int   $limit                  How many to return.
1249
+	 * @param array $query_params           Extra conditions on the query.
1250
+	 * @param null  $columns_to_select      If left null, then an array of
1251
+	 *                                      EE_Base_Class objects is returned,
1252
+	 *                                      otherwise you can indicate just the
1253
+	 *                                      columns you want returned.
1254
+	 * @return EE_Base_Class[]|array
1255
+	 * @throws EE_Error
1256
+	 */
1257
+	public function previous_x(
1258
+		$current_field_value,
1259
+		$field_to_order_by = null,
1260
+		$limit = 1,
1261
+		$query_params = array(),
1262
+		$columns_to_select = null
1263
+	) {
1264
+		return $this->_get_consecutive(
1265
+			$current_field_value,
1266
+			'<',
1267
+			$field_to_order_by,
1268
+			$limit,
1269
+			$query_params,
1270
+			$columns_to_select
1271
+		);
1272
+	}
1273
+
1274
+
1275
+
1276
+	/**
1277
+	 * Returns the next item in sequence from the given value as found in the
1278
+	 * database matching the given query conditions.
1279
+	 *
1280
+	 * @param mixed $current_field_value    Value used for the reference point.
1281
+	 * @param null  $field_to_order_by      What field is used for the
1282
+	 *                                      reference point.
1283
+	 * @param array $query_params           Extra conditions on the query.
1284
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1285
+	 *                                      object is returned, otherwise you
1286
+	 *                                      can indicate just the columns you
1287
+	 *                                      want and a single array indexed by
1288
+	 *                                      the columns will be returned.
1289
+	 * @return EE_Base_Class|null|array()
1290
+	 * @throws EE_Error
1291
+	 */
1292
+	public function next(
1293
+		$current_field_value,
1294
+		$field_to_order_by = null,
1295
+		$query_params = array(),
1296
+		$columns_to_select = null
1297
+	) {
1298
+		$results = $this->_get_consecutive(
1299
+			$current_field_value,
1300
+			'>',
1301
+			$field_to_order_by,
1302
+			1,
1303
+			$query_params,
1304
+			$columns_to_select
1305
+		);
1306
+		return empty($results) ? null : reset($results);
1307
+	}
1308
+
1309
+
1310
+
1311
+	/**
1312
+	 * Returns the previous item in sequence from the given value as found in
1313
+	 * the database matching the given query conditions.
1314
+	 *
1315
+	 * @param mixed $current_field_value    Value used for the reference point.
1316
+	 * @param null  $field_to_order_by      What field is used for the
1317
+	 *                                      reference point.
1318
+	 * @param array $query_params           Extra conditions on the query.
1319
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1320
+	 *                                      object is returned, otherwise you
1321
+	 *                                      can indicate just the columns you
1322
+	 *                                      want and a single array indexed by
1323
+	 *                                      the columns will be returned.
1324
+	 * @return EE_Base_Class|null|array()
1325
+	 * @throws EE_Error
1326
+	 */
1327
+	public function previous(
1328
+		$current_field_value,
1329
+		$field_to_order_by = null,
1330
+		$query_params = array(),
1331
+		$columns_to_select = null
1332
+	) {
1333
+		$results = $this->_get_consecutive(
1334
+			$current_field_value,
1335
+			'<',
1336
+			$field_to_order_by,
1337
+			1,
1338
+			$query_params,
1339
+			$columns_to_select
1340
+		);
1341
+		return empty($results) ? null : reset($results);
1342
+	}
1343
+
1344
+
1345
+
1346
+	/**
1347
+	 * Returns the a consecutive number of items in sequence from the given
1348
+	 * value as found in the database matching the given query conditions.
1349
+	 *
1350
+	 * @param mixed  $current_field_value   Value used for the reference point.
1351
+	 * @param string $operand               What operand is used for the sequence.
1352
+	 * @param string $field_to_order_by     What field is used for the reference point.
1353
+	 * @param int    $limit                 How many to return.
1354
+	 * @param array  $query_params          Extra conditions on the query.
1355
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1356
+	 *                                      otherwise you can indicate just the columns you want returned.
1357
+	 * @return EE_Base_Class[]|array
1358
+	 * @throws EE_Error
1359
+	 */
1360
+	protected function _get_consecutive(
1361
+		$current_field_value,
1362
+		$operand = '>',
1363
+		$field_to_order_by = null,
1364
+		$limit = 1,
1365
+		$query_params = array(),
1366
+		$columns_to_select = null
1367
+	) {
1368
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1369
+		if (empty($field_to_order_by)) {
1370
+			if ($this->has_primary_key_field()) {
1371
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1372
+			} else {
1373
+				if (WP_DEBUG) {
1374
+					throw new EE_Error(esc_html__(
1375
+						'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).',
1376
+						'event_espresso'
1377
+					));
1378
+				}
1379
+				EE_Error::add_error(esc_html__('There was an error with the query.', 'event_espresso'));
1380
+				return array();
1381
+			}
1382
+		}
1383
+		if (! is_array($query_params)) {
1384
+			EE_Error::doing_it_wrong(
1385
+				'EEM_Base::_get_consecutive',
1386
+				sprintf(
1387
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1388
+					gettype($query_params)
1389
+				),
1390
+				'4.6.0'
1391
+			);
1392
+			$query_params = array();
1393
+		}
1394
+		// let's add the where query param for consecutive look up.
1395
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1396
+		$query_params['limit'] = $limit;
1397
+		// set direction
1398
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1399
+		$query_params['order_by'] = $operand === '>'
1400
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1401
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1402
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1403
+		if (empty($columns_to_select)) {
1404
+			return $this->get_all($query_params);
1405
+		}
1406
+		// getting just the fields
1407
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1408
+	}
1409
+
1410
+
1411
+
1412
+	/**
1413
+	 * This sets the _timezone property after model object has been instantiated.
1414
+	 *
1415
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1416
+	 */
1417
+	public function set_timezone($timezone)
1418
+	{
1419
+		if ($timezone !== null) {
1420
+			$this->_timezone = $timezone;
1421
+		}
1422
+		// note we need to loop through relations and set the timezone on those objects as well.
1423
+		foreach ($this->_model_relations as $relation) {
1424
+			$relation->set_timezone($timezone);
1425
+		}
1426
+		// and finally we do the same for any datetime fields
1427
+		foreach ($this->_fields as $field) {
1428
+			if ($field instanceof EE_Datetime_Field) {
1429
+				$field->set_timezone($timezone);
1430
+			}
1431
+		}
1432
+	}
1433
+
1434
+
1435
+
1436
+	/**
1437
+	 * This just returns whatever is set for the current timezone.
1438
+	 *
1439
+	 * @access public
1440
+	 * @return string
1441
+	 */
1442
+	public function get_timezone()
1443
+	{
1444
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1445
+		if (empty($this->_timezone)) {
1446
+			foreach ($this->_fields as $field) {
1447
+				if ($field instanceof EE_Datetime_Field) {
1448
+					$this->set_timezone($field->get_timezone());
1449
+					break;
1450
+				}
1451
+			}
1452
+		}
1453
+		// if timezone STILL empty then return the default timezone for the site.
1454
+		if (empty($this->_timezone)) {
1455
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1456
+		}
1457
+		return $this->_timezone;
1458
+	}
1459
+
1460
+
1461
+
1462
+	/**
1463
+	 * This returns the date formats set for the given field name and also ensures that
1464
+	 * $this->_timezone property is set correctly.
1465
+	 *
1466
+	 * @since 4.6.x
1467
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1468
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1469
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1470
+	 * @return array formats in an array with the date format first, and the time format last.
1471
+	 */
1472
+	public function get_formats_for($field_name, $pretty = false)
1473
+	{
1474
+		$field_settings = $this->field_settings_for($field_name);
1475
+		// if not a valid EE_Datetime_Field then throw error
1476
+		if (! $field_settings instanceof EE_Datetime_Field) {
1477
+			throw new EE_Error(sprintf(esc_html__(
1478
+				'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.',
1479
+				'event_espresso'
1480
+			), $field_name));
1481
+		}
1482
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1483
+		// the field.
1484
+		$this->_timezone = $field_settings->get_timezone();
1485
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1486
+	}
1487
+
1488
+
1489
+
1490
+	/**
1491
+	 * This returns the current time in a format setup for a query on this model.
1492
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1493
+	 * it will return:
1494
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1495
+	 *  NOW
1496
+	 *  - or a unix timestamp (equivalent to time())
1497
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1498
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1499
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1500
+	 * @since 4.6.x
1501
+	 * @param string $field_name       The field the current time is needed for.
1502
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1503
+	 *                                 formatted string matching the set format for the field in the set timezone will
1504
+	 *                                 be returned.
1505
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1506
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1507
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1508
+	 *                                 exception is triggered.
1509
+	 */
1510
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1511
+	{
1512
+		$formats = $this->get_formats_for($field_name);
1513
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1514
+		if ($timestamp) {
1515
+			return $DateTime->format('U');
1516
+		}
1517
+		// not returning timestamp, so return formatted string in timezone.
1518
+		switch ($what) {
1519
+			case 'time':
1520
+				return $DateTime->format($formats[1]);
1521
+				break;
1522
+			case 'date':
1523
+				return $DateTime->format($formats[0]);
1524
+				break;
1525
+			default:
1526
+				return $DateTime->format(implode(' ', $formats));
1527
+				break;
1528
+		}
1529
+	}
1530
+
1531
+
1532
+
1533
+	/**
1534
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1535
+	 * for the model are.  Returns a DateTime object.
1536
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1537
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1538
+	 * ignored.
1539
+	 *
1540
+	 * @param string $field_name      The field being setup.
1541
+	 * @param string $timestring      The date time string being used.
1542
+	 * @param string $incoming_format The format for the time string.
1543
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1544
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1545
+	 *                                format is
1546
+	 *                                'U', this is ignored.
1547
+	 * @return DateTime
1548
+	 * @throws EE_Error
1549
+	 */
1550
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1551
+	{
1552
+		// just using this to ensure the timezone is set correctly internally
1553
+		$this->get_formats_for($field_name);
1554
+		// load EEH_DTT_Helper
1555
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1556
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1557
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1558
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1559
+	}
1560
+
1561
+
1562
+
1563
+	/**
1564
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1565
+	 *
1566
+	 * @return EE_Table_Base[]
1567
+	 */
1568
+	public function get_tables()
1569
+	{
1570
+		return $this->_tables;
1571
+	}
1572
+
1573
+
1574
+
1575
+	/**
1576
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1577
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1578
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1579
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1580
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1581
+	 * model object with EVT_ID = 1
1582
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1583
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1584
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1585
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1586
+	 * are not specified)
1587
+	 *
1588
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1589
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1590
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1591
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1592
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1593
+	 *                                         ID=34, we'd use this method as follows:
1594
+	 *                                         EEM_Transaction::instance()->update(
1595
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1596
+	 *                                         array(array('TXN_ID'=>34)));
1597
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1598
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1599
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1600
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1601
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1602
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1603
+	 *                                         TRUE, it is assumed that you've already called
1604
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1605
+	 *                                         malicious javascript. However, if
1606
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1607
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1608
+	 *                                         and every other field, before insertion. We provide this parameter
1609
+	 *                                         because model objects perform their prepare_for_set function on all
1610
+	 *                                         their values, and so don't need to be called again (and in many cases,
1611
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1612
+	 *                                         prepare_for_set method...)
1613
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1614
+	 *                                         in this model's entity map according to $fields_n_values that match
1615
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1616
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1617
+	 *                                         could get out-of-sync with the database
1618
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1619
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1620
+	 *                                         bad)
1621
+	 * @throws EE_Error
1622
+	 */
1623
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1624
+	{
1625
+		if (! is_array($query_params)) {
1626
+			EE_Error::doing_it_wrong(
1627
+				'EEM_Base::update',
1628
+				sprintf(
1629
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1630
+					gettype($query_params)
1631
+				),
1632
+				'4.6.0'
1633
+			);
1634
+			$query_params = array();
1635
+		}
1636
+		/**
1637
+		 * Action called before a model update call has been made.
1638
+		 *
1639
+		 * @param EEM_Base $model
1640
+		 * @param array    $fields_n_values the updated fields and their new values
1641
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1642
+		 */
1643
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1644
+		/**
1645
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1646
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1647
+		 *
1648
+		 * @param array    $fields_n_values fields and their new values
1649
+		 * @param EEM_Base $model           the model being queried
1650
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1651
+		 */
1652
+		$fields_n_values = (array) apply_filters(
1653
+			'FHEE__EEM_Base__update__fields_n_values',
1654
+			$fields_n_values,
1655
+			$this,
1656
+			$query_params
1657
+		);
1658
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1659
+		// to do that, for each table, verify that it's PK isn't null.
1660
+		$tables = $this->get_tables();
1661
+		// 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
1662
+		// NOTE: we should make this code more efficient by NOT querying twice
1663
+		// before the real update, but that needs to first go through ALPHA testing
1664
+		// as it's dangerous. says Mike August 8 2014
1665
+		// we want to make sure the default_where strategy is ignored
1666
+		$this->_ignore_where_strategy = true;
1667
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1668
+		foreach ($wpdb_select_results as $wpdb_result) {
1669
+			// type cast stdClass as array
1670
+			$wpdb_result = (array) $wpdb_result;
1671
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1672
+			if ($this->has_primary_key_field()) {
1673
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1674
+			} else {
1675
+				// 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)
1676
+				$main_table_pk_value = null;
1677
+			}
1678
+			// 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
1679
+			// 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
1680
+			if (count($tables) > 1) {
1681
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1682
+				// in that table, and so we'll want to insert one
1683
+				foreach ($tables as $table_obj) {
1684
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1685
+					// if there is no private key for this table on the results, it means there's no entry
1686
+					// in this table, right? so insert a row in the current table, using any fields available
1687
+					if (
1688
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1689
+						   && $wpdb_result[ $this_table_pk_column ])
1690
+					) {
1691
+						$success = $this->_insert_into_specific_table(
1692
+							$table_obj,
1693
+							$fields_n_values,
1694
+							$main_table_pk_value
1695
+						);
1696
+						// if we died here, report the error
1697
+						if (! $success) {
1698
+							return false;
1699
+						}
1700
+					}
1701
+				}
1702
+			}
1703
+			//              //and now check that if we have cached any models by that ID on the model, that
1704
+			//              //they also get updated properly
1705
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1706
+			//              if( $model_object ){
1707
+			//                  foreach( $fields_n_values as $field => $value ){
1708
+			//                      $model_object->set($field, $value);
1709
+			// let's make sure default_where strategy is followed now
1710
+			$this->_ignore_where_strategy = false;
1711
+		}
1712
+		// if we want to keep model objects in sync, AND
1713
+		// if this wasn't called from a model object (to update itself)
1714
+		// then we want to make sure we keep all the existing
1715
+		// model objects in sync with the db
1716
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1717
+			if ($this->has_primary_key_field()) {
1718
+				$model_objs_affected_ids = $this->get_col($query_params);
1719
+			} else {
1720
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1721
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1722
+				$model_objs_affected_ids = array();
1723
+				foreach ($models_affected_key_columns as $row) {
1724
+					$combined_index_key = $this->get_index_primary_key_string($row);
1725
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1726
+				}
1727
+			}
1728
+			if (! $model_objs_affected_ids) {
1729
+				// wait wait wait- if nothing was affected let's stop here
1730
+				return 0;
1731
+			}
1732
+			foreach ($model_objs_affected_ids as $id) {
1733
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1734
+				if ($model_obj_in_entity_map) {
1735
+					foreach ($fields_n_values as $field => $new_value) {
1736
+						$model_obj_in_entity_map->set($field, $new_value);
1737
+					}
1738
+				}
1739
+			}
1740
+			// if there is a primary key on this model, we can now do a slight optimization
1741
+			if ($this->has_primary_key_field()) {
1742
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1743
+				$query_params = array(
1744
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1745
+					'limit'                    => count($model_objs_affected_ids),
1746
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1747
+				);
1748
+			}
1749
+		}
1750
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1751
+		$SQL = "UPDATE "
1752
+			   . $model_query_info->get_full_join_sql()
1753
+			   . " SET "
1754
+			   . $this->_construct_update_sql($fields_n_values)
1755
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1756
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1757
+		/**
1758
+		 * Action called after a model update call has been made.
1759
+		 *
1760
+		 * @param EEM_Base $model
1761
+		 * @param array    $fields_n_values the updated fields and their new values
1762
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1763
+		 * @param int      $rows_affected
1764
+		 */
1765
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1766
+		return $rows_affected;// how many supposedly got updated
1767
+	}
1768
+
1769
+
1770
+
1771
+	/**
1772
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1773
+	 * are teh values of the field specified (or by default the primary key field)
1774
+	 * that matched the query params. Note that you should pass the name of the
1775
+	 * model FIELD, not the database table's column name.
1776
+	 *
1777
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1778
+	 * @param string $field_to_select
1779
+	 * @return array just like $wpdb->get_col()
1780
+	 * @throws EE_Error
1781
+	 */
1782
+	public function get_col($query_params = array(), $field_to_select = null)
1783
+	{
1784
+		if ($field_to_select) {
1785
+			$field = $this->field_settings_for($field_to_select);
1786
+		} elseif ($this->has_primary_key_field()) {
1787
+			$field = $this->get_primary_key_field();
1788
+		} else {
1789
+			// no primary key, just grab the first column
1790
+			$field = reset($this->field_settings());
1791
+		}
1792
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1793
+		$select_expressions = $field->get_qualified_column();
1794
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1795
+		return $this->_do_wpdb_query('get_col', array($SQL));
1796
+	}
1797
+
1798
+
1799
+
1800
+	/**
1801
+	 * Returns a single column value for a single row from the database
1802
+	 *
1803
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1804
+	 * @param string $field_to_select @see EEM_Base::get_col()
1805
+	 * @return string
1806
+	 * @throws EE_Error
1807
+	 */
1808
+	public function get_var($query_params = array(), $field_to_select = null)
1809
+	{
1810
+		$query_params['limit'] = 1;
1811
+		$col = $this->get_col($query_params, $field_to_select);
1812
+		if (! empty($col)) {
1813
+			return reset($col);
1814
+		}
1815
+		return null;
1816
+	}
1817
+
1818
+
1819
+
1820
+	/**
1821
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1822
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1823
+	 * injection, but currently no further filtering is done
1824
+	 *
1825
+	 * @global      $wpdb
1826
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1827
+	 *                               be updated to in the DB
1828
+	 * @return string of SQL
1829
+	 * @throws EE_Error
1830
+	 */
1831
+	public function _construct_update_sql($fields_n_values)
1832
+	{
1833
+		/** @type WPDB $wpdb */
1834
+		global $wpdb;
1835
+		$cols_n_values = array();
1836
+		foreach ($fields_n_values as $field_name => $value) {
1837
+			$field_obj = $this->field_settings_for($field_name);
1838
+			// if the value is NULL, we want to assign the value to that.
1839
+			// wpdb->prepare doesn't really handle that properly
1840
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1841
+			$value_sql = $prepared_value === null ? 'NULL'
1842
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1843
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1844
+		}
1845
+		return implode(",", $cols_n_values);
1846
+	}
1847
+
1848
+
1849
+
1850
+	/**
1851
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1852
+	 * Performs a HARD delete, meaning the database row should always be removed,
1853
+	 * not just have a flag field on it switched
1854
+	 * Wrapper for EEM_Base::delete_permanently()
1855
+	 *
1856
+	 * @param mixed $id
1857
+	 * @param boolean $allow_blocking
1858
+	 * @return int the number of rows deleted
1859
+	 * @throws EE_Error
1860
+	 */
1861
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1862
+	{
1863
+		return $this->delete_permanently(
1864
+			array(
1865
+				array($this->get_primary_key_field()->get_name() => $id),
1866
+				'limit' => 1,
1867
+			),
1868
+			$allow_blocking
1869
+		);
1870
+	}
1871
+
1872
+
1873
+
1874
+	/**
1875
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1876
+	 * Wrapper for EEM_Base::delete()
1877
+	 *
1878
+	 * @param mixed $id
1879
+	 * @param boolean $allow_blocking
1880
+	 * @return int the number of rows deleted
1881
+	 * @throws EE_Error
1882
+	 */
1883
+	public function delete_by_ID($id, $allow_blocking = true)
1884
+	{
1885
+		return $this->delete(
1886
+			array(
1887
+				array($this->get_primary_key_field()->get_name() => $id),
1888
+				'limit' => 1,
1889
+			),
1890
+			$allow_blocking
1891
+		);
1892
+	}
1893
+
1894
+
1895
+
1896
+	/**
1897
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1898
+	 * meaning if the model has a field that indicates its been "trashed" or
1899
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1900
+	 *
1901
+	 * @see EEM_Base::delete_permanently
1902
+	 * @param array   $query_params
1903
+	 * @param boolean $allow_blocking
1904
+	 * @return int how many rows got deleted
1905
+	 * @throws EE_Error
1906
+	 */
1907
+	public function delete($query_params, $allow_blocking = true)
1908
+	{
1909
+		return $this->delete_permanently($query_params, $allow_blocking);
1910
+	}
1911
+
1912
+
1913
+
1914
+	/**
1915
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1916
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1917
+	 * as archived, not actually deleted
1918
+	 *
1919
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1920
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1921
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1922
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1923
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1924
+	 *                                DB
1925
+	 * @return int how many rows got deleted
1926
+	 * @throws EE_Error
1927
+	 */
1928
+	public function delete_permanently($query_params, $allow_blocking = true)
1929
+	{
1930
+		/**
1931
+		 * Action called just before performing a real deletion query. You can use the
1932
+		 * model and its $query_params to find exactly which items will be deleted
1933
+		 *
1934
+		 * @param EEM_Base $model
1935
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1936
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1937
+		 *                                 to block (prevent) this deletion
1938
+		 */
1939
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1940
+		// some MySQL databases may be running safe mode, which may restrict
1941
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1942
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1943
+		// to delete them
1944
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1945
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1946
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1947
+			$columns_and_ids_for_deleting
1948
+		);
1949
+		/**
1950
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1951
+		 *
1952
+		 * @param EEM_Base $this  The model instance being acted on.
1953
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1954
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1955
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1956
+		 *                                                  derived from the incoming query parameters.
1957
+		 *                                                  @see details on the structure of this array in the phpdocs
1958
+		 *                                                  for the `_get_ids_for_delete_method`
1959
+		 *
1960
+		 */
1961
+		do_action(
1962
+			'AHEE__EEM_Base__delete__before_query',
1963
+			$this,
1964
+			$query_params,
1965
+			$allow_blocking,
1966
+			$columns_and_ids_for_deleting
1967
+		);
1968
+		if ($deletion_where_query_part) {
1969
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1970
+			$table_aliases = array_keys($this->_tables);
1971
+			$SQL = "DELETE "
1972
+				   . implode(", ", $table_aliases)
1973
+				   . " FROM "
1974
+				   . $model_query_info->get_full_join_sql()
1975
+				   . " WHERE "
1976
+				   . $deletion_where_query_part;
1977
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1978
+		} else {
1979
+			$rows_deleted = 0;
1980
+		}
1981
+
1982
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1983
+		// there was no error with the delete query.
1984
+		if (
1985
+			$this->has_primary_key_field()
1986
+			&& $rows_deleted !== false
1987
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1988
+		) {
1989
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1990
+			foreach ($ids_for_removal as $id) {
1991
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1992
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1993
+				}
1994
+			}
1995
+
1996
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1997
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1998
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1999
+			// (although it is possible).
2000
+			// Note this can be skipped by using the provided filter and returning false.
2001
+			if (
2002
+				apply_filters(
2003
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2004
+					! $this instanceof EEM_Extra_Meta,
2005
+					$this
2006
+				)
2007
+			) {
2008
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2009
+					0 => array(
2010
+						'EXM_type' => $this->get_this_model_name(),
2011
+						'OBJ_ID'   => array(
2012
+							'IN',
2013
+							$ids_for_removal
2014
+						)
2015
+					)
2016
+				));
2017
+			}
2018
+		}
2019
+
2020
+		/**
2021
+		 * Action called just after performing a real deletion query. Although at this point the
2022
+		 * items should have been deleted
2023
+		 *
2024
+		 * @param EEM_Base $model
2025
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2026
+		 * @param int      $rows_deleted
2027
+		 */
2028
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
+		return $rows_deleted;// how many supposedly got deleted
2030
+	}
2031
+
2032
+
2033
+
2034
+	/**
2035
+	 * Checks all the relations that throw error messages when there are blocking related objects
2036
+	 * for related model objects. If there are any related model objects on those relations,
2037
+	 * adds an EE_Error, and return true
2038
+	 *
2039
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2040
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2041
+	 *                                                 should be ignored when determining whether there are related
2042
+	 *                                                 model objects which block this model object's deletion. Useful
2043
+	 *                                                 if you know A is related to B and are considering deleting A,
2044
+	 *                                                 but want to see if A has any other objects blocking its deletion
2045
+	 *                                                 before removing the relation between A and B
2046
+	 * @return boolean
2047
+	 * @throws EE_Error
2048
+	 */
2049
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2050
+	{
2051
+		// first, if $ignore_this_model_obj was supplied, get its model
2052
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2053
+			$ignored_model = $ignore_this_model_obj->get_model();
2054
+		} else {
2055
+			$ignored_model = null;
2056
+		}
2057
+		// now check all the relations of $this_model_obj_or_id and see if there
2058
+		// are any related model objects blocking it?
2059
+		$is_blocked = false;
2060
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2061
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2062
+				// if $ignore_this_model_obj was supplied, then for the query
2063
+				// on that model needs to be told to ignore $ignore_this_model_obj
2064
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2065
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2066
+						array(
2067
+							$ignored_model->get_primary_key_field()->get_name() => array(
2068
+								'!=',
2069
+								$ignore_this_model_obj->ID(),
2070
+							),
2071
+						),
2072
+					));
2073
+				} else {
2074
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2075
+				}
2076
+				if ($related_model_objects) {
2077
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2078
+					$is_blocked = true;
2079
+				}
2080
+			}
2081
+		}
2082
+		return $is_blocked;
2083
+	}
2084
+
2085
+
2086
+	/**
2087
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2088
+	 * @param array $row_results_for_deleting
2089
+	 * @param bool  $allow_blocking
2090
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2091
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2092
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2093
+	 *                 deleted. Example:
2094
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2095
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2096
+	 *                 where each element is a group of columns and values that get deleted. Example:
2097
+	 *                      array(
2098
+	 *                          0 => array(
2099
+	 *                              'Term_Relationship.object_id' => 1
2100
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2101
+	 *                          ),
2102
+	 *                          1 => array(
2103
+	 *                              'Term_Relationship.object_id' => 1
2104
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2105
+	 *                          )
2106
+	 *                      )
2107
+	 * @throws EE_Error
2108
+	 */
2109
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2110
+	{
2111
+		$ids_to_delete_indexed_by_column = array();
2112
+		if ($this->has_primary_key_field()) {
2113
+			$primary_table = $this->_get_main_table();
2114
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2115
+			$other_tables = $this->_get_other_tables();
2116
+			$ids_to_delete_indexed_by_column = $query = array();
2117
+			foreach ($row_results_for_deleting as $item_to_delete) {
2118
+				// before we mark this item for deletion,
2119
+				// make sure there's no related entities blocking its deletion (if we're checking)
2120
+				if (
2121
+					$allow_blocking
2122
+					&& $this->delete_is_blocked_by_related_models(
2123
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2124
+					)
2125
+				) {
2126
+					continue;
2127
+				}
2128
+				// primary table deletes
2129
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2130
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2131
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2132
+				}
2133
+			}
2134
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2135
+			$fields = $this->get_combined_primary_key_fields();
2136
+			foreach ($row_results_for_deleting as $item_to_delete) {
2137
+				$ids_to_delete_indexed_by_column_for_row = array();
2138
+				foreach ($fields as $cpk_field) {
2139
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2140
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2141
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2142
+					}
2143
+				}
2144
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2145
+			}
2146
+		} else {
2147
+			// so there's no primary key and no combined key...
2148
+			// sorry, can't help you
2149
+			throw new EE_Error(
2150
+				sprintf(
2151
+					esc_html__(
2152
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2153
+						"event_espresso"
2154
+					),
2155
+					get_class($this)
2156
+				)
2157
+			);
2158
+		}
2159
+		return $ids_to_delete_indexed_by_column;
2160
+	}
2161
+
2162
+
2163
+	/**
2164
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2165
+	 * the corresponding query_part for the query performing the delete.
2166
+	 *
2167
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2168
+	 * @return string
2169
+	 * @throws EE_Error
2170
+	 */
2171
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2172
+	{
2173
+		$query_part = '';
2174
+		if (empty($ids_to_delete_indexed_by_column)) {
2175
+			return $query_part;
2176
+		} elseif ($this->has_primary_key_field()) {
2177
+			$query = array();
2178
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2179
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2180
+			}
2181
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2182
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2183
+			$ways_to_identify_a_row = array();
2184
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2185
+				$values_for_each_combined_primary_key_for_a_row = array();
2186
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2187
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2188
+				}
2189
+				$ways_to_identify_a_row[] = '('
2190
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2191
+											. ')';
2192
+			}
2193
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2194
+		}
2195
+		return $query_part;
2196
+	}
2197
+
2198
+
2199
+
2200
+	/**
2201
+	 * Gets the model field by the fully qualified name
2202
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2203
+	 * @return EE_Model_Field_Base
2204
+	 */
2205
+	public function get_field_by_column($qualified_column_name)
2206
+	{
2207
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2208
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2209
+				return $field_obj;
2210
+			}
2211
+		}
2212
+		throw new EE_Error(
2213
+			sprintf(
2214
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2215
+				$this->get_this_model_name(),
2216
+				$qualified_column_name
2217
+			)
2218
+		);
2219
+	}
2220
+
2221
+
2222
+
2223
+	/**
2224
+	 * Count all the rows that match criteria the model query params.
2225
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2226
+	 * column
2227
+	 *
2228
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2229
+	 * @param string $field_to_count field on model to count by (not column name)
2230
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2231
+	 *                               that by the setting $distinct to TRUE;
2232
+	 * @return int
2233
+	 * @throws EE_Error
2234
+	 */
2235
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2236
+	{
2237
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2238
+		if ($field_to_count) {
2239
+			$field_obj = $this->field_settings_for($field_to_count);
2240
+			$column_to_count = $field_obj->get_qualified_column();
2241
+		} elseif ($this->has_primary_key_field()) {
2242
+			$pk_field_obj = $this->get_primary_key_field();
2243
+			$column_to_count = $pk_field_obj->get_qualified_column();
2244
+		} else {
2245
+			// there's no primary key
2246
+			// if we're counting distinct items, and there's no primary key,
2247
+			// we need to list out the columns for distinction;
2248
+			// otherwise we can just use star
2249
+			if ($distinct) {
2250
+				$columns_to_use = array();
2251
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2252
+					$columns_to_use[] = $field_obj->get_qualified_column();
2253
+				}
2254
+				$column_to_count = implode(',', $columns_to_use);
2255
+			} else {
2256
+				$column_to_count = '*';
2257
+			}
2258
+		}
2259
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2260
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2262
+	}
2263
+
2264
+
2265
+
2266
+	/**
2267
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2268
+	 *
2269
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2270
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2271
+	 * @return float
2272
+	 * @throws EE_Error
2273
+	 */
2274
+	public function sum($query_params, $field_to_sum = null)
2275
+	{
2276
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2277
+		if ($field_to_sum) {
2278
+			$field_obj = $this->field_settings_for($field_to_sum);
2279
+		} else {
2280
+			$field_obj = $this->get_primary_key_field();
2281
+		}
2282
+		$column_to_count = $field_obj->get_qualified_column();
2283
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2284
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2285
+		$data_type = $field_obj->get_wpdb_data_type();
2286
+		if ($data_type === '%d' || $data_type === '%s') {
2287
+			return (float) $return_value;
2288
+		}
2289
+		// must be %f
2290
+		return (float) $return_value;
2291
+	}
2292
+
2293
+
2294
+
2295
+	/**
2296
+	 * Just calls the specified method on $wpdb with the given arguments
2297
+	 * Consolidates a little extra error handling code
2298
+	 *
2299
+	 * @param string $wpdb_method
2300
+	 * @param array  $arguments_to_provide
2301
+	 * @throws EE_Error
2302
+	 * @global wpdb  $wpdb
2303
+	 * @return mixed
2304
+	 */
2305
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2306
+	{
2307
+		// if we're in maintenance mode level 2, DON'T run any queries
2308
+		// because level 2 indicates the database needs updating and
2309
+		// is probably out of sync with the code
2310
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2311
+			throw new EE_Error(sprintf(esc_html__(
2312
+				"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.",
2313
+				"event_espresso"
2314
+			)));
2315
+		}
2316
+		/** @type WPDB $wpdb */
2317
+		global $wpdb;
2318
+		if (! method_exists($wpdb, $wpdb_method)) {
2319
+			throw new EE_Error(sprintf(esc_html__(
2320
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2321
+				'event_espresso'
2322
+			), $wpdb_method));
2323
+		}
2324
+		if (WP_DEBUG) {
2325
+			$old_show_errors_value = $wpdb->show_errors;
2326
+			$wpdb->show_errors(false);
2327
+		}
2328
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2329
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2330
+		if (WP_DEBUG) {
2331
+			$wpdb->show_errors($old_show_errors_value);
2332
+			if (! empty($wpdb->last_error)) {
2333
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2334
+			}
2335
+			if ($result === false) {
2336
+				throw new EE_Error(sprintf(esc_html__(
2337
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2338
+					'event_espresso'
2339
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2340
+			}
2341
+		} elseif ($result === false) {
2342
+			EE_Error::add_error(
2343
+				sprintf(
2344
+					esc_html__(
2345
+						'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"',
2346
+						'event_espresso'
2347
+					),
2348
+					$wpdb_method,
2349
+					var_export($arguments_to_provide, true),
2350
+					$wpdb->last_error
2351
+				),
2352
+				__FILE__,
2353
+				__FUNCTION__,
2354
+				__LINE__
2355
+			);
2356
+		}
2357
+		return $result;
2358
+	}
2359
+
2360
+
2361
+
2362
+	/**
2363
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2364
+	 * and if there's an error tries to verify the DB is correct. Uses
2365
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2366
+	 * we should try to fix the EE core db, the addons, or just give up
2367
+	 *
2368
+	 * @param string $wpdb_method
2369
+	 * @param array  $arguments_to_provide
2370
+	 * @return mixed
2371
+	 */
2372
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2373
+	{
2374
+		/** @type WPDB $wpdb */
2375
+		global $wpdb;
2376
+		$wpdb->last_error = null;
2377
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2378
+		// was there an error running the query? but we don't care on new activations
2379
+		// (we're going to setup the DB anyway on new activations)
2380
+		if (
2381
+			($result === false || ! empty($wpdb->last_error))
2382
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2383
+		) {
2384
+			switch (EEM_Base::$_db_verification_level) {
2385
+				case EEM_Base::db_verified_none:
2386
+					// let's double-check core's DB
2387
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2388
+					break;
2389
+				case EEM_Base::db_verified_core:
2390
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2391
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2392
+					break;
2393
+				case EEM_Base::db_verified_addons:
2394
+					// ummmm... you in trouble
2395
+					return $result;
2396
+					break;
2397
+			}
2398
+			if (! empty($error_message)) {
2399
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2400
+				trigger_error($error_message);
2401
+			}
2402
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2403
+		}
2404
+		return $result;
2405
+	}
2406
+
2407
+
2408
+
2409
+	/**
2410
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2411
+	 * EEM_Base::$_db_verification_level
2412
+	 *
2413
+	 * @param string $wpdb_method
2414
+	 * @param array  $arguments_to_provide
2415
+	 * @return string
2416
+	 */
2417
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2418
+	{
2419
+		/** @type WPDB $wpdb */
2420
+		global $wpdb;
2421
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2422
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2423
+		$error_message = sprintf(
2424
+			esc_html__(
2425
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2426
+				'event_espresso'
2427
+			),
2428
+			$wpdb->last_error,
2429
+			$wpdb_method,
2430
+			wp_json_encode($arguments_to_provide)
2431
+		);
2432
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2433
+		return $error_message;
2434
+	}
2435
+
2436
+
2437
+
2438
+	/**
2439
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2440
+	 * EEM_Base::$_db_verification_level
2441
+	 *
2442
+	 * @param $wpdb_method
2443
+	 * @param $arguments_to_provide
2444
+	 * @return string
2445
+	 */
2446
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2447
+	{
2448
+		/** @type WPDB $wpdb */
2449
+		global $wpdb;
2450
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2451
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2452
+		$error_message = sprintf(
2453
+			esc_html__(
2454
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2455
+				'event_espresso'
2456
+			),
2457
+			$wpdb->last_error,
2458
+			$wpdb_method,
2459
+			wp_json_encode($arguments_to_provide)
2460
+		);
2461
+		EE_System::instance()->initialize_addons();
2462
+		return $error_message;
2463
+	}
2464
+
2465
+
2466
+
2467
+	/**
2468
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2469
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2470
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2471
+	 * ..."
2472
+	 *
2473
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2474
+	 * @return string
2475
+	 */
2476
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2477
+	{
2478
+		return " FROM " . $model_query_info->get_full_join_sql() .
2479
+			   $model_query_info->get_where_sql() .
2480
+			   $model_query_info->get_group_by_sql() .
2481
+			   $model_query_info->get_having_sql() .
2482
+			   $model_query_info->get_order_by_sql() .
2483
+			   $model_query_info->get_limit_sql();
2484
+	}
2485
+
2486
+
2487
+
2488
+	/**
2489
+	 * Set to easily debug the next X queries ran from this model.
2490
+	 *
2491
+	 * @param int $count
2492
+	 */
2493
+	public function show_next_x_db_queries($count = 1)
2494
+	{
2495
+		$this->_show_next_x_db_queries = $count;
2496
+	}
2497
+
2498
+
2499
+
2500
+	/**
2501
+	 * @param $sql_query
2502
+	 */
2503
+	public function show_db_query_if_previously_requested($sql_query)
2504
+	{
2505
+		if ($this->_show_next_x_db_queries > 0) {
2506
+			echo esc_html($sql_query);
2507
+			$this->_show_next_x_db_queries--;
2508
+		}
2509
+	}
2510
+
2511
+
2512
+
2513
+	/**
2514
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2515
+	 * There are the 3 cases:
2516
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2517
+	 * $otherModelObject has no ID, it is first saved.
2518
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2519
+	 * has no ID, it is first saved.
2520
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2521
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2522
+	 * join table
2523
+	 *
2524
+	 * @param        EE_Base_Class                     /int $thisModelObject
2525
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2526
+	 * @param string $relationName                     , key in EEM_Base::_relations
2527
+	 *                                                 an attendee to a group, you also want to specify which role they
2528
+	 *                                                 will have in that group. So you would use this parameter to
2529
+	 *                                                 specify array('role-column-name'=>'role-id')
2530
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2531
+	 *                                                 to for relation to methods that allow you to further specify
2532
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2533
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2534
+	 *                                                 because these will be inserted in any new rows created as well.
2535
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2536
+	 * @throws EE_Error
2537
+	 */
2538
+	public function add_relationship_to(
2539
+		$id_or_obj,
2540
+		$other_model_id_or_obj,
2541
+		$relationName,
2542
+		$extra_join_model_fields_n_values = array()
2543
+	) {
2544
+		$relation_obj = $this->related_settings_for($relationName);
2545
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2546
+	}
2547
+
2548
+
2549
+
2550
+	/**
2551
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2552
+	 * There are the 3 cases:
2553
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2554
+	 * error
2555
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2556
+	 * an error
2557
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2558
+	 *
2559
+	 * @param        EE_Base_Class /int $id_or_obj
2560
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2561
+	 * @param string $relationName key in EEM_Base::_relations
2562
+	 * @return boolean of success
2563
+	 * @throws EE_Error
2564
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2565
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2566
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2567
+	 *                             because these will be inserted in any new rows created as well.
2568
+	 */
2569
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2570
+	{
2571
+		$relation_obj = $this->related_settings_for($relationName);
2572
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2573
+	}
2574
+
2575
+
2576
+
2577
+	/**
2578
+	 * @param mixed           $id_or_obj
2579
+	 * @param string          $relationName
2580
+	 * @param array           $where_query_params
2581
+	 * @param EE_Base_Class[] objects to which relations were removed
2582
+	 * @return \EE_Base_Class[]
2583
+	 * @throws EE_Error
2584
+	 */
2585
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2586
+	{
2587
+		$relation_obj = $this->related_settings_for($relationName);
2588
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2589
+	}
2590
+
2591
+
2592
+
2593
+	/**
2594
+	 * Gets all the related items of the specified $model_name, using $query_params.
2595
+	 * Note: by default, we remove the "default query params"
2596
+	 * because we want to get even deleted items etc.
2597
+	 *
2598
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2599
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2600
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2601
+	 * @return EE_Base_Class[]
2602
+	 * @throws EE_Error
2603
+	 */
2604
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2605
+	{
2606
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2607
+		$relation_settings = $this->related_settings_for($model_name);
2608
+		return $relation_settings->get_all_related($model_obj, $query_params);
2609
+	}
2610
+
2611
+
2612
+
2613
+	/**
2614
+	 * Deletes all the model objects across the relation indicated by $model_name
2615
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2616
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2617
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2618
+	 *
2619
+	 * @param EE_Base_Class|int|string $id_or_obj
2620
+	 * @param string                   $model_name
2621
+	 * @param array                    $query_params
2622
+	 * @return int how many deleted
2623
+	 * @throws EE_Error
2624
+	 */
2625
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2626
+	{
2627
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2628
+		$relation_settings = $this->related_settings_for($model_name);
2629
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2630
+	}
2631
+
2632
+
2633
+
2634
+	/**
2635
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2636
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2637
+	 * the model objects can't be hard deleted because of blocking related model objects,
2638
+	 * just does a soft-delete on them instead.
2639
+	 *
2640
+	 * @param EE_Base_Class|int|string $id_or_obj
2641
+	 * @param string                   $model_name
2642
+	 * @param array                    $query_params
2643
+	 * @return int how many deleted
2644
+	 * @throws EE_Error
2645
+	 */
2646
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2647
+	{
2648
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2649
+		$relation_settings = $this->related_settings_for($model_name);
2650
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2651
+	}
2652
+
2653
+
2654
+
2655
+	/**
2656
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2657
+	 * unless otherwise specified in the $query_params
2658
+	 *
2659
+	 * @param        int             /EE_Base_Class $id_or_obj
2660
+	 * @param string $model_name     like 'Event', or 'Registration'
2661
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2662
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2663
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2664
+	 *                               that by the setting $distinct to TRUE;
2665
+	 * @return int
2666
+	 * @throws EE_Error
2667
+	 */
2668
+	public function count_related(
2669
+		$id_or_obj,
2670
+		$model_name,
2671
+		$query_params = array(),
2672
+		$field_to_count = null,
2673
+		$distinct = false
2674
+	) {
2675
+		$related_model = $this->get_related_model_obj($model_name);
2676
+		// we're just going to use the query params on the related model's normal get_all query,
2677
+		// except add a condition to say to match the current mod
2678
+		if (! isset($query_params['default_where_conditions'])) {
2679
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2680
+		}
2681
+		$this_model_name = $this->get_this_model_name();
2682
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2683
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2684
+		return $related_model->count($query_params, $field_to_count, $distinct);
2685
+	}
2686
+
2687
+
2688
+
2689
+	/**
2690
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2691
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2692
+	 *
2693
+	 * @param        int           /EE_Base_Class $id_or_obj
2694
+	 * @param string $model_name   like 'Event', or 'Registration'
2695
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2696
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2697
+	 * @return float
2698
+	 * @throws EE_Error
2699
+	 */
2700
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2701
+	{
2702
+		$related_model = $this->get_related_model_obj($model_name);
2703
+		if (! is_array($query_params)) {
2704
+			EE_Error::doing_it_wrong(
2705
+				'EEM_Base::sum_related',
2706
+				sprintf(
2707
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2708
+					gettype($query_params)
2709
+				),
2710
+				'4.6.0'
2711
+			);
2712
+			$query_params = array();
2713
+		}
2714
+		// we're just going to use the query params on the related model's normal get_all query,
2715
+		// except add a condition to say to match the current mod
2716
+		if (! isset($query_params['default_where_conditions'])) {
2717
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2718
+		}
2719
+		$this_model_name = $this->get_this_model_name();
2720
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2721
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2722
+		return $related_model->sum($query_params, $field_to_sum);
2723
+	}
2724
+
2725
+
2726
+
2727
+	/**
2728
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2729
+	 * $modelObject
2730
+	 *
2731
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2732
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2733
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2734
+	 * @return EE_Base_Class
2735
+	 * @throws EE_Error
2736
+	 */
2737
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2738
+	{
2739
+		$query_params['limit'] = 1;
2740
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2741
+		if ($results) {
2742
+			return array_shift($results);
2743
+		}
2744
+		return null;
2745
+	}
2746
+
2747
+
2748
+
2749
+	/**
2750
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2751
+	 *
2752
+	 * @return string
2753
+	 */
2754
+	public function get_this_model_name()
2755
+	{
2756
+		return str_replace("EEM_", "", get_class($this));
2757
+	}
2758
+
2759
+
2760
+
2761
+	/**
2762
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2763
+	 *
2764
+	 * @return EE_Any_Foreign_Model_Name_Field
2765
+	 * @throws EE_Error
2766
+	 */
2767
+	public function get_field_containing_related_model_name()
2768
+	{
2769
+		foreach ($this->field_settings(true) as $field) {
2770
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2771
+				$field_with_model_name = $field;
2772
+			}
2773
+		}
2774
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2775
+			throw new EE_Error(sprintf(
2776
+				esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2777
+				$this->get_this_model_name()
2778
+			));
2779
+		}
2780
+		return $field_with_model_name;
2781
+	}
2782
+
2783
+
2784
+
2785
+	/**
2786
+	 * Inserts a new entry into the database, for each table.
2787
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2788
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2789
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2790
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2791
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2792
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2793
+	 *
2794
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2795
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2796
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2797
+	 *                              of EEM_Base)
2798
+	 * @return int|string new primary key on main table that got inserted
2799
+	 * @throws EE_Error
2800
+	 */
2801
+	public function insert($field_n_values)
2802
+	{
2803
+		/**
2804
+		 * Filters the fields and their values before inserting an item using the models
2805
+		 *
2806
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2807
+		 * @param EEM_Base $model           the model used
2808
+		 */
2809
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2810
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2811
+			$main_table = $this->_get_main_table();
2812
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2813
+			if ($new_id !== false) {
2814
+				foreach ($this->_get_other_tables() as $other_table) {
2815
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2816
+				}
2817
+			}
2818
+			/**
2819
+			 * Done just after attempting to insert a new model object
2820
+			 *
2821
+			 * @param EEM_Base   $model           used
2822
+			 * @param array      $fields_n_values fields and their values
2823
+			 * @param int|string the              ID of the newly-inserted model object
2824
+			 */
2825
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2826
+			return $new_id;
2827
+		}
2828
+		return false;
2829
+	}
2830
+
2831
+
2832
+
2833
+	/**
2834
+	 * Checks that the result would satisfy the unique indexes on this model
2835
+	 *
2836
+	 * @param array  $field_n_values
2837
+	 * @param string $action
2838
+	 * @return boolean
2839
+	 * @throws EE_Error
2840
+	 */
2841
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2842
+	{
2843
+		foreach ($this->unique_indexes() as $index_name => $index) {
2844
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2845
+			if ($this->exists(array($uniqueness_where_params))) {
2846
+				EE_Error::add_error(
2847
+					sprintf(
2848
+						esc_html__(
2849
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2850
+							"event_espresso"
2851
+						),
2852
+						$action,
2853
+						$this->_get_class_name(),
2854
+						$index_name,
2855
+						implode(",", $index->field_names()),
2856
+						http_build_query($uniqueness_where_params)
2857
+					),
2858
+					__FILE__,
2859
+					__FUNCTION__,
2860
+					__LINE__
2861
+				);
2862
+				return false;
2863
+			}
2864
+		}
2865
+		return true;
2866
+	}
2867
+
2868
+
2869
+
2870
+	/**
2871
+	 * Checks the database for an item that conflicts (ie, if this item were
2872
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2873
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2874
+	 * can be either an EE_Base_Class or an array of fields n values
2875
+	 *
2876
+	 * @param EE_Base_Class|array $obj_or_fields_array
2877
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2878
+	 *                                                 when looking for conflicts
2879
+	 *                                                 (ie, if false, we ignore the model object's primary key
2880
+	 *                                                 when finding "conflicts". If true, it's also considered).
2881
+	 *                                                 Only works for INT primary key,
2882
+	 *                                                 STRING primary keys cannot be ignored
2883
+	 * @throws EE_Error
2884
+	 * @return EE_Base_Class|array
2885
+	 */
2886
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2887
+	{
2888
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2889
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2890
+		} elseif (is_array($obj_or_fields_array)) {
2891
+			$fields_n_values = $obj_or_fields_array;
2892
+		} else {
2893
+			throw new EE_Error(
2894
+				sprintf(
2895
+					esc_html__(
2896
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2897
+						"event_espresso"
2898
+					),
2899
+					get_class($this),
2900
+					$obj_or_fields_array
2901
+				)
2902
+			);
2903
+		}
2904
+		$query_params = array();
2905
+		if (
2906
+			$this->has_primary_key_field()
2907
+			&& ($include_primary_key
2908
+				|| $this->get_primary_key_field()
2909
+				   instanceof
2910
+				   EE_Primary_Key_String_Field)
2911
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2912
+		) {
2913
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2914
+		}
2915
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2916
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2917
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2918
+		}
2919
+		// if there is nothing to base this search on, then we shouldn't find anything
2920
+		if (empty($query_params)) {
2921
+			return array();
2922
+		}
2923
+		return $this->get_one($query_params);
2924
+	}
2925
+
2926
+
2927
+
2928
+	/**
2929
+	 * Like count, but is optimized and returns a boolean instead of an int
2930
+	 *
2931
+	 * @param array $query_params
2932
+	 * @return boolean
2933
+	 * @throws EE_Error
2934
+	 */
2935
+	public function exists($query_params)
2936
+	{
2937
+		$query_params['limit'] = 1;
2938
+		return $this->count($query_params) > 0;
2939
+	}
2940
+
2941
+
2942
+
2943
+	/**
2944
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2945
+	 *
2946
+	 * @param int|string $id
2947
+	 * @return boolean
2948
+	 * @throws EE_Error
2949
+	 */
2950
+	public function exists_by_ID($id)
2951
+	{
2952
+		return $this->exists(
2953
+			array(
2954
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2955
+				array(
2956
+					$this->primary_key_name() => $id,
2957
+				),
2958
+			)
2959
+		);
2960
+	}
2961
+
2962
+
2963
+
2964
+	/**
2965
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2966
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2967
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2968
+	 * on the main table)
2969
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2970
+	 * cases where we want to call it directly rather than via insert().
2971
+	 *
2972
+	 * @access   protected
2973
+	 * @param EE_Table_Base $table
2974
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2975
+	 *                                       float
2976
+	 * @param int           $new_id          for now we assume only int keys
2977
+	 * @throws EE_Error
2978
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2979
+	 * @return int ID of new row inserted, or FALSE on failure
2980
+	 */
2981
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2982
+	{
2983
+		global $wpdb;
2984
+		$insertion_col_n_values = array();
2985
+		$format_for_insertion = array();
2986
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2987
+		foreach ($fields_on_table as $field_name => $field_obj) {
2988
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2989
+			if ($field_obj->is_auto_increment()) {
2990
+				continue;
2991
+			}
2992
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2993
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2994
+			if ($prepared_value !== null) {
2995
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2996
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2997
+			}
2998
+		}
2999
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3000
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3001
+			// so add the fk to the main table as a column
3002
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3003
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
3004
+		}
3005
+		// insert the new entry
3006
+		$result = $this->_do_wpdb_query(
3007
+			'insert',
3008
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3009
+		);
3010
+		if ($result === false) {
3011
+			return false;
3012
+		}
3013
+		// ok, now what do we return for the ID of the newly-inserted thing?
3014
+		if ($this->has_primary_key_field()) {
3015
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3016
+				return $wpdb->insert_id;
3017
+			}
3018
+			// it's not an auto-increment primary key, so
3019
+			// it must have been supplied
3020
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3021
+		}
3022
+		// we can't return a  primary key because there is none. instead return
3023
+		// a unique string indicating this model
3024
+		return $this->get_index_primary_key_string($fields_n_values);
3025
+	}
3026
+
3027
+
3028
+
3029
+	/**
3030
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3031
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3032
+	 * and there is no default, we pass it along. WPDB will take care of it)
3033
+	 *
3034
+	 * @param EE_Model_Field_Base $field_obj
3035
+	 * @param array               $fields_n_values
3036
+	 * @return mixed string|int|float depending on what the table column will be expecting
3037
+	 * @throws EE_Error
3038
+	 */
3039
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3040
+	{
3041
+		// if this field doesn't allow nullable, don't allow it
3042
+		if (
3043
+			! $field_obj->is_nullable()
3044
+			&& (
3045
+				! isset($fields_n_values[ $field_obj->get_name() ])
3046
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3047
+			)
3048
+		) {
3049
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3050
+		}
3051
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3052
+			? $fields_n_values[ $field_obj->get_name() ]
3053
+			: null;
3054
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3055
+	}
3056
+
3057
+
3058
+
3059
+	/**
3060
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3061
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3062
+	 * the field's prepare_for_set() method.
3063
+	 *
3064
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3065
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3066
+	 *                                   top of file)
3067
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3068
+	 *                                   $value is a custom selection
3069
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3070
+	 */
3071
+	private function _prepare_value_for_use_in_db($value, $field)
3072
+	{
3073
+		if ($field && $field instanceof EE_Model_Field_Base) {
3074
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3075
+			switch ($this->_values_already_prepared_by_model_object) {
3076
+				/** @noinspection PhpMissingBreakStatementInspection */
3077
+				case self::not_prepared_by_model_object:
3078
+					$value = $field->prepare_for_set($value);
3079
+				// purposefully left out "return"
3080
+				case self::prepared_by_model_object:
3081
+					/** @noinspection SuspiciousAssignmentsInspection */
3082
+					$value = $field->prepare_for_use_in_db($value);
3083
+				case self::prepared_for_use_in_db:
3084
+					// leave the value alone
3085
+			}
3086
+			return $value;
3087
+			// phpcs:enable
3088
+		}
3089
+		return $value;
3090
+	}
3091
+
3092
+
3093
+
3094
+	/**
3095
+	 * Returns the main table on this model
3096
+	 *
3097
+	 * @return EE_Primary_Table
3098
+	 * @throws EE_Error
3099
+	 */
3100
+	protected function _get_main_table()
3101
+	{
3102
+		foreach ($this->_tables as $table) {
3103
+			if ($table instanceof EE_Primary_Table) {
3104
+				return $table;
3105
+			}
3106
+		}
3107
+		throw new EE_Error(sprintf(esc_html__(
3108
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3109
+			'event_espresso'
3110
+		), get_class($this)));
3111
+	}
3112
+
3113
+
3114
+
3115
+	/**
3116
+	 * table
3117
+	 * returns EE_Primary_Table table name
3118
+	 *
3119
+	 * @return string
3120
+	 * @throws EE_Error
3121
+	 */
3122
+	public function table()
3123
+	{
3124
+		return $this->_get_main_table()->get_table_name();
3125
+	}
3126
+
3127
+
3128
+
3129
+	/**
3130
+	 * table
3131
+	 * returns first EE_Secondary_Table table name
3132
+	 *
3133
+	 * @return string
3134
+	 */
3135
+	public function second_table()
3136
+	{
3137
+		// grab second table from tables array
3138
+		$second_table = end($this->_tables);
3139
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3140
+	}
3141
+
3142
+
3143
+
3144
+	/**
3145
+	 * get_table_obj_by_alias
3146
+	 * returns table name given it's alias
3147
+	 *
3148
+	 * @param string $table_alias
3149
+	 * @return EE_Primary_Table | EE_Secondary_Table
3150
+	 */
3151
+	public function get_table_obj_by_alias($table_alias = '')
3152
+	{
3153
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3154
+	}
3155
+
3156
+
3157
+
3158
+	/**
3159
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3160
+	 *
3161
+	 * @return EE_Secondary_Table[]
3162
+	 */
3163
+	protected function _get_other_tables()
3164
+	{
3165
+		$other_tables = array();
3166
+		foreach ($this->_tables as $table_alias => $table) {
3167
+			if ($table instanceof EE_Secondary_Table) {
3168
+				$other_tables[ $table_alias ] = $table;
3169
+			}
3170
+		}
3171
+		return $other_tables;
3172
+	}
3173
+
3174
+
3175
+
3176
+	/**
3177
+	 * Finds all the fields that correspond to the given table
3178
+	 *
3179
+	 * @param string $table_alias , array key in EEM_Base::_tables
3180
+	 * @return EE_Model_Field_Base[]
3181
+	 */
3182
+	public function _get_fields_for_table($table_alias)
3183
+	{
3184
+		return $this->_fields[ $table_alias ];
3185
+	}
3186
+
3187
+
3188
+
3189
+	/**
3190
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3191
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3192
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3193
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3194
+	 * related Registration, Transaction, and Payment models.
3195
+	 *
3196
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3197
+	 * @return EE_Model_Query_Info_Carrier
3198
+	 * @throws EE_Error
3199
+	 */
3200
+	public function _extract_related_models_from_query($query_params)
3201
+	{
3202
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3203
+		if (array_key_exists(0, $query_params)) {
3204
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3205
+		}
3206
+		if (array_key_exists('group_by', $query_params)) {
3207
+			if (is_array($query_params['group_by'])) {
3208
+				$this->_extract_related_models_from_sub_params_array_values(
3209
+					$query_params['group_by'],
3210
+					$query_info_carrier,
3211
+					'group_by'
3212
+				);
3213
+			} elseif (! empty($query_params['group_by'])) {
3214
+				$this->_extract_related_model_info_from_query_param(
3215
+					$query_params['group_by'],
3216
+					$query_info_carrier,
3217
+					'group_by'
3218
+				);
3219
+			}
3220
+		}
3221
+		if (array_key_exists('having', $query_params)) {
3222
+			$this->_extract_related_models_from_sub_params_array_keys(
3223
+				$query_params[0],
3224
+				$query_info_carrier,
3225
+				'having'
3226
+			);
3227
+		}
3228
+		if (array_key_exists('order_by', $query_params)) {
3229
+			if (is_array($query_params['order_by'])) {
3230
+				$this->_extract_related_models_from_sub_params_array_keys(
3231
+					$query_params['order_by'],
3232
+					$query_info_carrier,
3233
+					'order_by'
3234
+				);
3235
+			} elseif (! empty($query_params['order_by'])) {
3236
+				$this->_extract_related_model_info_from_query_param(
3237
+					$query_params['order_by'],
3238
+					$query_info_carrier,
3239
+					'order_by'
3240
+				);
3241
+			}
3242
+		}
3243
+		if (array_key_exists('force_join', $query_params)) {
3244
+			$this->_extract_related_models_from_sub_params_array_values(
3245
+				$query_params['force_join'],
3246
+				$query_info_carrier,
3247
+				'force_join'
3248
+			);
3249
+		}
3250
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3251
+		return $query_info_carrier;
3252
+	}
3253
+
3254
+
3255
+
3256
+	/**
3257
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3258
+	 *
3259
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3260
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3261
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3262
+	 * @throws EE_Error
3263
+	 * @return \EE_Model_Query_Info_Carrier
3264
+	 */
3265
+	private function _extract_related_models_from_sub_params_array_keys(
3266
+		$sub_query_params,
3267
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3268
+		$query_param_type
3269
+	) {
3270
+		if (! empty($sub_query_params)) {
3271
+			$sub_query_params = (array) $sub_query_params;
3272
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3273
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3274
+				$this->_extract_related_model_info_from_query_param(
3275
+					$param,
3276
+					$model_query_info_carrier,
3277
+					$query_param_type
3278
+				);
3279
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3280
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3281
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3282
+				// of array('Registration.TXN_ID'=>23)
3283
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
+					if (! is_array($possibly_array_of_params)) {
3286
+						throw new EE_Error(sprintf(
3287
+							esc_html__(
3288
+								"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'))",
3289
+								"event_espresso"
3290
+							),
3291
+							$param,
3292
+							$possibly_array_of_params
3293
+						));
3294
+					}
3295
+					$this->_extract_related_models_from_sub_params_array_keys(
3296
+						$possibly_array_of_params,
3297
+						$model_query_info_carrier,
3298
+						$query_param_type
3299
+					);
3300
+				} elseif (
3301
+					$query_param_type === 0 // ie WHERE
3302
+						  && is_array($possibly_array_of_params)
3303
+						  && isset($possibly_array_of_params[2])
3304
+						  && $possibly_array_of_params[2] == true
3305
+				) {
3306
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3307
+					// indicating that $possible_array_of_params[1] is actually a field name,
3308
+					// from which we should extract query parameters!
3309
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3310
+						throw new EE_Error(sprintf(esc_html__(
3311
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3312
+							"event_espresso"
3313
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3314
+					}
3315
+					$this->_extract_related_model_info_from_query_param(
3316
+						$possibly_array_of_params[1],
3317
+						$model_query_info_carrier,
3318
+						$query_param_type
3319
+					);
3320
+				}
3321
+			}
3322
+		}
3323
+		return $model_query_info_carrier;
3324
+	}
3325
+
3326
+
3327
+
3328
+	/**
3329
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3330
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3331
+	 *
3332
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3333
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3334
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3335
+	 * @throws EE_Error
3336
+	 * @return \EE_Model_Query_Info_Carrier
3337
+	 */
3338
+	private function _extract_related_models_from_sub_params_array_values(
3339
+		$sub_query_params,
3340
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3341
+		$query_param_type
3342
+	) {
3343
+		if (! empty($sub_query_params)) {
3344
+			if (! is_array($sub_query_params)) {
3345
+				throw new EE_Error(sprintf(
3346
+					esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3347
+					$sub_query_params
3348
+				));
3349
+			}
3350
+			foreach ($sub_query_params as $param) {
3351
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3352
+				$this->_extract_related_model_info_from_query_param(
3353
+					$param,
3354
+					$model_query_info_carrier,
3355
+					$query_param_type
3356
+				);
3357
+			}
3358
+		}
3359
+		return $model_query_info_carrier;
3360
+	}
3361
+
3362
+
3363
+	/**
3364
+	 * Extract all the query parts from  model query params
3365
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3366
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3367
+	 * but use them in a different order. Eg, we need to know what models we are querying
3368
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3369
+	 * other models before we can finalize the where clause SQL.
3370
+	 *
3371
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3372
+	 * @throws EE_Error
3373
+	 * @return EE_Model_Query_Info_Carrier
3374
+	 * @throws ModelConfigurationException
3375
+	 */
3376
+	public function _create_model_query_info_carrier($query_params)
3377
+	{
3378
+		if (! is_array($query_params)) {
3379
+			EE_Error::doing_it_wrong(
3380
+				'EEM_Base::_create_model_query_info_carrier',
3381
+				sprintf(
3382
+					esc_html__(
3383
+						'$query_params should be an array, you passed a variable of type %s',
3384
+						'event_espresso'
3385
+					),
3386
+					gettype($query_params)
3387
+				),
3388
+				'4.6.0'
3389
+			);
3390
+			$query_params = array();
3391
+		}
3392
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3393
+		// first check if we should alter the query to account for caps or not
3394
+		// because the caps might require us to do extra joins
3395
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3396
+			$query_params[0] = array_replace_recursive(
3397
+				$query_params[0],
3398
+				$this->caps_where_conditions(
3399
+					$query_params['caps']
3400
+				)
3401
+			);
3402
+		}
3403
+
3404
+		// check if we should alter the query to remove data related to protected
3405
+		// custom post types
3406
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3407
+			$where_param_key_for_password = $this->modelChainAndPassword();
3408
+			// only include if related to a cpt where no password has been set
3409
+			$query_params[0]['OR*nopassword'] = array(
3410
+				$where_param_key_for_password => '',
3411
+				$where_param_key_for_password . '*' => array('IS_NULL')
3412
+			);
3413
+		}
3414
+		$query_object = $this->_extract_related_models_from_query($query_params);
3415
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3416
+		foreach ($query_params[0] as $key => $value) {
3417
+			if (is_int($key)) {
3418
+				throw new EE_Error(
3419
+					sprintf(
3420
+						esc_html__(
3421
+							"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.",
3422
+							"event_espresso"
3423
+						),
3424
+						$key,
3425
+						var_export($value, true),
3426
+						var_export($query_params, true),
3427
+						get_class($this)
3428
+					)
3429
+				);
3430
+			}
3431
+		}
3432
+		if (
3433
+			array_key_exists('default_where_conditions', $query_params)
3434
+			&& ! empty($query_params['default_where_conditions'])
3435
+		) {
3436
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3437
+		} else {
3438
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3439
+		}
3440
+		$query_params[0] = array_merge(
3441
+			$this->_get_default_where_conditions_for_models_in_query(
3442
+				$query_object,
3443
+				$use_default_where_conditions,
3444
+				$query_params[0]
3445
+			),
3446
+			$query_params[0]
3447
+		);
3448
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3449
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3450
+		// So we need to setup a subquery and use that for the main join.
3451
+		// Note for now this only works on the primary table for the model.
3452
+		// So for instance, you could set the limit array like this:
3453
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3454
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3455
+			$query_object->set_main_model_join_sql(
3456
+				$this->_construct_limit_join_select(
3457
+					$query_params['on_join_limit'][0],
3458
+					$query_params['on_join_limit'][1]
3459
+				)
3460
+			);
3461
+		}
3462
+		// set limit
3463
+		if (array_key_exists('limit', $query_params)) {
3464
+			if (is_array($query_params['limit'])) {
3465
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3466
+					$e = sprintf(
3467
+						esc_html__(
3468
+							"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)",
3469
+							"event_espresso"
3470
+						),
3471
+						http_build_query($query_params['limit'])
3472
+					);
3473
+					throw new EE_Error($e . "|" . $e);
3474
+				}
3475
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3476
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3477
+			} elseif (! empty($query_params['limit'])) {
3478
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3479
+			}
3480
+		}
3481
+		// set order by
3482
+		if (array_key_exists('order_by', $query_params)) {
3483
+			if (is_array($query_params['order_by'])) {
3484
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3485
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3486
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3487
+				if (array_key_exists('order', $query_params)) {
3488
+					throw new EE_Error(
3489
+						sprintf(
3490
+							esc_html__(
3491
+								"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 ",
3492
+								"event_espresso"
3493
+							),
3494
+							get_class($this),
3495
+							implode(", ", array_keys($query_params['order_by'])),
3496
+							implode(", ", $query_params['order_by']),
3497
+							$query_params['order']
3498
+						)
3499
+					);
3500
+				}
3501
+				$this->_extract_related_models_from_sub_params_array_keys(
3502
+					$query_params['order_by'],
3503
+					$query_object,
3504
+					'order_by'
3505
+				);
3506
+				// assume it's an array of fields to order by
3507
+				$order_array = array();
3508
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3509
+					$order = $this->_extract_order($order);
3510
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3511
+				}
3512
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3513
+			} elseif (! empty($query_params['order_by'])) {
3514
+				$this->_extract_related_model_info_from_query_param(
3515
+					$query_params['order_by'],
3516
+					$query_object,
3517
+					'order',
3518
+					$query_params['order_by']
3519
+				);
3520
+				$order = isset($query_params['order'])
3521
+					? $this->_extract_order($query_params['order'])
3522
+					: 'DESC';
3523
+				$query_object->set_order_by_sql(
3524
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3525
+				);
3526
+			}
3527
+		}
3528
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3529
+		if (
3530
+			! array_key_exists('order_by', $query_params)
3531
+			&& array_key_exists('order', $query_params)
3532
+			&& ! empty($query_params['order'])
3533
+		) {
3534
+			$pk_field = $this->get_primary_key_field();
3535
+			$order = $this->_extract_order($query_params['order']);
3536
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3537
+		}
3538
+		// set group by
3539
+		if (array_key_exists('group_by', $query_params)) {
3540
+			if (is_array($query_params['group_by'])) {
3541
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3542
+				$group_by_array = array();
3543
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3544
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3545
+				}
3546
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3547
+			} elseif (! empty($query_params['group_by'])) {
3548
+				$query_object->set_group_by_sql(
3549
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3550
+				);
3551
+			}
3552
+		}
3553
+		// set having
3554
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3555
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3556
+		}
3557
+		// now, just verify they didn't pass anything wack
3558
+		foreach ($query_params as $query_key => $query_value) {
3559
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3560
+				throw new EE_Error(
3561
+					sprintf(
3562
+						esc_html__(
3563
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3564
+							'event_espresso'
3565
+						),
3566
+						$query_key,
3567
+						get_class($this),
3568
+						//                      print_r( $this->_allowed_query_params, TRUE )
3569
+						implode(',', $this->_allowed_query_params)
3570
+					)
3571
+				);
3572
+			}
3573
+		}
3574
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3575
+		if (empty($main_model_join_sql)) {
3576
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3577
+		}
3578
+		return $query_object;
3579
+	}
3580
+
3581
+
3582
+
3583
+	/**
3584
+	 * Gets the where conditions that should be imposed on the query based on the
3585
+	 * context (eg reading frontend, backend, edit or delete).
3586
+	 *
3587
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3588
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3589
+	 * @throws EE_Error
3590
+	 */
3591
+	public function caps_where_conditions($context = self::caps_read)
3592
+	{
3593
+		EEM_Base::verify_is_valid_cap_context($context);
3594
+		$cap_where_conditions = array();
3595
+		$cap_restrictions = $this->caps_missing($context);
3596
+		/**
3597
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3598
+		 */
3599
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3600
+			$cap_where_conditions = array_replace_recursive(
3601
+				$cap_where_conditions,
3602
+				$restriction_if_no_cap->get_default_where_conditions()
3603
+			);
3604
+		}
3605
+		return apply_filters(
3606
+			'FHEE__EEM_Base__caps_where_conditions__return',
3607
+			$cap_where_conditions,
3608
+			$this,
3609
+			$context,
3610
+			$cap_restrictions
3611
+		);
3612
+	}
3613
+
3614
+
3615
+
3616
+	/**
3617
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3618
+	 * otherwise throws an exception
3619
+	 *
3620
+	 * @param string $should_be_order_string
3621
+	 * @return string either ASC, asc, DESC or desc
3622
+	 * @throws EE_Error
3623
+	 */
3624
+	private function _extract_order($should_be_order_string)
3625
+	{
3626
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3627
+			return $should_be_order_string;
3628
+		}
3629
+		throw new EE_Error(
3630
+			sprintf(
3631
+				esc_html__(
3632
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3633
+					"event_espresso"
3634
+				),
3635
+				get_class($this),
3636
+				$should_be_order_string
3637
+			)
3638
+		);
3639
+	}
3640
+
3641
+
3642
+
3643
+	/**
3644
+	 * Looks at all the models which are included in this query, and asks each
3645
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3646
+	 * so they can be merged
3647
+	 *
3648
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3649
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3650
+	 *                                                                  'none' means NO default where conditions will
3651
+	 *                                                                  be used AT ALL during this query.
3652
+	 *                                                                  'other_models_only' means default where
3653
+	 *                                                                  conditions from other models will be used, but
3654
+	 *                                                                  not for this primary model. 'all', the default,
3655
+	 *                                                                  means default where conditions will apply as
3656
+	 *                                                                  normal
3657
+	 * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3658
+	 * @throws EE_Error
3659
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3660
+	 */
3661
+	private function _get_default_where_conditions_for_models_in_query(
3662
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3663
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3664
+		$where_query_params = array()
3665
+	) {
3666
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3667
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3668
+			throw new EE_Error(sprintf(
3669
+				esc_html__(
3670
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3671
+					"event_espresso"
3672
+				),
3673
+				$use_default_where_conditions,
3674
+				implode(", ", $allowed_used_default_where_conditions_values)
3675
+			));
3676
+		}
3677
+		$universal_query_params = array();
3678
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3679
+			$universal_query_params = $this->_get_default_where_conditions();
3680
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3681
+			$universal_query_params = $this->_get_minimum_where_conditions();
3682
+		}
3683
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3684
+			$related_model = $this->get_related_model_obj($model_name);
3685
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3686
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3687
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3688
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3689
+			} else {
3690
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3691
+				continue;
3692
+			}
3693
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3694
+				$related_model_universal_where_params,
3695
+				$where_query_params,
3696
+				$related_model,
3697
+				$model_relation_path
3698
+			);
3699
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3700
+				$universal_query_params,
3701
+				$overrides
3702
+			);
3703
+		}
3704
+		return $universal_query_params;
3705
+	}
3706
+
3707
+
3708
+
3709
+	/**
3710
+	 * Determines whether or not we should use default where conditions for the model in question
3711
+	 * (this model, or other related models).
3712
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3713
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3714
+	 * We should use default where conditions on related models when they requested to use default where conditions
3715
+	 * on all models, or specifically just on other related models
3716
+	 * @param      $default_where_conditions_value
3717
+	 * @param bool $for_this_model false means this is for OTHER related models
3718
+	 * @return bool
3719
+	 */
3720
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3721
+	{
3722
+		return (
3723
+				   $for_this_model
3724
+				   && in_array(
3725
+					   $default_where_conditions_value,
3726
+					   array(
3727
+						   EEM_Base::default_where_conditions_all,
3728
+						   EEM_Base::default_where_conditions_this_only,
3729
+						   EEM_Base::default_where_conditions_minimum_others,
3730
+					   ),
3731
+					   true
3732
+				   )
3733
+			   )
3734
+			   || (
3735
+				   ! $for_this_model
3736
+				   && in_array(
3737
+					   $default_where_conditions_value,
3738
+					   array(
3739
+						   EEM_Base::default_where_conditions_all,
3740
+						   EEM_Base::default_where_conditions_others_only,
3741
+					   ),
3742
+					   true
3743
+				   )
3744
+			   );
3745
+	}
3746
+
3747
+	/**
3748
+	 * Determines whether or not we should use default minimum conditions for the model in question
3749
+	 * (this model, or other related models).
3750
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3751
+	 * where conditions.
3752
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3753
+	 * on this model or others
3754
+	 * @param      $default_where_conditions_value
3755
+	 * @param bool $for_this_model false means this is for OTHER related models
3756
+	 * @return bool
3757
+	 */
3758
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3759
+	{
3760
+		return (
3761
+				   $for_this_model
3762
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3763
+			   )
3764
+			   || (
3765
+				   ! $for_this_model
3766
+				   && in_array(
3767
+					   $default_where_conditions_value,
3768
+					   array(
3769
+						   EEM_Base::default_where_conditions_minimum_others,
3770
+						   EEM_Base::default_where_conditions_minimum_all,
3771
+					   ),
3772
+					   true
3773
+				   )
3774
+			   );
3775
+	}
3776
+
3777
+
3778
+	/**
3779
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3780
+	 * then we also add a special where condition which allows for that model's primary key
3781
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3782
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3783
+	 *
3784
+	 * @param array    $default_where_conditions
3785
+	 * @param array    $provided_where_conditions
3786
+	 * @param EEM_Base $model
3787
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3788
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3789
+	 * @throws EE_Error
3790
+	 */
3791
+	private function _override_defaults_or_make_null_friendly(
3792
+		$default_where_conditions,
3793
+		$provided_where_conditions,
3794
+		$model,
3795
+		$model_relation_path
3796
+	) {
3797
+		$null_friendly_where_conditions = array();
3798
+		$none_overridden = true;
3799
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3800
+		foreach ($default_where_conditions as $key => $val) {
3801
+			if (isset($provided_where_conditions[ $key ])) {
3802
+				$none_overridden = false;
3803
+			} else {
3804
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3805
+			}
3806
+		}
3807
+		if ($none_overridden && $default_where_conditions) {
3808
+			if ($model->has_primary_key_field()) {
3809
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3810
+																				. "."
3811
+																				. $model->primary_key_name() ] = array('IS NULL');
3812
+			}/*else{
3813 3813
                 //@todo NO PK, use other defaults
3814 3814
             }*/
3815
-        }
3816
-        return $null_friendly_where_conditions;
3817
-    }
3818
-
3819
-
3820
-
3821
-    /**
3822
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3823
-     * default where conditions on all get_all, update, and delete queries done by this model.
3824
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3825
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3826
-     *
3827
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3828
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3829
-     */
3830
-    private function _get_default_where_conditions($model_relation_path = null)
3831
-    {
3832
-        if ($this->_ignore_where_strategy) {
3833
-            return array();
3834
-        }
3835
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3836
-    }
3837
-
3838
-
3839
-
3840
-    /**
3841
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3842
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3843
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3844
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3845
-     * Similar to _get_default_where_conditions
3846
-     *
3847
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3848
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3849
-     */
3850
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3851
-    {
3852
-        if ($this->_ignore_where_strategy) {
3853
-            return array();
3854
-        }
3855
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3856
-    }
3857
-
3858
-
3859
-
3860
-    /**
3861
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3862
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3863
-     *
3864
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3865
-     * @return string
3866
-     * @throws EE_Error
3867
-     */
3868
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3869
-    {
3870
-        $selects = $this->_get_columns_to_select_for_this_model();
3871
-        foreach (
3872
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3873
-        ) {
3874
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3875
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3876
-            foreach ($other_model_selects as $key => $value) {
3877
-                $selects[] = $value;
3878
-            }
3879
-        }
3880
-        return implode(", ", $selects);
3881
-    }
3882
-
3883
-
3884
-
3885
-    /**
3886
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3887
-     * So that's going to be the columns for all the fields on the model
3888
-     *
3889
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3890
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3891
-     */
3892
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3893
-    {
3894
-        $fields = $this->field_settings();
3895
-        $selects = array();
3896
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3897
-            $model_relation_chain,
3898
-            $this->get_this_model_name()
3899
-        );
3900
-        foreach ($fields as $field_obj) {
3901
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3902
-                         . $field_obj->get_table_alias()
3903
-                         . "."
3904
-                         . $field_obj->get_table_column()
3905
-                         . " AS '"
3906
-                         . $table_alias_with_model_relation_chain_prefix
3907
-                         . $field_obj->get_table_alias()
3908
-                         . "."
3909
-                         . $field_obj->get_table_column()
3910
-                         . "'";
3911
-        }
3912
-        // make sure we are also getting the PKs of each table
3913
-        $tables = $this->get_tables();
3914
-        if (count($tables) > 1) {
3915
-            foreach ($tables as $table_obj) {
3916
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3917
-                                       . $table_obj->get_fully_qualified_pk_column();
3918
-                if (! in_array($qualified_pk_column, $selects)) {
3919
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3920
-                }
3921
-            }
3922
-        }
3923
-        return $selects;
3924
-    }
3925
-
3926
-
3927
-
3928
-    /**
3929
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3930
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3931
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3932
-     * SQL for joining, and the data types
3933
-     *
3934
-     * @param null|string                 $original_query_param
3935
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3936
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3937
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3938
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3939
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3940
-     *                                                          or 'Registration's
3941
-     * @param string                      $original_query_param what it originally was (eg
3942
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3943
-     *                                                          matches $query_param
3944
-     * @throws EE_Error
3945
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3946
-     */
3947
-    private function _extract_related_model_info_from_query_param(
3948
-        $query_param,
3949
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3950
-        $query_param_type,
3951
-        $original_query_param = null
3952
-    ) {
3953
-        if ($original_query_param === null) {
3954
-            $original_query_param = $query_param;
3955
-        }
3956
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3957
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3958
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3959
-        $allow_fields = in_array(
3960
-            $query_param_type,
3961
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3962
-            true
3963
-        );
3964
-        // check to see if we have a field on this model
3965
-        $this_model_fields = $this->field_settings(true);
3966
-        if (array_key_exists($query_param, $this_model_fields)) {
3967
-            if ($allow_fields) {
3968
-                return;
3969
-            }
3970
-            throw new EE_Error(
3971
-                sprintf(
3972
-                    esc_html__(
3973
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3974
-                        "event_espresso"
3975
-                    ),
3976
-                    $query_param,
3977
-                    get_class($this),
3978
-                    $query_param_type,
3979
-                    $original_query_param
3980
-                )
3981
-            );
3982
-        }
3983
-        // check if this is a special logic query param
3984
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3985
-            if ($allow_logic_query_params) {
3986
-                return;
3987
-            }
3988
-            throw new EE_Error(
3989
-                sprintf(
3990
-                    esc_html__(
3991
-                        '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',
3992
-                        'event_espresso'
3993
-                    ),
3994
-                    implode('", "', $this->_logic_query_param_keys),
3995
-                    $query_param,
3996
-                    get_class($this),
3997
-                    '<br />',
3998
-                    "\t"
3999
-                    . ' $passed_in_query_info = <pre>'
4000
-                    . print_r($passed_in_query_info, true)
4001
-                    . '</pre>'
4002
-                    . "\n\t"
4003
-                    . ' $query_param_type = '
4004
-                    . $query_param_type
4005
-                    . "\n\t"
4006
-                    . ' $original_query_param = '
4007
-                    . $original_query_param
4008
-                )
4009
-            );
4010
-        }
4011
-        // check if it's a custom selection
4012
-        if (
4013
-            $this->_custom_selections instanceof CustomSelects
4014
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4015
-        ) {
4016
-            return;
4017
-        }
4018
-        // check if has a model name at the beginning
4019
-        // and
4020
-        // check if it's a field on a related model
4021
-        if (
4022
-            $this->extractJoinModelFromQueryParams(
4023
-                $passed_in_query_info,
4024
-                $query_param,
4025
-                $original_query_param,
4026
-                $query_param_type
4027
-            )
4028
-        ) {
4029
-            return;
4030
-        }
4031
-
4032
-        // ok so $query_param didn't start with a model name
4033
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4034
-        // it's wack, that's what it is
4035
-        throw new EE_Error(
4036
-            sprintf(
4037
-                esc_html__(
4038
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4039
-                    "event_espresso"
4040
-                ),
4041
-                $query_param,
4042
-                get_class($this),
4043
-                $query_param_type,
4044
-                $original_query_param
4045
-            )
4046
-        );
4047
-    }
4048
-
4049
-
4050
-    /**
4051
-     * Extracts any possible join model information from the provided possible_join_string.
4052
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4053
-     * parts that should be added to the query.
4054
-     *
4055
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4056
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4057
-     * @param null|string                 $original_query_param
4058
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4059
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4060
-     * @return bool  returns true if a join was added and false if not.
4061
-     * @throws EE_Error
4062
-     */
4063
-    private function extractJoinModelFromQueryParams(
4064
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4065
-        $possible_join_string,
4066
-        $original_query_param,
4067
-        $query_parameter_type
4068
-    ) {
4069
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4070
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4071
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4072
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4073
-                if ($possible_join_string === '') {
4074
-                    // nothing left to $query_param
4075
-                    // we should actually end in a field name, not a model like this!
4076
-                    throw new EE_Error(
4077
-                        sprintf(
4078
-                            esc_html__(
4079
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4080
-                                "event_espresso"
4081
-                            ),
4082
-                            $possible_join_string,
4083
-                            $query_parameter_type,
4084
-                            get_class($this),
4085
-                            $valid_related_model_name
4086
-                        )
4087
-                    );
4088
-                }
4089
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4090
-                $related_model_obj->_extract_related_model_info_from_query_param(
4091
-                    $possible_join_string,
4092
-                    $query_info_carrier,
4093
-                    $query_parameter_type,
4094
-                    $original_query_param
4095
-                );
4096
-                return true;
4097
-            }
4098
-            if ($possible_join_string === $valid_related_model_name) {
4099
-                $this->_add_join_to_model(
4100
-                    $valid_related_model_name,
4101
-                    $query_info_carrier,
4102
-                    $original_query_param
4103
-                );
4104
-                return true;
4105
-            }
4106
-        }
4107
-        return false;
4108
-    }
4109
-
4110
-
4111
-    /**
4112
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4113
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4114
-     * @throws EE_Error
4115
-     */
4116
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4117
-    {
4118
-        if (
4119
-            $this->_custom_selections instanceof CustomSelects
4120
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4121
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4122
-            )
4123
-        ) {
4124
-            $original_selects = $this->_custom_selections->originalSelects();
4125
-            foreach ($original_selects as $alias => $select_configuration) {
4126
-                $this->extractJoinModelFromQueryParams(
4127
-                    $query_info_carrier,
4128
-                    $select_configuration[0],
4129
-                    $select_configuration[0],
4130
-                    'custom_selects'
4131
-                );
4132
-            }
4133
-        }
4134
-    }
4135
-
4136
-
4137
-
4138
-    /**
4139
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4140
-     * and store it on $passed_in_query_info
4141
-     *
4142
-     * @param string                      $model_name
4143
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4144
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4145
-     *                                                          model and $model_name. Eg, if we are querying Event,
4146
-     *                                                          and are adding a join to 'Payment' with the original
4147
-     *                                                          query param key
4148
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4149
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4150
-     *                                                          Payment wants to add default query params so that it
4151
-     *                                                          will know what models to prepend onto its default query
4152
-     *                                                          params or in case it wants to rename tables (in case
4153
-     *                                                          there are multiple joins to the same table)
4154
-     * @return void
4155
-     * @throws EE_Error
4156
-     */
4157
-    private function _add_join_to_model(
4158
-        $model_name,
4159
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4160
-        $original_query_param
4161
-    ) {
4162
-        $relation_obj = $this->related_settings_for($model_name);
4163
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4164
-        // check if the relation is HABTM, because then we're essentially doing two joins
4165
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4166
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4167
-            $join_model_obj = $relation_obj->get_join_model();
4168
-            // replace the model specified with the join model for this relation chain, whi
4169
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4170
-                $model_name,
4171
-                $join_model_obj->get_this_model_name(),
4172
-                $model_relation_chain
4173
-            );
4174
-            $passed_in_query_info->merge(
4175
-                new EE_Model_Query_Info_Carrier(
4176
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4177
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4178
-                )
4179
-            );
4180
-        }
4181
-        // now just join to the other table pointed to by the relation object, and add its data types
4182
-        $passed_in_query_info->merge(
4183
-            new EE_Model_Query_Info_Carrier(
4184
-                array($model_relation_chain => $model_name),
4185
-                $relation_obj->get_join_statement($model_relation_chain)
4186
-            )
4187
-        );
4188
-    }
4189
-
4190
-
4191
-
4192
-    /**
4193
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4194
-     *
4195
-     * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4196
-     * @return string of SQL
4197
-     * @throws EE_Error
4198
-     */
4199
-    private function _construct_where_clause($where_params)
4200
-    {
4201
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4202
-        if ($SQL) {
4203
-            return " WHERE " . $SQL;
4204
-        }
4205
-        return '';
4206
-    }
4207
-
4208
-
4209
-
4210
-    /**
4211
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4212
-     * and should be passed HAVING parameters, not WHERE parameters
4213
-     *
4214
-     * @param array $having_params
4215
-     * @return string
4216
-     * @throws EE_Error
4217
-     */
4218
-    private function _construct_having_clause($having_params)
4219
-    {
4220
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4221
-        if ($SQL) {
4222
-            return " HAVING " . $SQL;
4223
-        }
4224
-        return '';
4225
-    }
4226
-
4227
-
4228
-    /**
4229
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4230
-     * Event_Meta.meta_value = 'foo'))"
4231
-     *
4232
-     * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4233
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4234
-     * @throws EE_Error
4235
-     * @return string of SQL
4236
-     */
4237
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4238
-    {
4239
-        $where_clauses = array();
4240
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4241
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4242
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4243
-                switch ($query_param) {
4244
-                    case 'not':
4245
-                    case 'NOT':
4246
-                        $where_clauses[] = "! ("
4247
-                                           . $this->_construct_condition_clause_recursive(
4248
-                                               $op_and_value_or_sub_condition,
4249
-                                               $glue
4250
-                                           )
4251
-                                           . ")";
4252
-                        break;
4253
-                    case 'and':
4254
-                    case 'AND':
4255
-                        $where_clauses[] = " ("
4256
-                                           . $this->_construct_condition_clause_recursive(
4257
-                                               $op_and_value_or_sub_condition,
4258
-                                               ' AND '
4259
-                                           )
4260
-                                           . ")";
4261
-                        break;
4262
-                    case 'or':
4263
-                    case 'OR':
4264
-                        $where_clauses[] = " ("
4265
-                                           . $this->_construct_condition_clause_recursive(
4266
-                                               $op_and_value_or_sub_condition,
4267
-                                               ' OR '
4268
-                                           )
4269
-                                           . ")";
4270
-                        break;
4271
-                }
4272
-            } else {
4273
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4274
-                // if it's not a normal field, maybe it's a custom selection?
4275
-                if (! $field_obj) {
4276
-                    if ($this->_custom_selections instanceof CustomSelects) {
4277
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4278
-                    } else {
4279
-                        throw new EE_Error(sprintf(esc_html__(
4280
-                            "%s is neither a valid model field name, nor a custom selection",
4281
-                            "event_espresso"
4282
-                        ), $query_param));
4283
-                    }
4284
-                }
4285
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4286
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4287
-            }
4288
-        }
4289
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4290
-    }
4291
-
4292
-
4293
-
4294
-    /**
4295
-     * Takes the input parameter and extract the table name (alias) and column name
4296
-     *
4297
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4298
-     * @throws EE_Error
4299
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4300
-     */
4301
-    private function _deduce_column_name_from_query_param($query_param)
4302
-    {
4303
-        $field = $this->_deduce_field_from_query_param($query_param);
4304
-        if ($field) {
4305
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4306
-                $field->get_model_name(),
4307
-                $query_param
4308
-            );
4309
-            return $table_alias_prefix . $field->get_qualified_column();
4310
-        }
4311
-        if (
4312
-            $this->_custom_selections instanceof CustomSelects
4313
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4314
-        ) {
4315
-            // maybe it's custom selection item?
4316
-            // if so, just use it as the "column name"
4317
-            return $query_param;
4318
-        }
4319
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4320
-            ? implode(',', $this->_custom_selections->columnAliases())
4321
-            : '';
4322
-        throw new EE_Error(
4323
-            sprintf(
4324
-                esc_html__(
4325
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4326
-                    "event_espresso"
4327
-                ),
4328
-                $query_param,
4329
-                $custom_select_aliases
4330
-            )
4331
-        );
4332
-    }
4333
-
4334
-
4335
-
4336
-    /**
4337
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4338
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4339
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4340
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4341
-     *
4342
-     * @param string $condition_query_param_key
4343
-     * @return string
4344
-     */
4345
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4346
-    {
4347
-        $pos_of_star = strpos($condition_query_param_key, '*');
4348
-        if ($pos_of_star === false) {
4349
-            return $condition_query_param_key;
4350
-        }
4351
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4352
-        return $condition_query_param_sans_star;
4353
-    }
4354
-
4355
-
4356
-
4357
-    /**
4358
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4359
-     *
4360
-     * @param                            mixed      array | string    $op_and_value
4361
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4362
-     * @throws EE_Error
4363
-     * @return string
4364
-     */
4365
-    private function _construct_op_and_value($op_and_value, $field_obj)
4366
-    {
4367
-        if (is_array($op_and_value)) {
4368
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4369
-            if (! $operator) {
4370
-                $php_array_like_string = array();
4371
-                foreach ($op_and_value as $key => $value) {
4372
-                    $php_array_like_string[] = "$key=>$value";
4373
-                }
4374
-                throw new EE_Error(
4375
-                    sprintf(
4376
-                        esc_html__(
4377
-                            "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))",
4378
-                            "event_espresso"
4379
-                        ),
4380
-                        implode(",", $php_array_like_string)
4381
-                    )
4382
-                );
4383
-            }
4384
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4385
-        } else {
4386
-            $operator = '=';
4387
-            $value = $op_and_value;
4388
-        }
4389
-        // check to see if the value is actually another field
4390
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4391
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4392
-        }
4393
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4394
-            // in this case, the value should be an array, or at least a comma-separated list
4395
-            // it will need to handle a little differently
4396
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4397
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4398
-            return $operator . SP . $cleaned_value;
4399
-        }
4400
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4401
-            // the value should be an array with count of two.
4402
-            if (count($value) !== 2) {
4403
-                throw new EE_Error(
4404
-                    sprintf(
4405
-                        esc_html__(
4406
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4407
-                            'event_espresso'
4408
-                        ),
4409
-                        "BETWEEN"
4410
-                    )
4411
-                );
4412
-            }
4413
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4414
-            return $operator . SP . $cleaned_value;
4415
-        }
4416
-        if (in_array($operator, $this->valid_null_style_operators())) {
4417
-            if ($value !== null) {
4418
-                throw new EE_Error(
4419
-                    sprintf(
4420
-                        esc_html__(
4421
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4422
-                            "event_espresso"
4423
-                        ),
4424
-                        $value,
4425
-                        $operator
4426
-                    )
4427
-                );
4428
-            }
4429
-            return $operator;
4430
-        }
4431
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4432
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4433
-            // remove other junk. So just treat it as a string.
4434
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4435
-        }
4436
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4438
-        }
4439
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4440
-            throw new EE_Error(
4441
-                sprintf(
4442
-                    esc_html__(
4443
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4444
-                        'event_espresso'
4445
-                    ),
4446
-                    $operator,
4447
-                    $operator
4448
-                )
4449
-            );
4450
-        }
4451
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452
-            throw new EE_Error(
4453
-                sprintf(
4454
-                    esc_html__(
4455
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4456
-                        'event_espresso'
4457
-                    ),
4458
-                    $operator,
4459
-                    $operator
4460
-                )
4461
-            );
4462
-        }
4463
-        throw new EE_Error(
4464
-            sprintf(
4465
-                esc_html__(
4466
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4467
-                    "event_espresso"
4468
-                ),
4469
-                http_build_query($op_and_value)
4470
-            )
4471
-        );
4472
-    }
4473
-
4474
-
4475
-
4476
-    /**
4477
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4478
-     *
4479
-     * @param array                      $values
4480
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4481
-     *                                              '%s'
4482
-     * @return string
4483
-     * @throws EE_Error
4484
-     */
4485
-    public function _construct_between_value($values, $field_obj)
4486
-    {
4487
-        $cleaned_values = array();
4488
-        foreach ($values as $value) {
4489
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4490
-        }
4491
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4492
-    }
4493
-
4494
-
4495
-    /**
4496
-     * Takes an array or a comma-separated list of $values and cleans them
4497
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4498
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4499
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4500
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4501
-     *
4502
-     * @param mixed                      $values    array or comma-separated string
4503
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4504
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4505
-     * @throws EE_Error
4506
-     */
4507
-    public function _construct_in_value($values, $field_obj)
4508
-    {
4509
-        $prepped = [];
4510
-        // check if the value is a CSV list
4511
-        if (is_string($values)) {
4512
-            // in which case, turn it into an array
4513
-            $values = explode(',', $values);
4514
-        }
4515
-        // make sure we only have one of each value in the list
4516
-        $values = array_unique($values);
4517
-        foreach ($values as $value) {
4518
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4519
-        }
4520
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4521
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4522
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4523
-        if (empty($prepped)) {
4524
-            $all_fields = $this->field_settings();
4525
-            $first_field    = reset($all_fields);
4526
-            $main_table = $this->_get_main_table();
4527
-            $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4528
-        }
4529
-        return '(' . implode(',', $prepped) . ')';
4530
-    }
4531
-
4532
-
4533
-
4534
-    /**
4535
-     * @param mixed                      $value
4536
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4537
-     * @throws EE_Error
4538
-     * @return false|null|string
4539
-     */
4540
-    private function _wpdb_prepare_using_field($value, $field_obj)
4541
-    {
4542
-        /** @type WPDB $wpdb */
4543
-        global $wpdb;
4544
-        if ($field_obj instanceof EE_Model_Field_Base) {
4545
-            return $wpdb->prepare(
4546
-                $field_obj->get_wpdb_data_type(),
4547
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4548
-            );
4549
-        } //$field_obj should really just be a data type
4550
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4551
-            throw new EE_Error(
4552
-                sprintf(
4553
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4554
-                    $field_obj,
4555
-                    implode(",", $this->_valid_wpdb_data_types)
4556
-                )
4557
-            );
4558
-        }
4559
-        return $wpdb->prepare($field_obj, $value);
4560
-    }
4561
-
4562
-
4563
-
4564
-    /**
4565
-     * Takes the input parameter and finds the model field that it indicates.
4566
-     *
4567
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4568
-     * @throws EE_Error
4569
-     * @return EE_Model_Field_Base
4570
-     */
4571
-    protected function _deduce_field_from_query_param($query_param_name)
4572
-    {
4573
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4574
-        // which will help us find the database table and column
4575
-        $query_param_parts = explode(".", $query_param_name);
4576
-        if (empty($query_param_parts)) {
4577
-            throw new EE_Error(sprintf(esc_html__(
4578
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4579
-                'event_espresso'
4580
-            ), $query_param_name));
4581
-        }
4582
-        $number_of_parts = count($query_param_parts);
4583
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4584
-        if ($number_of_parts === 1) {
4585
-            $field_name = $last_query_param_part;
4586
-            $model_obj = $this;
4587
-        } else {// $number_of_parts >= 2
4588
-            // the last part is the column name, and there are only 2parts. therefore...
4589
-            $field_name = $last_query_param_part;
4590
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4591
-        }
4592
-        try {
4593
-            return $model_obj->field_settings_for($field_name);
4594
-        } catch (EE_Error $e) {
4595
-            return null;
4596
-        }
4597
-    }
4598
-
4599
-
4600
-
4601
-    /**
4602
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4603
-     * alias and column which corresponds to it
4604
-     *
4605
-     * @param string $field_name
4606
-     * @throws EE_Error
4607
-     * @return string
4608
-     */
4609
-    public function _get_qualified_column_for_field($field_name)
4610
-    {
4611
-        $all_fields = $this->field_settings();
4612
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4613
-        if ($field) {
4614
-            return $field->get_qualified_column();
4615
-        }
4616
-        throw new EE_Error(
4617
-            sprintf(
4618
-                esc_html__(
4619
-                    "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.",
4620
-                    'event_espresso'
4621
-                ),
4622
-                $field_name,
4623
-                get_class($this)
4624
-            )
4625
-        );
4626
-    }
4627
-
4628
-
4629
-
4630
-    /**
4631
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4632
-     * Example usage:
4633
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4634
-     *      array(),
4635
-     *      ARRAY_A,
4636
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4637
-     *  );
4638
-     * is equivalent to
4639
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4640
-     * and
4641
-     *  EEM_Event::instance()->get_all_wpdb_results(
4642
-     *      array(
4643
-     *          array(
4644
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4645
-     *          ),
4646
-     *          ARRAY_A,
4647
-     *          implode(
4648
-     *              ', ',
4649
-     *              array_merge(
4650
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4651
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4652
-     *              )
4653
-     *          )
4654
-     *      )
4655
-     *  );
4656
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4657
-     *
4658
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4659
-     *                                            and the one whose fields you are selecting for example: when querying
4660
-     *                                            tickets model and selecting fields from the tickets model you would
4661
-     *                                            leave this parameter empty, because no models are needed to join
4662
-     *                                            between the queried model and the selected one. Likewise when
4663
-     *                                            querying the datetime model and selecting fields from the tickets
4664
-     *                                            model, it would also be left empty, because there is a direct
4665
-     *                                            relation from datetimes to tickets, so no model is needed to join
4666
-     *                                            them together. However, when querying from the event model and
4667
-     *                                            selecting fields from the ticket model, you should provide the string
4668
-     *                                            'Datetime', indicating that the event model must first join to the
4669
-     *                                            datetime model in order to find its relation to ticket model.
4670
-     *                                            Also, when querying from the venue model and selecting fields from
4671
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4672
-     *                                            indicating you need to join the venue model to the event model,
4673
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4674
-     *                                            This string is used to deduce the prefix that gets added onto the
4675
-     *                                            models' tables qualified columns
4676
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4677
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4678
-     *                                            qualified column names
4679
-     * @return array|string
4680
-     */
4681
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4682
-    {
4683
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4684
-        $qualified_columns = array();
4685
-        foreach ($this->field_settings() as $field_name => $field) {
4686
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4687
-        }
4688
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4689
-    }
4690
-
4691
-
4692
-
4693
-    /**
4694
-     * constructs the select use on special limit joins
4695
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4696
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4697
-     * (as that is typically where the limits would be set).
4698
-     *
4699
-     * @param  string       $table_alias The table the select is being built for
4700
-     * @param  mixed|string $limit       The limit for this select
4701
-     * @return string                The final select join element for the query.
4702
-     */
4703
-    public function _construct_limit_join_select($table_alias, $limit)
4704
-    {
4705
-        $SQL = '';
4706
-        foreach ($this->_tables as $table_obj) {
4707
-            if ($table_obj instanceof EE_Primary_Table) {
4708
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4709
-                    ? $table_obj->get_select_join_limit($limit)
4710
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4711
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4712
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4713
-                    ? $table_obj->get_select_join_limit_join($limit)
4714
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4715
-            }
4716
-        }
4717
-        return $SQL;
4718
-    }
4719
-
4720
-
4721
-
4722
-    /**
4723
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4724
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4725
-     *
4726
-     * @return string SQL
4727
-     * @throws EE_Error
4728
-     */
4729
-    public function _construct_internal_join()
4730
-    {
4731
-        $SQL = $this->_get_main_table()->get_table_sql();
4732
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4733
-        return $SQL;
4734
-    }
4735
-
4736
-
4737
-
4738
-    /**
4739
-     * Constructs the SQL for joining all the tables on this model.
4740
-     * Normally $alias should be the primary table's alias, but in cases where
4741
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4742
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4743
-     * alias, this will construct SQL like:
4744
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4745
-     * With $alias being a secondary table's alias, this will construct SQL like:
4746
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
-     *
4748
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4749
-     * @return string
4750
-     */
4751
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4752
-    {
4753
-        $SQL = '';
4754
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4755
-        foreach ($this->_tables as $table_obj) {
4756
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4757
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4758
-                    // so we're joining to this table, meaning the table is already in
4759
-                    // the FROM statement, BUT the primary table isn't. So we want
4760
-                    // to add the inverse join sql
4761
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4762
-                } else {
4763
-                    // just add a regular JOIN to this table from the primary table
4764
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4765
-                }
4766
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4767
-        }
4768
-        return $SQL;
4769
-    }
4770
-
4771
-
4772
-
4773
-    /**
4774
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4775
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4776
-     * their data type (eg, '%s', '%d', etc)
4777
-     *
4778
-     * @return array
4779
-     */
4780
-    public function _get_data_types()
4781
-    {
4782
-        $data_types = array();
4783
-        foreach ($this->field_settings() as $field_obj) {
4784
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4785
-            /** @var $field_obj EE_Model_Field_Base */
4786
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4787
-        }
4788
-        return $data_types;
4789
-    }
4790
-
4791
-
4792
-
4793
-    /**
4794
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4795
-     *
4796
-     * @param string $model_name
4797
-     * @throws EE_Error
4798
-     * @return EEM_Base
4799
-     */
4800
-    public function get_related_model_obj($model_name)
4801
-    {
4802
-        $model_classname = "EEM_" . $model_name;
4803
-        if (! class_exists($model_classname)) {
4804
-            throw new EE_Error(sprintf(esc_html__(
4805
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4806
-                'event_espresso'
4807
-            ), $model_name, $model_classname));
4808
-        }
4809
-        return call_user_func($model_classname . "::instance");
4810
-    }
4811
-
4812
-
4813
-
4814
-    /**
4815
-     * Returns the array of EE_ModelRelations for this model.
4816
-     *
4817
-     * @return EE_Model_Relation_Base[]
4818
-     */
4819
-    public function relation_settings()
4820
-    {
4821
-        return $this->_model_relations;
4822
-    }
4823
-
4824
-
4825
-
4826
-    /**
4827
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4828
-     * because without THOSE models, this model probably doesn't have much purpose.
4829
-     * (Eg, without an event, datetimes have little purpose.)
4830
-     *
4831
-     * @return EE_Belongs_To_Relation[]
4832
-     */
4833
-    public function belongs_to_relations()
4834
-    {
4835
-        $belongs_to_relations = array();
4836
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4837
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4838
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4839
-            }
4840
-        }
4841
-        return $belongs_to_relations;
4842
-    }
4843
-
4844
-
4845
-
4846
-    /**
4847
-     * Returns the specified EE_Model_Relation, or throws an exception
4848
-     *
4849
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4850
-     * @throws EE_Error
4851
-     * @return EE_Model_Relation_Base
4852
-     */
4853
-    public function related_settings_for($relation_name)
4854
-    {
4855
-        $relatedModels = $this->relation_settings();
4856
-        if (! array_key_exists($relation_name, $relatedModels)) {
4857
-            throw new EE_Error(
4858
-                sprintf(
4859
-                    esc_html__(
4860
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4861
-                        'event_espresso'
4862
-                    ),
4863
-                    $relation_name,
4864
-                    $this->_get_class_name(),
4865
-                    implode(', ', array_keys($relatedModels))
4866
-                )
4867
-            );
4868
-        }
4869
-        return $relatedModels[ $relation_name ];
4870
-    }
4871
-
4872
-
4873
-
4874
-    /**
4875
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4876
-     * fields
4877
-     *
4878
-     * @param string $fieldName
4879
-     * @param boolean $include_db_only_fields
4880
-     * @throws EE_Error
4881
-     * @return EE_Model_Field_Base
4882
-     */
4883
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4884
-    {
4885
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4886
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4887
-            throw new EE_Error(sprintf(
4888
-                esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4889
-                $fieldName,
4890
-                get_class($this)
4891
-            ));
4892
-        }
4893
-        return $fieldSettings[ $fieldName ];
4894
-    }
4895
-
4896
-
4897
-
4898
-    /**
4899
-     * Checks if this field exists on this model
4900
-     *
4901
-     * @param string $fieldName a key in the model's _field_settings array
4902
-     * @return boolean
4903
-     */
4904
-    public function has_field($fieldName)
4905
-    {
4906
-        $fieldSettings = $this->field_settings(true);
4907
-        if (isset($fieldSettings[ $fieldName ])) {
4908
-            return true;
4909
-        }
4910
-        return false;
4911
-    }
4912
-
4913
-
4914
-
4915
-    /**
4916
-     * Returns whether or not this model has a relation to the specified model
4917
-     *
4918
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4919
-     * @return boolean
4920
-     */
4921
-    public function has_relation($relation_name)
4922
-    {
4923
-        $relations = $this->relation_settings();
4924
-        if (isset($relations[ $relation_name ])) {
4925
-            return true;
4926
-        }
4927
-        return false;
4928
-    }
4929
-
4930
-
4931
-
4932
-    /**
4933
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4934
-     * Eg, on EE_Answer that would be ANS_ID field object
4935
-     *
4936
-     * @param $field_obj
4937
-     * @return boolean
4938
-     */
4939
-    public function is_primary_key_field($field_obj)
4940
-    {
4941
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4942
-    }
4943
-
4944
-
4945
-
4946
-    /**
4947
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4948
-     * Eg, on EE_Answer that would be ANS_ID field object
4949
-     *
4950
-     * @return EE_Model_Field_Base
4951
-     * @throws EE_Error
4952
-     */
4953
-    public function get_primary_key_field()
4954
-    {
4955
-        if ($this->_primary_key_field === null) {
4956
-            foreach ($this->field_settings(true) as $field_obj) {
4957
-                if ($this->is_primary_key_field($field_obj)) {
4958
-                    $this->_primary_key_field = $field_obj;
4959
-                    break;
4960
-                }
4961
-            }
4962
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4963
-                throw new EE_Error(sprintf(
4964
-                    esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4965
-                    get_class($this)
4966
-                ));
4967
-            }
4968
-        }
4969
-        return $this->_primary_key_field;
4970
-    }
4971
-
4972
-
4973
-
4974
-    /**
4975
-     * Returns whether or not not there is a primary key on this model.
4976
-     * Internally does some caching.
4977
-     *
4978
-     * @return boolean
4979
-     */
4980
-    public function has_primary_key_field()
4981
-    {
4982
-        if ($this->_has_primary_key_field === null) {
4983
-            try {
4984
-                $this->get_primary_key_field();
4985
-                $this->_has_primary_key_field = true;
4986
-            } catch (EE_Error $e) {
4987
-                $this->_has_primary_key_field = false;
4988
-            }
4989
-        }
4990
-        return $this->_has_primary_key_field;
4991
-    }
4992
-
4993
-
4994
-
4995
-    /**
4996
-     * Finds the first field of type $field_class_name.
4997
-     *
4998
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4999
-     *                                 EE_Foreign_Key_Field, etc
5000
-     * @return EE_Model_Field_Base or null if none is found
5001
-     */
5002
-    public function get_a_field_of_type($field_class_name)
5003
-    {
5004
-        foreach ($this->field_settings() as $field) {
5005
-            if ($field instanceof $field_class_name) {
5006
-                return $field;
5007
-            }
5008
-        }
5009
-        return null;
5010
-    }
5011
-
5012
-
5013
-
5014
-    /**
5015
-     * Gets a foreign key field pointing to model.
5016
-     *
5017
-     * @param string $model_name eg Event, Registration, not EEM_Event
5018
-     * @return EE_Foreign_Key_Field_Base
5019
-     * @throws EE_Error
5020
-     */
5021
-    public function get_foreign_key_to($model_name)
5022
-    {
5023
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5024
-            foreach ($this->field_settings() as $field) {
5025
-                if (
5026
-                    $field instanceof EE_Foreign_Key_Field_Base
5027
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5028
-                ) {
5029
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5030
-                    break;
5031
-                }
5032
-            }
5033
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5034
-                throw new EE_Error(sprintf(esc_html__(
5035
-                    "There is no foreign key field pointing to model %s on model %s",
5036
-                    'event_espresso'
5037
-                ), $model_name, get_class($this)));
5038
-            }
5039
-        }
5040
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5041
-    }
5042
-
5043
-
5044
-
5045
-    /**
5046
-     * Gets the table name (including $wpdb->prefix) for the table alias
5047
-     *
5048
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5049
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5050
-     *                            Either one works
5051
-     * @return string
5052
-     */
5053
-    public function get_table_for_alias($table_alias)
5054
-    {
5055
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5056
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5057
-    }
5058
-
5059
-
5060
-
5061
-    /**
5062
-     * Returns a flat array of all field son this model, instead of organizing them
5063
-     * by table_alias as they are in the constructor.
5064
-     *
5065
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5066
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5067
-     */
5068
-    public function field_settings($include_db_only_fields = false)
5069
-    {
5070
-        if ($include_db_only_fields) {
5071
-            if ($this->_cached_fields === null) {
5072
-                $this->_cached_fields = array();
5073
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5074
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5075
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5076
-                    }
5077
-                }
5078
-            }
5079
-            return $this->_cached_fields;
5080
-        }
5081
-        if ($this->_cached_fields_non_db_only === null) {
5082
-            $this->_cached_fields_non_db_only = array();
5083
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5084
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5085
-                    /** @var $field_obj EE_Model_Field_Base */
5086
-                    if (! $field_obj->is_db_only_field()) {
5087
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5088
-                    }
5089
-                }
5090
-            }
5091
-        }
5092
-        return $this->_cached_fields_non_db_only;
5093
-    }
5094
-
5095
-
5096
-
5097
-    /**
5098
-     *        cycle though array of attendees and create objects out of each item
5099
-     *
5100
-     * @access        private
5101
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5102
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5103
-     *                           numerically indexed)
5104
-     * @throws EE_Error
5105
-     */
5106
-    protected function _create_objects($rows = array())
5107
-    {
5108
-        $array_of_objects = array();
5109
-        if (empty($rows)) {
5110
-            return array();
5111
-        }
5112
-        $count_if_model_has_no_primary_key = 0;
5113
-        $has_primary_key = $this->has_primary_key_field();
5114
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5115
-        foreach ((array) $rows as $row) {
5116
-            if (empty($row)) {
5117
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5118
-                return array();
5119
-            }
5120
-            // check if we've already set this object in the results array,
5121
-            // in which case there's no need to process it further (again)
5122
-            if ($has_primary_key) {
5123
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5124
-                    $row,
5125
-                    $primary_key_field->get_qualified_column(),
5126
-                    $primary_key_field->get_table_column()
5127
-                );
5128
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5129
-                    continue;
5130
-                }
5131
-            }
5132
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5133
-            if (! $classInstance) {
5134
-                throw new EE_Error(
5135
-                    sprintf(
5136
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5137
-                        $this->get_this_model_name(),
5138
-                        http_build_query($row)
5139
-                    )
5140
-                );
5141
-            }
5142
-            // set the timezone on the instantiated objects
5143
-            $classInstance->set_timezone($this->_timezone);
5144
-            // make sure if there is any timezone setting present that we set the timezone for the object
5145
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5146
-            $array_of_objects[ $key ] = $classInstance;
5147
-            // also, for all the relations of type BelongsTo, see if we can cache
5148
-            // those related models
5149
-            // (we could do this for other relations too, but if there are conditions
5150
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5151
-            // so it requires a little more thought than just caching them immediately...)
5152
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5153
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5154
-                    // check if this model's INFO is present. If so, cache it on the model
5155
-                    $other_model = $relation_obj->get_other_model();
5156
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5157
-                    // if we managed to make a model object from the results, cache it on the main model object
5158
-                    if ($other_model_obj_maybe) {
5159
-                        // set timezone on these other model objects if they are present
5160
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5161
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5162
-                    }
5163
-                }
5164
-            }
5165
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5166
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5167
-            // the field in the CustomSelects object
5168
-            if ($this->_custom_selections instanceof CustomSelects) {
5169
-                $classInstance->setCustomSelectsValues(
5170
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5171
-                );
5172
-            }
5173
-        }
5174
-        return $array_of_objects;
5175
-    }
5176
-
5177
-
5178
-    /**
5179
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5180
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5181
-     *
5182
-     * @param array $db_results_row
5183
-     * @return array
5184
-     */
5185
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5186
-    {
5187
-        $results = array();
5188
-        if ($this->_custom_selections instanceof CustomSelects) {
5189
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5190
-                if (isset($db_results_row[ $alias ])) {
5191
-                    $results[ $alias ] = $this->convertValueToDataType(
5192
-                        $db_results_row[ $alias ],
5193
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5194
-                    );
5195
-                }
5196
-            }
5197
-        }
5198
-        return $results;
5199
-    }
5200
-
5201
-
5202
-    /**
5203
-     * This will set the value for the given alias
5204
-     * @param string $value
5205
-     * @param string $datatype (one of %d, %s, %f)
5206
-     * @return int|string|float (int for %d, string for %s, float for %f)
5207
-     */
5208
-    protected function convertValueToDataType($value, $datatype)
5209
-    {
5210
-        switch ($datatype) {
5211
-            case '%f':
5212
-                return (float) $value;
5213
-            case '%d':
5214
-                return (int) $value;
5215
-            default:
5216
-                return (string) $value;
5217
-        }
5218
-    }
5219
-
5220
-
5221
-    /**
5222
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5223
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5224
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5225
-     * object (as set in the model_field!).
5226
-     *
5227
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5228
-     */
5229
-    public function create_default_object()
5230
-    {
5231
-        $this_model_fields_and_values = array();
5232
-        // setup the row using default values;
5233
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5234
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5235
-        }
5236
-        $className = $this->_get_class_name();
5237
-        $classInstance = EE_Registry::instance()
5238
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5239
-        return $classInstance;
5240
-    }
5241
-
5242
-
5243
-
5244
-    /**
5245
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5246
-     *                             or an stdClass where each property is the name of a column,
5247
-     * @return EE_Base_Class
5248
-     * @throws EE_Error
5249
-     */
5250
-    public function instantiate_class_from_array_or_object($cols_n_values)
5251
-    {
5252
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5253
-            $cols_n_values = get_object_vars($cols_n_values);
5254
-        }
5255
-        $primary_key = null;
5256
-        // make sure the array only has keys that are fields/columns on this model
5257
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5258
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5259
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5260
-        }
5261
-        $className = $this->_get_class_name();
5262
-        // check we actually found results that we can use to build our model object
5263
-        // if not, return null
5264
-        if ($this->has_primary_key_field()) {
5265
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5266
-                return null;
5267
-            }
5268
-        } elseif ($this->unique_indexes()) {
5269
-            $first_column = reset($this_model_fields_n_values);
5270
-            if (empty($first_column)) {
5271
-                return null;
5272
-            }
5273
-        }
5274
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5275
-        if ($primary_key) {
5276
-            $classInstance = $this->get_from_entity_map($primary_key);
5277
-            if (! $classInstance) {
5278
-                $classInstance = EE_Registry::instance()
5279
-                                            ->load_class(
5280
-                                                $className,
5281
-                                                array($this_model_fields_n_values, $this->_timezone),
5282
-                                                true,
5283
-                                                false
5284
-                                            );
5285
-                // add this new object to the entity map
5286
-                $classInstance = $this->add_to_entity_map($classInstance);
5287
-            }
5288
-        } else {
5289
-            $classInstance = EE_Registry::instance()
5290
-                                        ->load_class(
5291
-                                            $className,
5292
-                                            array($this_model_fields_n_values, $this->_timezone),
5293
-                                            true,
5294
-                                            false
5295
-                                        );
5296
-        }
5297
-        return $classInstance;
5298
-    }
5299
-
5300
-
5301
-
5302
-    /**
5303
-     * Gets the model object from the  entity map if it exists
5304
-     *
5305
-     * @param int|string $id the ID of the model object
5306
-     * @return EE_Base_Class
5307
-     */
5308
-    public function get_from_entity_map($id)
5309
-    {
5310
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5311
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5312
-    }
5313
-
5314
-
5315
-
5316
-    /**
5317
-     * add_to_entity_map
5318
-     * Adds the object to the model's entity mappings
5319
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5320
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5321
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5322
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5323
-     *        then this method should be called immediately after the update query
5324
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5325
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5326
-     *
5327
-     * @param    EE_Base_Class $object
5328
-     * @throws EE_Error
5329
-     * @return \EE_Base_Class
5330
-     */
5331
-    public function add_to_entity_map(EE_Base_Class $object)
5332
-    {
5333
-        $className = $this->_get_class_name();
5334
-        if (! $object instanceof $className) {
5335
-            throw new EE_Error(sprintf(
5336
-                esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5337
-                is_object($object) ? get_class($object) : $object,
5338
-                $className
5339
-            ));
5340
-        }
5341
-        /** @var $object EE_Base_Class */
5342
-        if (! $object->ID()) {
5343
-            throw new EE_Error(sprintf(esc_html__(
5344
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5345
-                "event_espresso"
5346
-            ), get_class($this)));
5347
-        }
5348
-        // double check it's not already there
5349
-        $classInstance = $this->get_from_entity_map($object->ID());
5350
-        if ($classInstance) {
5351
-            return $classInstance;
5352
-        }
5353
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5354
-        return $object;
5355
-    }
5356
-
5357
-
5358
-
5359
-    /**
5360
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5361
-     * if no identifier is provided, then the entire entity map is emptied
5362
-     *
5363
-     * @param int|string $id the ID of the model object
5364
-     * @return boolean
5365
-     */
5366
-    public function clear_entity_map($id = null)
5367
-    {
5368
-        if (empty($id)) {
5369
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5370
-            return true;
5371
-        }
5372
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5373
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5374
-            return true;
5375
-        }
5376
-        return false;
5377
-    }
5378
-
5379
-
5380
-
5381
-    /**
5382
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5383
-     * Given an array where keys are column (or column alias) names and values,
5384
-     * returns an array of their corresponding field names and database values
5385
-     *
5386
-     * @param array $cols_n_values
5387
-     * @return array
5388
-     */
5389
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5390
-    {
5391
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5392
-    }
5393
-
5394
-
5395
-
5396
-    /**
5397
-     * _deduce_fields_n_values_from_cols_n_values
5398
-     * Given an array where keys are column (or column alias) names and values,
5399
-     * returns an array of their corresponding field names and database values
5400
-     *
5401
-     * @param string $cols_n_values
5402
-     * @return array
5403
-     */
5404
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5405
-    {
5406
-        $this_model_fields_n_values = array();
5407
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5408
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5409
-                $cols_n_values,
5410
-                $table_obj->get_fully_qualified_pk_column(),
5411
-                $table_obj->get_pk_column()
5412
-            );
5413
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5414
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5415
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5416
-                    if (! $field_obj->is_db_only_field()) {
5417
-                        // prepare field as if its coming from db
5418
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5419
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5420
-                    }
5421
-                }
5422
-            } else {
5423
-                // the table's rows existed. Use their values
5424
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5425
-                    if (! $field_obj->is_db_only_field()) {
5426
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5427
-                            $cols_n_values,
5428
-                            $field_obj->get_qualified_column(),
5429
-                            $field_obj->get_table_column()
5430
-                        );
5431
-                    }
5432
-                }
5433
-            }
5434
-        }
5435
-        return $this_model_fields_n_values;
5436
-    }
5437
-
5438
-
5439
-    /**
5440
-     * @param $cols_n_values
5441
-     * @param $qualified_column
5442
-     * @param $regular_column
5443
-     * @return null
5444
-     * @throws EE_Error
5445
-     * @throws ReflectionException
5446
-     */
5447
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5448
-    {
5449
-        $value = null;
5450
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5451
-        // does the field on the model relate to this column retrieved from the db?
5452
-        // or is it a db-only field? (not relating to the model)
5453
-        if (isset($cols_n_values[ $qualified_column ])) {
5454
-            $value = $cols_n_values[ $qualified_column ];
5455
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5456
-            $value = $cols_n_values[ $regular_column ];
5457
-        } elseif (! empty($this->foreign_key_aliases)) {
5458
-            // no PK?  ok check if there is a foreign key alias set for this table
5459
-            // then check if that alias exists in the incoming data
5460
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5461
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5462
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5463
-                    $value = $cols_n_values[ $FK_alias ];
5464
-                    list($pk_class) = explode('.', $PK_column);
5465
-                    $pk_model_name = "EEM_{$pk_class}";
5466
-                    /** @var EEM_Base $pk_model */
5467
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5468
-                    if ($pk_model instanceof EEM_Base) {
5469
-                        // make sure object is pulled from db and added to entity map
5470
-                        $pk_model->get_one_by_ID($value);
5471
-                    }
5472
-                    break;
5473
-                }
5474
-            }
5475
-        }
5476
-        return $value;
5477
-    }
5478
-
5479
-
5480
-
5481
-    /**
5482
-     * refresh_entity_map_from_db
5483
-     * Makes sure the model object in the entity map at $id assumes the values
5484
-     * of the database (opposite of EE_base_Class::save())
5485
-     *
5486
-     * @param int|string $id
5487
-     * @return EE_Base_Class
5488
-     * @throws EE_Error
5489
-     */
5490
-    public function refresh_entity_map_from_db($id)
5491
-    {
5492
-        $obj_in_map = $this->get_from_entity_map($id);
5493
-        if ($obj_in_map) {
5494
-            $wpdb_results = $this->_get_all_wpdb_results(
5495
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5496
-            );
5497
-            if ($wpdb_results && is_array($wpdb_results)) {
5498
-                $one_row = reset($wpdb_results);
5499
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5500
-                    $obj_in_map->set_from_db($field_name, $db_value);
5501
-                }
5502
-                // clear the cache of related model objects
5503
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5504
-                    $obj_in_map->clear_cache($relation_name, null, true);
5505
-                }
5506
-            }
5507
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5508
-            return $obj_in_map;
5509
-        }
5510
-        return $this->get_one_by_ID($id);
5511
-    }
5512
-
5513
-
5514
-
5515
-    /**
5516
-     * refresh_entity_map_with
5517
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5518
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5519
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5520
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5521
-     *
5522
-     * @param int|string    $id
5523
-     * @param EE_Base_Class $replacing_model_obj
5524
-     * @return \EE_Base_Class
5525
-     * @throws EE_Error
5526
-     */
5527
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5528
-    {
5529
-        $obj_in_map = $this->get_from_entity_map($id);
5530
-        if ($obj_in_map) {
5531
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5532
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5533
-                    $obj_in_map->set($field_name, $value);
5534
-                }
5535
-                // make the model object in the entity map's cache match the $replacing_model_obj
5536
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5537
-                    $obj_in_map->clear_cache($relation_name, null, true);
5538
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5539
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5540
-                    }
5541
-                }
5542
-            }
5543
-            return $obj_in_map;
5544
-        }
5545
-        $this->add_to_entity_map($replacing_model_obj);
5546
-        return $replacing_model_obj;
5547
-    }
5548
-
5549
-
5550
-
5551
-    /**
5552
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5553
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5554
-     * require_once($this->_getClassName().".class.php");
5555
-     *
5556
-     * @return string
5557
-     */
5558
-    private function _get_class_name()
5559
-    {
5560
-        return "EE_" . $this->get_this_model_name();
5561
-    }
5562
-
5563
-
5564
-
5565
-    /**
5566
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5567
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5568
-     * it would be 'Events'.
5569
-     *
5570
-     * @param int $quantity
5571
-     * @return string
5572
-     */
5573
-    public function item_name($quantity = 1)
5574
-    {
5575
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5576
-    }
5577
-
5578
-
5579
-
5580
-    /**
5581
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5582
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5583
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5584
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5585
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5586
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5587
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5588
-     * returns will be returned by this function.
5589
-     *
5590
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5591
-     * @param array  $args       array of original arguments passed to the function
5592
-     * @throws EE_Error
5593
-     * @return mixed whatever the plugin which calls add_filter decides
5594
-     */
5595
-    public function __call($methodName, $args)
5596
-    {
5597
-        $className = get_class($this);
5598
-        $tagName = "FHEE__{$className}__{$methodName}";
5599
-        if (! has_filter($tagName)) {
5600
-            throw new EE_Error(
5601
-                sprintf(
5602
-                    esc_html__(
5603
-                        '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 );',
5604
-                        'event_espresso'
5605
-                    ),
5606
-                    $methodName,
5607
-                    $className,
5608
-                    $tagName,
5609
-                    '<br />'
5610
-                )
5611
-            );
5612
-        }
5613
-        return apply_filters($tagName, null, $this, $args);
5614
-    }
5615
-
5616
-
5617
-
5618
-    /**
5619
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5620
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5621
-     *
5622
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5623
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5624
-     *                                                       the object's class name
5625
-     *                                                       or object's ID
5626
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5627
-     *                                                       exists in the database. If it does not, we add it
5628
-     * @throws EE_Error
5629
-     * @return EE_Base_Class
5630
-     */
5631
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5632
-    {
5633
-        $className = $this->_get_class_name();
5634
-        if ($base_class_obj_or_id instanceof $className) {
5635
-            $model_object = $base_class_obj_or_id;
5636
-        } else {
5637
-            $primary_key_field = $this->get_primary_key_field();
5638
-            if (
5639
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5640
-                && (
5641
-                    is_int($base_class_obj_or_id)
5642
-                    || is_string($base_class_obj_or_id)
5643
-                )
5644
-            ) {
5645
-                // assume it's an ID.
5646
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5647
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5648
-            } elseif (
5649
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5650
-                && is_string($base_class_obj_or_id)
5651
-            ) {
5652
-                // assume its a string representation of the object
5653
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5654
-            } else {
5655
-                throw new EE_Error(
5656
-                    sprintf(
5657
-                        esc_html__(
5658
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5659
-                            'event_espresso'
5660
-                        ),
5661
-                        $base_class_obj_or_id,
5662
-                        $this->_get_class_name(),
5663
-                        print_r($base_class_obj_or_id, true)
5664
-                    )
5665
-                );
5666
-            }
5667
-        }
5668
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5669
-            $model_object->save();
5670
-        }
5671
-        return $model_object;
5672
-    }
5673
-
5674
-
5675
-
5676
-    /**
5677
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5678
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5679
-     * returns it ID.
5680
-     *
5681
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5682
-     * @return int|string depending on the type of this model object's ID
5683
-     * @throws EE_Error
5684
-     */
5685
-    public function ensure_is_ID($base_class_obj_or_id)
5686
-    {
5687
-        $className = $this->_get_class_name();
5688
-        if ($base_class_obj_or_id instanceof $className) {
5689
-            /** @var $base_class_obj_or_id EE_Base_Class */
5690
-            $id = $base_class_obj_or_id->ID();
5691
-        } elseif (is_int($base_class_obj_or_id)) {
5692
-            // assume it's an ID
5693
-            $id = $base_class_obj_or_id;
5694
-        } elseif (is_string($base_class_obj_or_id)) {
5695
-            // assume its a string representation of the object
5696
-            $id = $base_class_obj_or_id;
5697
-        } else {
5698
-            throw new EE_Error(sprintf(
5699
-                esc_html__(
5700
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5701
-                    'event_espresso'
5702
-                ),
5703
-                $base_class_obj_or_id,
5704
-                $this->_get_class_name(),
5705
-                print_r($base_class_obj_or_id, true)
5706
-            ));
5707
-        }
5708
-        return $id;
5709
-    }
5710
-
5711
-
5712
-
5713
-    /**
5714
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5715
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5716
-     * been sanitized and converted into the appropriate domain.
5717
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5718
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5719
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5720
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5721
-     * $EVT = EEM_Event::instance(); $old_setting =
5722
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5723
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5724
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5725
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5726
-     *
5727
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5728
-     * @return void
5729
-     */
5730
-    public function assume_values_already_prepared_by_model_object(
5731
-        $values_already_prepared = self::not_prepared_by_model_object
5732
-    ) {
5733
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5734
-    }
5735
-
5736
-
5737
-
5738
-    /**
5739
-     * Read comments for assume_values_already_prepared_by_model_object()
5740
-     *
5741
-     * @return int
5742
-     */
5743
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5744
-    {
5745
-        return $this->_values_already_prepared_by_model_object;
5746
-    }
5747
-
5748
-
5749
-
5750
-    /**
5751
-     * Gets all the indexes on this model
5752
-     *
5753
-     * @return EE_Index[]
5754
-     */
5755
-    public function indexes()
5756
-    {
5757
-        return $this->_indexes;
5758
-    }
5759
-
5760
-
5761
-
5762
-    /**
5763
-     * Gets all the Unique Indexes on this model
5764
-     *
5765
-     * @return EE_Unique_Index[]
5766
-     */
5767
-    public function unique_indexes()
5768
-    {
5769
-        $unique_indexes = array();
5770
-        foreach ($this->_indexes as $name => $index) {
5771
-            if ($index instanceof EE_Unique_Index) {
5772
-                $unique_indexes [ $name ] = $index;
5773
-            }
5774
-        }
5775
-        return $unique_indexes;
5776
-    }
5777
-
5778
-
5779
-
5780
-    /**
5781
-     * Gets all the fields which, when combined, make the primary key.
5782
-     * This is usually just an array with 1 element (the primary key), but in cases
5783
-     * where there is no primary key, it's a combination of fields as defined
5784
-     * on a primary index
5785
-     *
5786
-     * @return EE_Model_Field_Base[] indexed by the field's name
5787
-     * @throws EE_Error
5788
-     */
5789
-    public function get_combined_primary_key_fields()
5790
-    {
5791
-        foreach ($this->indexes() as $index) {
5792
-            if ($index instanceof EE_Primary_Key_Index) {
5793
-                return $index->fields();
5794
-            }
5795
-        }
5796
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5797
-    }
5798
-
5799
-
5800
-
5801
-    /**
5802
-     * Used to build a primary key string (when the model has no primary key),
5803
-     * which can be used a unique string to identify this model object.
5804
-     *
5805
-     * @param array $fields_n_values keys are field names, values are their values.
5806
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5807
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5808
-     *                               before passing it to this function (that will convert it from columns-n-values
5809
-     *                               to field-names-n-values).
5810
-     * @return string
5811
-     * @throws EE_Error
5812
-     */
5813
-    public function get_index_primary_key_string($fields_n_values)
5814
-    {
5815
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5816
-            $fields_n_values,
5817
-            $this->get_combined_primary_key_fields()
5818
-        );
5819
-        return http_build_query($cols_n_values_for_primary_key_index);
5820
-    }
5821
-
5822
-
5823
-
5824
-    /**
5825
-     * Gets the field values from the primary key string
5826
-     *
5827
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5828
-     * @param string $index_primary_key_string
5829
-     * @return null|array
5830
-     * @throws EE_Error
5831
-     */
5832
-    public function parse_index_primary_key_string($index_primary_key_string)
5833
-    {
5834
-        $key_fields = $this->get_combined_primary_key_fields();
5835
-        // check all of them are in the $id
5836
-        $key_vals_in_combined_pk = array();
5837
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5838
-        foreach ($key_fields as $key_field_name => $field_obj) {
5839
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5840
-                return null;
5841
-            }
5842
-        }
5843
-        return $key_vals_in_combined_pk;
5844
-    }
5845
-
5846
-
5847
-
5848
-    /**
5849
-     * verifies that an array of key-value pairs for model fields has a key
5850
-     * for each field comprising the primary key index
5851
-     *
5852
-     * @param array $key_vals
5853
-     * @return boolean
5854
-     * @throws EE_Error
5855
-     */
5856
-    public function has_all_combined_primary_key_fields($key_vals)
5857
-    {
5858
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5859
-        foreach ($keys_it_should_have as $key) {
5860
-            if (! isset($key_vals[ $key ])) {
5861
-                return false;
5862
-            }
5863
-        }
5864
-        return true;
5865
-    }
5866
-
5867
-
5868
-
5869
-    /**
5870
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5871
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5872
-     *
5873
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5874
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5875
-     * @throws EE_Error
5876
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5877
-     *                                                              indexed)
5878
-     */
5879
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5880
-    {
5881
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5882
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5883
-        } elseif (is_array($model_object_or_attributes_array)) {
5884
-            $attributes_array = $model_object_or_attributes_array;
5885
-        } else {
5886
-            throw new EE_Error(sprintf(esc_html__(
5887
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5888
-                "event_espresso"
5889
-            ), $model_object_or_attributes_array));
5890
-        }
5891
-        // even copies obviously won't have the same ID, so remove the primary key
5892
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5893
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5894
-            unset($attributes_array[ $this->primary_key_name() ]);
5895
-        }
5896
-        if (isset($query_params[0])) {
5897
-            $query_params[0] = array_merge($attributes_array, $query_params);
5898
-        } else {
5899
-            $query_params[0] = $attributes_array;
5900
-        }
5901
-        return $this->get_all($query_params);
5902
-    }
5903
-
5904
-
5905
-
5906
-    /**
5907
-     * Gets the first copy we find. See get_all_copies for more details
5908
-     *
5909
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5910
-     * @param array $query_params
5911
-     * @return EE_Base_Class
5912
-     * @throws EE_Error
5913
-     */
5914
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5915
-    {
5916
-        if (! is_array($query_params)) {
5917
-            EE_Error::doing_it_wrong(
5918
-                'EEM_Base::get_one_copy',
5919
-                sprintf(
5920
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5921
-                    gettype($query_params)
5922
-                ),
5923
-                '4.6.0'
5924
-            );
5925
-            $query_params = array();
5926
-        }
5927
-        $query_params['limit'] = 1;
5928
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5929
-        if (is_array($copies)) {
5930
-            return array_shift($copies);
5931
-        }
5932
-        return null;
5933
-    }
5934
-
5935
-
5936
-
5937
-    /**
5938
-     * Updates the item with the specified id. Ignores default query parameters because
5939
-     * we have specified the ID, and its assumed we KNOW what we're doing
5940
-     *
5941
-     * @param array      $fields_n_values keys are field names, values are their new values
5942
-     * @param int|string $id              the value of the primary key to update
5943
-     * @return int number of rows updated
5944
-     * @throws EE_Error
5945
-     */
5946
-    public function update_by_ID($fields_n_values, $id)
5947
-    {
5948
-        $query_params = array(
5949
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5950
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5951
-        );
5952
-        return $this->update($fields_n_values, $query_params);
5953
-    }
5954
-
5955
-
5956
-
5957
-    /**
5958
-     * Changes an operator which was supplied to the models into one usable in SQL
5959
-     *
5960
-     * @param string $operator_supplied
5961
-     * @return string an operator which can be used in SQL
5962
-     * @throws EE_Error
5963
-     */
5964
-    private function _prepare_operator_for_sql($operator_supplied)
5965
-    {
5966
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5967
-            : null;
5968
-        if ($sql_operator) {
5969
-            return $sql_operator;
5970
-        }
5971
-        throw new EE_Error(
5972
-            sprintf(
5973
-                esc_html__(
5974
-                    "The operator '%s' is not in the list of valid operators: %s",
5975
-                    "event_espresso"
5976
-                ),
5977
-                $operator_supplied,
5978
-                implode(",", array_keys($this->_valid_operators))
5979
-            )
5980
-        );
5981
-    }
5982
-
5983
-
5984
-
5985
-    /**
5986
-     * Gets the valid operators
5987
-     * @return array keys are accepted strings, values are the SQL they are converted to
5988
-     */
5989
-    public function valid_operators()
5990
-    {
5991
-        return $this->_valid_operators;
5992
-    }
5993
-
5994
-
5995
-
5996
-    /**
5997
-     * Gets the between-style operators (take 2 arguments).
5998
-     * @return array keys are accepted strings, values are the SQL they are converted to
5999
-     */
6000
-    public function valid_between_style_operators()
6001
-    {
6002
-        return array_intersect(
6003
-            $this->valid_operators(),
6004
-            $this->_between_style_operators
6005
-        );
6006
-    }
6007
-
6008
-    /**
6009
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6010
-     * @return array keys are accepted strings, values are the SQL they are converted to
6011
-     */
6012
-    public function valid_like_style_operators()
6013
-    {
6014
-        return array_intersect(
6015
-            $this->valid_operators(),
6016
-            $this->_like_style_operators
6017
-        );
6018
-    }
6019
-
6020
-    /**
6021
-     * Gets the "in"-style operators
6022
-     * @return array keys are accepted strings, values are the SQL they are converted to
6023
-     */
6024
-    public function valid_in_style_operators()
6025
-    {
6026
-        return array_intersect(
6027
-            $this->valid_operators(),
6028
-            $this->_in_style_operators
6029
-        );
6030
-    }
6031
-
6032
-    /**
6033
-     * Gets the "null"-style operators (accept no arguments)
6034
-     * @return array keys are accepted strings, values are the SQL they are converted to
6035
-     */
6036
-    public function valid_null_style_operators()
6037
-    {
6038
-        return array_intersect(
6039
-            $this->valid_operators(),
6040
-            $this->_null_style_operators
6041
-        );
6042
-    }
6043
-
6044
-    /**
6045
-     * Gets an array where keys are the primary keys and values are their 'names'
6046
-     * (as determined by the model object's name() function, which is often overridden)
6047
-     *
6048
-     * @param array $query_params like get_all's
6049
-     * @return string[]
6050
-     * @throws EE_Error
6051
-     */
6052
-    public function get_all_names($query_params = array())
6053
-    {
6054
-        $objs = $this->get_all($query_params);
6055
-        $names = array();
6056
-        foreach ($objs as $obj) {
6057
-            $names[ $obj->ID() ] = $obj->name();
6058
-        }
6059
-        return $names;
6060
-    }
6061
-
6062
-
6063
-
6064
-    /**
6065
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6066
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6067
-     * this is duplicated effort and reduces efficiency) you would be better to use
6068
-     * array_keys() on $model_objects.
6069
-     *
6070
-     * @param \EE_Base_Class[] $model_objects
6071
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6072
-     *                                               in the returned array
6073
-     * @return array
6074
-     * @throws EE_Error
6075
-     */
6076
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6077
-    {
6078
-        if (! $this->has_primary_key_field()) {
6079
-            if (WP_DEBUG) {
6080
-                EE_Error::add_error(
6081
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6082
-                    __FILE__,
6083
-                    __FUNCTION__,
6084
-                    __LINE__
6085
-                );
6086
-            }
6087
-        }
6088
-        $IDs = array();
6089
-        foreach ($model_objects as $model_object) {
6090
-            $id = $model_object->ID();
6091
-            if (! $id) {
6092
-                if ($filter_out_empty_ids) {
6093
-                    continue;
6094
-                }
6095
-                if (WP_DEBUG) {
6096
-                    EE_Error::add_error(
6097
-                        esc_html__(
6098
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6099
-                            'event_espresso'
6100
-                        ),
6101
-                        __FILE__,
6102
-                        __FUNCTION__,
6103
-                        __LINE__
6104
-                    );
6105
-                }
6106
-            }
6107
-            $IDs[] = $id;
6108
-        }
6109
-        return $IDs;
6110
-    }
6111
-
6112
-
6113
-
6114
-    /**
6115
-     * Returns the string used in capabilities relating to this model. If there
6116
-     * are no capabilities that relate to this model returns false
6117
-     *
6118
-     * @return string|false
6119
-     */
6120
-    public function cap_slug()
6121
-    {
6122
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6123
-    }
6124
-
6125
-
6126
-
6127
-    /**
6128
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6129
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6130
-     * only returns the cap restrictions array in that context (ie, the array
6131
-     * at that key)
6132
-     *
6133
-     * @param string $context
6134
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6135
-     * @throws EE_Error
6136
-     */
6137
-    public function cap_restrictions($context = EEM_Base::caps_read)
6138
-    {
6139
-        EEM_Base::verify_is_valid_cap_context($context);
6140
-        // check if we ought to run the restriction generator first
6141
-        if (
6142
-            isset($this->_cap_restriction_generators[ $context ])
6143
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6144
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6145
-        ) {
6146
-            $this->_cap_restrictions[ $context ] = array_merge(
6147
-                $this->_cap_restrictions[ $context ],
6148
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6149
-            );
6150
-        }
6151
-        // and make sure we've finalized the construction of each restriction
6152
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6153
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6154
-                $where_conditions_obj->_finalize_construct($this);
6155
-            }
6156
-        }
6157
-        return $this->_cap_restrictions[ $context ];
6158
-    }
6159
-
6160
-
6161
-
6162
-    /**
6163
-     * Indicating whether or not this model thinks its a wp core model
6164
-     *
6165
-     * @return boolean
6166
-     */
6167
-    public function is_wp_core_model()
6168
-    {
6169
-        return $this->_wp_core_model;
6170
-    }
6171
-
6172
-
6173
-
6174
-    /**
6175
-     * Gets all the caps that are missing which impose a restriction on
6176
-     * queries made in this context
6177
-     *
6178
-     * @param string $context one of EEM_Base::caps_ constants
6179
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6180
-     * @throws EE_Error
6181
-     */
6182
-    public function caps_missing($context = EEM_Base::caps_read)
6183
-    {
6184
-        $missing_caps = array();
6185
-        $cap_restrictions = $this->cap_restrictions($context);
6186
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6187
-            if (
6188
-                ! EE_Capabilities::instance()
6189
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6190
-            ) {
6191
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6192
-            }
6193
-        }
6194
-        return $missing_caps;
6195
-    }
6196
-
6197
-
6198
-
6199
-    /**
6200
-     * Gets the mapping from capability contexts to action strings used in capability names
6201
-     *
6202
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6203
-     * one of 'read', 'edit', or 'delete'
6204
-     */
6205
-    public function cap_contexts_to_cap_action_map()
6206
-    {
6207
-        return apply_filters(
6208
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6209
-            $this->_cap_contexts_to_cap_action_map,
6210
-            $this
6211
-        );
6212
-    }
6213
-
6214
-
6215
-
6216
-    /**
6217
-     * Gets the action string for the specified capability context
6218
-     *
6219
-     * @param string $context
6220
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6221
-     * @throws EE_Error
6222
-     */
6223
-    public function cap_action_for_context($context)
6224
-    {
6225
-        $mapping = $this->cap_contexts_to_cap_action_map();
6226
-        if (isset($mapping[ $context ])) {
6227
-            return $mapping[ $context ];
6228
-        }
6229
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6230
-            return $action;
6231
-        }
6232
-        throw new EE_Error(
6233
-            sprintf(
6234
-                esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6235
-                $context,
6236
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6237
-            )
6238
-        );
6239
-    }
6240
-
6241
-
6242
-
6243
-    /**
6244
-     * Returns all the capability contexts which are valid when querying models
6245
-     *
6246
-     * @return array
6247
-     */
6248
-    public static function valid_cap_contexts()
6249
-    {
6250
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6251
-            self::caps_read,
6252
-            self::caps_read_admin,
6253
-            self::caps_edit,
6254
-            self::caps_delete,
6255
-        ));
6256
-    }
6257
-
6258
-
6259
-
6260
-    /**
6261
-     * Returns all valid options for 'default_where_conditions'
6262
-     *
6263
-     * @return array
6264
-     */
6265
-    public static function valid_default_where_conditions()
6266
-    {
6267
-        return array(
6268
-            EEM_Base::default_where_conditions_all,
6269
-            EEM_Base::default_where_conditions_this_only,
6270
-            EEM_Base::default_where_conditions_others_only,
6271
-            EEM_Base::default_where_conditions_minimum_all,
6272
-            EEM_Base::default_where_conditions_minimum_others,
6273
-            EEM_Base::default_where_conditions_none
6274
-        );
6275
-    }
6276
-
6277
-    // public static function default_where_conditions_full
6278
-    /**
6279
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6280
-     *
6281
-     * @param string $context
6282
-     * @return bool
6283
-     * @throws EE_Error
6284
-     */
6285
-    public static function verify_is_valid_cap_context($context)
6286
-    {
6287
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6288
-        if (in_array($context, $valid_cap_contexts)) {
6289
-            return true;
6290
-        }
6291
-        throw new EE_Error(
6292
-            sprintf(
6293
-                esc_html__(
6294
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6295
-                    'event_espresso'
6296
-                ),
6297
-                $context,
6298
-                'EEM_Base',
6299
-                implode(',', $valid_cap_contexts)
6300
-            )
6301
-        );
6302
-    }
6303
-
6304
-
6305
-
6306
-    /**
6307
-     * Clears all the models field caches. This is only useful when a sub-class
6308
-     * might have added a field or something and these caches might be invalidated
6309
-     */
6310
-    protected function _invalidate_field_caches()
6311
-    {
6312
-        $this->_cache_foreign_key_to_fields = array();
6313
-        $this->_cached_fields = null;
6314
-        $this->_cached_fields_non_db_only = null;
6315
-    }
6316
-
6317
-
6318
-
6319
-    /**
6320
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6321
-     * (eg "and", "or", "not").
6322
-     *
6323
-     * @return array
6324
-     */
6325
-    public function logic_query_param_keys()
6326
-    {
6327
-        return $this->_logic_query_param_keys;
6328
-    }
6329
-
6330
-
6331
-
6332
-    /**
6333
-     * Determines whether or not the where query param array key is for a logic query param.
6334
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6335
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6336
-     *
6337
-     * @param $query_param_key
6338
-     * @return bool
6339
-     */
6340
-    public function is_logic_query_param_key($query_param_key)
6341
-    {
6342
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6343
-            if (
6344
-                $query_param_key === $logic_query_param_key
6345
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6346
-            ) {
6347
-                return true;
6348
-            }
6349
-        }
6350
-        return false;
6351
-    }
6352
-
6353
-    /**
6354
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6355
-     * @since 4.9.74.p
6356
-     * @return boolean
6357
-     */
6358
-    public function hasPassword()
6359
-    {
6360
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6361
-        if ($this->has_password_field === null) {
6362
-            $password_field = $this->getPasswordField();
6363
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6364
-        }
6365
-        return $this->has_password_field;
6366
-    }
6367
-
6368
-    /**
6369
-     * Returns the password field on this model, if there is one
6370
-     * @since 4.9.74.p
6371
-     * @return EE_Password_Field|null
6372
-     */
6373
-    public function getPasswordField()
6374
-    {
6375
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6376
-        // there's no need to search for it. If we don't know yet, then find out
6377
-        if ($this->has_password_field === null && $this->password_field === null) {
6378
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6379
-        }
6380
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6381
-        return $this->password_field;
6382
-    }
6383
-
6384
-
6385
-    /**
6386
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6387
-     * @since 4.9.74.p
6388
-     * @return EE_Model_Field_Base[]
6389
-     * @throws EE_Error
6390
-     */
6391
-    public function getPasswordProtectedFields()
6392
-    {
6393
-        $password_field = $this->getPasswordField();
6394
-        $fields = array();
6395
-        if ($password_field instanceof EE_Password_Field) {
6396
-            $field_names = $password_field->protectedFields();
6397
-            foreach ($field_names as $field_name) {
6398
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6399
-            }
6400
-        }
6401
-        return $fields;
6402
-    }
6403
-
6404
-
6405
-    /**
6406
-     * Checks if the current user can perform the requested action on this model
6407
-     * @since 4.9.74.p
6408
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6409
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6410
-     * @return bool
6411
-     * @throws EE_Error
6412
-     * @throws InvalidArgumentException
6413
-     * @throws InvalidDataTypeException
6414
-     * @throws InvalidInterfaceException
6415
-     * @throws ReflectionException
6416
-     * @throws UnexpectedEntityException
6417
-     */
6418
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6419
-    {
6420
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6421
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6422
-        }
6423
-        if (!is_array($model_obj_or_fields_n_values)) {
6424
-            throw new UnexpectedEntityException(
6425
-                $model_obj_or_fields_n_values,
6426
-                'EE_Base_Class',
6427
-                sprintf(
6428
-                    esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6429
-                    __FUNCTION__
6430
-                )
6431
-            );
6432
-        }
6433
-        return $this->exists(
6434
-            $this->alter_query_params_to_restrict_by_ID(
6435
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6436
-                array(
6437
-                    'default_where_conditions' => 'none',
6438
-                    'caps'                     => $cap_to_check,
6439
-                )
6440
-            )
6441
-        );
6442
-    }
6443
-
6444
-    /**
6445
-     * Returns the query param where conditions key to the password affecting this model.
6446
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6447
-     * @since 4.9.74.p
6448
-     * @return null|string
6449
-     * @throws EE_Error
6450
-     * @throws InvalidArgumentException
6451
-     * @throws InvalidDataTypeException
6452
-     * @throws InvalidInterfaceException
6453
-     * @throws ModelConfigurationException
6454
-     * @throws ReflectionException
6455
-     */
6456
-    public function modelChainAndPassword()
6457
-    {
6458
-        if ($this->model_chain_to_password === null) {
6459
-            throw new ModelConfigurationException(
6460
-                $this,
6461
-                esc_html_x(
6462
-                // @codingStandardsIgnoreStart
6463
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6464
-                    // @codingStandardsIgnoreEnd
6465
-                    '1: model name',
6466
-                    'event_espresso'
6467
-                )
6468
-            );
6469
-        }
6470
-        if ($this->model_chain_to_password === '') {
6471
-            $model_with_password = $this;
6472
-        } else {
6473
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6474
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6475
-            } else {
6476
-                $last_model_in_chain = $this->model_chain_to_password;
6477
-            }
6478
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6479
-        }
6480
-
6481
-        $password_field = $model_with_password->getPasswordField();
6482
-        if ($password_field instanceof EE_Password_Field) {
6483
-            $password_field_name = $password_field->get_name();
6484
-        } else {
6485
-            throw new ModelConfigurationException(
6486
-                $this,
6487
-                sprintf(
6488
-                    esc_html_x(
6489
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6490
-                        '1: model name, 2: special string',
6491
-                        'event_espresso'
6492
-                    ),
6493
-                    $model_with_password->get_this_model_name(),
6494
-                    $this->model_chain_to_password
6495
-                )
6496
-            );
6497
-        }
6498
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6499
-    }
6500
-
6501
-    /**
6502
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6503
-     * or if this model itself has a password affecting access to some of its other fields.
6504
-     * @since 4.9.74.p
6505
-     * @return boolean
6506
-     */
6507
-    public function restrictedByRelatedModelPassword()
6508
-    {
6509
-        return $this->model_chain_to_password !== null;
6510
-    }
3815
+		}
3816
+		return $null_friendly_where_conditions;
3817
+	}
3818
+
3819
+
3820
+
3821
+	/**
3822
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3823
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3824
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3825
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3826
+	 *
3827
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3828
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3829
+	 */
3830
+	private function _get_default_where_conditions($model_relation_path = null)
3831
+	{
3832
+		if ($this->_ignore_where_strategy) {
3833
+			return array();
3834
+		}
3835
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3836
+	}
3837
+
3838
+
3839
+
3840
+	/**
3841
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3842
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3843
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3844
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3845
+	 * Similar to _get_default_where_conditions
3846
+	 *
3847
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3848
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3849
+	 */
3850
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3851
+	{
3852
+		if ($this->_ignore_where_strategy) {
3853
+			return array();
3854
+		}
3855
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3856
+	}
3857
+
3858
+
3859
+
3860
+	/**
3861
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3862
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3863
+	 *
3864
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3865
+	 * @return string
3866
+	 * @throws EE_Error
3867
+	 */
3868
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3869
+	{
3870
+		$selects = $this->_get_columns_to_select_for_this_model();
3871
+		foreach (
3872
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3873
+		) {
3874
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3875
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3876
+			foreach ($other_model_selects as $key => $value) {
3877
+				$selects[] = $value;
3878
+			}
3879
+		}
3880
+		return implode(", ", $selects);
3881
+	}
3882
+
3883
+
3884
+
3885
+	/**
3886
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3887
+	 * So that's going to be the columns for all the fields on the model
3888
+	 *
3889
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3890
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3891
+	 */
3892
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3893
+	{
3894
+		$fields = $this->field_settings();
3895
+		$selects = array();
3896
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3897
+			$model_relation_chain,
3898
+			$this->get_this_model_name()
3899
+		);
3900
+		foreach ($fields as $field_obj) {
3901
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3902
+						 . $field_obj->get_table_alias()
3903
+						 . "."
3904
+						 . $field_obj->get_table_column()
3905
+						 . " AS '"
3906
+						 . $table_alias_with_model_relation_chain_prefix
3907
+						 . $field_obj->get_table_alias()
3908
+						 . "."
3909
+						 . $field_obj->get_table_column()
3910
+						 . "'";
3911
+		}
3912
+		// make sure we are also getting the PKs of each table
3913
+		$tables = $this->get_tables();
3914
+		if (count($tables) > 1) {
3915
+			foreach ($tables as $table_obj) {
3916
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3917
+									   . $table_obj->get_fully_qualified_pk_column();
3918
+				if (! in_array($qualified_pk_column, $selects)) {
3919
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3920
+				}
3921
+			}
3922
+		}
3923
+		return $selects;
3924
+	}
3925
+
3926
+
3927
+
3928
+	/**
3929
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3930
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3931
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3932
+	 * SQL for joining, and the data types
3933
+	 *
3934
+	 * @param null|string                 $original_query_param
3935
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3936
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3937
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3938
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3939
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3940
+	 *                                                          or 'Registration's
3941
+	 * @param string                      $original_query_param what it originally was (eg
3942
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3943
+	 *                                                          matches $query_param
3944
+	 * @throws EE_Error
3945
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3946
+	 */
3947
+	private function _extract_related_model_info_from_query_param(
3948
+		$query_param,
3949
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3950
+		$query_param_type,
3951
+		$original_query_param = null
3952
+	) {
3953
+		if ($original_query_param === null) {
3954
+			$original_query_param = $query_param;
3955
+		}
3956
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3957
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3958
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3959
+		$allow_fields = in_array(
3960
+			$query_param_type,
3961
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3962
+			true
3963
+		);
3964
+		// check to see if we have a field on this model
3965
+		$this_model_fields = $this->field_settings(true);
3966
+		if (array_key_exists($query_param, $this_model_fields)) {
3967
+			if ($allow_fields) {
3968
+				return;
3969
+			}
3970
+			throw new EE_Error(
3971
+				sprintf(
3972
+					esc_html__(
3973
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3974
+						"event_espresso"
3975
+					),
3976
+					$query_param,
3977
+					get_class($this),
3978
+					$query_param_type,
3979
+					$original_query_param
3980
+				)
3981
+			);
3982
+		}
3983
+		// check if this is a special logic query param
3984
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3985
+			if ($allow_logic_query_params) {
3986
+				return;
3987
+			}
3988
+			throw new EE_Error(
3989
+				sprintf(
3990
+					esc_html__(
3991
+						'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',
3992
+						'event_espresso'
3993
+					),
3994
+					implode('", "', $this->_logic_query_param_keys),
3995
+					$query_param,
3996
+					get_class($this),
3997
+					'<br />',
3998
+					"\t"
3999
+					. ' $passed_in_query_info = <pre>'
4000
+					. print_r($passed_in_query_info, true)
4001
+					. '</pre>'
4002
+					. "\n\t"
4003
+					. ' $query_param_type = '
4004
+					. $query_param_type
4005
+					. "\n\t"
4006
+					. ' $original_query_param = '
4007
+					. $original_query_param
4008
+				)
4009
+			);
4010
+		}
4011
+		// check if it's a custom selection
4012
+		if (
4013
+			$this->_custom_selections instanceof CustomSelects
4014
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4015
+		) {
4016
+			return;
4017
+		}
4018
+		// check if has a model name at the beginning
4019
+		// and
4020
+		// check if it's a field on a related model
4021
+		if (
4022
+			$this->extractJoinModelFromQueryParams(
4023
+				$passed_in_query_info,
4024
+				$query_param,
4025
+				$original_query_param,
4026
+				$query_param_type
4027
+			)
4028
+		) {
4029
+			return;
4030
+		}
4031
+
4032
+		// ok so $query_param didn't start with a model name
4033
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4034
+		// it's wack, that's what it is
4035
+		throw new EE_Error(
4036
+			sprintf(
4037
+				esc_html__(
4038
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4039
+					"event_espresso"
4040
+				),
4041
+				$query_param,
4042
+				get_class($this),
4043
+				$query_param_type,
4044
+				$original_query_param
4045
+			)
4046
+		);
4047
+	}
4048
+
4049
+
4050
+	/**
4051
+	 * Extracts any possible join model information from the provided possible_join_string.
4052
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4053
+	 * parts that should be added to the query.
4054
+	 *
4055
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4056
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4057
+	 * @param null|string                 $original_query_param
4058
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4059
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4060
+	 * @return bool  returns true if a join was added and false if not.
4061
+	 * @throws EE_Error
4062
+	 */
4063
+	private function extractJoinModelFromQueryParams(
4064
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4065
+		$possible_join_string,
4066
+		$original_query_param,
4067
+		$query_parameter_type
4068
+	) {
4069
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4070
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4071
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4072
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4073
+				if ($possible_join_string === '') {
4074
+					// nothing left to $query_param
4075
+					// we should actually end in a field name, not a model like this!
4076
+					throw new EE_Error(
4077
+						sprintf(
4078
+							esc_html__(
4079
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4080
+								"event_espresso"
4081
+							),
4082
+							$possible_join_string,
4083
+							$query_parameter_type,
4084
+							get_class($this),
4085
+							$valid_related_model_name
4086
+						)
4087
+					);
4088
+				}
4089
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4090
+				$related_model_obj->_extract_related_model_info_from_query_param(
4091
+					$possible_join_string,
4092
+					$query_info_carrier,
4093
+					$query_parameter_type,
4094
+					$original_query_param
4095
+				);
4096
+				return true;
4097
+			}
4098
+			if ($possible_join_string === $valid_related_model_name) {
4099
+				$this->_add_join_to_model(
4100
+					$valid_related_model_name,
4101
+					$query_info_carrier,
4102
+					$original_query_param
4103
+				);
4104
+				return true;
4105
+			}
4106
+		}
4107
+		return false;
4108
+	}
4109
+
4110
+
4111
+	/**
4112
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4113
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4114
+	 * @throws EE_Error
4115
+	 */
4116
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4117
+	{
4118
+		if (
4119
+			$this->_custom_selections instanceof CustomSelects
4120
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4121
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4122
+			)
4123
+		) {
4124
+			$original_selects = $this->_custom_selections->originalSelects();
4125
+			foreach ($original_selects as $alias => $select_configuration) {
4126
+				$this->extractJoinModelFromQueryParams(
4127
+					$query_info_carrier,
4128
+					$select_configuration[0],
4129
+					$select_configuration[0],
4130
+					'custom_selects'
4131
+				);
4132
+			}
4133
+		}
4134
+	}
4135
+
4136
+
4137
+
4138
+	/**
4139
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4140
+	 * and store it on $passed_in_query_info
4141
+	 *
4142
+	 * @param string                      $model_name
4143
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4144
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4145
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4146
+	 *                                                          and are adding a join to 'Payment' with the original
4147
+	 *                                                          query param key
4148
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4149
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4150
+	 *                                                          Payment wants to add default query params so that it
4151
+	 *                                                          will know what models to prepend onto its default query
4152
+	 *                                                          params or in case it wants to rename tables (in case
4153
+	 *                                                          there are multiple joins to the same table)
4154
+	 * @return void
4155
+	 * @throws EE_Error
4156
+	 */
4157
+	private function _add_join_to_model(
4158
+		$model_name,
4159
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4160
+		$original_query_param
4161
+	) {
4162
+		$relation_obj = $this->related_settings_for($model_name);
4163
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4164
+		// check if the relation is HABTM, because then we're essentially doing two joins
4165
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4166
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4167
+			$join_model_obj = $relation_obj->get_join_model();
4168
+			// replace the model specified with the join model for this relation chain, whi
4169
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4170
+				$model_name,
4171
+				$join_model_obj->get_this_model_name(),
4172
+				$model_relation_chain
4173
+			);
4174
+			$passed_in_query_info->merge(
4175
+				new EE_Model_Query_Info_Carrier(
4176
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4177
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4178
+				)
4179
+			);
4180
+		}
4181
+		// now just join to the other table pointed to by the relation object, and add its data types
4182
+		$passed_in_query_info->merge(
4183
+			new EE_Model_Query_Info_Carrier(
4184
+				array($model_relation_chain => $model_name),
4185
+				$relation_obj->get_join_statement($model_relation_chain)
4186
+			)
4187
+		);
4188
+	}
4189
+
4190
+
4191
+
4192
+	/**
4193
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4194
+	 *
4195
+	 * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4196
+	 * @return string of SQL
4197
+	 * @throws EE_Error
4198
+	 */
4199
+	private function _construct_where_clause($where_params)
4200
+	{
4201
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4202
+		if ($SQL) {
4203
+			return " WHERE " . $SQL;
4204
+		}
4205
+		return '';
4206
+	}
4207
+
4208
+
4209
+
4210
+	/**
4211
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4212
+	 * and should be passed HAVING parameters, not WHERE parameters
4213
+	 *
4214
+	 * @param array $having_params
4215
+	 * @return string
4216
+	 * @throws EE_Error
4217
+	 */
4218
+	private function _construct_having_clause($having_params)
4219
+	{
4220
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4221
+		if ($SQL) {
4222
+			return " HAVING " . $SQL;
4223
+		}
4224
+		return '';
4225
+	}
4226
+
4227
+
4228
+	/**
4229
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4230
+	 * Event_Meta.meta_value = 'foo'))"
4231
+	 *
4232
+	 * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4233
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4234
+	 * @throws EE_Error
4235
+	 * @return string of SQL
4236
+	 */
4237
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4238
+	{
4239
+		$where_clauses = array();
4240
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4241
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4242
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4243
+				switch ($query_param) {
4244
+					case 'not':
4245
+					case 'NOT':
4246
+						$where_clauses[] = "! ("
4247
+										   . $this->_construct_condition_clause_recursive(
4248
+											   $op_and_value_or_sub_condition,
4249
+											   $glue
4250
+										   )
4251
+										   . ")";
4252
+						break;
4253
+					case 'and':
4254
+					case 'AND':
4255
+						$where_clauses[] = " ("
4256
+										   . $this->_construct_condition_clause_recursive(
4257
+											   $op_and_value_or_sub_condition,
4258
+											   ' AND '
4259
+										   )
4260
+										   . ")";
4261
+						break;
4262
+					case 'or':
4263
+					case 'OR':
4264
+						$where_clauses[] = " ("
4265
+										   . $this->_construct_condition_clause_recursive(
4266
+											   $op_and_value_or_sub_condition,
4267
+											   ' OR '
4268
+										   )
4269
+										   . ")";
4270
+						break;
4271
+				}
4272
+			} else {
4273
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4274
+				// if it's not a normal field, maybe it's a custom selection?
4275
+				if (! $field_obj) {
4276
+					if ($this->_custom_selections instanceof CustomSelects) {
4277
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4278
+					} else {
4279
+						throw new EE_Error(sprintf(esc_html__(
4280
+							"%s is neither a valid model field name, nor a custom selection",
4281
+							"event_espresso"
4282
+						), $query_param));
4283
+					}
4284
+				}
4285
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4286
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4287
+			}
4288
+		}
4289
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4290
+	}
4291
+
4292
+
4293
+
4294
+	/**
4295
+	 * Takes the input parameter and extract the table name (alias) and column name
4296
+	 *
4297
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4298
+	 * @throws EE_Error
4299
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4300
+	 */
4301
+	private function _deduce_column_name_from_query_param($query_param)
4302
+	{
4303
+		$field = $this->_deduce_field_from_query_param($query_param);
4304
+		if ($field) {
4305
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4306
+				$field->get_model_name(),
4307
+				$query_param
4308
+			);
4309
+			return $table_alias_prefix . $field->get_qualified_column();
4310
+		}
4311
+		if (
4312
+			$this->_custom_selections instanceof CustomSelects
4313
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4314
+		) {
4315
+			// maybe it's custom selection item?
4316
+			// if so, just use it as the "column name"
4317
+			return $query_param;
4318
+		}
4319
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4320
+			? implode(',', $this->_custom_selections->columnAliases())
4321
+			: '';
4322
+		throw new EE_Error(
4323
+			sprintf(
4324
+				esc_html__(
4325
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4326
+					"event_espresso"
4327
+				),
4328
+				$query_param,
4329
+				$custom_select_aliases
4330
+			)
4331
+		);
4332
+	}
4333
+
4334
+
4335
+
4336
+	/**
4337
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4338
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4339
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4340
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4341
+	 *
4342
+	 * @param string $condition_query_param_key
4343
+	 * @return string
4344
+	 */
4345
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4346
+	{
4347
+		$pos_of_star = strpos($condition_query_param_key, '*');
4348
+		if ($pos_of_star === false) {
4349
+			return $condition_query_param_key;
4350
+		}
4351
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4352
+		return $condition_query_param_sans_star;
4353
+	}
4354
+
4355
+
4356
+
4357
+	/**
4358
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4359
+	 *
4360
+	 * @param                            mixed      array | string    $op_and_value
4361
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4362
+	 * @throws EE_Error
4363
+	 * @return string
4364
+	 */
4365
+	private function _construct_op_and_value($op_and_value, $field_obj)
4366
+	{
4367
+		if (is_array($op_and_value)) {
4368
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4369
+			if (! $operator) {
4370
+				$php_array_like_string = array();
4371
+				foreach ($op_and_value as $key => $value) {
4372
+					$php_array_like_string[] = "$key=>$value";
4373
+				}
4374
+				throw new EE_Error(
4375
+					sprintf(
4376
+						esc_html__(
4377
+							"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))",
4378
+							"event_espresso"
4379
+						),
4380
+						implode(",", $php_array_like_string)
4381
+					)
4382
+				);
4383
+			}
4384
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4385
+		} else {
4386
+			$operator = '=';
4387
+			$value = $op_and_value;
4388
+		}
4389
+		// check to see if the value is actually another field
4390
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4391
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4392
+		}
4393
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4394
+			// in this case, the value should be an array, or at least a comma-separated list
4395
+			// it will need to handle a little differently
4396
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4397
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4398
+			return $operator . SP . $cleaned_value;
4399
+		}
4400
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4401
+			// the value should be an array with count of two.
4402
+			if (count($value) !== 2) {
4403
+				throw new EE_Error(
4404
+					sprintf(
4405
+						esc_html__(
4406
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4407
+							'event_espresso'
4408
+						),
4409
+						"BETWEEN"
4410
+					)
4411
+				);
4412
+			}
4413
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4414
+			return $operator . SP . $cleaned_value;
4415
+		}
4416
+		if (in_array($operator, $this->valid_null_style_operators())) {
4417
+			if ($value !== null) {
4418
+				throw new EE_Error(
4419
+					sprintf(
4420
+						esc_html__(
4421
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4422
+							"event_espresso"
4423
+						),
4424
+						$value,
4425
+						$operator
4426
+					)
4427
+				);
4428
+			}
4429
+			return $operator;
4430
+		}
4431
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4432
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4433
+			// remove other junk. So just treat it as a string.
4434
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4435
+		}
4436
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4437
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4438
+		}
4439
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4440
+			throw new EE_Error(
4441
+				sprintf(
4442
+					esc_html__(
4443
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4444
+						'event_espresso'
4445
+					),
4446
+					$operator,
4447
+					$operator
4448
+				)
4449
+			);
4450
+		}
4451
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452
+			throw new EE_Error(
4453
+				sprintf(
4454
+					esc_html__(
4455
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4456
+						'event_espresso'
4457
+					),
4458
+					$operator,
4459
+					$operator
4460
+				)
4461
+			);
4462
+		}
4463
+		throw new EE_Error(
4464
+			sprintf(
4465
+				esc_html__(
4466
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4467
+					"event_espresso"
4468
+				),
4469
+				http_build_query($op_and_value)
4470
+			)
4471
+		);
4472
+	}
4473
+
4474
+
4475
+
4476
+	/**
4477
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4478
+	 *
4479
+	 * @param array                      $values
4480
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4481
+	 *                                              '%s'
4482
+	 * @return string
4483
+	 * @throws EE_Error
4484
+	 */
4485
+	public function _construct_between_value($values, $field_obj)
4486
+	{
4487
+		$cleaned_values = array();
4488
+		foreach ($values as $value) {
4489
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4490
+		}
4491
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4492
+	}
4493
+
4494
+
4495
+	/**
4496
+	 * Takes an array or a comma-separated list of $values and cleans them
4497
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4498
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4499
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4500
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4501
+	 *
4502
+	 * @param mixed                      $values    array or comma-separated string
4503
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4504
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4505
+	 * @throws EE_Error
4506
+	 */
4507
+	public function _construct_in_value($values, $field_obj)
4508
+	{
4509
+		$prepped = [];
4510
+		// check if the value is a CSV list
4511
+		if (is_string($values)) {
4512
+			// in which case, turn it into an array
4513
+			$values = explode(',', $values);
4514
+		}
4515
+		// make sure we only have one of each value in the list
4516
+		$values = array_unique($values);
4517
+		foreach ($values as $value) {
4518
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4519
+		}
4520
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4521
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4522
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4523
+		if (empty($prepped)) {
4524
+			$all_fields = $this->field_settings();
4525
+			$first_field    = reset($all_fields);
4526
+			$main_table = $this->_get_main_table();
4527
+			$prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4528
+		}
4529
+		return '(' . implode(',', $prepped) . ')';
4530
+	}
4531
+
4532
+
4533
+
4534
+	/**
4535
+	 * @param mixed                      $value
4536
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4537
+	 * @throws EE_Error
4538
+	 * @return false|null|string
4539
+	 */
4540
+	private function _wpdb_prepare_using_field($value, $field_obj)
4541
+	{
4542
+		/** @type WPDB $wpdb */
4543
+		global $wpdb;
4544
+		if ($field_obj instanceof EE_Model_Field_Base) {
4545
+			return $wpdb->prepare(
4546
+				$field_obj->get_wpdb_data_type(),
4547
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4548
+			);
4549
+		} //$field_obj should really just be a data type
4550
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4551
+			throw new EE_Error(
4552
+				sprintf(
4553
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4554
+					$field_obj,
4555
+					implode(",", $this->_valid_wpdb_data_types)
4556
+				)
4557
+			);
4558
+		}
4559
+		return $wpdb->prepare($field_obj, $value);
4560
+	}
4561
+
4562
+
4563
+
4564
+	/**
4565
+	 * Takes the input parameter and finds the model field that it indicates.
4566
+	 *
4567
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4568
+	 * @throws EE_Error
4569
+	 * @return EE_Model_Field_Base
4570
+	 */
4571
+	protected function _deduce_field_from_query_param($query_param_name)
4572
+	{
4573
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4574
+		// which will help us find the database table and column
4575
+		$query_param_parts = explode(".", $query_param_name);
4576
+		if (empty($query_param_parts)) {
4577
+			throw new EE_Error(sprintf(esc_html__(
4578
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4579
+				'event_espresso'
4580
+			), $query_param_name));
4581
+		}
4582
+		$number_of_parts = count($query_param_parts);
4583
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4584
+		if ($number_of_parts === 1) {
4585
+			$field_name = $last_query_param_part;
4586
+			$model_obj = $this;
4587
+		} else {// $number_of_parts >= 2
4588
+			// the last part is the column name, and there are only 2parts. therefore...
4589
+			$field_name = $last_query_param_part;
4590
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4591
+		}
4592
+		try {
4593
+			return $model_obj->field_settings_for($field_name);
4594
+		} catch (EE_Error $e) {
4595
+			return null;
4596
+		}
4597
+	}
4598
+
4599
+
4600
+
4601
+	/**
4602
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4603
+	 * alias and column which corresponds to it
4604
+	 *
4605
+	 * @param string $field_name
4606
+	 * @throws EE_Error
4607
+	 * @return string
4608
+	 */
4609
+	public function _get_qualified_column_for_field($field_name)
4610
+	{
4611
+		$all_fields = $this->field_settings();
4612
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4613
+		if ($field) {
4614
+			return $field->get_qualified_column();
4615
+		}
4616
+		throw new EE_Error(
4617
+			sprintf(
4618
+				esc_html__(
4619
+					"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.",
4620
+					'event_espresso'
4621
+				),
4622
+				$field_name,
4623
+				get_class($this)
4624
+			)
4625
+		);
4626
+	}
4627
+
4628
+
4629
+
4630
+	/**
4631
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4632
+	 * Example usage:
4633
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4634
+	 *      array(),
4635
+	 *      ARRAY_A,
4636
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4637
+	 *  );
4638
+	 * is equivalent to
4639
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4640
+	 * and
4641
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4642
+	 *      array(
4643
+	 *          array(
4644
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4645
+	 *          ),
4646
+	 *          ARRAY_A,
4647
+	 *          implode(
4648
+	 *              ', ',
4649
+	 *              array_merge(
4650
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4651
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4652
+	 *              )
4653
+	 *          )
4654
+	 *      )
4655
+	 *  );
4656
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4657
+	 *
4658
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4659
+	 *                                            and the one whose fields you are selecting for example: when querying
4660
+	 *                                            tickets model and selecting fields from the tickets model you would
4661
+	 *                                            leave this parameter empty, because no models are needed to join
4662
+	 *                                            between the queried model and the selected one. Likewise when
4663
+	 *                                            querying the datetime model and selecting fields from the tickets
4664
+	 *                                            model, it would also be left empty, because there is a direct
4665
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4666
+	 *                                            them together. However, when querying from the event model and
4667
+	 *                                            selecting fields from the ticket model, you should provide the string
4668
+	 *                                            'Datetime', indicating that the event model must first join to the
4669
+	 *                                            datetime model in order to find its relation to ticket model.
4670
+	 *                                            Also, when querying from the venue model and selecting fields from
4671
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4672
+	 *                                            indicating you need to join the venue model to the event model,
4673
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4674
+	 *                                            This string is used to deduce the prefix that gets added onto the
4675
+	 *                                            models' tables qualified columns
4676
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4677
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4678
+	 *                                            qualified column names
4679
+	 * @return array|string
4680
+	 */
4681
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4682
+	{
4683
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4684
+		$qualified_columns = array();
4685
+		foreach ($this->field_settings() as $field_name => $field) {
4686
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4687
+		}
4688
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4689
+	}
4690
+
4691
+
4692
+
4693
+	/**
4694
+	 * constructs the select use on special limit joins
4695
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4696
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4697
+	 * (as that is typically where the limits would be set).
4698
+	 *
4699
+	 * @param  string       $table_alias The table the select is being built for
4700
+	 * @param  mixed|string $limit       The limit for this select
4701
+	 * @return string                The final select join element for the query.
4702
+	 */
4703
+	public function _construct_limit_join_select($table_alias, $limit)
4704
+	{
4705
+		$SQL = '';
4706
+		foreach ($this->_tables as $table_obj) {
4707
+			if ($table_obj instanceof EE_Primary_Table) {
4708
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4709
+					? $table_obj->get_select_join_limit($limit)
4710
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4711
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4712
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4713
+					? $table_obj->get_select_join_limit_join($limit)
4714
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4715
+			}
4716
+		}
4717
+		return $SQL;
4718
+	}
4719
+
4720
+
4721
+
4722
+	/**
4723
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4724
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4725
+	 *
4726
+	 * @return string SQL
4727
+	 * @throws EE_Error
4728
+	 */
4729
+	public function _construct_internal_join()
4730
+	{
4731
+		$SQL = $this->_get_main_table()->get_table_sql();
4732
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4733
+		return $SQL;
4734
+	}
4735
+
4736
+
4737
+
4738
+	/**
4739
+	 * Constructs the SQL for joining all the tables on this model.
4740
+	 * Normally $alias should be the primary table's alias, but in cases where
4741
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4742
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4743
+	 * alias, this will construct SQL like:
4744
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4745
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4746
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4747
+	 *
4748
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4749
+	 * @return string
4750
+	 */
4751
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4752
+	{
4753
+		$SQL = '';
4754
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4755
+		foreach ($this->_tables as $table_obj) {
4756
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4757
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4758
+					// so we're joining to this table, meaning the table is already in
4759
+					// the FROM statement, BUT the primary table isn't. So we want
4760
+					// to add the inverse join sql
4761
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4762
+				} else {
4763
+					// just add a regular JOIN to this table from the primary table
4764
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4765
+				}
4766
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4767
+		}
4768
+		return $SQL;
4769
+	}
4770
+
4771
+
4772
+
4773
+	/**
4774
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4775
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4776
+	 * their data type (eg, '%s', '%d', etc)
4777
+	 *
4778
+	 * @return array
4779
+	 */
4780
+	public function _get_data_types()
4781
+	{
4782
+		$data_types = array();
4783
+		foreach ($this->field_settings() as $field_obj) {
4784
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4785
+			/** @var $field_obj EE_Model_Field_Base */
4786
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4787
+		}
4788
+		return $data_types;
4789
+	}
4790
+
4791
+
4792
+
4793
+	/**
4794
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4795
+	 *
4796
+	 * @param string $model_name
4797
+	 * @throws EE_Error
4798
+	 * @return EEM_Base
4799
+	 */
4800
+	public function get_related_model_obj($model_name)
4801
+	{
4802
+		$model_classname = "EEM_" . $model_name;
4803
+		if (! class_exists($model_classname)) {
4804
+			throw new EE_Error(sprintf(esc_html__(
4805
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4806
+				'event_espresso'
4807
+			), $model_name, $model_classname));
4808
+		}
4809
+		return call_user_func($model_classname . "::instance");
4810
+	}
4811
+
4812
+
4813
+
4814
+	/**
4815
+	 * Returns the array of EE_ModelRelations for this model.
4816
+	 *
4817
+	 * @return EE_Model_Relation_Base[]
4818
+	 */
4819
+	public function relation_settings()
4820
+	{
4821
+		return $this->_model_relations;
4822
+	}
4823
+
4824
+
4825
+
4826
+	/**
4827
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4828
+	 * because without THOSE models, this model probably doesn't have much purpose.
4829
+	 * (Eg, without an event, datetimes have little purpose.)
4830
+	 *
4831
+	 * @return EE_Belongs_To_Relation[]
4832
+	 */
4833
+	public function belongs_to_relations()
4834
+	{
4835
+		$belongs_to_relations = array();
4836
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4837
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4838
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4839
+			}
4840
+		}
4841
+		return $belongs_to_relations;
4842
+	}
4843
+
4844
+
4845
+
4846
+	/**
4847
+	 * Returns the specified EE_Model_Relation, or throws an exception
4848
+	 *
4849
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4850
+	 * @throws EE_Error
4851
+	 * @return EE_Model_Relation_Base
4852
+	 */
4853
+	public function related_settings_for($relation_name)
4854
+	{
4855
+		$relatedModels = $this->relation_settings();
4856
+		if (! array_key_exists($relation_name, $relatedModels)) {
4857
+			throw new EE_Error(
4858
+				sprintf(
4859
+					esc_html__(
4860
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4861
+						'event_espresso'
4862
+					),
4863
+					$relation_name,
4864
+					$this->_get_class_name(),
4865
+					implode(', ', array_keys($relatedModels))
4866
+				)
4867
+			);
4868
+		}
4869
+		return $relatedModels[ $relation_name ];
4870
+	}
4871
+
4872
+
4873
+
4874
+	/**
4875
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4876
+	 * fields
4877
+	 *
4878
+	 * @param string $fieldName
4879
+	 * @param boolean $include_db_only_fields
4880
+	 * @throws EE_Error
4881
+	 * @return EE_Model_Field_Base
4882
+	 */
4883
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4884
+	{
4885
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4886
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4887
+			throw new EE_Error(sprintf(
4888
+				esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4889
+				$fieldName,
4890
+				get_class($this)
4891
+			));
4892
+		}
4893
+		return $fieldSettings[ $fieldName ];
4894
+	}
4895
+
4896
+
4897
+
4898
+	/**
4899
+	 * Checks if this field exists on this model
4900
+	 *
4901
+	 * @param string $fieldName a key in the model's _field_settings array
4902
+	 * @return boolean
4903
+	 */
4904
+	public function has_field($fieldName)
4905
+	{
4906
+		$fieldSettings = $this->field_settings(true);
4907
+		if (isset($fieldSettings[ $fieldName ])) {
4908
+			return true;
4909
+		}
4910
+		return false;
4911
+	}
4912
+
4913
+
4914
+
4915
+	/**
4916
+	 * Returns whether or not this model has a relation to the specified model
4917
+	 *
4918
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4919
+	 * @return boolean
4920
+	 */
4921
+	public function has_relation($relation_name)
4922
+	{
4923
+		$relations = $this->relation_settings();
4924
+		if (isset($relations[ $relation_name ])) {
4925
+			return true;
4926
+		}
4927
+		return false;
4928
+	}
4929
+
4930
+
4931
+
4932
+	/**
4933
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4934
+	 * Eg, on EE_Answer that would be ANS_ID field object
4935
+	 *
4936
+	 * @param $field_obj
4937
+	 * @return boolean
4938
+	 */
4939
+	public function is_primary_key_field($field_obj)
4940
+	{
4941
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4942
+	}
4943
+
4944
+
4945
+
4946
+	/**
4947
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4948
+	 * Eg, on EE_Answer that would be ANS_ID field object
4949
+	 *
4950
+	 * @return EE_Model_Field_Base
4951
+	 * @throws EE_Error
4952
+	 */
4953
+	public function get_primary_key_field()
4954
+	{
4955
+		if ($this->_primary_key_field === null) {
4956
+			foreach ($this->field_settings(true) as $field_obj) {
4957
+				if ($this->is_primary_key_field($field_obj)) {
4958
+					$this->_primary_key_field = $field_obj;
4959
+					break;
4960
+				}
4961
+			}
4962
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4963
+				throw new EE_Error(sprintf(
4964
+					esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
4965
+					get_class($this)
4966
+				));
4967
+			}
4968
+		}
4969
+		return $this->_primary_key_field;
4970
+	}
4971
+
4972
+
4973
+
4974
+	/**
4975
+	 * Returns whether or not not there is a primary key on this model.
4976
+	 * Internally does some caching.
4977
+	 *
4978
+	 * @return boolean
4979
+	 */
4980
+	public function has_primary_key_field()
4981
+	{
4982
+		if ($this->_has_primary_key_field === null) {
4983
+			try {
4984
+				$this->get_primary_key_field();
4985
+				$this->_has_primary_key_field = true;
4986
+			} catch (EE_Error $e) {
4987
+				$this->_has_primary_key_field = false;
4988
+			}
4989
+		}
4990
+		return $this->_has_primary_key_field;
4991
+	}
4992
+
4993
+
4994
+
4995
+	/**
4996
+	 * Finds the first field of type $field_class_name.
4997
+	 *
4998
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4999
+	 *                                 EE_Foreign_Key_Field, etc
5000
+	 * @return EE_Model_Field_Base or null if none is found
5001
+	 */
5002
+	public function get_a_field_of_type($field_class_name)
5003
+	{
5004
+		foreach ($this->field_settings() as $field) {
5005
+			if ($field instanceof $field_class_name) {
5006
+				return $field;
5007
+			}
5008
+		}
5009
+		return null;
5010
+	}
5011
+
5012
+
5013
+
5014
+	/**
5015
+	 * Gets a foreign key field pointing to model.
5016
+	 *
5017
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5018
+	 * @return EE_Foreign_Key_Field_Base
5019
+	 * @throws EE_Error
5020
+	 */
5021
+	public function get_foreign_key_to($model_name)
5022
+	{
5023
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5024
+			foreach ($this->field_settings() as $field) {
5025
+				if (
5026
+					$field instanceof EE_Foreign_Key_Field_Base
5027
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5028
+				) {
5029
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5030
+					break;
5031
+				}
5032
+			}
5033
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5034
+				throw new EE_Error(sprintf(esc_html__(
5035
+					"There is no foreign key field pointing to model %s on model %s",
5036
+					'event_espresso'
5037
+				), $model_name, get_class($this)));
5038
+			}
5039
+		}
5040
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5041
+	}
5042
+
5043
+
5044
+
5045
+	/**
5046
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5047
+	 *
5048
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5049
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5050
+	 *                            Either one works
5051
+	 * @return string
5052
+	 */
5053
+	public function get_table_for_alias($table_alias)
5054
+	{
5055
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5056
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5057
+	}
5058
+
5059
+
5060
+
5061
+	/**
5062
+	 * Returns a flat array of all field son this model, instead of organizing them
5063
+	 * by table_alias as they are in the constructor.
5064
+	 *
5065
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5066
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5067
+	 */
5068
+	public function field_settings($include_db_only_fields = false)
5069
+	{
5070
+		if ($include_db_only_fields) {
5071
+			if ($this->_cached_fields === null) {
5072
+				$this->_cached_fields = array();
5073
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5074
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5075
+						$this->_cached_fields[ $field_name ] = $field_obj;
5076
+					}
5077
+				}
5078
+			}
5079
+			return $this->_cached_fields;
5080
+		}
5081
+		if ($this->_cached_fields_non_db_only === null) {
5082
+			$this->_cached_fields_non_db_only = array();
5083
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5084
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5085
+					/** @var $field_obj EE_Model_Field_Base */
5086
+					if (! $field_obj->is_db_only_field()) {
5087
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5088
+					}
5089
+				}
5090
+			}
5091
+		}
5092
+		return $this->_cached_fields_non_db_only;
5093
+	}
5094
+
5095
+
5096
+
5097
+	/**
5098
+	 *        cycle though array of attendees and create objects out of each item
5099
+	 *
5100
+	 * @access        private
5101
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5102
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5103
+	 *                           numerically indexed)
5104
+	 * @throws EE_Error
5105
+	 */
5106
+	protected function _create_objects($rows = array())
5107
+	{
5108
+		$array_of_objects = array();
5109
+		if (empty($rows)) {
5110
+			return array();
5111
+		}
5112
+		$count_if_model_has_no_primary_key = 0;
5113
+		$has_primary_key = $this->has_primary_key_field();
5114
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5115
+		foreach ((array) $rows as $row) {
5116
+			if (empty($row)) {
5117
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5118
+				return array();
5119
+			}
5120
+			// check if we've already set this object in the results array,
5121
+			// in which case there's no need to process it further (again)
5122
+			if ($has_primary_key) {
5123
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5124
+					$row,
5125
+					$primary_key_field->get_qualified_column(),
5126
+					$primary_key_field->get_table_column()
5127
+				);
5128
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5129
+					continue;
5130
+				}
5131
+			}
5132
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5133
+			if (! $classInstance) {
5134
+				throw new EE_Error(
5135
+					sprintf(
5136
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5137
+						$this->get_this_model_name(),
5138
+						http_build_query($row)
5139
+					)
5140
+				);
5141
+			}
5142
+			// set the timezone on the instantiated objects
5143
+			$classInstance->set_timezone($this->_timezone);
5144
+			// make sure if there is any timezone setting present that we set the timezone for the object
5145
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5146
+			$array_of_objects[ $key ] = $classInstance;
5147
+			// also, for all the relations of type BelongsTo, see if we can cache
5148
+			// those related models
5149
+			// (we could do this for other relations too, but if there are conditions
5150
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5151
+			// so it requires a little more thought than just caching them immediately...)
5152
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5153
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5154
+					// check if this model's INFO is present. If so, cache it on the model
5155
+					$other_model = $relation_obj->get_other_model();
5156
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5157
+					// if we managed to make a model object from the results, cache it on the main model object
5158
+					if ($other_model_obj_maybe) {
5159
+						// set timezone on these other model objects if they are present
5160
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5161
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5162
+					}
5163
+				}
5164
+			}
5165
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5166
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5167
+			// the field in the CustomSelects object
5168
+			if ($this->_custom_selections instanceof CustomSelects) {
5169
+				$classInstance->setCustomSelectsValues(
5170
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5171
+				);
5172
+			}
5173
+		}
5174
+		return $array_of_objects;
5175
+	}
5176
+
5177
+
5178
+	/**
5179
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5180
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5181
+	 *
5182
+	 * @param array $db_results_row
5183
+	 * @return array
5184
+	 */
5185
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5186
+	{
5187
+		$results = array();
5188
+		if ($this->_custom_selections instanceof CustomSelects) {
5189
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5190
+				if (isset($db_results_row[ $alias ])) {
5191
+					$results[ $alias ] = $this->convertValueToDataType(
5192
+						$db_results_row[ $alias ],
5193
+						$this->_custom_selections->getDataTypeForAlias($alias)
5194
+					);
5195
+				}
5196
+			}
5197
+		}
5198
+		return $results;
5199
+	}
5200
+
5201
+
5202
+	/**
5203
+	 * This will set the value for the given alias
5204
+	 * @param string $value
5205
+	 * @param string $datatype (one of %d, %s, %f)
5206
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5207
+	 */
5208
+	protected function convertValueToDataType($value, $datatype)
5209
+	{
5210
+		switch ($datatype) {
5211
+			case '%f':
5212
+				return (float) $value;
5213
+			case '%d':
5214
+				return (int) $value;
5215
+			default:
5216
+				return (string) $value;
5217
+		}
5218
+	}
5219
+
5220
+
5221
+	/**
5222
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5223
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5224
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5225
+	 * object (as set in the model_field!).
5226
+	 *
5227
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5228
+	 */
5229
+	public function create_default_object()
5230
+	{
5231
+		$this_model_fields_and_values = array();
5232
+		// setup the row using default values;
5233
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5234
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5235
+		}
5236
+		$className = $this->_get_class_name();
5237
+		$classInstance = EE_Registry::instance()
5238
+									->load_class($className, array($this_model_fields_and_values), false, false);
5239
+		return $classInstance;
5240
+	}
5241
+
5242
+
5243
+
5244
+	/**
5245
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5246
+	 *                             or an stdClass where each property is the name of a column,
5247
+	 * @return EE_Base_Class
5248
+	 * @throws EE_Error
5249
+	 */
5250
+	public function instantiate_class_from_array_or_object($cols_n_values)
5251
+	{
5252
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5253
+			$cols_n_values = get_object_vars($cols_n_values);
5254
+		}
5255
+		$primary_key = null;
5256
+		// make sure the array only has keys that are fields/columns on this model
5257
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5258
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5259
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5260
+		}
5261
+		$className = $this->_get_class_name();
5262
+		// check we actually found results that we can use to build our model object
5263
+		// if not, return null
5264
+		if ($this->has_primary_key_field()) {
5265
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5266
+				return null;
5267
+			}
5268
+		} elseif ($this->unique_indexes()) {
5269
+			$first_column = reset($this_model_fields_n_values);
5270
+			if (empty($first_column)) {
5271
+				return null;
5272
+			}
5273
+		}
5274
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5275
+		if ($primary_key) {
5276
+			$classInstance = $this->get_from_entity_map($primary_key);
5277
+			if (! $classInstance) {
5278
+				$classInstance = EE_Registry::instance()
5279
+											->load_class(
5280
+												$className,
5281
+												array($this_model_fields_n_values, $this->_timezone),
5282
+												true,
5283
+												false
5284
+											);
5285
+				// add this new object to the entity map
5286
+				$classInstance = $this->add_to_entity_map($classInstance);
5287
+			}
5288
+		} else {
5289
+			$classInstance = EE_Registry::instance()
5290
+										->load_class(
5291
+											$className,
5292
+											array($this_model_fields_n_values, $this->_timezone),
5293
+											true,
5294
+											false
5295
+										);
5296
+		}
5297
+		return $classInstance;
5298
+	}
5299
+
5300
+
5301
+
5302
+	/**
5303
+	 * Gets the model object from the  entity map if it exists
5304
+	 *
5305
+	 * @param int|string $id the ID of the model object
5306
+	 * @return EE_Base_Class
5307
+	 */
5308
+	public function get_from_entity_map($id)
5309
+	{
5310
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5311
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5312
+	}
5313
+
5314
+
5315
+
5316
+	/**
5317
+	 * add_to_entity_map
5318
+	 * Adds the object to the model's entity mappings
5319
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5320
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5321
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5322
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5323
+	 *        then this method should be called immediately after the update query
5324
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5325
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5326
+	 *
5327
+	 * @param    EE_Base_Class $object
5328
+	 * @throws EE_Error
5329
+	 * @return \EE_Base_Class
5330
+	 */
5331
+	public function add_to_entity_map(EE_Base_Class $object)
5332
+	{
5333
+		$className = $this->_get_class_name();
5334
+		if (! $object instanceof $className) {
5335
+			throw new EE_Error(sprintf(
5336
+				esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5337
+				is_object($object) ? get_class($object) : $object,
5338
+				$className
5339
+			));
5340
+		}
5341
+		/** @var $object EE_Base_Class */
5342
+		if (! $object->ID()) {
5343
+			throw new EE_Error(sprintf(esc_html__(
5344
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5345
+				"event_espresso"
5346
+			), get_class($this)));
5347
+		}
5348
+		// double check it's not already there
5349
+		$classInstance = $this->get_from_entity_map($object->ID());
5350
+		if ($classInstance) {
5351
+			return $classInstance;
5352
+		}
5353
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5354
+		return $object;
5355
+	}
5356
+
5357
+
5358
+
5359
+	/**
5360
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5361
+	 * if no identifier is provided, then the entire entity map is emptied
5362
+	 *
5363
+	 * @param int|string $id the ID of the model object
5364
+	 * @return boolean
5365
+	 */
5366
+	public function clear_entity_map($id = null)
5367
+	{
5368
+		if (empty($id)) {
5369
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5370
+			return true;
5371
+		}
5372
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5373
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5374
+			return true;
5375
+		}
5376
+		return false;
5377
+	}
5378
+
5379
+
5380
+
5381
+	/**
5382
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5383
+	 * Given an array where keys are column (or column alias) names and values,
5384
+	 * returns an array of their corresponding field names and database values
5385
+	 *
5386
+	 * @param array $cols_n_values
5387
+	 * @return array
5388
+	 */
5389
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5390
+	{
5391
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5392
+	}
5393
+
5394
+
5395
+
5396
+	/**
5397
+	 * _deduce_fields_n_values_from_cols_n_values
5398
+	 * Given an array where keys are column (or column alias) names and values,
5399
+	 * returns an array of their corresponding field names and database values
5400
+	 *
5401
+	 * @param string $cols_n_values
5402
+	 * @return array
5403
+	 */
5404
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5405
+	{
5406
+		$this_model_fields_n_values = array();
5407
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5408
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5409
+				$cols_n_values,
5410
+				$table_obj->get_fully_qualified_pk_column(),
5411
+				$table_obj->get_pk_column()
5412
+			);
5413
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5414
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5415
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5416
+					if (! $field_obj->is_db_only_field()) {
5417
+						// prepare field as if its coming from db
5418
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5419
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5420
+					}
5421
+				}
5422
+			} else {
5423
+				// the table's rows existed. Use their values
5424
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5425
+					if (! $field_obj->is_db_only_field()) {
5426
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5427
+							$cols_n_values,
5428
+							$field_obj->get_qualified_column(),
5429
+							$field_obj->get_table_column()
5430
+						);
5431
+					}
5432
+				}
5433
+			}
5434
+		}
5435
+		return $this_model_fields_n_values;
5436
+	}
5437
+
5438
+
5439
+	/**
5440
+	 * @param $cols_n_values
5441
+	 * @param $qualified_column
5442
+	 * @param $regular_column
5443
+	 * @return null
5444
+	 * @throws EE_Error
5445
+	 * @throws ReflectionException
5446
+	 */
5447
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5448
+	{
5449
+		$value = null;
5450
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5451
+		// does the field on the model relate to this column retrieved from the db?
5452
+		// or is it a db-only field? (not relating to the model)
5453
+		if (isset($cols_n_values[ $qualified_column ])) {
5454
+			$value = $cols_n_values[ $qualified_column ];
5455
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5456
+			$value = $cols_n_values[ $regular_column ];
5457
+		} elseif (! empty($this->foreign_key_aliases)) {
5458
+			// no PK?  ok check if there is a foreign key alias set for this table
5459
+			// then check if that alias exists in the incoming data
5460
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5461
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5462
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5463
+					$value = $cols_n_values[ $FK_alias ];
5464
+					list($pk_class) = explode('.', $PK_column);
5465
+					$pk_model_name = "EEM_{$pk_class}";
5466
+					/** @var EEM_Base $pk_model */
5467
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5468
+					if ($pk_model instanceof EEM_Base) {
5469
+						// make sure object is pulled from db and added to entity map
5470
+						$pk_model->get_one_by_ID($value);
5471
+					}
5472
+					break;
5473
+				}
5474
+			}
5475
+		}
5476
+		return $value;
5477
+	}
5478
+
5479
+
5480
+
5481
+	/**
5482
+	 * refresh_entity_map_from_db
5483
+	 * Makes sure the model object in the entity map at $id assumes the values
5484
+	 * of the database (opposite of EE_base_Class::save())
5485
+	 *
5486
+	 * @param int|string $id
5487
+	 * @return EE_Base_Class
5488
+	 * @throws EE_Error
5489
+	 */
5490
+	public function refresh_entity_map_from_db($id)
5491
+	{
5492
+		$obj_in_map = $this->get_from_entity_map($id);
5493
+		if ($obj_in_map) {
5494
+			$wpdb_results = $this->_get_all_wpdb_results(
5495
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5496
+			);
5497
+			if ($wpdb_results && is_array($wpdb_results)) {
5498
+				$one_row = reset($wpdb_results);
5499
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5500
+					$obj_in_map->set_from_db($field_name, $db_value);
5501
+				}
5502
+				// clear the cache of related model objects
5503
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5504
+					$obj_in_map->clear_cache($relation_name, null, true);
5505
+				}
5506
+			}
5507
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5508
+			return $obj_in_map;
5509
+		}
5510
+		return $this->get_one_by_ID($id);
5511
+	}
5512
+
5513
+
5514
+
5515
+	/**
5516
+	 * refresh_entity_map_with
5517
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5518
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5519
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5520
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5521
+	 *
5522
+	 * @param int|string    $id
5523
+	 * @param EE_Base_Class $replacing_model_obj
5524
+	 * @return \EE_Base_Class
5525
+	 * @throws EE_Error
5526
+	 */
5527
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5528
+	{
5529
+		$obj_in_map = $this->get_from_entity_map($id);
5530
+		if ($obj_in_map) {
5531
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5532
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5533
+					$obj_in_map->set($field_name, $value);
5534
+				}
5535
+				// make the model object in the entity map's cache match the $replacing_model_obj
5536
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5537
+					$obj_in_map->clear_cache($relation_name, null, true);
5538
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5539
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5540
+					}
5541
+				}
5542
+			}
5543
+			return $obj_in_map;
5544
+		}
5545
+		$this->add_to_entity_map($replacing_model_obj);
5546
+		return $replacing_model_obj;
5547
+	}
5548
+
5549
+
5550
+
5551
+	/**
5552
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5553
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5554
+	 * require_once($this->_getClassName().".class.php");
5555
+	 *
5556
+	 * @return string
5557
+	 */
5558
+	private function _get_class_name()
5559
+	{
5560
+		return "EE_" . $this->get_this_model_name();
5561
+	}
5562
+
5563
+
5564
+
5565
+	/**
5566
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5567
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5568
+	 * it would be 'Events'.
5569
+	 *
5570
+	 * @param int $quantity
5571
+	 * @return string
5572
+	 */
5573
+	public function item_name($quantity = 1)
5574
+	{
5575
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5576
+	}
5577
+
5578
+
5579
+
5580
+	/**
5581
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5582
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5583
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5584
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5585
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5586
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5587
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5588
+	 * returns will be returned by this function.
5589
+	 *
5590
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5591
+	 * @param array  $args       array of original arguments passed to the function
5592
+	 * @throws EE_Error
5593
+	 * @return mixed whatever the plugin which calls add_filter decides
5594
+	 */
5595
+	public function __call($methodName, $args)
5596
+	{
5597
+		$className = get_class($this);
5598
+		$tagName = "FHEE__{$className}__{$methodName}";
5599
+		if (! has_filter($tagName)) {
5600
+			throw new EE_Error(
5601
+				sprintf(
5602
+					esc_html__(
5603
+						'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 );',
5604
+						'event_espresso'
5605
+					),
5606
+					$methodName,
5607
+					$className,
5608
+					$tagName,
5609
+					'<br />'
5610
+				)
5611
+			);
5612
+		}
5613
+		return apply_filters($tagName, null, $this, $args);
5614
+	}
5615
+
5616
+
5617
+
5618
+	/**
5619
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5620
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5621
+	 *
5622
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5623
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5624
+	 *                                                       the object's class name
5625
+	 *                                                       or object's ID
5626
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5627
+	 *                                                       exists in the database. If it does not, we add it
5628
+	 * @throws EE_Error
5629
+	 * @return EE_Base_Class
5630
+	 */
5631
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5632
+	{
5633
+		$className = $this->_get_class_name();
5634
+		if ($base_class_obj_or_id instanceof $className) {
5635
+			$model_object = $base_class_obj_or_id;
5636
+		} else {
5637
+			$primary_key_field = $this->get_primary_key_field();
5638
+			if (
5639
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5640
+				&& (
5641
+					is_int($base_class_obj_or_id)
5642
+					|| is_string($base_class_obj_or_id)
5643
+				)
5644
+			) {
5645
+				// assume it's an ID.
5646
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5647
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5648
+			} elseif (
5649
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5650
+				&& is_string($base_class_obj_or_id)
5651
+			) {
5652
+				// assume its a string representation of the object
5653
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5654
+			} else {
5655
+				throw new EE_Error(
5656
+					sprintf(
5657
+						esc_html__(
5658
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5659
+							'event_espresso'
5660
+						),
5661
+						$base_class_obj_or_id,
5662
+						$this->_get_class_name(),
5663
+						print_r($base_class_obj_or_id, true)
5664
+					)
5665
+				);
5666
+			}
5667
+		}
5668
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5669
+			$model_object->save();
5670
+		}
5671
+		return $model_object;
5672
+	}
5673
+
5674
+
5675
+
5676
+	/**
5677
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5678
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5679
+	 * returns it ID.
5680
+	 *
5681
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5682
+	 * @return int|string depending on the type of this model object's ID
5683
+	 * @throws EE_Error
5684
+	 */
5685
+	public function ensure_is_ID($base_class_obj_or_id)
5686
+	{
5687
+		$className = $this->_get_class_name();
5688
+		if ($base_class_obj_or_id instanceof $className) {
5689
+			/** @var $base_class_obj_or_id EE_Base_Class */
5690
+			$id = $base_class_obj_or_id->ID();
5691
+		} elseif (is_int($base_class_obj_or_id)) {
5692
+			// assume it's an ID
5693
+			$id = $base_class_obj_or_id;
5694
+		} elseif (is_string($base_class_obj_or_id)) {
5695
+			// assume its a string representation of the object
5696
+			$id = $base_class_obj_or_id;
5697
+		} else {
5698
+			throw new EE_Error(sprintf(
5699
+				esc_html__(
5700
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5701
+					'event_espresso'
5702
+				),
5703
+				$base_class_obj_or_id,
5704
+				$this->_get_class_name(),
5705
+				print_r($base_class_obj_or_id, true)
5706
+			));
5707
+		}
5708
+		return $id;
5709
+	}
5710
+
5711
+
5712
+
5713
+	/**
5714
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5715
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5716
+	 * been sanitized and converted into the appropriate domain.
5717
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5718
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5719
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5720
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5721
+	 * $EVT = EEM_Event::instance(); $old_setting =
5722
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5723
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5724
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5725
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5726
+	 *
5727
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5728
+	 * @return void
5729
+	 */
5730
+	public function assume_values_already_prepared_by_model_object(
5731
+		$values_already_prepared = self::not_prepared_by_model_object
5732
+	) {
5733
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5734
+	}
5735
+
5736
+
5737
+
5738
+	/**
5739
+	 * Read comments for assume_values_already_prepared_by_model_object()
5740
+	 *
5741
+	 * @return int
5742
+	 */
5743
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5744
+	{
5745
+		return $this->_values_already_prepared_by_model_object;
5746
+	}
5747
+
5748
+
5749
+
5750
+	/**
5751
+	 * Gets all the indexes on this model
5752
+	 *
5753
+	 * @return EE_Index[]
5754
+	 */
5755
+	public function indexes()
5756
+	{
5757
+		return $this->_indexes;
5758
+	}
5759
+
5760
+
5761
+
5762
+	/**
5763
+	 * Gets all the Unique Indexes on this model
5764
+	 *
5765
+	 * @return EE_Unique_Index[]
5766
+	 */
5767
+	public function unique_indexes()
5768
+	{
5769
+		$unique_indexes = array();
5770
+		foreach ($this->_indexes as $name => $index) {
5771
+			if ($index instanceof EE_Unique_Index) {
5772
+				$unique_indexes [ $name ] = $index;
5773
+			}
5774
+		}
5775
+		return $unique_indexes;
5776
+	}
5777
+
5778
+
5779
+
5780
+	/**
5781
+	 * Gets all the fields which, when combined, make the primary key.
5782
+	 * This is usually just an array with 1 element (the primary key), but in cases
5783
+	 * where there is no primary key, it's a combination of fields as defined
5784
+	 * on a primary index
5785
+	 *
5786
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5787
+	 * @throws EE_Error
5788
+	 */
5789
+	public function get_combined_primary_key_fields()
5790
+	{
5791
+		foreach ($this->indexes() as $index) {
5792
+			if ($index instanceof EE_Primary_Key_Index) {
5793
+				return $index->fields();
5794
+			}
5795
+		}
5796
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5797
+	}
5798
+
5799
+
5800
+
5801
+	/**
5802
+	 * Used to build a primary key string (when the model has no primary key),
5803
+	 * which can be used a unique string to identify this model object.
5804
+	 *
5805
+	 * @param array $fields_n_values keys are field names, values are their values.
5806
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5807
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5808
+	 *                               before passing it to this function (that will convert it from columns-n-values
5809
+	 *                               to field-names-n-values).
5810
+	 * @return string
5811
+	 * @throws EE_Error
5812
+	 */
5813
+	public function get_index_primary_key_string($fields_n_values)
5814
+	{
5815
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5816
+			$fields_n_values,
5817
+			$this->get_combined_primary_key_fields()
5818
+		);
5819
+		return http_build_query($cols_n_values_for_primary_key_index);
5820
+	}
5821
+
5822
+
5823
+
5824
+	/**
5825
+	 * Gets the field values from the primary key string
5826
+	 *
5827
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5828
+	 * @param string $index_primary_key_string
5829
+	 * @return null|array
5830
+	 * @throws EE_Error
5831
+	 */
5832
+	public function parse_index_primary_key_string($index_primary_key_string)
5833
+	{
5834
+		$key_fields = $this->get_combined_primary_key_fields();
5835
+		// check all of them are in the $id
5836
+		$key_vals_in_combined_pk = array();
5837
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5838
+		foreach ($key_fields as $key_field_name => $field_obj) {
5839
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5840
+				return null;
5841
+			}
5842
+		}
5843
+		return $key_vals_in_combined_pk;
5844
+	}
5845
+
5846
+
5847
+
5848
+	/**
5849
+	 * verifies that an array of key-value pairs for model fields has a key
5850
+	 * for each field comprising the primary key index
5851
+	 *
5852
+	 * @param array $key_vals
5853
+	 * @return boolean
5854
+	 * @throws EE_Error
5855
+	 */
5856
+	public function has_all_combined_primary_key_fields($key_vals)
5857
+	{
5858
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5859
+		foreach ($keys_it_should_have as $key) {
5860
+			if (! isset($key_vals[ $key ])) {
5861
+				return false;
5862
+			}
5863
+		}
5864
+		return true;
5865
+	}
5866
+
5867
+
5868
+
5869
+	/**
5870
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5871
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5872
+	 *
5873
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5874
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5875
+	 * @throws EE_Error
5876
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5877
+	 *                                                              indexed)
5878
+	 */
5879
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5880
+	{
5881
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5882
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5883
+		} elseif (is_array($model_object_or_attributes_array)) {
5884
+			$attributes_array = $model_object_or_attributes_array;
5885
+		} else {
5886
+			throw new EE_Error(sprintf(esc_html__(
5887
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5888
+				"event_espresso"
5889
+			), $model_object_or_attributes_array));
5890
+		}
5891
+		// even copies obviously won't have the same ID, so remove the primary key
5892
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5893
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5894
+			unset($attributes_array[ $this->primary_key_name() ]);
5895
+		}
5896
+		if (isset($query_params[0])) {
5897
+			$query_params[0] = array_merge($attributes_array, $query_params);
5898
+		} else {
5899
+			$query_params[0] = $attributes_array;
5900
+		}
5901
+		return $this->get_all($query_params);
5902
+	}
5903
+
5904
+
5905
+
5906
+	/**
5907
+	 * Gets the first copy we find. See get_all_copies for more details
5908
+	 *
5909
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5910
+	 * @param array $query_params
5911
+	 * @return EE_Base_Class
5912
+	 * @throws EE_Error
5913
+	 */
5914
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5915
+	{
5916
+		if (! is_array($query_params)) {
5917
+			EE_Error::doing_it_wrong(
5918
+				'EEM_Base::get_one_copy',
5919
+				sprintf(
5920
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5921
+					gettype($query_params)
5922
+				),
5923
+				'4.6.0'
5924
+			);
5925
+			$query_params = array();
5926
+		}
5927
+		$query_params['limit'] = 1;
5928
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5929
+		if (is_array($copies)) {
5930
+			return array_shift($copies);
5931
+		}
5932
+		return null;
5933
+	}
5934
+
5935
+
5936
+
5937
+	/**
5938
+	 * Updates the item with the specified id. Ignores default query parameters because
5939
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5940
+	 *
5941
+	 * @param array      $fields_n_values keys are field names, values are their new values
5942
+	 * @param int|string $id              the value of the primary key to update
5943
+	 * @return int number of rows updated
5944
+	 * @throws EE_Error
5945
+	 */
5946
+	public function update_by_ID($fields_n_values, $id)
5947
+	{
5948
+		$query_params = array(
5949
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5950
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5951
+		);
5952
+		return $this->update($fields_n_values, $query_params);
5953
+	}
5954
+
5955
+
5956
+
5957
+	/**
5958
+	 * Changes an operator which was supplied to the models into one usable in SQL
5959
+	 *
5960
+	 * @param string $operator_supplied
5961
+	 * @return string an operator which can be used in SQL
5962
+	 * @throws EE_Error
5963
+	 */
5964
+	private function _prepare_operator_for_sql($operator_supplied)
5965
+	{
5966
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5967
+			: null;
5968
+		if ($sql_operator) {
5969
+			return $sql_operator;
5970
+		}
5971
+		throw new EE_Error(
5972
+			sprintf(
5973
+				esc_html__(
5974
+					"The operator '%s' is not in the list of valid operators: %s",
5975
+					"event_espresso"
5976
+				),
5977
+				$operator_supplied,
5978
+				implode(",", array_keys($this->_valid_operators))
5979
+			)
5980
+		);
5981
+	}
5982
+
5983
+
5984
+
5985
+	/**
5986
+	 * Gets the valid operators
5987
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5988
+	 */
5989
+	public function valid_operators()
5990
+	{
5991
+		return $this->_valid_operators;
5992
+	}
5993
+
5994
+
5995
+
5996
+	/**
5997
+	 * Gets the between-style operators (take 2 arguments).
5998
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5999
+	 */
6000
+	public function valid_between_style_operators()
6001
+	{
6002
+		return array_intersect(
6003
+			$this->valid_operators(),
6004
+			$this->_between_style_operators
6005
+		);
6006
+	}
6007
+
6008
+	/**
6009
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6010
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6011
+	 */
6012
+	public function valid_like_style_operators()
6013
+	{
6014
+		return array_intersect(
6015
+			$this->valid_operators(),
6016
+			$this->_like_style_operators
6017
+		);
6018
+	}
6019
+
6020
+	/**
6021
+	 * Gets the "in"-style operators
6022
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6023
+	 */
6024
+	public function valid_in_style_operators()
6025
+	{
6026
+		return array_intersect(
6027
+			$this->valid_operators(),
6028
+			$this->_in_style_operators
6029
+		);
6030
+	}
6031
+
6032
+	/**
6033
+	 * Gets the "null"-style operators (accept no arguments)
6034
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6035
+	 */
6036
+	public function valid_null_style_operators()
6037
+	{
6038
+		return array_intersect(
6039
+			$this->valid_operators(),
6040
+			$this->_null_style_operators
6041
+		);
6042
+	}
6043
+
6044
+	/**
6045
+	 * Gets an array where keys are the primary keys and values are their 'names'
6046
+	 * (as determined by the model object's name() function, which is often overridden)
6047
+	 *
6048
+	 * @param array $query_params like get_all's
6049
+	 * @return string[]
6050
+	 * @throws EE_Error
6051
+	 */
6052
+	public function get_all_names($query_params = array())
6053
+	{
6054
+		$objs = $this->get_all($query_params);
6055
+		$names = array();
6056
+		foreach ($objs as $obj) {
6057
+			$names[ $obj->ID() ] = $obj->name();
6058
+		}
6059
+		return $names;
6060
+	}
6061
+
6062
+
6063
+
6064
+	/**
6065
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6066
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6067
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6068
+	 * array_keys() on $model_objects.
6069
+	 *
6070
+	 * @param \EE_Base_Class[] $model_objects
6071
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6072
+	 *                                               in the returned array
6073
+	 * @return array
6074
+	 * @throws EE_Error
6075
+	 */
6076
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6077
+	{
6078
+		if (! $this->has_primary_key_field()) {
6079
+			if (WP_DEBUG) {
6080
+				EE_Error::add_error(
6081
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6082
+					__FILE__,
6083
+					__FUNCTION__,
6084
+					__LINE__
6085
+				);
6086
+			}
6087
+		}
6088
+		$IDs = array();
6089
+		foreach ($model_objects as $model_object) {
6090
+			$id = $model_object->ID();
6091
+			if (! $id) {
6092
+				if ($filter_out_empty_ids) {
6093
+					continue;
6094
+				}
6095
+				if (WP_DEBUG) {
6096
+					EE_Error::add_error(
6097
+						esc_html__(
6098
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6099
+							'event_espresso'
6100
+						),
6101
+						__FILE__,
6102
+						__FUNCTION__,
6103
+						__LINE__
6104
+					);
6105
+				}
6106
+			}
6107
+			$IDs[] = $id;
6108
+		}
6109
+		return $IDs;
6110
+	}
6111
+
6112
+
6113
+
6114
+	/**
6115
+	 * Returns the string used in capabilities relating to this model. If there
6116
+	 * are no capabilities that relate to this model returns false
6117
+	 *
6118
+	 * @return string|false
6119
+	 */
6120
+	public function cap_slug()
6121
+	{
6122
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6123
+	}
6124
+
6125
+
6126
+
6127
+	/**
6128
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6129
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6130
+	 * only returns the cap restrictions array in that context (ie, the array
6131
+	 * at that key)
6132
+	 *
6133
+	 * @param string $context
6134
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6135
+	 * @throws EE_Error
6136
+	 */
6137
+	public function cap_restrictions($context = EEM_Base::caps_read)
6138
+	{
6139
+		EEM_Base::verify_is_valid_cap_context($context);
6140
+		// check if we ought to run the restriction generator first
6141
+		if (
6142
+			isset($this->_cap_restriction_generators[ $context ])
6143
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6144
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6145
+		) {
6146
+			$this->_cap_restrictions[ $context ] = array_merge(
6147
+				$this->_cap_restrictions[ $context ],
6148
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6149
+			);
6150
+		}
6151
+		// and make sure we've finalized the construction of each restriction
6152
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6153
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6154
+				$where_conditions_obj->_finalize_construct($this);
6155
+			}
6156
+		}
6157
+		return $this->_cap_restrictions[ $context ];
6158
+	}
6159
+
6160
+
6161
+
6162
+	/**
6163
+	 * Indicating whether or not this model thinks its a wp core model
6164
+	 *
6165
+	 * @return boolean
6166
+	 */
6167
+	public function is_wp_core_model()
6168
+	{
6169
+		return $this->_wp_core_model;
6170
+	}
6171
+
6172
+
6173
+
6174
+	/**
6175
+	 * Gets all the caps that are missing which impose a restriction on
6176
+	 * queries made in this context
6177
+	 *
6178
+	 * @param string $context one of EEM_Base::caps_ constants
6179
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6180
+	 * @throws EE_Error
6181
+	 */
6182
+	public function caps_missing($context = EEM_Base::caps_read)
6183
+	{
6184
+		$missing_caps = array();
6185
+		$cap_restrictions = $this->cap_restrictions($context);
6186
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6187
+			if (
6188
+				! EE_Capabilities::instance()
6189
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6190
+			) {
6191
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6192
+			}
6193
+		}
6194
+		return $missing_caps;
6195
+	}
6196
+
6197
+
6198
+
6199
+	/**
6200
+	 * Gets the mapping from capability contexts to action strings used in capability names
6201
+	 *
6202
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6203
+	 * one of 'read', 'edit', or 'delete'
6204
+	 */
6205
+	public function cap_contexts_to_cap_action_map()
6206
+	{
6207
+		return apply_filters(
6208
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6209
+			$this->_cap_contexts_to_cap_action_map,
6210
+			$this
6211
+		);
6212
+	}
6213
+
6214
+
6215
+
6216
+	/**
6217
+	 * Gets the action string for the specified capability context
6218
+	 *
6219
+	 * @param string $context
6220
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6221
+	 * @throws EE_Error
6222
+	 */
6223
+	public function cap_action_for_context($context)
6224
+	{
6225
+		$mapping = $this->cap_contexts_to_cap_action_map();
6226
+		if (isset($mapping[ $context ])) {
6227
+			return $mapping[ $context ];
6228
+		}
6229
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6230
+			return $action;
6231
+		}
6232
+		throw new EE_Error(
6233
+			sprintf(
6234
+				esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6235
+				$context,
6236
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6237
+			)
6238
+		);
6239
+	}
6240
+
6241
+
6242
+
6243
+	/**
6244
+	 * Returns all the capability contexts which are valid when querying models
6245
+	 *
6246
+	 * @return array
6247
+	 */
6248
+	public static function valid_cap_contexts()
6249
+	{
6250
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6251
+			self::caps_read,
6252
+			self::caps_read_admin,
6253
+			self::caps_edit,
6254
+			self::caps_delete,
6255
+		));
6256
+	}
6257
+
6258
+
6259
+
6260
+	/**
6261
+	 * Returns all valid options for 'default_where_conditions'
6262
+	 *
6263
+	 * @return array
6264
+	 */
6265
+	public static function valid_default_where_conditions()
6266
+	{
6267
+		return array(
6268
+			EEM_Base::default_where_conditions_all,
6269
+			EEM_Base::default_where_conditions_this_only,
6270
+			EEM_Base::default_where_conditions_others_only,
6271
+			EEM_Base::default_where_conditions_minimum_all,
6272
+			EEM_Base::default_where_conditions_minimum_others,
6273
+			EEM_Base::default_where_conditions_none
6274
+		);
6275
+	}
6276
+
6277
+	// public static function default_where_conditions_full
6278
+	/**
6279
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6280
+	 *
6281
+	 * @param string $context
6282
+	 * @return bool
6283
+	 * @throws EE_Error
6284
+	 */
6285
+	public static function verify_is_valid_cap_context($context)
6286
+	{
6287
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6288
+		if (in_array($context, $valid_cap_contexts)) {
6289
+			return true;
6290
+		}
6291
+		throw new EE_Error(
6292
+			sprintf(
6293
+				esc_html__(
6294
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6295
+					'event_espresso'
6296
+				),
6297
+				$context,
6298
+				'EEM_Base',
6299
+				implode(',', $valid_cap_contexts)
6300
+			)
6301
+		);
6302
+	}
6303
+
6304
+
6305
+
6306
+	/**
6307
+	 * Clears all the models field caches. This is only useful when a sub-class
6308
+	 * might have added a field or something and these caches might be invalidated
6309
+	 */
6310
+	protected function _invalidate_field_caches()
6311
+	{
6312
+		$this->_cache_foreign_key_to_fields = array();
6313
+		$this->_cached_fields = null;
6314
+		$this->_cached_fields_non_db_only = null;
6315
+	}
6316
+
6317
+
6318
+
6319
+	/**
6320
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6321
+	 * (eg "and", "or", "not").
6322
+	 *
6323
+	 * @return array
6324
+	 */
6325
+	public function logic_query_param_keys()
6326
+	{
6327
+		return $this->_logic_query_param_keys;
6328
+	}
6329
+
6330
+
6331
+
6332
+	/**
6333
+	 * Determines whether or not the where query param array key is for a logic query param.
6334
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6335
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6336
+	 *
6337
+	 * @param $query_param_key
6338
+	 * @return bool
6339
+	 */
6340
+	public function is_logic_query_param_key($query_param_key)
6341
+	{
6342
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6343
+			if (
6344
+				$query_param_key === $logic_query_param_key
6345
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6346
+			) {
6347
+				return true;
6348
+			}
6349
+		}
6350
+		return false;
6351
+	}
6352
+
6353
+	/**
6354
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6355
+	 * @since 4.9.74.p
6356
+	 * @return boolean
6357
+	 */
6358
+	public function hasPassword()
6359
+	{
6360
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6361
+		if ($this->has_password_field === null) {
6362
+			$password_field = $this->getPasswordField();
6363
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6364
+		}
6365
+		return $this->has_password_field;
6366
+	}
6367
+
6368
+	/**
6369
+	 * Returns the password field on this model, if there is one
6370
+	 * @since 4.9.74.p
6371
+	 * @return EE_Password_Field|null
6372
+	 */
6373
+	public function getPasswordField()
6374
+	{
6375
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6376
+		// there's no need to search for it. If we don't know yet, then find out
6377
+		if ($this->has_password_field === null && $this->password_field === null) {
6378
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6379
+		}
6380
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6381
+		return $this->password_field;
6382
+	}
6383
+
6384
+
6385
+	/**
6386
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6387
+	 * @since 4.9.74.p
6388
+	 * @return EE_Model_Field_Base[]
6389
+	 * @throws EE_Error
6390
+	 */
6391
+	public function getPasswordProtectedFields()
6392
+	{
6393
+		$password_field = $this->getPasswordField();
6394
+		$fields = array();
6395
+		if ($password_field instanceof EE_Password_Field) {
6396
+			$field_names = $password_field->protectedFields();
6397
+			foreach ($field_names as $field_name) {
6398
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6399
+			}
6400
+		}
6401
+		return $fields;
6402
+	}
6403
+
6404
+
6405
+	/**
6406
+	 * Checks if the current user can perform the requested action on this model
6407
+	 * @since 4.9.74.p
6408
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6409
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6410
+	 * @return bool
6411
+	 * @throws EE_Error
6412
+	 * @throws InvalidArgumentException
6413
+	 * @throws InvalidDataTypeException
6414
+	 * @throws InvalidInterfaceException
6415
+	 * @throws ReflectionException
6416
+	 * @throws UnexpectedEntityException
6417
+	 */
6418
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6419
+	{
6420
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6421
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6422
+		}
6423
+		if (!is_array($model_obj_or_fields_n_values)) {
6424
+			throw new UnexpectedEntityException(
6425
+				$model_obj_or_fields_n_values,
6426
+				'EE_Base_Class',
6427
+				sprintf(
6428
+					esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6429
+					__FUNCTION__
6430
+				)
6431
+			);
6432
+		}
6433
+		return $this->exists(
6434
+			$this->alter_query_params_to_restrict_by_ID(
6435
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6436
+				array(
6437
+					'default_where_conditions' => 'none',
6438
+					'caps'                     => $cap_to_check,
6439
+				)
6440
+			)
6441
+		);
6442
+	}
6443
+
6444
+	/**
6445
+	 * Returns the query param where conditions key to the password affecting this model.
6446
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6447
+	 * @since 4.9.74.p
6448
+	 * @return null|string
6449
+	 * @throws EE_Error
6450
+	 * @throws InvalidArgumentException
6451
+	 * @throws InvalidDataTypeException
6452
+	 * @throws InvalidInterfaceException
6453
+	 * @throws ModelConfigurationException
6454
+	 * @throws ReflectionException
6455
+	 */
6456
+	public function modelChainAndPassword()
6457
+	{
6458
+		if ($this->model_chain_to_password === null) {
6459
+			throw new ModelConfigurationException(
6460
+				$this,
6461
+				esc_html_x(
6462
+				// @codingStandardsIgnoreStart
6463
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6464
+					// @codingStandardsIgnoreEnd
6465
+					'1: model name',
6466
+					'event_espresso'
6467
+				)
6468
+			);
6469
+		}
6470
+		if ($this->model_chain_to_password === '') {
6471
+			$model_with_password = $this;
6472
+		} else {
6473
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6474
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6475
+			} else {
6476
+				$last_model_in_chain = $this->model_chain_to_password;
6477
+			}
6478
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6479
+		}
6480
+
6481
+		$password_field = $model_with_password->getPasswordField();
6482
+		if ($password_field instanceof EE_Password_Field) {
6483
+			$password_field_name = $password_field->get_name();
6484
+		} else {
6485
+			throw new ModelConfigurationException(
6486
+				$this,
6487
+				sprintf(
6488
+					esc_html_x(
6489
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6490
+						'1: model name, 2: special string',
6491
+						'event_espresso'
6492
+					),
6493
+					$model_with_password->get_this_model_name(),
6494
+					$this->model_chain_to_password
6495
+				)
6496
+			);
6497
+		}
6498
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6499
+	}
6500
+
6501
+	/**
6502
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6503
+	 * or if this model itself has a password affecting access to some of its other fields.
6504
+	 * @since 4.9.74.p
6505
+	 * @return boolean
6506
+	 */
6507
+	public function restrictedByRelatedModelPassword()
6508
+	{
6509
+		return $this->model_chain_to_password !== null;
6510
+	}
6511 6511
 }
Please login to merge, or discard this patch.
core/entities/models/JsonModelSchema.php 1 patch
Indentation   +231 added lines, -231 removed lines patch added patch discarded remove patch
@@ -25,252 +25,252 @@
 block discarded – undo
25 25
 class JsonModelSchema
26 26
 {
27 27
 
28
-    /**
29
-     * @var EEM_Base
30
-     */
31
-    protected $model;
28
+	/**
29
+	 * @var EEM_Base
30
+	 */
31
+	protected $model;
32 32
 
33
-    /**
34
-     * @var CalculatedModelFields
35
-     */
36
-    protected $fields_calculator;
33
+	/**
34
+	 * @var CalculatedModelFields
35
+	 */
36
+	protected $fields_calculator;
37 37
 
38 38
 
39
-    /**
40
-     * JsonModelSchema constructor.
41
-     *
42
-     * @param EEM_Base              $model
43
-     * @param CalculatedModelFields $fields_calculator
44
-     */
45
-    public function __construct(EEM_Base $model, CalculatedModelFields $fields_calculator)
46
-    {
47
-        $this->model = $model;
48
-        $this->fields_calculator = $fields_calculator;
49
-    }
39
+	/**
40
+	 * JsonModelSchema constructor.
41
+	 *
42
+	 * @param EEM_Base              $model
43
+	 * @param CalculatedModelFields $fields_calculator
44
+	 */
45
+	public function __construct(EEM_Base $model, CalculatedModelFields $fields_calculator)
46
+	{
47
+		$this->model = $model;
48
+		$this->fields_calculator = $fields_calculator;
49
+	}
50 50
 
51 51
 
52
-    /**
53
-     * Return the schema for a given model from a given model.
54
-     *
55
-     * @return array
56
-     */
57
-    public function getModelSchema()
58
-    {
59
-        return $this->getModelSchemaForRelations(
60
-            $this->model->relation_settings(),
61
-            $this->getModelSchemaForFields(
62
-                $this->model->field_settings(),
63
-                $this->getInitialSchemaStructure()
64
-            )
65
-        );
66
-    }
52
+	/**
53
+	 * Return the schema for a given model from a given model.
54
+	 *
55
+	 * @return array
56
+	 */
57
+	public function getModelSchema()
58
+	{
59
+		return $this->getModelSchemaForRelations(
60
+			$this->model->relation_settings(),
61
+			$this->getModelSchemaForFields(
62
+				$this->model->field_settings(),
63
+				$this->getInitialSchemaStructure()
64
+			)
65
+		);
66
+	}
67 67
 
68 68
 
69
-    /**
70
-     * Get the schema for a given set of model fields.
71
-     *
72
-     * @param EE_Model_Field_Base[] $model_fields
73
-     * @param array                  $schema
74
-     * @return array
75
-     */
76
-    public function getModelSchemaForFields(array $model_fields, array $schema)
77
-    {
78
-        foreach ($model_fields as $field => $model_field) {
79
-            if (! $model_field instanceof EE_Model_Field_Base) {
80
-                continue;
81
-            }
82
-            $schema['properties'][ $field ] = $model_field->getSchema();
69
+	/**
70
+	 * Get the schema for a given set of model fields.
71
+	 *
72
+	 * @param EE_Model_Field_Base[] $model_fields
73
+	 * @param array                  $schema
74
+	 * @return array
75
+	 */
76
+	public function getModelSchemaForFields(array $model_fields, array $schema)
77
+	{
78
+		foreach ($model_fields as $field => $model_field) {
79
+			if (! $model_field instanceof EE_Model_Field_Base) {
80
+				continue;
81
+			}
82
+			$schema['properties'][ $field ] = $model_field->getSchema();
83 83
 
84
-            // if this is a primary key field add the primary key item
85
-            if ($model_field instanceof EE_Primary_Key_Field_Base) {
86
-                $schema['properties'][ $field ]['primary_key'] = true;
87
-                if ($model_field instanceof EE_Primary_Key_Int_Field) {
88
-                    $schema['properties'][ $field ]['readonly'] = true;
89
-                }
90
-            }
84
+			// if this is a primary key field add the primary key item
85
+			if ($model_field instanceof EE_Primary_Key_Field_Base) {
86
+				$schema['properties'][ $field ]['primary_key'] = true;
87
+				if ($model_field instanceof EE_Primary_Key_Int_Field) {
88
+					$schema['properties'][ $field ]['readonly'] = true;
89
+				}
90
+			}
91 91
 
92
-            // if this is a foreign key field add the foreign key item
93
-            if ($model_field instanceof EE_Foreign_Key_Field_Base) {
94
-                $schema['properties'][ $field ]['foreign_key'] = array(
95
-                    'description' => esc_html__(
96
-                        'This is a foreign key the points to the given models.',
97
-                        'event_espresso'
98
-                    ),
99
-                    'type'        => 'array',
100
-                    'enum'        => $model_field->get_model_class_names_pointed_to(),
101
-                );
102
-            }
103
-        }
104
-        return $schema;
105
-    }
92
+			// if this is a foreign key field add the foreign key item
93
+			if ($model_field instanceof EE_Foreign_Key_Field_Base) {
94
+				$schema['properties'][ $field ]['foreign_key'] = array(
95
+					'description' => esc_html__(
96
+						'This is a foreign key the points to the given models.',
97
+						'event_espresso'
98
+					),
99
+					'type'        => 'array',
100
+					'enum'        => $model_field->get_model_class_names_pointed_to(),
101
+				);
102
+			}
103
+		}
104
+		return $schema;
105
+	}
106 106
 
107 107
 
108
-    /**
109
-     * Get the schema for a given set of model relations
110
-     *
111
-     * @param EE_Model_Relation_Base[] $relations_on_model
112
-     * @param array                    $schema
113
-     * @return array
114
-     */
115
-    public function getModelSchemaForRelations(array $relations_on_model, array $schema)
116
-    {
117
-        foreach ($relations_on_model as $model_name => $relation) {
118
-            if (! $relation instanceof EE_Model_Relation_Base) {
119
-                continue;
120
-            }
121
-            $model_name_for_schema = $relation instanceof EE_Belongs_To_Relation
122
-                ? strtolower($model_name)
123
-                : EEH_Inflector::pluralize_and_lower($model_name);
124
-            $schema['properties'][ $model_name_for_schema ] = $relation->getSchema();
125
-            $schema['properties'][ $model_name_for_schema ]['relation_model'] = $model_name;
108
+	/**
109
+	 * Get the schema for a given set of model relations
110
+	 *
111
+	 * @param EE_Model_Relation_Base[] $relations_on_model
112
+	 * @param array                    $schema
113
+	 * @return array
114
+	 */
115
+	public function getModelSchemaForRelations(array $relations_on_model, array $schema)
116
+	{
117
+		foreach ($relations_on_model as $model_name => $relation) {
118
+			if (! $relation instanceof EE_Model_Relation_Base) {
119
+				continue;
120
+			}
121
+			$model_name_for_schema = $relation instanceof EE_Belongs_To_Relation
122
+				? strtolower($model_name)
123
+				: EEH_Inflector::pluralize_and_lower($model_name);
124
+			$schema['properties'][ $model_name_for_schema ] = $relation->getSchema();
125
+			$schema['properties'][ $model_name_for_schema ]['relation_model'] = $model_name;
126 126
 
127
-            // links schema
128
-            $links_key = 'https://api.eventespresso.com/' . strtolower($model_name);
129
-            $schema['properties']['_links']['properties'][ $links_key ] = array(
130
-                'description' => esc_html__(
131
-                    'Array of objects describing the link(s) for this relation resource.',
132
-                    'event_espresso'
133
-                ),
134
-                'type' => 'array',
135
-                'readonly' => true,
136
-                'items' => array(
137
-                    'type' => 'object',
138
-                    'properties' => array(
139
-                        'href' => array(
140
-                            'type' => 'string',
141
-                            'description' => sprintf(
142
-                                // translators: placeholder is the model name for the relation.
143
-                                esc_html__(
144
-                                    'The link to the resource for the %s relation(s) to this entity',
145
-                                    'event_espresso'
146
-                                ),
147
-                                $model_name
148
-                            ),
149
-                        ),
150
-                        'single' => array(
151
-                            'type' => 'boolean',
152
-                            'description' => sprintf(
153
-                                // translators: placeholder is the model name for the relation.
154
-                                esc_html__(
155
-                                    'Whether or not there is only a single %s relation to this entity',
156
-                                    'event_espresso'
157
-                                ),
158
-                                $model_name
159
-                            ),
160
-                        ),
161
-                    ),
162
-                    'additionalProperties' => false
163
-                ),
164
-            );
165
-        }
166
-        return $schema;
167
-    }
127
+			// links schema
128
+			$links_key = 'https://api.eventespresso.com/' . strtolower($model_name);
129
+			$schema['properties']['_links']['properties'][ $links_key ] = array(
130
+				'description' => esc_html__(
131
+					'Array of objects describing the link(s) for this relation resource.',
132
+					'event_espresso'
133
+				),
134
+				'type' => 'array',
135
+				'readonly' => true,
136
+				'items' => array(
137
+					'type' => 'object',
138
+					'properties' => array(
139
+						'href' => array(
140
+							'type' => 'string',
141
+							'description' => sprintf(
142
+								// translators: placeholder is the model name for the relation.
143
+								esc_html__(
144
+									'The link to the resource for the %s relation(s) to this entity',
145
+									'event_espresso'
146
+								),
147
+								$model_name
148
+							),
149
+						),
150
+						'single' => array(
151
+							'type' => 'boolean',
152
+							'description' => sprintf(
153
+								// translators: placeholder is the model name for the relation.
154
+								esc_html__(
155
+									'Whether or not there is only a single %s relation to this entity',
156
+									'event_espresso'
157
+								),
158
+								$model_name
159
+							),
160
+						),
161
+					),
162
+					'additionalProperties' => false
163
+				),
164
+			);
165
+		}
166
+		return $schema;
167
+	}
168 168
 
169 169
 
170
-    /**
171
-     * Outputs the schema header for a model.
172
-     *
173
-     * @return array
174
-     */
175
-    public function getInitialSchemaStructure()
176
-    {
177
-        return array(
178
-            '$schema'    => 'http://json-schema.org/draft-04/schema#',
179
-            'title'      => $this->model->get_this_model_name(),
180
-            'type'       => 'object',
181
-            'properties' => array(
182
-                'link' => array(
183
-                    'description' => esc_html__(
184
-                        'Link to event on WordPress site hosting events.',
185
-                        'event_espresso'
186
-                    ),
187
-                    'type' => 'string',
188
-                    'readonly' => true,
189
-                ),
190
-                '_links' => array(
191
-                    'description' => esc_html__(
192
-                        'Various links for resources related to the entity.',
193
-                        'event_espresso'
194
-                    ),
195
-                    'type' => 'object',
196
-                    'readonly' => true,
197
-                    'properties' => array(
198
-                        'self' => array(
199
-                            'description' => esc_html__(
200
-                                'Link to this entities resource.',
201
-                                'event_espresso'
202
-                            ),
203
-                            'type' => 'array',
204
-                            'items' => array(
205
-                                'type' => 'object',
206
-                                'properties' => array(
207
-                                    'href' => array(
208
-                                        'type' => 'string',
209
-                                    ),
210
-                                ),
211
-                                'additionalProperties' => false
212
-                            ),
213
-                            'readonly' => true
214
-                        ),
215
-                        'collection' => array(
216
-                            'description' => esc_html__(
217
-                                'Link to this entities collection resource.',
218
-                                'event_espresso'
219
-                            ),
220
-                            'type' => 'array',
221
-                            'items' => array(
222
-                                'type' => 'object',
223
-                                'properties' => array(
224
-                                    'href' => array(
225
-                                        'type' => 'string'
226
-                                    ),
227
-                                ),
228
-                                'additionalProperties' => false
229
-                            ),
230
-                            'readonly' => true
231
-                        ),
232
-                    ),
233
-                    'additionalProperties' => false,
234
-                ),
235
-                '_calculated_fields' => array_merge(
236
-                    $this->fields_calculator->getJsonSchemaForModel($this->model),
237
-                    array(
238
-                        '_protected' => $this->getProtectedFieldsSchema()
239
-                    )
240
-                ),
241
-                '_protected' => $this->getProtectedFieldsSchema()
242
-            ),
243
-            'additionalProperties' => false,
244
-        );
245
-    }
170
+	/**
171
+	 * Outputs the schema header for a model.
172
+	 *
173
+	 * @return array
174
+	 */
175
+	public function getInitialSchemaStructure()
176
+	{
177
+		return array(
178
+			'$schema'    => 'http://json-schema.org/draft-04/schema#',
179
+			'title'      => $this->model->get_this_model_name(),
180
+			'type'       => 'object',
181
+			'properties' => array(
182
+				'link' => array(
183
+					'description' => esc_html__(
184
+						'Link to event on WordPress site hosting events.',
185
+						'event_espresso'
186
+					),
187
+					'type' => 'string',
188
+					'readonly' => true,
189
+				),
190
+				'_links' => array(
191
+					'description' => esc_html__(
192
+						'Various links for resources related to the entity.',
193
+						'event_espresso'
194
+					),
195
+					'type' => 'object',
196
+					'readonly' => true,
197
+					'properties' => array(
198
+						'self' => array(
199
+							'description' => esc_html__(
200
+								'Link to this entities resource.',
201
+								'event_espresso'
202
+							),
203
+							'type' => 'array',
204
+							'items' => array(
205
+								'type' => 'object',
206
+								'properties' => array(
207
+									'href' => array(
208
+										'type' => 'string',
209
+									),
210
+								),
211
+								'additionalProperties' => false
212
+							),
213
+							'readonly' => true
214
+						),
215
+						'collection' => array(
216
+							'description' => esc_html__(
217
+								'Link to this entities collection resource.',
218
+								'event_espresso'
219
+							),
220
+							'type' => 'array',
221
+							'items' => array(
222
+								'type' => 'object',
223
+								'properties' => array(
224
+									'href' => array(
225
+										'type' => 'string'
226
+									),
227
+								),
228
+								'additionalProperties' => false
229
+							),
230
+							'readonly' => true
231
+						),
232
+					),
233
+					'additionalProperties' => false,
234
+				),
235
+				'_calculated_fields' => array_merge(
236
+					$this->fields_calculator->getJsonSchemaForModel($this->model),
237
+					array(
238
+						'_protected' => $this->getProtectedFieldsSchema()
239
+					)
240
+				),
241
+				'_protected' => $this->getProtectedFieldsSchema()
242
+			),
243
+			'additionalProperties' => false,
244
+		);
245
+	}
246 246
 
247
-    /**
248
-     * Returns an array of JSON schema to describe the _protected property on responses
249
-     * @since 4.9.74.p
250
-     * @return array
251
-     */
252
-    protected function getProtectedFieldsSchema()
253
-    {
254
-        return array(
255
-            'description' => esc_html__('Array of property names whose values were replaced with their default (because they are related to a password-protected entity.)', 'event_espresso'),
256
-            'type' => 'array',
257
-            'items' => array(
258
-                'description' => esc_html__('Each name corresponds to a property that is protected by password for this entity and has its default value returned in the response.', 'event_espresso'),
259
-                'type' => 'string',
260
-                'readonly' => true,
261
-            ),
262
-            'readonly' => true
263
-        );
264
-    }
247
+	/**
248
+	 * Returns an array of JSON schema to describe the _protected property on responses
249
+	 * @since 4.9.74.p
250
+	 * @return array
251
+	 */
252
+	protected function getProtectedFieldsSchema()
253
+	{
254
+		return array(
255
+			'description' => esc_html__('Array of property names whose values were replaced with their default (because they are related to a password-protected entity.)', 'event_espresso'),
256
+			'type' => 'array',
257
+			'items' => array(
258
+				'description' => esc_html__('Each name corresponds to a property that is protected by password for this entity and has its default value returned in the response.', 'event_espresso'),
259
+				'type' => 'string',
260
+				'readonly' => true,
261
+			),
262
+			'readonly' => true
263
+		);
264
+	}
265 265
 
266 266
 
267
-    /**
268
-     * Allows one to just use the object as a string to get the json.
269
-     *
270
-     * @return bool|false|mixed|string
271
-     */
272
-    public function __toString()
273
-    {
274
-        return wp_json_encode($this->getModelSchema());
275
-    }
267
+	/**
268
+	 * Allows one to just use the object as a string to get the json.
269
+	 *
270
+	 * @return bool|false|mixed|string
271
+	 */
272
+	public function __toString()
273
+	{
274
+		return wp_json_encode($this->getModelSchema());
275
+	}
276 276
 }
Please login to merge, or discard this patch.
core/libraries/form_sections/base/EE_Form_Section_Proper.form.php 1 patch
Indentation   +1528 added lines, -1528 removed lines patch added patch discarded remove patch
@@ -16,1532 +16,1532 @@
 block discarded – undo
16 16
 class EE_Form_Section_Proper extends EE_Form_Section_Validatable
17 17
 {
18 18
 
19
-    const SUBMITTED_FORM_DATA_SSN_KEY = 'submitted_form_data';
20
-
21
-    /**
22
-     * Subsections
23
-     *
24
-     * @var EE_Form_Section_Validatable[]
25
-     */
26
-    protected $_subsections = array();
27
-
28
-    /**
29
-     * Strategy for laying out the form
30
-     *
31
-     * @var EE_Form_Section_Layout_Base
32
-     */
33
-    protected $_layout_strategy;
34
-
35
-    /**
36
-     * Whether or not this form has received and validated a form submission yet
37
-     *
38
-     * @var boolean
39
-     */
40
-    protected $_received_submission = false;
41
-
42
-    /**
43
-     * message displayed to users upon successful form submission
44
-     *
45
-     * @var string
46
-     */
47
-    protected $_form_submission_success_message = '';
48
-
49
-    /**
50
-     * message displayed to users upon unsuccessful form submission
51
-     *
52
-     * @var string
53
-     */
54
-    protected $_form_submission_error_message = '';
55
-
56
-    /**
57
-     * @var array like post / request
58
-     */
59
-    protected $cached_request_data;
60
-
61
-    /**
62
-     * Stores whether this form (and its sub-sections) were found to be valid or not.
63
-     * Starts off as null, but once the form is validated, it set to either true or false
64
-     * @var boolean|null
65
-     */
66
-    protected $is_valid;
67
-
68
-    /**
69
-     * Stores all the data that will localized for form validation
70
-     *
71
-     * @var array
72
-     */
73
-    protected static $_js_localization = array();
74
-
75
-    /**
76
-     * whether or not the form's localized validation JS vars have been set
77
-     *
78
-     * @type boolean
79
-     */
80
-    protected static $_scripts_localized = false;
81
-
82
-
83
-    /**
84
-     * when constructing a proper form section, calls _construct_finalize on children
85
-     * so that they know who their parent is, and what name they've been given.
86
-     *
87
-     * @param array[] $options_array   {
88
-     * @type          $subsections     EE_Form_Section_Validatable[] where keys are the section's name
89
-     * @type          $include         string[] numerically-indexed where values are section names to be included,
90
-     *                                 and in that order. This is handy if you want
91
-     *                                 the subsections to be ordered differently than the default, and if you override
92
-     *                                 which fields are shown
93
-     * @type          $exclude         string[] values are subsections to be excluded. This is handy if you want
94
-     *                                 to remove certain default subsections (note: if you specify BOTH 'include' AND
95
-     *                                 'exclude', the inclusions will be applied first, and the exclusions will exclude
96
-     *                                 items from that list of inclusions)
97
-     * @type          $layout_strategy EE_Form_Section_Layout_Base strategy for laying out the form
98
-     *                                 } @see EE_Form_Section_Validatable::__construct()
99
-     * @throws EE_Error
100
-     */
101
-    public function __construct($options_array = array())
102
-    {
103
-        $options_array = (array) apply_filters(
104
-            'FHEE__EE_Form_Section_Proper___construct__options_array',
105
-            $options_array,
106
-            $this
107
-        );
108
-        // call parent first, as it may be setting the name
109
-        parent::__construct($options_array);
110
-        // if they've included subsections in the constructor, add them now
111
-        if (isset($options_array['include'])) {
112
-            // we are going to make sure we ONLY have those subsections to include
113
-            // AND we are going to make sure they're in that specified order
114
-            $reordered_subsections = array();
115
-            foreach ($options_array['include'] as $input_name) {
116
-                if (isset($this->_subsections[ $input_name ])) {
117
-                    $reordered_subsections[ $input_name ] = $this->_subsections[ $input_name ];
118
-                }
119
-            }
120
-            $this->_subsections = $reordered_subsections;
121
-        }
122
-        if (isset($options_array['exclude'])) {
123
-            $exclude            = $options_array['exclude'];
124
-            $this->_subsections = array_diff_key($this->_subsections, array_flip($exclude));
125
-        }
126
-        if (isset($options_array['layout_strategy'])) {
127
-            $this->_layout_strategy = $options_array['layout_strategy'];
128
-        }
129
-        if (! $this->_layout_strategy) {
130
-            $this->_layout_strategy = is_admin() ? new EE_Admin_Two_Column_Layout() : new EE_Two_Column_Layout();
131
-        }
132
-        $this->_layout_strategy->_construct_finalize($this);
133
-        // ok so we are definitely going to want the forms JS,
134
-        // so enqueue it or remember to enqueue it during wp_enqueue_scripts
135
-        if (did_action('wp_enqueue_scripts') || did_action('admin_enqueue_scripts')) {
136
-            // ok so they've constructed this object after when they should have.
137
-            // just enqueue the generic form scripts and initialize the form immediately in the JS
138
-            EE_Form_Section_Proper::wp_enqueue_scripts(true);
139
-        } else {
140
-            add_action('wp_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
141
-            add_action('admin_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
142
-        }
143
-        add_action('wp_footer', array($this, 'ensure_scripts_localized'), 1);
144
-        /**
145
-         * Gives other plugins a chance to hook in before construct finalize is called.
146
-         * The form probably doesn't yet have a parent form section.
147
-         * Since 4.9.32, when this action was introduced, this is the best place to add a subsection onto a form,
148
-         * assuming you don't care what the form section's name, HTML ID, or HTML name etc are.
149
-         * Also see AHEE__EE_Form_Section_Proper___construct_finalize__end
150
-         *
151
-         * @since 4.9.32
152
-         * @param EE_Form_Section_Proper $this          before __construct is done, but all of its logic,
153
-         *                                              except maybe calling _construct_finalize has been done
154
-         * @param array                  $options_array options passed into the constructor
155
-         */
156
-        do_action(
157
-            'AHEE__EE_Form_Input_Base___construct__before_construct_finalize_called',
158
-            $this,
159
-            $options_array
160
-        );
161
-        if (isset($options_array['name'])) {
162
-            $this->_construct_finalize(null, $options_array['name']);
163
-        }
164
-    }
165
-
166
-
167
-    /**
168
-     * Finishes construction given the parent form section and this form section's name
169
-     *
170
-     * @param EE_Form_Section_Proper $parent_form_section
171
-     * @param string                 $name
172
-     * @throws EE_Error
173
-     */
174
-    public function _construct_finalize($parent_form_section, $name)
175
-    {
176
-        parent::_construct_finalize($parent_form_section, $name);
177
-        $this->_set_default_name_if_empty();
178
-        $this->_set_default_html_id_if_empty();
179
-        foreach ($this->_subsections as $subsection_name => $subsection) {
180
-            if ($subsection instanceof EE_Form_Section_Base) {
181
-                $subsection->_construct_finalize($this, $subsection_name);
182
-            } else {
183
-                throw new EE_Error(
184
-                    sprintf(
185
-                        esc_html__(
186
-                            'Subsection "%s" is not an instanceof EE_Form_Section_Base on form "%s". It is a "%s"',
187
-                            'event_espresso'
188
-                        ),
189
-                        $subsection_name,
190
-                        get_class($this),
191
-                        $subsection ? get_class($subsection) : esc_html__('NULL', 'event_espresso')
192
-                    )
193
-                );
194
-            }
195
-        }
196
-        /**
197
-         * Action performed just after form has been given a name (and HTML ID etc) and is fully constructed.
198
-         * If you have code that should modify the form and needs it and its subsections to have a name, HTML ID
199
-         * (or other attributes derived from the name like the HTML label id, etc), this is where it should be done.
200
-         * This might only happen just before displaying the form, or just before it receives form submission data.
201
-         * If you need to modify the form or its subsections before _construct_finalize is called on it (and we've
202
-         * ensured it has a name, HTML IDs, etc
203
-         *
204
-         * @param EE_Form_Section_Proper      $this
205
-         * @param EE_Form_Section_Proper|null $parent_form_section
206
-         * @param string                      $name
207
-         */
208
-        do_action(
209
-            'AHEE__EE_Form_Section_Proper___construct_finalize__end',
210
-            $this,
211
-            $parent_form_section,
212
-            $name
213
-        );
214
-    }
215
-
216
-
217
-    /**
218
-     * Gets the layout strategy for this form section
219
-     *
220
-     * @return EE_Form_Section_Layout_Base
221
-     */
222
-    public function get_layout_strategy()
223
-    {
224
-        return $this->_layout_strategy;
225
-    }
226
-
227
-
228
-    /**
229
-     * Gets the HTML for a single input for this form section according
230
-     * to the layout strategy
231
-     *
232
-     * @param EE_Form_Input_Base $input
233
-     * @return string
234
-     */
235
-    public function get_html_for_input($input)
236
-    {
237
-        return $this->_layout_strategy->layout_input($input);
238
-    }
239
-
240
-
241
-    /**
242
-     * was_submitted - checks if form inputs are present in request data
243
-     * Basically an alias for form_data_present_in() (which is used by both
244
-     * proper form sections and form inputs)
245
-     *
246
-     * @param null $form_data
247
-     * @return boolean
248
-     * @throws EE_Error
249
-     */
250
-    public function was_submitted($form_data = null)
251
-    {
252
-        return $this->form_data_present_in($form_data);
253
-    }
254
-
255
-    /**
256
-     * Gets the cached request data; but if there is none, or $req_data was set with
257
-     * something different, refresh the cache, and then return it
258
-     * @param null $req_data
259
-     * @return array
260
-     */
261
-    protected function getCachedRequest($req_data = null)
262
-    {
263
-        if (
264
-            $this->cached_request_data === null
265
-            || (
266
-                $req_data !== null
267
-                && $req_data !== $this->cached_request_data
268
-            )
269
-        ) {
270
-            $req_data = apply_filters(
271
-                'FHEE__EE_Form_Section_Proper__receive_form_submission__req_data',
272
-                $req_data,
273
-                $this
274
-            );
275
-            if ($req_data === null) {
276
-                /** @var RequestInterface $request */
277
-                $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
278
-                $req_data = $request->requestParams();
279
-            }
280
-            $req_data = apply_filters(
281
-                'FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
282
-                $req_data,
283
-                $this
284
-            );
285
-            $this->cached_request_data = (array) $req_data;
286
-        }
287
-        return $this->cached_request_data;
288
-    }
289
-
290
-
291
-    /**
292
-     * After the form section is initially created, call this to sanitize the data in the submission
293
-     * which relates to this form section, validate it, and set it as properties on the form.
294
-     *
295
-     * @param array|null $req_data should usually be post data (the default).
296
-     *                             However, you CAN supply a different array.
297
-     *                             Consider using set_defaults() instead however.
298
-     *                             (If you rendered the form in the page using $form_x->get_html()
299
-     *                             the inputs will have the correct name in the request data for this function
300
-     *                             to find them and populate the form with them.
301
-     *                             If you have a flat form (with only input subsections),
302
-     *                             you can supply a flat array where keys
303
-     *                             are the form input names and values are their values)
304
-     * @param boolean    $validate whether or not to perform validation on this data. Default is,
305
-     *                             of course, to validate that data, and set errors on the invalid values.
306
-     *                             But if the data has already been validated
307
-     *                             (eg you validated the data then stored it in the DB)
308
-     *                             you may want to skip this step.
309
-     * @throws InvalidArgumentException
310
-     * @throws InvalidInterfaceException
311
-     * @throws InvalidDataTypeException
312
-     * @throws EE_Error
313
-     */
314
-    public function receive_form_submission($req_data = null, $validate = true)
315
-    {
316
-        $req_data = $this->getCachedRequest($req_data);
317
-        $this->_normalize($req_data);
318
-        if ($validate) {
319
-            $this->_validate();
320
-            // if it's invalid, we're going to want to re-display so remember what they submitted
321
-            if (! $this->is_valid()) {
322
-                $this->store_submitted_form_data_in_session();
323
-            }
324
-        }
325
-        if ($this->submission_error_message() === '' && ! $this->is_valid()) {
326
-            $this->set_submission_error_message();
327
-        }
328
-        do_action(
329
-            'AHEE__EE_Form_Section_Proper__receive_form_submission__end',
330
-            $req_data,
331
-            $this,
332
-            $validate
333
-        );
334
-    }
335
-
336
-
337
-    /**
338
-     * caches the originally submitted input values in the session
339
-     * so that they can be used to repopulate the form if it failed validation
340
-     *
341
-     * @return boolean whether or not the data was successfully stored in the session
342
-     * @throws InvalidArgumentException
343
-     * @throws InvalidInterfaceException
344
-     * @throws InvalidDataTypeException
345
-     * @throws EE_Error
346
-     */
347
-    protected function store_submitted_form_data_in_session()
348
-    {
349
-        return EE_Registry::instance()->SSN->set_session_data(
350
-            array(
351
-                EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY => $this->submitted_values(true),
352
-            )
353
-        );
354
-    }
355
-
356
-
357
-    /**
358
-     * retrieves the originally submitted input values in the session
359
-     * so that they can be used to repopulate the form if it failed validation
360
-     *
361
-     * @return array
362
-     * @throws InvalidArgumentException
363
-     * @throws InvalidInterfaceException
364
-     * @throws InvalidDataTypeException
365
-     */
366
-    protected function get_submitted_form_data_from_session()
367
-    {
368
-        $session = EE_Registry::instance()->SSN;
369
-        if ($session instanceof EE_Session) {
370
-            return $session->get_session_data(
371
-                EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY
372
-            );
373
-        }
374
-        return array();
375
-    }
376
-
377
-
378
-    /**
379
-     * flushed the originally submitted input values from the session
380
-     *
381
-     * @return boolean whether or not the data was successfully removed from the session
382
-     * @throws InvalidArgumentException
383
-     * @throws InvalidInterfaceException
384
-     * @throws InvalidDataTypeException
385
-     */
386
-    public static function flush_submitted_form_data_from_session()
387
-    {
388
-        return EE_Registry::instance()->SSN->reset_data(
389
-            array(EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY)
390
-        );
391
-    }
392
-
393
-
394
-    /**
395
-     * Populates this form and its subsections with data from the session.
396
-     * (Wrapper for EE_Form_Section_Proper::receive_form_submission, so it shows
397
-     * validation errors when displaying too)
398
-     * Returns true if the form was populated from the session, false otherwise
399
-     *
400
-     * @return boolean
401
-     * @throws InvalidArgumentException
402
-     * @throws InvalidInterfaceException
403
-     * @throws InvalidDataTypeException
404
-     * @throws EE_Error
405
-     */
406
-    public function populate_from_session()
407
-    {
408
-        $form_data_in_session = $this->get_submitted_form_data_from_session();
409
-        if (empty($form_data_in_session)) {
410
-            return false;
411
-        }
412
-        $this->receive_form_submission($form_data_in_session);
413
-        add_action('shutdown', array('EE_Form_Section_Proper', 'flush_submitted_form_data_from_session'));
414
-        if ($this->form_data_present_in($form_data_in_session)) {
415
-            return true;
416
-        }
417
-        return false;
418
-    }
419
-
420
-
421
-    /**
422
-     * Populates the default data for the form, given an array where keys are
423
-     * the input names, and values are their values (preferably normalized to be their
424
-     * proper PHP types, not all strings... although that should be ok too).
425
-     * Proper subsections are sub-arrays, the key being the subsection's name, and
426
-     * the value being an array formatted in teh same way
427
-     *
428
-     * @param array $default_data
429
-     * @throws EE_Error
430
-     */
431
-    public function populate_defaults($default_data)
432
-    {
433
-        foreach ($this->subsections(false) as $subsection_name => $subsection) {
434
-            if (isset($default_data[ $subsection_name ])) {
435
-                if ($subsection instanceof EE_Form_Input_Base) {
436
-                    $subsection->set_default($default_data[ $subsection_name ]);
437
-                } elseif ($subsection instanceof EE_Form_Section_Proper) {
438
-                    $subsection->populate_defaults($default_data[ $subsection_name ]);
439
-                }
440
-            }
441
-        }
442
-    }
443
-
444
-
445
-    /**
446
-     * returns true if subsection exists
447
-     *
448
-     * @param string $name
449
-     * @return boolean
450
-     */
451
-    public function subsection_exists($name)
452
-    {
453
-        return isset($this->_subsections[ $name ]) ? true : false;
454
-    }
455
-
456
-
457
-    /**
458
-     * Gets the subsection specified by its name
459
-     *
460
-     * @param string  $name
461
-     * @param boolean $require_construction_to_be_finalized most client code should leave this as TRUE
462
-     *                                                      so that the inputs will be properly configured.
463
-     *                                                      However, some client code may be ok
464
-     *                                                      with construction finalize being called later
465
-     *                                                      (realizing that the subsections' html names
466
-     *                                                      might not be set yet, etc.)
467
-     * @return EE_Form_Section_Base
468
-     * @throws EE_Error
469
-     */
470
-    public function get_subsection($name, $require_construction_to_be_finalized = true)
471
-    {
472
-        if ($require_construction_to_be_finalized) {
473
-            $this->ensure_construct_finalized_called();
474
-        }
475
-        return $this->subsection_exists($name) ? $this->_subsections[ $name ] : null;
476
-    }
477
-
478
-
479
-    /**
480
-     * Gets all the validatable subsections of this form section
481
-     *
482
-     * @return EE_Form_Section_Validatable[]
483
-     * @throws EE_Error
484
-     */
485
-    public function get_validatable_subsections()
486
-    {
487
-        $validatable_subsections = array();
488
-        foreach ($this->subsections() as $name => $obj) {
489
-            if ($obj instanceof EE_Form_Section_Validatable) {
490
-                $validatable_subsections[ $name ] = $obj;
491
-            }
492
-        }
493
-        return $validatable_subsections;
494
-    }
495
-
496
-
497
-    /**
498
-     * Gets an input by the given name. If not found, or if its not an EE_FOrm_Input_Base child,
499
-     * throw an EE_Error.
500
-     *
501
-     * @param string  $name
502
-     * @param boolean $require_construction_to_be_finalized most client code should
503
-     *                                                      leave this as TRUE so that the inputs will be properly
504
-     *                                                      configured. However, some client code may be ok with
505
-     *                                                      construction finalize being called later
506
-     *                                                      (realizing that the subsections' html names might not be
507
-     *                                                      set yet, etc.)
508
-     * @return EE_Form_Input_Base
509
-     * @throws EE_Error
510
-     */
511
-    public function get_input($name, $require_construction_to_be_finalized = true)
512
-    {
513
-        $subsection = $this->get_subsection(
514
-            $name,
515
-            $require_construction_to_be_finalized
516
-        );
517
-        if (! $subsection instanceof EE_Form_Input_Base) {
518
-            throw new EE_Error(
519
-                sprintf(
520
-                    esc_html__(
521
-                        "Subsection '%s' is not an instanceof EE_Form_Input_Base on form '%s'. It is a '%s'",
522
-                        'event_espresso'
523
-                    ),
524
-                    $name,
525
-                    get_class($this),
526
-                    $subsection ? get_class($subsection) : esc_html__('NULL', 'event_espresso')
527
-                )
528
-            );
529
-        }
530
-        return $subsection;
531
-    }
532
-
533
-
534
-    /**
535
-     * Like get_input(), gets the proper subsection of the form given the name,
536
-     * otherwise throws an EE_Error
537
-     *
538
-     * @param string  $name
539
-     * @param boolean $require_construction_to_be_finalized most client code should
540
-     *                                                      leave this as TRUE so that the inputs will be properly
541
-     *                                                      configured. However, some client code may be ok with
542
-     *                                                      construction finalize being called later
543
-     *                                                      (realizing that the subsections' html names might not be
544
-     *                                                      set yet, etc.)
545
-     * @return EE_Form_Section_Proper
546
-     * @throws EE_Error
547
-     */
548
-    public function get_proper_subsection($name, $require_construction_to_be_finalized = true)
549
-    {
550
-        $subsection = $this->get_subsection(
551
-            $name,
552
-            $require_construction_to_be_finalized
553
-        );
554
-        if (! $subsection instanceof EE_Form_Section_Proper) {
555
-            throw new EE_Error(
556
-                sprintf(
557
-                    esc_html__(
558
-                        "Subsection '%'s is not an instanceof EE_Form_Section_Proper on form '%s'",
559
-                        'event_espresso'
560
-                    ),
561
-                    $name,
562
-                    get_class($this)
563
-                )
564
-            );
565
-        }
566
-        return $subsection;
567
-    }
568
-
569
-
570
-    /**
571
-     * Gets the value of the specified input. Should be called after receive_form_submission()
572
-     * or populate_defaults() on the form, where the normalized value on the input is set.
573
-     *
574
-     * @param string $name
575
-     * @return mixed depending on the input's type and its normalization strategy
576
-     * @throws EE_Error
577
-     */
578
-    public function get_input_value($name)
579
-    {
580
-        $input = $this->get_input($name);
581
-        return $input->normalized_value();
582
-    }
583
-
584
-
585
-    /**
586
-     * Checks if this form section itself is valid, and then checks its subsections
587
-     *
588
-     * @throws EE_Error
589
-     * @return boolean
590
-     */
591
-    public function is_valid()
592
-    {
593
-        if ($this->is_valid === null) {
594
-            if (! $this->has_received_submission()) {
595
-                throw new EE_Error(
596
-                    sprintf(
597
-                        esc_html__(
598
-                            'You cannot check if a form is valid before receiving the form submission using receive_form_submission',
599
-                            'event_espresso'
600
-                        )
601
-                    )
602
-                );
603
-            }
604
-            if (! parent::is_valid()) {
605
-                $this->is_valid = false;
606
-            } else {
607
-                // ok so no general errors to this entire form section.
608
-                // so let's check the subsections, but only set errors if that hasn't been done yet
609
-                $this->is_valid = true;
610
-                foreach ($this->get_validatable_subsections() as $subsection) {
611
-                    if (! $subsection->is_valid()) {
612
-                        $this->is_valid = false;
613
-                    }
614
-                }
615
-            }
616
-        }
617
-        return $this->is_valid;
618
-    }
619
-
620
-
621
-    /**
622
-     * gets the default name of this form section if none is specified
623
-     *
624
-     * @return void
625
-     */
626
-    protected function _set_default_name_if_empty()
627
-    {
628
-        if (! $this->_name) {
629
-            $classname    = get_class($this);
630
-            $default_name = str_replace('EE_', '', $classname);
631
-            $this->_name  = $default_name;
632
-        }
633
-    }
634
-
635
-
636
-    /**
637
-     * Returns the HTML for the form, except for the form opening and closing tags
638
-     * (as the form section doesn't know where you necessarily want to send the information to),
639
-     * and except for a submit button. Enqueues JS and CSS; if called early enough we will
640
-     * try to enqueue them in the header, otherwise they'll be enqueued in the footer.
641
-     * Not doing_it_wrong because theoretically this CAN be used properly,
642
-     * provided its used during "wp_enqueue_scripts", or it doesn't need to enqueue
643
-     * any CSS.
644
-     *
645
-     * @throws InvalidArgumentException
646
-     * @throws InvalidInterfaceException
647
-     * @throws InvalidDataTypeException
648
-     * @throws EE_Error
649
-     */
650
-    public function get_html_and_js()
651
-    {
652
-        $this->enqueue_js();
653
-        return $this->get_html();
654
-    }
655
-
656
-
657
-    /**
658
-     * returns HTML for displaying this form section. recursively calls display_section() on all subsections
659
-     *
660
-     * @param bool $display_previously_submitted_data
661
-     * @return string
662
-     * @throws InvalidArgumentException
663
-     * @throws InvalidInterfaceException
664
-     * @throws InvalidDataTypeException
665
-     * @throws EE_Error
666
-     * @throws EE_Error
667
-     * @throws EE_Error
668
-     */
669
-    public function get_html($display_previously_submitted_data = true)
670
-    {
671
-        $this->ensure_construct_finalized_called();
672
-        if ($display_previously_submitted_data) {
673
-            $this->populate_from_session();
674
-        }
675
-        return $this->_form_html_filter
676
-            ? $this->_form_html_filter->filterHtml($this->_layout_strategy->layout_form(), $this)
677
-            : $this->_layout_strategy->layout_form();
678
-    }
679
-
680
-
681
-    /**
682
-     * enqueues JS and CSS for the form.
683
-     * It is preferred to call this before wp_enqueue_scripts so the
684
-     * scripts and styles can be put in the header, but if called later
685
-     * they will be put in the footer (which is OK for JS, but in HTML4 CSS should
686
-     * only be in the header; but in HTML5 its ok in the body.
687
-     * See http://stackoverflow.com/questions/4957446/load-external-css-file-in-body-tag.
688
-     * So if your form enqueues CSS, it's preferred to call this before wp_enqueue_scripts.)
689
-     *
690
-     * @return void
691
-     * @throws EE_Error
692
-     */
693
-    public function enqueue_js()
694
-    {
695
-        $this->_enqueue_and_localize_form_js();
696
-        foreach ($this->subsections() as $subsection) {
697
-            $subsection->enqueue_js();
698
-        }
699
-    }
700
-
701
-
702
-    /**
703
-     * adds a filter so that jquery validate gets enqueued in EE_System::wp_enqueue_scripts().
704
-     * This must be done BEFORE wp_enqueue_scripts() gets called, which is on
705
-     * the wp_enqueue_scripts hook.
706
-     * However, registering the form js and localizing it can happen when we
707
-     * actually output the form (which is preferred, seeing how teh form's fields
708
-     * could change until it's actually outputted)
709
-     *
710
-     * @param boolean $init_form_validation_automatically whether or not we want the form validation
711
-     *                                                    to be triggered automatically or not
712
-     * @return void
713
-     */
714
-    public static function wp_enqueue_scripts($init_form_validation_automatically = true)
715
-    {
716
-        wp_register_script(
717
-            'ee_form_section_validation',
718
-            EE_GLOBAL_ASSETS_URL . 'scripts' . '/form_section_validation.js',
719
-            array('jquery-validate', 'jquery-ui-datepicker', 'jquery-validate-extra-methods'),
720
-            EVENT_ESPRESSO_VERSION,
721
-            true
722
-        );
723
-        wp_localize_script(
724
-            'ee_form_section_validation',
725
-            'ee_form_section_validation_init',
726
-            array('init' => $init_form_validation_automatically ? '1' : '0')
727
-        );
728
-    }
729
-
730
-
731
-    /**
732
-     * gets the variables used by form_section_validation.js.
733
-     * This needs to be called AFTER we've called $this->_enqueue_jquery_validate_script,
734
-     * but before the wordpress hook wp_loaded
735
-     *
736
-     * @throws EE_Error
737
-     */
738
-    public function _enqueue_and_localize_form_js()
739
-    {
740
-        $this->ensure_construct_finalized_called();
741
-        // actually, we don't want to localize just yet. There may be other forms on the page.
742
-        // so we need to add our form section data to a static variable accessible by all form sections
743
-        // and localize it just before the footer
744
-        $this->localize_validation_rules();
745
-        add_action('wp_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'), 2);
746
-        add_action('admin_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'));
747
-    }
748
-
749
-
750
-    /**
751
-     * add our form section data to a static variable accessible by all form sections
752
-     *
753
-     * @param bool $return_for_subsection
754
-     * @return void
755
-     * @throws EE_Error
756
-     */
757
-    public function localize_validation_rules($return_for_subsection = false)
758
-    {
759
-        // we only want to localize vars ONCE for the entire form,
760
-        // so if the form section doesn't have a parent, then it must be the top dog
761
-        if ($return_for_subsection || ! $this->parent_section()) {
762
-            EE_Form_Section_Proper::$_js_localization['form_data'][ $this->html_id() ] = array(
763
-                'form_section_id'  => $this->html_id(true),
764
-                'validation_rules' => $this->get_jquery_validation_rules(),
765
-                'other_data'       => $this->get_other_js_data(),
766
-                'errors'           => $this->subsection_validation_errors_by_html_name(),
767
-            );
768
-            EE_Form_Section_Proper::$_scripts_localized                                = true;
769
-        }
770
-    }
771
-
772
-
773
-    /**
774
-     * Gets an array of extra data that will be useful for client-side javascript.
775
-     * This is primarily data added by inputs and forms in addition to any
776
-     * scripts they might enqueue
777
-     *
778
-     * @param array $form_other_js_data
779
-     * @return array
780
-     * @throws EE_Error
781
-     */
782
-    public function get_other_js_data($form_other_js_data = array())
783
-    {
784
-        foreach ($this->subsections() as $subsection) {
785
-            $form_other_js_data = $subsection->get_other_js_data($form_other_js_data);
786
-        }
787
-        return $form_other_js_data;
788
-    }
789
-
790
-
791
-    /**
792
-     * Gets a flat array of inputs for this form section and its subsections.
793
-     * Keys are their form names, and values are the inputs themselves
794
-     *
795
-     * @return EE_Form_Input_Base
796
-     * @throws EE_Error
797
-     */
798
-    public function inputs_in_subsections()
799
-    {
800
-        $inputs = array();
801
-        foreach ($this->subsections() as $subsection) {
802
-            if ($subsection instanceof EE_Form_Input_Base) {
803
-                $inputs[ $subsection->html_name() ] = $subsection;
804
-            } elseif ($subsection instanceof EE_Form_Section_Proper) {
805
-                $inputs += $subsection->inputs_in_subsections();
806
-            }
807
-        }
808
-        return $inputs;
809
-    }
810
-
811
-
812
-    /**
813
-     * Gets a flat array of all the validation errors.
814
-     * Keys are html names (because those should be unique)
815
-     * and values are a string of all their validation errors
816
-     *
817
-     * @return string[]
818
-     * @throws EE_Error
819
-     */
820
-    public function subsection_validation_errors_by_html_name()
821
-    {
822
-        $inputs = $this->inputs();
823
-        $errors = array();
824
-        foreach ($inputs as $form_input) {
825
-            if ($form_input instanceof EE_Form_Input_Base && $form_input->get_validation_errors()) {
826
-                $errors[ $form_input->html_name() ] = $form_input->get_validation_error_string();
827
-            }
828
-        }
829
-        return $errors;
830
-    }
831
-
832
-
833
-    /**
834
-     * passes all the form data required by the JS to the JS, and enqueues the few required JS files.
835
-     * Should be setup by each form during the _enqueues_and_localize_form_js
836
-     *
837
-     * @throws InvalidArgumentException
838
-     * @throws InvalidInterfaceException
839
-     * @throws InvalidDataTypeException
840
-     */
841
-    public static function localize_script_for_all_forms()
842
-    {
843
-        // allow inputs and stuff to hook in their JS and stuff here
844
-        do_action('AHEE__EE_Form_Section_Proper__localize_script_for_all_forms__begin');
845
-        EE_Form_Section_Proper::$_js_localization['localized_error_messages'] = EE_Form_Section_Proper::_get_localized_error_messages();
846
-        $email_validation_level = isset(EE_Registry::instance()->CFG->registration->email_validation_level)
847
-            ? EE_Registry::instance()->CFG->registration->email_validation_level
848
-            : 'wp_default';
849
-        EE_Form_Section_Proper::$_js_localization['email_validation_level']   = $email_validation_level;
850
-        wp_enqueue_script('ee_form_section_validation');
851
-        wp_localize_script(
852
-            'ee_form_section_validation',
853
-            'ee_form_section_vars',
854
-            EE_Form_Section_Proper::$_js_localization
855
-        );
856
-    }
857
-
858
-
859
-    /**
860
-     * ensure_scripts_localized
861
-     *
862
-     * @throws EE_Error
863
-     */
864
-    public function ensure_scripts_localized()
865
-    {
866
-        if (! EE_Form_Section_Proper::$_scripts_localized) {
867
-            $this->_enqueue_and_localize_form_js();
868
-        }
869
-    }
870
-
871
-
872
-    /**
873
-     * Gets the hard-coded validation error messages to be used in the JS. The convention
874
-     * is that the key here should be the same as the custom validation rule put in the JS file
875
-     *
876
-     * @return array keys are custom validation rules, and values are internationalized strings
877
-     */
878
-    private static function _get_localized_error_messages()
879
-    {
880
-        return array(
881
-            'validUrl' => wp_strip_all_tags(__('This is not a valid absolute URL. Eg, http://domain.com/monkey.jpg', 'event_espresso')),
882
-            'regex'    => wp_strip_all_tags(__('Please check your input', 'event_espresso'))
883
-        );
884
-    }
885
-
886
-
887
-    /**
888
-     * @return array
889
-     */
890
-    public static function js_localization()
891
-    {
892
-        return self::$_js_localization;
893
-    }
894
-
895
-
896
-    /**
897
-     * @return void
898
-     */
899
-    public static function reset_js_localization()
900
-    {
901
-        self::$_js_localization = array();
902
-    }
903
-
904
-
905
-    /**
906
-     * Gets the JS to put inside the jquery validation rules for subsection of this form section.
907
-     * See parent function for more...
908
-     *
909
-     * @return array
910
-     * @throws EE_Error
911
-     */
912
-    public function get_jquery_validation_rules()
913
-    {
914
-        $jquery_validation_rules = array();
915
-        foreach ($this->get_validatable_subsections() as $subsection) {
916
-            $jquery_validation_rules = array_merge(
917
-                $jquery_validation_rules,
918
-                $subsection->get_jquery_validation_rules()
919
-            );
920
-        }
921
-        return $jquery_validation_rules;
922
-    }
923
-
924
-
925
-    /**
926
-     * Sanitizes all the data and sets the sanitized value of each field
927
-     *
928
-     * @param array $req_data
929
-     * @return void
930
-     * @throws EE_Error
931
-     */
932
-    protected function _normalize($req_data)
933
-    {
934
-        $this->_received_submission = true;
935
-        $this->_validation_errors   = array();
936
-        foreach ($this->get_validatable_subsections() as $subsection) {
937
-            try {
938
-                $subsection->_normalize($req_data);
939
-            } catch (EE_Validation_Error $e) {
940
-                $subsection->add_validation_error($e);
941
-            }
942
-        }
943
-    }
944
-
945
-
946
-    /**
947
-     * Performs validation on this form section and its subsections.
948
-     * For each subsection,
949
-     * calls _validate_{subsection_name} on THIS form (if the function exists)
950
-     * and passes it the subsection, then calls _validate on that subsection.
951
-     * If you need to perform validation on the form as a whole (considering multiple)
952
-     * you would be best to override this _validate method,
953
-     * calling parent::_validate() first.
954
-     *
955
-     * @throws EE_Error
956
-     */
957
-    protected function _validate()
958
-    {
959
-        // reset the cache of whether this form is valid or not- we're re-validating it now
960
-        $this->is_valid = null;
961
-        foreach ($this->get_validatable_subsections() as $subsection_name => $subsection) {
962
-            if (method_exists($this, '_validate_' . $subsection_name)) {
963
-                call_user_func_array(array($this, '_validate_' . $subsection_name), array($subsection));
964
-            }
965
-            $subsection->_validate();
966
-        }
967
-    }
968
-
969
-
970
-    /**
971
-     * Gets all the validated inputs for the form section
972
-     *
973
-     * @return array
974
-     * @throws EE_Error
975
-     */
976
-    public function valid_data()
977
-    {
978
-        $inputs = array();
979
-        foreach ($this->subsections() as $subsection_name => $subsection) {
980
-            if ($subsection instanceof EE_Form_Section_Proper) {
981
-                $inputs[ $subsection_name ] = $subsection->valid_data();
982
-            } elseif ($subsection instanceof EE_Form_Input_Base) {
983
-                $inputs[ $subsection_name ] = $subsection->normalized_value();
984
-            }
985
-        }
986
-        return $inputs;
987
-    }
988
-
989
-
990
-    /**
991
-     * Gets all the inputs on this form section
992
-     *
993
-     * @return EE_Form_Input_Base[]
994
-     * @throws EE_Error
995
-     */
996
-    public function inputs()
997
-    {
998
-        $inputs = array();
999
-        foreach ($this->subsections() as $subsection_name => $subsection) {
1000
-            if ($subsection instanceof EE_Form_Input_Base) {
1001
-                $inputs[ $subsection_name ] = $subsection;
1002
-            }
1003
-        }
1004
-        return $inputs;
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Gets all the subsections which are a proper form
1010
-     *
1011
-     * @return EE_Form_Section_Proper[]
1012
-     * @throws EE_Error
1013
-     */
1014
-    public function subforms()
1015
-    {
1016
-        $form_sections = array();
1017
-        foreach ($this->subsections() as $name => $obj) {
1018
-            if ($obj instanceof EE_Form_Section_Proper) {
1019
-                $form_sections[ $name ] = $obj;
1020
-            }
1021
-        }
1022
-        return $form_sections;
1023
-    }
1024
-
1025
-
1026
-    /**
1027
-     * Gets all the subsections (inputs, proper subsections, or html-only sections).
1028
-     * Consider using inputs() or subforms()
1029
-     * if you only want form inputs or proper form sections.
1030
-     *
1031
-     * @param boolean $require_construction_to_be_finalized most client code should
1032
-     *                                                      leave this as TRUE so that the inputs will be properly
1033
-     *                                                      configured. However, some client code may be ok with
1034
-     *                                                      construction finalize being called later
1035
-     *                                                      (realizing that the subsections' html names might not be
1036
-     *                                                      set yet, etc.)
1037
-     * @return EE_Form_Section_Proper[]
1038
-     * @throws EE_Error
1039
-     */
1040
-    public function subsections($require_construction_to_be_finalized = true)
1041
-    {
1042
-        if ($require_construction_to_be_finalized) {
1043
-            $this->ensure_construct_finalized_called();
1044
-        }
1045
-        return $this->_subsections;
1046
-    }
1047
-
1048
-
1049
-    /**
1050
-     * Returns whether this form has any subforms or inputs
1051
-     * @return bool
1052
-     */
1053
-    public function hasSubsections()
1054
-    {
1055
-        return ! empty($this->_subsections);
1056
-    }
1057
-
1058
-
1059
-    /**
1060
-     * Returns a simple array where keys are input names, and values are their normalized
1061
-     * values. (Similar to calling get_input_value on inputs)
1062
-     *
1063
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1064
-     *                                        or just this forms' direct children inputs
1065
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1066
-     *                                        or allow multidimensional array
1067
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array
1068
-     *                                        with array keys being input names
1069
-     *                                        (regardless of whether they are from a subsection or not),
1070
-     *                                        and if $flatten is FALSE it can be a multidimensional array
1071
-     *                                        where keys are always subsection names and values are either
1072
-     *                                        the input's normalized value, or an array like the top-level array
1073
-     * @throws EE_Error
1074
-     */
1075
-    public function input_values($include_subform_inputs = false, $flatten = false)
1076
-    {
1077
-        return $this->_input_values(false, $include_subform_inputs, $flatten);
1078
-    }
1079
-
1080
-
1081
-    /**
1082
-     * Similar to EE_Form_Section_Proper::input_values(), except this returns the 'display_value'
1083
-     * of each input. On some inputs (especially radio boxes or checkboxes), the value stored
1084
-     * is not necessarily the value we want to display to users. This creates an array
1085
-     * where keys are the input names, and values are their display values
1086
-     *
1087
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1088
-     *                                        or just this forms' direct children inputs
1089
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1090
-     *                                        or allow multidimensional array
1091
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array
1092
-     *                                        with array keys being input names
1093
-     *                                        (regardless of whether they are from a subsection or not),
1094
-     *                                        and if $flatten is FALSE it can be a multidimensional array
1095
-     *                                        where keys are always subsection names and values are either
1096
-     *                                        the input's normalized value, or an array like the top-level array
1097
-     * @throws EE_Error
1098
-     */
1099
-    public function input_pretty_values($include_subform_inputs = false, $flatten = false)
1100
-    {
1101
-        return $this->_input_values(true, $include_subform_inputs, $flatten);
1102
-    }
1103
-
1104
-
1105
-    /**
1106
-     * Gets the input values from the form
1107
-     *
1108
-     * @param boolean $pretty                 Whether to retrieve the pretty value,
1109
-     *                                        or just the normalized value
1110
-     * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1111
-     *                                        or just this forms' direct children inputs
1112
-     * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1113
-     *                                        or allow multidimensional array
1114
-     * @return array if $flatten is TRUE it will always be a 1-dimensional array with array keys being
1115
-     *                                        input names (regardless of whether they are from a subsection or not),
1116
-     *                                        and if $flatten is FALSE it can be a multidimensional array
1117
-     *                                        where keys are always subsection names and values are either
1118
-     *                                        the input's normalized value, or an array like the top-level array
1119
-     * @throws EE_Error
1120
-     */
1121
-    public function _input_values($pretty = false, $include_subform_inputs = false, $flatten = false)
1122
-    {
1123
-        $input_values = array();
1124
-        foreach ($this->subsections() as $subsection_name => $subsection) {
1125
-            if ($subsection instanceof EE_Form_Input_Base) {
1126
-                $input_values[ $subsection_name ] = $pretty
1127
-                    ? $subsection->pretty_value()
1128
-                    : $subsection->normalized_value();
1129
-            } elseif ($subsection instanceof EE_Form_Section_Proper && $include_subform_inputs) {
1130
-                $subform_input_values = $subsection->_input_values(
1131
-                    $pretty,
1132
-                    $include_subform_inputs,
1133
-                    $flatten
1134
-                );
1135
-                if ($flatten) {
1136
-                    $input_values = array_merge($input_values, $subform_input_values);
1137
-                } else {
1138
-                    $input_values[ $subsection_name ] = $subform_input_values;
1139
-                }
1140
-            }
1141
-        }
1142
-        return $input_values;
1143
-    }
1144
-
1145
-
1146
-    /**
1147
-     * Gets the originally submitted input values from the form
1148
-     *
1149
-     * @param boolean $include_subforms  Whether to include inputs from subforms,
1150
-     *                                   or just this forms' direct children inputs
1151
-     * @return array                     if $flatten is TRUE it will always be a 1-dimensional array
1152
-     *                                   with array keys being input names
1153
-     *                                   (regardless of whether they are from a subsection or not),
1154
-     *                                   and if $flatten is FALSE it can be a multidimensional array
1155
-     *                                   where keys are always subsection names and values are either
1156
-     *                                   the input's normalized value, or an array like the top-level array
1157
-     * @throws EE_Error
1158
-     */
1159
-    public function submitted_values($include_subforms = false)
1160
-    {
1161
-        $submitted_values = array();
1162
-        foreach ($this->subsections() as $subsection) {
1163
-            if ($subsection instanceof EE_Form_Input_Base) {
1164
-                // is this input part of an array of inputs?
1165
-                if (strpos($subsection->html_name(), '[') !== false) {
1166
-                    $full_input_name  = EEH_Array::convert_array_values_to_keys(
1167
-                        explode(
1168
-                            '[',
1169
-                            str_replace(']', '', $subsection->html_name())
1170
-                        ),
1171
-                        $subsection->raw_value()
1172
-                    );
1173
-                    $submitted_values = array_replace_recursive($submitted_values, $full_input_name);
1174
-                } else {
1175
-                    $submitted_values[ $subsection->html_name() ] = $subsection->raw_value();
1176
-                }
1177
-            } elseif ($subsection instanceof EE_Form_Section_Proper && $include_subforms) {
1178
-                $subform_input_values = $subsection->submitted_values($include_subforms);
1179
-                $submitted_values     = array_replace_recursive($submitted_values, $subform_input_values);
1180
-            }
1181
-        }
1182
-        return $submitted_values;
1183
-    }
1184
-
1185
-
1186
-    /**
1187
-     * Indicates whether or not this form has received a submission yet
1188
-     * (ie, had receive_form_submission called on it yet)
1189
-     *
1190
-     * @return boolean
1191
-     * @throws EE_Error
1192
-     */
1193
-    public function has_received_submission()
1194
-    {
1195
-        $this->ensure_construct_finalized_called();
1196
-        return $this->_received_submission;
1197
-    }
1198
-
1199
-
1200
-    /**
1201
-     * Equivalent to passing 'exclude' in the constructor's options array.
1202
-     * Removes the listed inputs from the form
1203
-     *
1204
-     * @param array $inputs_to_exclude values are the input names
1205
-     * @return void
1206
-     */
1207
-    public function exclude(array $inputs_to_exclude = array())
1208
-    {
1209
-        foreach ($inputs_to_exclude as $input_to_exclude_name) {
1210
-            unset($this->_subsections[ $input_to_exclude_name ]);
1211
-        }
1212
-    }
1213
-
1214
-
1215
-    /**
1216
-     * Changes these inputs' display strategy to be EE_Hidden_Display_Strategy.
1217
-     * @param array $inputs_to_hide
1218
-     * @throws EE_Error
1219
-     */
1220
-    public function hide(array $inputs_to_hide = array())
1221
-    {
1222
-        foreach ($inputs_to_hide as $input_to_hide) {
1223
-            $input = $this->get_input($input_to_hide);
1224
-            $input->set_display_strategy(new EE_Hidden_Display_Strategy());
1225
-        }
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * add_subsections
1231
-     * Adds the listed subsections to the form section.
1232
-     * If $subsection_name_to_target is provided,
1233
-     * then new subsections are added before or after that subsection,
1234
-     * otherwise to the start or end of the entire subsections array.
1235
-     *
1236
-     * @param EE_Form_Section_Base[] $new_subsections           array of new form subsections
1237
-     *                                                          where keys are their names
1238
-     * @param string                 $subsection_name_to_target an existing for section that $new_subsections
1239
-     *                                                          should be added before or after
1240
-     *                                                          IF $subsection_name_to_target is null,
1241
-     *                                                          then $new_subsections will be added to
1242
-     *                                                          the beginning or end of the entire subsections array
1243
-     * @param boolean                $add_before                whether to add $new_subsections, before or after
1244
-     *                                                          $subsection_name_to_target,
1245
-     *                                                          or if $subsection_name_to_target is null,
1246
-     *                                                          before or after entire subsections array
1247
-     * @return void
1248
-     * @throws EE_Error
1249
-     */
1250
-    public function add_subsections($new_subsections, $subsection_name_to_target = null, $add_before = true)
1251
-    {
1252
-        foreach ($new_subsections as $subsection_name => $subsection) {
1253
-            if (! $subsection instanceof EE_Form_Section_Base) {
1254
-                EE_Error::add_error(
1255
-                    sprintf(
1256
-                        esc_html__(
1257
-                            "Trying to add a %s as a subsection (it was named '%s') to the form section '%s'. It was removed.",
1258
-                            'event_espresso'
1259
-                        ),
1260
-                        get_class($subsection),
1261
-                        $subsection_name,
1262
-                        $this->name()
1263
-                    )
1264
-                );
1265
-                unset($new_subsections[ $subsection_name ]);
1266
-            }
1267
-        }
1268
-        $this->_subsections = EEH_Array::insert_into_array(
1269
-            $this->_subsections,
1270
-            $new_subsections,
1271
-            $subsection_name_to_target,
1272
-            $add_before
1273
-        );
1274
-        if ($this->_construction_finalized) {
1275
-            foreach ($this->_subsections as $name => $subsection) {
1276
-                $subsection->_construct_finalize($this, $name);
1277
-            }
1278
-        }
1279
-    }
1280
-
1281
-
1282
-    /**
1283
-     * @param string $subsection_name
1284
-     * @param bool   $recursive
1285
-     * @return bool
1286
-     */
1287
-    public function has_subsection($subsection_name, $recursive = false)
1288
-    {
1289
-        foreach ($this->_subsections as $name => $subsection) {
1290
-            if (
1291
-                $name === $subsection_name
1292
-                || (
1293
-                    $recursive
1294
-                    && $subsection instanceof EE_Form_Section_Proper
1295
-                    && $subsection->has_subsection($subsection_name, $recursive)
1296
-                )
1297
-            ) {
1298
-                return true;
1299
-            }
1300
-        }
1301
-        return false;
1302
-    }
1303
-
1304
-
1305
-
1306
-    /**
1307
-     * Just gets all validatable subsections to clean their sensitive data
1308
-     *
1309
-     * @throws EE_Error
1310
-     */
1311
-    public function clean_sensitive_data()
1312
-    {
1313
-        foreach ($this->get_validatable_subsections() as $subsection) {
1314
-            $subsection->clean_sensitive_data();
1315
-        }
1316
-    }
1317
-
1318
-
1319
-    /**
1320
-     * Sets the submission error message (aka validation error message for this form section and all sub-sections)
1321
-     * @param string                           $form_submission_error_message
1322
-     * @param EE_Form_Section_Validatable $form_section unused
1323
-     * @throws EE_Error
1324
-     */
1325
-    public function set_submission_error_message(
1326
-        $form_submission_error_message = ''
1327
-    ) {
1328
-        $this->_form_submission_error_message = ! empty($form_submission_error_message)
1329
-            ? $form_submission_error_message
1330
-            : $this->getAllValidationErrorsString();
1331
-    }
1332
-
1333
-
1334
-    /**
1335
-     * Returns the cached error message. A default value is set for this during _validate(),
1336
-     * (called during receive_form_submission) but it can be explicitly set using
1337
-     * set_submission_error_message
1338
-     *
1339
-     * @return string
1340
-     */
1341
-    public function submission_error_message()
1342
-    {
1343
-        return $this->_form_submission_error_message;
1344
-    }
1345
-
1346
-
1347
-    /**
1348
-     * Sets a message to display if the data submitted to the form was valid.
1349
-     * @param string $form_submission_success_message
1350
-     */
1351
-    public function set_submission_success_message($form_submission_success_message = '')
1352
-    {
1353
-        $this->_form_submission_success_message = ! empty($form_submission_success_message)
1354
-            ? $form_submission_success_message
1355
-            : esc_html__('Form submitted successfully', 'event_espresso');
1356
-    }
1357
-
1358
-
1359
-    /**
1360
-     * Gets a message appropriate for display when the form is correctly submitted
1361
-     * @return string
1362
-     */
1363
-    public function submission_success_message()
1364
-    {
1365
-        return $this->_form_submission_success_message;
1366
-    }
1367
-
1368
-
1369
-    /**
1370
-     * Returns the prefix that should be used on child of this form section for
1371
-     * their html names. If this form section itself has a parent, prepends ITS
1372
-     * prefix onto this form section's prefix. Used primarily by
1373
-     * EE_Form_Input_Base::_set_default_html_name_if_empty
1374
-     *
1375
-     * @return string
1376
-     * @throws EE_Error
1377
-     */
1378
-    public function html_name_prefix()
1379
-    {
1380
-        if ($this->parent_section() instanceof EE_Form_Section_Proper) {
1381
-            return $this->parent_section()->html_name_prefix() . '[' . $this->name() . ']';
1382
-        }
1383
-        return $this->name();
1384
-    }
1385
-
1386
-
1387
-    /**
1388
-     * Gets the name, but first checks _construct_finalize has been called. If not,
1389
-     * calls it (assumes there is no parent and that we want the name to be whatever
1390
-     * was set, which is probably nothing, or the classname)
1391
-     *
1392
-     * @return string
1393
-     * @throws EE_Error
1394
-     */
1395
-    public function name()
1396
-    {
1397
-        $this->ensure_construct_finalized_called();
1398
-        return parent::name();
1399
-    }
1400
-
1401
-
1402
-    /**
1403
-     * @return EE_Form_Section_Proper
1404
-     * @throws EE_Error
1405
-     */
1406
-    public function parent_section()
1407
-    {
1408
-        $this->ensure_construct_finalized_called();
1409
-        return parent::parent_section();
1410
-    }
1411
-
1412
-
1413
-    /**
1414
-     * make sure construction finalized was called, otherwise children might not be ready
1415
-     *
1416
-     * @return void
1417
-     * @throws EE_Error
1418
-     */
1419
-    public function ensure_construct_finalized_called()
1420
-    {
1421
-        if (! $this->_construction_finalized) {
1422
-            $this->_construct_finalize($this->_parent_section, $this->_name);
1423
-        }
1424
-    }
1425
-
1426
-
1427
-    /**
1428
-     * Checks if any of this form section's inputs, or any of its children's inputs,
1429
-     * are in teh form data. If any are found, returns true. Else false
1430
-     *
1431
-     * @param array $req_data
1432
-     * @return boolean
1433
-     * @throws EE_Error
1434
-     */
1435
-    public function form_data_present_in($req_data = null)
1436
-    {
1437
-        $req_data = $this->getCachedRequest($req_data);
1438
-        foreach ($this->subsections() as $subsection) {
1439
-            if ($subsection instanceof EE_Form_Input_Base) {
1440
-                if ($subsection->form_data_present_in($req_data)) {
1441
-                    return true;
1442
-                }
1443
-            } elseif ($subsection instanceof EE_Form_Section_Proper) {
1444
-                if ($subsection->form_data_present_in($req_data)) {
1445
-                    return true;
1446
-                }
1447
-            }
1448
-        }
1449
-        return false;
1450
-    }
1451
-
1452
-
1453
-    /**
1454
-     * Gets validation errors for this form section and subsections
1455
-     * Similar to EE_Form_Section_Validatable::get_validation_errors() except this
1456
-     * gets the validation errors for ALL subsection
1457
-     *
1458
-     * @return EE_Validation_Error[]
1459
-     * @throws EE_Error
1460
-     */
1461
-    public function get_validation_errors_accumulated()
1462
-    {
1463
-        $validation_errors = $this->get_validation_errors();
1464
-        foreach ($this->get_validatable_subsections() as $subsection) {
1465
-            if ($subsection instanceof EE_Form_Section_Proper) {
1466
-                $validation_errors_on_this_subsection = $subsection->get_validation_errors_accumulated();
1467
-            } else {
1468
-                $validation_errors_on_this_subsection = $subsection->get_validation_errors();
1469
-            }
1470
-            if ($validation_errors_on_this_subsection) {
1471
-                $validation_errors = array_merge($validation_errors, $validation_errors_on_this_subsection);
1472
-            }
1473
-        }
1474
-        return $validation_errors;
1475
-    }
1476
-
1477
-    /**
1478
-     * Fetch validation errors from children and grandchildren and puts them in a single string.
1479
-     * This traverses the form section tree to generate this, but you probably want to instead use
1480
-     * get_form_submission_error_message() which is usually this message cached (or a custom validation error message)
1481
-     *
1482
-     * @return string
1483
-     * @since 4.9.59.p
1484
-     */
1485
-    protected function getAllValidationErrorsString()
1486
-    {
1487
-        $submission_error_messages = array();
1488
-        // bad, bad, bad registrant
1489
-        foreach ($this->get_validation_errors_accumulated() as $validation_error) {
1490
-            if ($validation_error instanceof EE_Validation_Error) {
1491
-                $form_section = $validation_error->get_form_section();
1492
-                if ($form_section instanceof EE_Form_Input_Base) {
1493
-                    $label = $validation_error->get_form_section()->html_label_text();
1494
-                } elseif ($form_section instanceof EE_Form_Section_Validatable) {
1495
-                    $label = $validation_error->get_form_section()->name();
1496
-                } else {
1497
-                    $label = esc_html__('Unknown', 'event_espresso');
1498
-                }
1499
-                $submission_error_messages[] = sprintf(
1500
-                    esc_html__('%s : %s', 'event_espresso'),
1501
-                    $label,
1502
-                    $validation_error->getMessage()
1503
-                );
1504
-            }
1505
-        }
1506
-        return implode('<br>', $submission_error_messages);
1507
-    }
1508
-
1509
-
1510
-    /**
1511
-     * This isn't just the name of an input, it's a path pointing to an input. The
1512
-     * path is similar to a folder path: slash (/) means to descend into a subsection,
1513
-     * dot-dot-slash (../) means to ascend into the parent section.
1514
-     * After a series of slashes and dot-dot-slashes, there should be the name of an input,
1515
-     * which will be returned.
1516
-     * Eg, if you want the related input to be conditional on a sibling input name 'foobar'
1517
-     * just use 'foobar'. If you want it to be conditional on an aunt/uncle input name
1518
-     * 'baz', use '../baz'. If you want it to be conditional on a cousin input,
1519
-     * the child of 'baz_section' named 'baz_child', use '../baz_section/baz_child'.
1520
-     * Etc
1521
-     *
1522
-     * @param string|false $form_section_path we accept false also because substr( '../', '../' ) = false
1523
-     * @return EE_Form_Section_Base
1524
-     * @throws EE_Error
1525
-     */
1526
-    public function find_section_from_path($form_section_path)
1527
-    {
1528
-        // check if we can find the input from purely going straight up the tree
1529
-        $input = parent::find_section_from_path($form_section_path);
1530
-        if ($input instanceof EE_Form_Section_Base) {
1531
-            return $input;
1532
-        }
1533
-        $next_slash_pos = strpos($form_section_path, '/');
1534
-        if ($next_slash_pos !== false) {
1535
-            $child_section_name = substr($form_section_path, 0, $next_slash_pos);
1536
-            $subpath            = substr($form_section_path, $next_slash_pos + 1);
1537
-        } else {
1538
-            $child_section_name = $form_section_path;
1539
-            $subpath            = '';
1540
-        }
1541
-        $child_section = $this->get_subsection($child_section_name);
1542
-        if ($child_section instanceof EE_Form_Section_Base) {
1543
-            return $child_section->find_section_from_path($subpath);
1544
-        }
1545
-        return null;
1546
-    }
19
+	const SUBMITTED_FORM_DATA_SSN_KEY = 'submitted_form_data';
20
+
21
+	/**
22
+	 * Subsections
23
+	 *
24
+	 * @var EE_Form_Section_Validatable[]
25
+	 */
26
+	protected $_subsections = array();
27
+
28
+	/**
29
+	 * Strategy for laying out the form
30
+	 *
31
+	 * @var EE_Form_Section_Layout_Base
32
+	 */
33
+	protected $_layout_strategy;
34
+
35
+	/**
36
+	 * Whether or not this form has received and validated a form submission yet
37
+	 *
38
+	 * @var boolean
39
+	 */
40
+	protected $_received_submission = false;
41
+
42
+	/**
43
+	 * message displayed to users upon successful form submission
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $_form_submission_success_message = '';
48
+
49
+	/**
50
+	 * message displayed to users upon unsuccessful form submission
51
+	 *
52
+	 * @var string
53
+	 */
54
+	protected $_form_submission_error_message = '';
55
+
56
+	/**
57
+	 * @var array like post / request
58
+	 */
59
+	protected $cached_request_data;
60
+
61
+	/**
62
+	 * Stores whether this form (and its sub-sections) were found to be valid or not.
63
+	 * Starts off as null, but once the form is validated, it set to either true or false
64
+	 * @var boolean|null
65
+	 */
66
+	protected $is_valid;
67
+
68
+	/**
69
+	 * Stores all the data that will localized for form validation
70
+	 *
71
+	 * @var array
72
+	 */
73
+	protected static $_js_localization = array();
74
+
75
+	/**
76
+	 * whether or not the form's localized validation JS vars have been set
77
+	 *
78
+	 * @type boolean
79
+	 */
80
+	protected static $_scripts_localized = false;
81
+
82
+
83
+	/**
84
+	 * when constructing a proper form section, calls _construct_finalize on children
85
+	 * so that they know who their parent is, and what name they've been given.
86
+	 *
87
+	 * @param array[] $options_array   {
88
+	 * @type          $subsections     EE_Form_Section_Validatable[] where keys are the section's name
89
+	 * @type          $include         string[] numerically-indexed where values are section names to be included,
90
+	 *                                 and in that order. This is handy if you want
91
+	 *                                 the subsections to be ordered differently than the default, and if you override
92
+	 *                                 which fields are shown
93
+	 * @type          $exclude         string[] values are subsections to be excluded. This is handy if you want
94
+	 *                                 to remove certain default subsections (note: if you specify BOTH 'include' AND
95
+	 *                                 'exclude', the inclusions will be applied first, and the exclusions will exclude
96
+	 *                                 items from that list of inclusions)
97
+	 * @type          $layout_strategy EE_Form_Section_Layout_Base strategy for laying out the form
98
+	 *                                 } @see EE_Form_Section_Validatable::__construct()
99
+	 * @throws EE_Error
100
+	 */
101
+	public function __construct($options_array = array())
102
+	{
103
+		$options_array = (array) apply_filters(
104
+			'FHEE__EE_Form_Section_Proper___construct__options_array',
105
+			$options_array,
106
+			$this
107
+		);
108
+		// call parent first, as it may be setting the name
109
+		parent::__construct($options_array);
110
+		// if they've included subsections in the constructor, add them now
111
+		if (isset($options_array['include'])) {
112
+			// we are going to make sure we ONLY have those subsections to include
113
+			// AND we are going to make sure they're in that specified order
114
+			$reordered_subsections = array();
115
+			foreach ($options_array['include'] as $input_name) {
116
+				if (isset($this->_subsections[ $input_name ])) {
117
+					$reordered_subsections[ $input_name ] = $this->_subsections[ $input_name ];
118
+				}
119
+			}
120
+			$this->_subsections = $reordered_subsections;
121
+		}
122
+		if (isset($options_array['exclude'])) {
123
+			$exclude            = $options_array['exclude'];
124
+			$this->_subsections = array_diff_key($this->_subsections, array_flip($exclude));
125
+		}
126
+		if (isset($options_array['layout_strategy'])) {
127
+			$this->_layout_strategy = $options_array['layout_strategy'];
128
+		}
129
+		if (! $this->_layout_strategy) {
130
+			$this->_layout_strategy = is_admin() ? new EE_Admin_Two_Column_Layout() : new EE_Two_Column_Layout();
131
+		}
132
+		$this->_layout_strategy->_construct_finalize($this);
133
+		// ok so we are definitely going to want the forms JS,
134
+		// so enqueue it or remember to enqueue it during wp_enqueue_scripts
135
+		if (did_action('wp_enqueue_scripts') || did_action('admin_enqueue_scripts')) {
136
+			// ok so they've constructed this object after when they should have.
137
+			// just enqueue the generic form scripts and initialize the form immediately in the JS
138
+			EE_Form_Section_Proper::wp_enqueue_scripts(true);
139
+		} else {
140
+			add_action('wp_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
141
+			add_action('admin_enqueue_scripts', array('EE_Form_Section_Proper', 'wp_enqueue_scripts'));
142
+		}
143
+		add_action('wp_footer', array($this, 'ensure_scripts_localized'), 1);
144
+		/**
145
+		 * Gives other plugins a chance to hook in before construct finalize is called.
146
+		 * The form probably doesn't yet have a parent form section.
147
+		 * Since 4.9.32, when this action was introduced, this is the best place to add a subsection onto a form,
148
+		 * assuming you don't care what the form section's name, HTML ID, or HTML name etc are.
149
+		 * Also see AHEE__EE_Form_Section_Proper___construct_finalize__end
150
+		 *
151
+		 * @since 4.9.32
152
+		 * @param EE_Form_Section_Proper $this          before __construct is done, but all of its logic,
153
+		 *                                              except maybe calling _construct_finalize has been done
154
+		 * @param array                  $options_array options passed into the constructor
155
+		 */
156
+		do_action(
157
+			'AHEE__EE_Form_Input_Base___construct__before_construct_finalize_called',
158
+			$this,
159
+			$options_array
160
+		);
161
+		if (isset($options_array['name'])) {
162
+			$this->_construct_finalize(null, $options_array['name']);
163
+		}
164
+	}
165
+
166
+
167
+	/**
168
+	 * Finishes construction given the parent form section and this form section's name
169
+	 *
170
+	 * @param EE_Form_Section_Proper $parent_form_section
171
+	 * @param string                 $name
172
+	 * @throws EE_Error
173
+	 */
174
+	public function _construct_finalize($parent_form_section, $name)
175
+	{
176
+		parent::_construct_finalize($parent_form_section, $name);
177
+		$this->_set_default_name_if_empty();
178
+		$this->_set_default_html_id_if_empty();
179
+		foreach ($this->_subsections as $subsection_name => $subsection) {
180
+			if ($subsection instanceof EE_Form_Section_Base) {
181
+				$subsection->_construct_finalize($this, $subsection_name);
182
+			} else {
183
+				throw new EE_Error(
184
+					sprintf(
185
+						esc_html__(
186
+							'Subsection "%s" is not an instanceof EE_Form_Section_Base on form "%s". It is a "%s"',
187
+							'event_espresso'
188
+						),
189
+						$subsection_name,
190
+						get_class($this),
191
+						$subsection ? get_class($subsection) : esc_html__('NULL', 'event_espresso')
192
+					)
193
+				);
194
+			}
195
+		}
196
+		/**
197
+		 * Action performed just after form has been given a name (and HTML ID etc) and is fully constructed.
198
+		 * If you have code that should modify the form and needs it and its subsections to have a name, HTML ID
199
+		 * (or other attributes derived from the name like the HTML label id, etc), this is where it should be done.
200
+		 * This might only happen just before displaying the form, or just before it receives form submission data.
201
+		 * If you need to modify the form or its subsections before _construct_finalize is called on it (and we've
202
+		 * ensured it has a name, HTML IDs, etc
203
+		 *
204
+		 * @param EE_Form_Section_Proper      $this
205
+		 * @param EE_Form_Section_Proper|null $parent_form_section
206
+		 * @param string                      $name
207
+		 */
208
+		do_action(
209
+			'AHEE__EE_Form_Section_Proper___construct_finalize__end',
210
+			$this,
211
+			$parent_form_section,
212
+			$name
213
+		);
214
+	}
215
+
216
+
217
+	/**
218
+	 * Gets the layout strategy for this form section
219
+	 *
220
+	 * @return EE_Form_Section_Layout_Base
221
+	 */
222
+	public function get_layout_strategy()
223
+	{
224
+		return $this->_layout_strategy;
225
+	}
226
+
227
+
228
+	/**
229
+	 * Gets the HTML for a single input for this form section according
230
+	 * to the layout strategy
231
+	 *
232
+	 * @param EE_Form_Input_Base $input
233
+	 * @return string
234
+	 */
235
+	public function get_html_for_input($input)
236
+	{
237
+		return $this->_layout_strategy->layout_input($input);
238
+	}
239
+
240
+
241
+	/**
242
+	 * was_submitted - checks if form inputs are present in request data
243
+	 * Basically an alias for form_data_present_in() (which is used by both
244
+	 * proper form sections and form inputs)
245
+	 *
246
+	 * @param null $form_data
247
+	 * @return boolean
248
+	 * @throws EE_Error
249
+	 */
250
+	public function was_submitted($form_data = null)
251
+	{
252
+		return $this->form_data_present_in($form_data);
253
+	}
254
+
255
+	/**
256
+	 * Gets the cached request data; but if there is none, or $req_data was set with
257
+	 * something different, refresh the cache, and then return it
258
+	 * @param null $req_data
259
+	 * @return array
260
+	 */
261
+	protected function getCachedRequest($req_data = null)
262
+	{
263
+		if (
264
+			$this->cached_request_data === null
265
+			|| (
266
+				$req_data !== null
267
+				&& $req_data !== $this->cached_request_data
268
+			)
269
+		) {
270
+			$req_data = apply_filters(
271
+				'FHEE__EE_Form_Section_Proper__receive_form_submission__req_data',
272
+				$req_data,
273
+				$this
274
+			);
275
+			if ($req_data === null) {
276
+				/** @var RequestInterface $request */
277
+				$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
278
+				$req_data = $request->requestParams();
279
+			}
280
+			$req_data = apply_filters(
281
+				'FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
282
+				$req_data,
283
+				$this
284
+			);
285
+			$this->cached_request_data = (array) $req_data;
286
+		}
287
+		return $this->cached_request_data;
288
+	}
289
+
290
+
291
+	/**
292
+	 * After the form section is initially created, call this to sanitize the data in the submission
293
+	 * which relates to this form section, validate it, and set it as properties on the form.
294
+	 *
295
+	 * @param array|null $req_data should usually be post data (the default).
296
+	 *                             However, you CAN supply a different array.
297
+	 *                             Consider using set_defaults() instead however.
298
+	 *                             (If you rendered the form in the page using $form_x->get_html()
299
+	 *                             the inputs will have the correct name in the request data for this function
300
+	 *                             to find them and populate the form with them.
301
+	 *                             If you have a flat form (with only input subsections),
302
+	 *                             you can supply a flat array where keys
303
+	 *                             are the form input names and values are their values)
304
+	 * @param boolean    $validate whether or not to perform validation on this data. Default is,
305
+	 *                             of course, to validate that data, and set errors on the invalid values.
306
+	 *                             But if the data has already been validated
307
+	 *                             (eg you validated the data then stored it in the DB)
308
+	 *                             you may want to skip this step.
309
+	 * @throws InvalidArgumentException
310
+	 * @throws InvalidInterfaceException
311
+	 * @throws InvalidDataTypeException
312
+	 * @throws EE_Error
313
+	 */
314
+	public function receive_form_submission($req_data = null, $validate = true)
315
+	{
316
+		$req_data = $this->getCachedRequest($req_data);
317
+		$this->_normalize($req_data);
318
+		if ($validate) {
319
+			$this->_validate();
320
+			// if it's invalid, we're going to want to re-display so remember what they submitted
321
+			if (! $this->is_valid()) {
322
+				$this->store_submitted_form_data_in_session();
323
+			}
324
+		}
325
+		if ($this->submission_error_message() === '' && ! $this->is_valid()) {
326
+			$this->set_submission_error_message();
327
+		}
328
+		do_action(
329
+			'AHEE__EE_Form_Section_Proper__receive_form_submission__end',
330
+			$req_data,
331
+			$this,
332
+			$validate
333
+		);
334
+	}
335
+
336
+
337
+	/**
338
+	 * caches the originally submitted input values in the session
339
+	 * so that they can be used to repopulate the form if it failed validation
340
+	 *
341
+	 * @return boolean whether or not the data was successfully stored in the session
342
+	 * @throws InvalidArgumentException
343
+	 * @throws InvalidInterfaceException
344
+	 * @throws InvalidDataTypeException
345
+	 * @throws EE_Error
346
+	 */
347
+	protected function store_submitted_form_data_in_session()
348
+	{
349
+		return EE_Registry::instance()->SSN->set_session_data(
350
+			array(
351
+				EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY => $this->submitted_values(true),
352
+			)
353
+		);
354
+	}
355
+
356
+
357
+	/**
358
+	 * retrieves the originally submitted input values in the session
359
+	 * so that they can be used to repopulate the form if it failed validation
360
+	 *
361
+	 * @return array
362
+	 * @throws InvalidArgumentException
363
+	 * @throws InvalidInterfaceException
364
+	 * @throws InvalidDataTypeException
365
+	 */
366
+	protected function get_submitted_form_data_from_session()
367
+	{
368
+		$session = EE_Registry::instance()->SSN;
369
+		if ($session instanceof EE_Session) {
370
+			return $session->get_session_data(
371
+				EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY
372
+			);
373
+		}
374
+		return array();
375
+	}
376
+
377
+
378
+	/**
379
+	 * flushed the originally submitted input values from the session
380
+	 *
381
+	 * @return boolean whether or not the data was successfully removed from the session
382
+	 * @throws InvalidArgumentException
383
+	 * @throws InvalidInterfaceException
384
+	 * @throws InvalidDataTypeException
385
+	 */
386
+	public static function flush_submitted_form_data_from_session()
387
+	{
388
+		return EE_Registry::instance()->SSN->reset_data(
389
+			array(EE_Form_Section_Proper::SUBMITTED_FORM_DATA_SSN_KEY)
390
+		);
391
+	}
392
+
393
+
394
+	/**
395
+	 * Populates this form and its subsections with data from the session.
396
+	 * (Wrapper for EE_Form_Section_Proper::receive_form_submission, so it shows
397
+	 * validation errors when displaying too)
398
+	 * Returns true if the form was populated from the session, false otherwise
399
+	 *
400
+	 * @return boolean
401
+	 * @throws InvalidArgumentException
402
+	 * @throws InvalidInterfaceException
403
+	 * @throws InvalidDataTypeException
404
+	 * @throws EE_Error
405
+	 */
406
+	public function populate_from_session()
407
+	{
408
+		$form_data_in_session = $this->get_submitted_form_data_from_session();
409
+		if (empty($form_data_in_session)) {
410
+			return false;
411
+		}
412
+		$this->receive_form_submission($form_data_in_session);
413
+		add_action('shutdown', array('EE_Form_Section_Proper', 'flush_submitted_form_data_from_session'));
414
+		if ($this->form_data_present_in($form_data_in_session)) {
415
+			return true;
416
+		}
417
+		return false;
418
+	}
419
+
420
+
421
+	/**
422
+	 * Populates the default data for the form, given an array where keys are
423
+	 * the input names, and values are their values (preferably normalized to be their
424
+	 * proper PHP types, not all strings... although that should be ok too).
425
+	 * Proper subsections are sub-arrays, the key being the subsection's name, and
426
+	 * the value being an array formatted in teh same way
427
+	 *
428
+	 * @param array $default_data
429
+	 * @throws EE_Error
430
+	 */
431
+	public function populate_defaults($default_data)
432
+	{
433
+		foreach ($this->subsections(false) as $subsection_name => $subsection) {
434
+			if (isset($default_data[ $subsection_name ])) {
435
+				if ($subsection instanceof EE_Form_Input_Base) {
436
+					$subsection->set_default($default_data[ $subsection_name ]);
437
+				} elseif ($subsection instanceof EE_Form_Section_Proper) {
438
+					$subsection->populate_defaults($default_data[ $subsection_name ]);
439
+				}
440
+			}
441
+		}
442
+	}
443
+
444
+
445
+	/**
446
+	 * returns true if subsection exists
447
+	 *
448
+	 * @param string $name
449
+	 * @return boolean
450
+	 */
451
+	public function subsection_exists($name)
452
+	{
453
+		return isset($this->_subsections[ $name ]) ? true : false;
454
+	}
455
+
456
+
457
+	/**
458
+	 * Gets the subsection specified by its name
459
+	 *
460
+	 * @param string  $name
461
+	 * @param boolean $require_construction_to_be_finalized most client code should leave this as TRUE
462
+	 *                                                      so that the inputs will be properly configured.
463
+	 *                                                      However, some client code may be ok
464
+	 *                                                      with construction finalize being called later
465
+	 *                                                      (realizing that the subsections' html names
466
+	 *                                                      might not be set yet, etc.)
467
+	 * @return EE_Form_Section_Base
468
+	 * @throws EE_Error
469
+	 */
470
+	public function get_subsection($name, $require_construction_to_be_finalized = true)
471
+	{
472
+		if ($require_construction_to_be_finalized) {
473
+			$this->ensure_construct_finalized_called();
474
+		}
475
+		return $this->subsection_exists($name) ? $this->_subsections[ $name ] : null;
476
+	}
477
+
478
+
479
+	/**
480
+	 * Gets all the validatable subsections of this form section
481
+	 *
482
+	 * @return EE_Form_Section_Validatable[]
483
+	 * @throws EE_Error
484
+	 */
485
+	public function get_validatable_subsections()
486
+	{
487
+		$validatable_subsections = array();
488
+		foreach ($this->subsections() as $name => $obj) {
489
+			if ($obj instanceof EE_Form_Section_Validatable) {
490
+				$validatable_subsections[ $name ] = $obj;
491
+			}
492
+		}
493
+		return $validatable_subsections;
494
+	}
495
+
496
+
497
+	/**
498
+	 * Gets an input by the given name. If not found, or if its not an EE_FOrm_Input_Base child,
499
+	 * throw an EE_Error.
500
+	 *
501
+	 * @param string  $name
502
+	 * @param boolean $require_construction_to_be_finalized most client code should
503
+	 *                                                      leave this as TRUE so that the inputs will be properly
504
+	 *                                                      configured. However, some client code may be ok with
505
+	 *                                                      construction finalize being called later
506
+	 *                                                      (realizing that the subsections' html names might not be
507
+	 *                                                      set yet, etc.)
508
+	 * @return EE_Form_Input_Base
509
+	 * @throws EE_Error
510
+	 */
511
+	public function get_input($name, $require_construction_to_be_finalized = true)
512
+	{
513
+		$subsection = $this->get_subsection(
514
+			$name,
515
+			$require_construction_to_be_finalized
516
+		);
517
+		if (! $subsection instanceof EE_Form_Input_Base) {
518
+			throw new EE_Error(
519
+				sprintf(
520
+					esc_html__(
521
+						"Subsection '%s' is not an instanceof EE_Form_Input_Base on form '%s'. It is a '%s'",
522
+						'event_espresso'
523
+					),
524
+					$name,
525
+					get_class($this),
526
+					$subsection ? get_class($subsection) : esc_html__('NULL', 'event_espresso')
527
+				)
528
+			);
529
+		}
530
+		return $subsection;
531
+	}
532
+
533
+
534
+	/**
535
+	 * Like get_input(), gets the proper subsection of the form given the name,
536
+	 * otherwise throws an EE_Error
537
+	 *
538
+	 * @param string  $name
539
+	 * @param boolean $require_construction_to_be_finalized most client code should
540
+	 *                                                      leave this as TRUE so that the inputs will be properly
541
+	 *                                                      configured. However, some client code may be ok with
542
+	 *                                                      construction finalize being called later
543
+	 *                                                      (realizing that the subsections' html names might not be
544
+	 *                                                      set yet, etc.)
545
+	 * @return EE_Form_Section_Proper
546
+	 * @throws EE_Error
547
+	 */
548
+	public function get_proper_subsection($name, $require_construction_to_be_finalized = true)
549
+	{
550
+		$subsection = $this->get_subsection(
551
+			$name,
552
+			$require_construction_to_be_finalized
553
+		);
554
+		if (! $subsection instanceof EE_Form_Section_Proper) {
555
+			throw new EE_Error(
556
+				sprintf(
557
+					esc_html__(
558
+						"Subsection '%'s is not an instanceof EE_Form_Section_Proper on form '%s'",
559
+						'event_espresso'
560
+					),
561
+					$name,
562
+					get_class($this)
563
+				)
564
+			);
565
+		}
566
+		return $subsection;
567
+	}
568
+
569
+
570
+	/**
571
+	 * Gets the value of the specified input. Should be called after receive_form_submission()
572
+	 * or populate_defaults() on the form, where the normalized value on the input is set.
573
+	 *
574
+	 * @param string $name
575
+	 * @return mixed depending on the input's type and its normalization strategy
576
+	 * @throws EE_Error
577
+	 */
578
+	public function get_input_value($name)
579
+	{
580
+		$input = $this->get_input($name);
581
+		return $input->normalized_value();
582
+	}
583
+
584
+
585
+	/**
586
+	 * Checks if this form section itself is valid, and then checks its subsections
587
+	 *
588
+	 * @throws EE_Error
589
+	 * @return boolean
590
+	 */
591
+	public function is_valid()
592
+	{
593
+		if ($this->is_valid === null) {
594
+			if (! $this->has_received_submission()) {
595
+				throw new EE_Error(
596
+					sprintf(
597
+						esc_html__(
598
+							'You cannot check if a form is valid before receiving the form submission using receive_form_submission',
599
+							'event_espresso'
600
+						)
601
+					)
602
+				);
603
+			}
604
+			if (! parent::is_valid()) {
605
+				$this->is_valid = false;
606
+			} else {
607
+				// ok so no general errors to this entire form section.
608
+				// so let's check the subsections, but only set errors if that hasn't been done yet
609
+				$this->is_valid = true;
610
+				foreach ($this->get_validatable_subsections() as $subsection) {
611
+					if (! $subsection->is_valid()) {
612
+						$this->is_valid = false;
613
+					}
614
+				}
615
+			}
616
+		}
617
+		return $this->is_valid;
618
+	}
619
+
620
+
621
+	/**
622
+	 * gets the default name of this form section if none is specified
623
+	 *
624
+	 * @return void
625
+	 */
626
+	protected function _set_default_name_if_empty()
627
+	{
628
+		if (! $this->_name) {
629
+			$classname    = get_class($this);
630
+			$default_name = str_replace('EE_', '', $classname);
631
+			$this->_name  = $default_name;
632
+		}
633
+	}
634
+
635
+
636
+	/**
637
+	 * Returns the HTML for the form, except for the form opening and closing tags
638
+	 * (as the form section doesn't know where you necessarily want to send the information to),
639
+	 * and except for a submit button. Enqueues JS and CSS; if called early enough we will
640
+	 * try to enqueue them in the header, otherwise they'll be enqueued in the footer.
641
+	 * Not doing_it_wrong because theoretically this CAN be used properly,
642
+	 * provided its used during "wp_enqueue_scripts", or it doesn't need to enqueue
643
+	 * any CSS.
644
+	 *
645
+	 * @throws InvalidArgumentException
646
+	 * @throws InvalidInterfaceException
647
+	 * @throws InvalidDataTypeException
648
+	 * @throws EE_Error
649
+	 */
650
+	public function get_html_and_js()
651
+	{
652
+		$this->enqueue_js();
653
+		return $this->get_html();
654
+	}
655
+
656
+
657
+	/**
658
+	 * returns HTML for displaying this form section. recursively calls display_section() on all subsections
659
+	 *
660
+	 * @param bool $display_previously_submitted_data
661
+	 * @return string
662
+	 * @throws InvalidArgumentException
663
+	 * @throws InvalidInterfaceException
664
+	 * @throws InvalidDataTypeException
665
+	 * @throws EE_Error
666
+	 * @throws EE_Error
667
+	 * @throws EE_Error
668
+	 */
669
+	public function get_html($display_previously_submitted_data = true)
670
+	{
671
+		$this->ensure_construct_finalized_called();
672
+		if ($display_previously_submitted_data) {
673
+			$this->populate_from_session();
674
+		}
675
+		return $this->_form_html_filter
676
+			? $this->_form_html_filter->filterHtml($this->_layout_strategy->layout_form(), $this)
677
+			: $this->_layout_strategy->layout_form();
678
+	}
679
+
680
+
681
+	/**
682
+	 * enqueues JS and CSS for the form.
683
+	 * It is preferred to call this before wp_enqueue_scripts so the
684
+	 * scripts and styles can be put in the header, but if called later
685
+	 * they will be put in the footer (which is OK for JS, but in HTML4 CSS should
686
+	 * only be in the header; but in HTML5 its ok in the body.
687
+	 * See http://stackoverflow.com/questions/4957446/load-external-css-file-in-body-tag.
688
+	 * So if your form enqueues CSS, it's preferred to call this before wp_enqueue_scripts.)
689
+	 *
690
+	 * @return void
691
+	 * @throws EE_Error
692
+	 */
693
+	public function enqueue_js()
694
+	{
695
+		$this->_enqueue_and_localize_form_js();
696
+		foreach ($this->subsections() as $subsection) {
697
+			$subsection->enqueue_js();
698
+		}
699
+	}
700
+
701
+
702
+	/**
703
+	 * adds a filter so that jquery validate gets enqueued in EE_System::wp_enqueue_scripts().
704
+	 * This must be done BEFORE wp_enqueue_scripts() gets called, which is on
705
+	 * the wp_enqueue_scripts hook.
706
+	 * However, registering the form js and localizing it can happen when we
707
+	 * actually output the form (which is preferred, seeing how teh form's fields
708
+	 * could change until it's actually outputted)
709
+	 *
710
+	 * @param boolean $init_form_validation_automatically whether or not we want the form validation
711
+	 *                                                    to be triggered automatically or not
712
+	 * @return void
713
+	 */
714
+	public static function wp_enqueue_scripts($init_form_validation_automatically = true)
715
+	{
716
+		wp_register_script(
717
+			'ee_form_section_validation',
718
+			EE_GLOBAL_ASSETS_URL . 'scripts' . '/form_section_validation.js',
719
+			array('jquery-validate', 'jquery-ui-datepicker', 'jquery-validate-extra-methods'),
720
+			EVENT_ESPRESSO_VERSION,
721
+			true
722
+		);
723
+		wp_localize_script(
724
+			'ee_form_section_validation',
725
+			'ee_form_section_validation_init',
726
+			array('init' => $init_form_validation_automatically ? '1' : '0')
727
+		);
728
+	}
729
+
730
+
731
+	/**
732
+	 * gets the variables used by form_section_validation.js.
733
+	 * This needs to be called AFTER we've called $this->_enqueue_jquery_validate_script,
734
+	 * but before the wordpress hook wp_loaded
735
+	 *
736
+	 * @throws EE_Error
737
+	 */
738
+	public function _enqueue_and_localize_form_js()
739
+	{
740
+		$this->ensure_construct_finalized_called();
741
+		// actually, we don't want to localize just yet. There may be other forms on the page.
742
+		// so we need to add our form section data to a static variable accessible by all form sections
743
+		// and localize it just before the footer
744
+		$this->localize_validation_rules();
745
+		add_action('wp_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'), 2);
746
+		add_action('admin_footer', array('EE_Form_Section_Proper', 'localize_script_for_all_forms'));
747
+	}
748
+
749
+
750
+	/**
751
+	 * add our form section data to a static variable accessible by all form sections
752
+	 *
753
+	 * @param bool $return_for_subsection
754
+	 * @return void
755
+	 * @throws EE_Error
756
+	 */
757
+	public function localize_validation_rules($return_for_subsection = false)
758
+	{
759
+		// we only want to localize vars ONCE for the entire form,
760
+		// so if the form section doesn't have a parent, then it must be the top dog
761
+		if ($return_for_subsection || ! $this->parent_section()) {
762
+			EE_Form_Section_Proper::$_js_localization['form_data'][ $this->html_id() ] = array(
763
+				'form_section_id'  => $this->html_id(true),
764
+				'validation_rules' => $this->get_jquery_validation_rules(),
765
+				'other_data'       => $this->get_other_js_data(),
766
+				'errors'           => $this->subsection_validation_errors_by_html_name(),
767
+			);
768
+			EE_Form_Section_Proper::$_scripts_localized                                = true;
769
+		}
770
+	}
771
+
772
+
773
+	/**
774
+	 * Gets an array of extra data that will be useful for client-side javascript.
775
+	 * This is primarily data added by inputs and forms in addition to any
776
+	 * scripts they might enqueue
777
+	 *
778
+	 * @param array $form_other_js_data
779
+	 * @return array
780
+	 * @throws EE_Error
781
+	 */
782
+	public function get_other_js_data($form_other_js_data = array())
783
+	{
784
+		foreach ($this->subsections() as $subsection) {
785
+			$form_other_js_data = $subsection->get_other_js_data($form_other_js_data);
786
+		}
787
+		return $form_other_js_data;
788
+	}
789
+
790
+
791
+	/**
792
+	 * Gets a flat array of inputs for this form section and its subsections.
793
+	 * Keys are their form names, and values are the inputs themselves
794
+	 *
795
+	 * @return EE_Form_Input_Base
796
+	 * @throws EE_Error
797
+	 */
798
+	public function inputs_in_subsections()
799
+	{
800
+		$inputs = array();
801
+		foreach ($this->subsections() as $subsection) {
802
+			if ($subsection instanceof EE_Form_Input_Base) {
803
+				$inputs[ $subsection->html_name() ] = $subsection;
804
+			} elseif ($subsection instanceof EE_Form_Section_Proper) {
805
+				$inputs += $subsection->inputs_in_subsections();
806
+			}
807
+		}
808
+		return $inputs;
809
+	}
810
+
811
+
812
+	/**
813
+	 * Gets a flat array of all the validation errors.
814
+	 * Keys are html names (because those should be unique)
815
+	 * and values are a string of all their validation errors
816
+	 *
817
+	 * @return string[]
818
+	 * @throws EE_Error
819
+	 */
820
+	public function subsection_validation_errors_by_html_name()
821
+	{
822
+		$inputs = $this->inputs();
823
+		$errors = array();
824
+		foreach ($inputs as $form_input) {
825
+			if ($form_input instanceof EE_Form_Input_Base && $form_input->get_validation_errors()) {
826
+				$errors[ $form_input->html_name() ] = $form_input->get_validation_error_string();
827
+			}
828
+		}
829
+		return $errors;
830
+	}
831
+
832
+
833
+	/**
834
+	 * passes all the form data required by the JS to the JS, and enqueues the few required JS files.
835
+	 * Should be setup by each form during the _enqueues_and_localize_form_js
836
+	 *
837
+	 * @throws InvalidArgumentException
838
+	 * @throws InvalidInterfaceException
839
+	 * @throws InvalidDataTypeException
840
+	 */
841
+	public static function localize_script_for_all_forms()
842
+	{
843
+		// allow inputs and stuff to hook in their JS and stuff here
844
+		do_action('AHEE__EE_Form_Section_Proper__localize_script_for_all_forms__begin');
845
+		EE_Form_Section_Proper::$_js_localization['localized_error_messages'] = EE_Form_Section_Proper::_get_localized_error_messages();
846
+		$email_validation_level = isset(EE_Registry::instance()->CFG->registration->email_validation_level)
847
+			? EE_Registry::instance()->CFG->registration->email_validation_level
848
+			: 'wp_default';
849
+		EE_Form_Section_Proper::$_js_localization['email_validation_level']   = $email_validation_level;
850
+		wp_enqueue_script('ee_form_section_validation');
851
+		wp_localize_script(
852
+			'ee_form_section_validation',
853
+			'ee_form_section_vars',
854
+			EE_Form_Section_Proper::$_js_localization
855
+		);
856
+	}
857
+
858
+
859
+	/**
860
+	 * ensure_scripts_localized
861
+	 *
862
+	 * @throws EE_Error
863
+	 */
864
+	public function ensure_scripts_localized()
865
+	{
866
+		if (! EE_Form_Section_Proper::$_scripts_localized) {
867
+			$this->_enqueue_and_localize_form_js();
868
+		}
869
+	}
870
+
871
+
872
+	/**
873
+	 * Gets the hard-coded validation error messages to be used in the JS. The convention
874
+	 * is that the key here should be the same as the custom validation rule put in the JS file
875
+	 *
876
+	 * @return array keys are custom validation rules, and values are internationalized strings
877
+	 */
878
+	private static function _get_localized_error_messages()
879
+	{
880
+		return array(
881
+			'validUrl' => wp_strip_all_tags(__('This is not a valid absolute URL. Eg, http://domain.com/monkey.jpg', 'event_espresso')),
882
+			'regex'    => wp_strip_all_tags(__('Please check your input', 'event_espresso'))
883
+		);
884
+	}
885
+
886
+
887
+	/**
888
+	 * @return array
889
+	 */
890
+	public static function js_localization()
891
+	{
892
+		return self::$_js_localization;
893
+	}
894
+
895
+
896
+	/**
897
+	 * @return void
898
+	 */
899
+	public static function reset_js_localization()
900
+	{
901
+		self::$_js_localization = array();
902
+	}
903
+
904
+
905
+	/**
906
+	 * Gets the JS to put inside the jquery validation rules for subsection of this form section.
907
+	 * See parent function for more...
908
+	 *
909
+	 * @return array
910
+	 * @throws EE_Error
911
+	 */
912
+	public function get_jquery_validation_rules()
913
+	{
914
+		$jquery_validation_rules = array();
915
+		foreach ($this->get_validatable_subsections() as $subsection) {
916
+			$jquery_validation_rules = array_merge(
917
+				$jquery_validation_rules,
918
+				$subsection->get_jquery_validation_rules()
919
+			);
920
+		}
921
+		return $jquery_validation_rules;
922
+	}
923
+
924
+
925
+	/**
926
+	 * Sanitizes all the data and sets the sanitized value of each field
927
+	 *
928
+	 * @param array $req_data
929
+	 * @return void
930
+	 * @throws EE_Error
931
+	 */
932
+	protected function _normalize($req_data)
933
+	{
934
+		$this->_received_submission = true;
935
+		$this->_validation_errors   = array();
936
+		foreach ($this->get_validatable_subsections() as $subsection) {
937
+			try {
938
+				$subsection->_normalize($req_data);
939
+			} catch (EE_Validation_Error $e) {
940
+				$subsection->add_validation_error($e);
941
+			}
942
+		}
943
+	}
944
+
945
+
946
+	/**
947
+	 * Performs validation on this form section and its subsections.
948
+	 * For each subsection,
949
+	 * calls _validate_{subsection_name} on THIS form (if the function exists)
950
+	 * and passes it the subsection, then calls _validate on that subsection.
951
+	 * If you need to perform validation on the form as a whole (considering multiple)
952
+	 * you would be best to override this _validate method,
953
+	 * calling parent::_validate() first.
954
+	 *
955
+	 * @throws EE_Error
956
+	 */
957
+	protected function _validate()
958
+	{
959
+		// reset the cache of whether this form is valid or not- we're re-validating it now
960
+		$this->is_valid = null;
961
+		foreach ($this->get_validatable_subsections() as $subsection_name => $subsection) {
962
+			if (method_exists($this, '_validate_' . $subsection_name)) {
963
+				call_user_func_array(array($this, '_validate_' . $subsection_name), array($subsection));
964
+			}
965
+			$subsection->_validate();
966
+		}
967
+	}
968
+
969
+
970
+	/**
971
+	 * Gets all the validated inputs for the form section
972
+	 *
973
+	 * @return array
974
+	 * @throws EE_Error
975
+	 */
976
+	public function valid_data()
977
+	{
978
+		$inputs = array();
979
+		foreach ($this->subsections() as $subsection_name => $subsection) {
980
+			if ($subsection instanceof EE_Form_Section_Proper) {
981
+				$inputs[ $subsection_name ] = $subsection->valid_data();
982
+			} elseif ($subsection instanceof EE_Form_Input_Base) {
983
+				$inputs[ $subsection_name ] = $subsection->normalized_value();
984
+			}
985
+		}
986
+		return $inputs;
987
+	}
988
+
989
+
990
+	/**
991
+	 * Gets all the inputs on this form section
992
+	 *
993
+	 * @return EE_Form_Input_Base[]
994
+	 * @throws EE_Error
995
+	 */
996
+	public function inputs()
997
+	{
998
+		$inputs = array();
999
+		foreach ($this->subsections() as $subsection_name => $subsection) {
1000
+			if ($subsection instanceof EE_Form_Input_Base) {
1001
+				$inputs[ $subsection_name ] = $subsection;
1002
+			}
1003
+		}
1004
+		return $inputs;
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Gets all the subsections which are a proper form
1010
+	 *
1011
+	 * @return EE_Form_Section_Proper[]
1012
+	 * @throws EE_Error
1013
+	 */
1014
+	public function subforms()
1015
+	{
1016
+		$form_sections = array();
1017
+		foreach ($this->subsections() as $name => $obj) {
1018
+			if ($obj instanceof EE_Form_Section_Proper) {
1019
+				$form_sections[ $name ] = $obj;
1020
+			}
1021
+		}
1022
+		return $form_sections;
1023
+	}
1024
+
1025
+
1026
+	/**
1027
+	 * Gets all the subsections (inputs, proper subsections, or html-only sections).
1028
+	 * Consider using inputs() or subforms()
1029
+	 * if you only want form inputs or proper form sections.
1030
+	 *
1031
+	 * @param boolean $require_construction_to_be_finalized most client code should
1032
+	 *                                                      leave this as TRUE so that the inputs will be properly
1033
+	 *                                                      configured. However, some client code may be ok with
1034
+	 *                                                      construction finalize being called later
1035
+	 *                                                      (realizing that the subsections' html names might not be
1036
+	 *                                                      set yet, etc.)
1037
+	 * @return EE_Form_Section_Proper[]
1038
+	 * @throws EE_Error
1039
+	 */
1040
+	public function subsections($require_construction_to_be_finalized = true)
1041
+	{
1042
+		if ($require_construction_to_be_finalized) {
1043
+			$this->ensure_construct_finalized_called();
1044
+		}
1045
+		return $this->_subsections;
1046
+	}
1047
+
1048
+
1049
+	/**
1050
+	 * Returns whether this form has any subforms or inputs
1051
+	 * @return bool
1052
+	 */
1053
+	public function hasSubsections()
1054
+	{
1055
+		return ! empty($this->_subsections);
1056
+	}
1057
+
1058
+
1059
+	/**
1060
+	 * Returns a simple array where keys are input names, and values are their normalized
1061
+	 * values. (Similar to calling get_input_value on inputs)
1062
+	 *
1063
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1064
+	 *                                        or just this forms' direct children inputs
1065
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1066
+	 *                                        or allow multidimensional array
1067
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array
1068
+	 *                                        with array keys being input names
1069
+	 *                                        (regardless of whether they are from a subsection or not),
1070
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
1071
+	 *                                        where keys are always subsection names and values are either
1072
+	 *                                        the input's normalized value, or an array like the top-level array
1073
+	 * @throws EE_Error
1074
+	 */
1075
+	public function input_values($include_subform_inputs = false, $flatten = false)
1076
+	{
1077
+		return $this->_input_values(false, $include_subform_inputs, $flatten);
1078
+	}
1079
+
1080
+
1081
+	/**
1082
+	 * Similar to EE_Form_Section_Proper::input_values(), except this returns the 'display_value'
1083
+	 * of each input. On some inputs (especially radio boxes or checkboxes), the value stored
1084
+	 * is not necessarily the value we want to display to users. This creates an array
1085
+	 * where keys are the input names, and values are their display values
1086
+	 *
1087
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1088
+	 *                                        or just this forms' direct children inputs
1089
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1090
+	 *                                        or allow multidimensional array
1091
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array
1092
+	 *                                        with array keys being input names
1093
+	 *                                        (regardless of whether they are from a subsection or not),
1094
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
1095
+	 *                                        where keys are always subsection names and values are either
1096
+	 *                                        the input's normalized value, or an array like the top-level array
1097
+	 * @throws EE_Error
1098
+	 */
1099
+	public function input_pretty_values($include_subform_inputs = false, $flatten = false)
1100
+	{
1101
+		return $this->_input_values(true, $include_subform_inputs, $flatten);
1102
+	}
1103
+
1104
+
1105
+	/**
1106
+	 * Gets the input values from the form
1107
+	 *
1108
+	 * @param boolean $pretty                 Whether to retrieve the pretty value,
1109
+	 *                                        or just the normalized value
1110
+	 * @param boolean $include_subform_inputs Whether to include inputs from subforms,
1111
+	 *                                        or just this forms' direct children inputs
1112
+	 * @param boolean $flatten                Whether to force the results into 1-dimensional array,
1113
+	 *                                        or allow multidimensional array
1114
+	 * @return array if $flatten is TRUE it will always be a 1-dimensional array with array keys being
1115
+	 *                                        input names (regardless of whether they are from a subsection or not),
1116
+	 *                                        and if $flatten is FALSE it can be a multidimensional array
1117
+	 *                                        where keys are always subsection names and values are either
1118
+	 *                                        the input's normalized value, or an array like the top-level array
1119
+	 * @throws EE_Error
1120
+	 */
1121
+	public function _input_values($pretty = false, $include_subform_inputs = false, $flatten = false)
1122
+	{
1123
+		$input_values = array();
1124
+		foreach ($this->subsections() as $subsection_name => $subsection) {
1125
+			if ($subsection instanceof EE_Form_Input_Base) {
1126
+				$input_values[ $subsection_name ] = $pretty
1127
+					? $subsection->pretty_value()
1128
+					: $subsection->normalized_value();
1129
+			} elseif ($subsection instanceof EE_Form_Section_Proper && $include_subform_inputs) {
1130
+				$subform_input_values = $subsection->_input_values(
1131
+					$pretty,
1132
+					$include_subform_inputs,
1133
+					$flatten
1134
+				);
1135
+				if ($flatten) {
1136
+					$input_values = array_merge($input_values, $subform_input_values);
1137
+				} else {
1138
+					$input_values[ $subsection_name ] = $subform_input_values;
1139
+				}
1140
+			}
1141
+		}
1142
+		return $input_values;
1143
+	}
1144
+
1145
+
1146
+	/**
1147
+	 * Gets the originally submitted input values from the form
1148
+	 *
1149
+	 * @param boolean $include_subforms  Whether to include inputs from subforms,
1150
+	 *                                   or just this forms' direct children inputs
1151
+	 * @return array                     if $flatten is TRUE it will always be a 1-dimensional array
1152
+	 *                                   with array keys being input names
1153
+	 *                                   (regardless of whether they are from a subsection or not),
1154
+	 *                                   and if $flatten is FALSE it can be a multidimensional array
1155
+	 *                                   where keys are always subsection names and values are either
1156
+	 *                                   the input's normalized value, or an array like the top-level array
1157
+	 * @throws EE_Error
1158
+	 */
1159
+	public function submitted_values($include_subforms = false)
1160
+	{
1161
+		$submitted_values = array();
1162
+		foreach ($this->subsections() as $subsection) {
1163
+			if ($subsection instanceof EE_Form_Input_Base) {
1164
+				// is this input part of an array of inputs?
1165
+				if (strpos($subsection->html_name(), '[') !== false) {
1166
+					$full_input_name  = EEH_Array::convert_array_values_to_keys(
1167
+						explode(
1168
+							'[',
1169
+							str_replace(']', '', $subsection->html_name())
1170
+						),
1171
+						$subsection->raw_value()
1172
+					);
1173
+					$submitted_values = array_replace_recursive($submitted_values, $full_input_name);
1174
+				} else {
1175
+					$submitted_values[ $subsection->html_name() ] = $subsection->raw_value();
1176
+				}
1177
+			} elseif ($subsection instanceof EE_Form_Section_Proper && $include_subforms) {
1178
+				$subform_input_values = $subsection->submitted_values($include_subforms);
1179
+				$submitted_values     = array_replace_recursive($submitted_values, $subform_input_values);
1180
+			}
1181
+		}
1182
+		return $submitted_values;
1183
+	}
1184
+
1185
+
1186
+	/**
1187
+	 * Indicates whether or not this form has received a submission yet
1188
+	 * (ie, had receive_form_submission called on it yet)
1189
+	 *
1190
+	 * @return boolean
1191
+	 * @throws EE_Error
1192
+	 */
1193
+	public function has_received_submission()
1194
+	{
1195
+		$this->ensure_construct_finalized_called();
1196
+		return $this->_received_submission;
1197
+	}
1198
+
1199
+
1200
+	/**
1201
+	 * Equivalent to passing 'exclude' in the constructor's options array.
1202
+	 * Removes the listed inputs from the form
1203
+	 *
1204
+	 * @param array $inputs_to_exclude values are the input names
1205
+	 * @return void
1206
+	 */
1207
+	public function exclude(array $inputs_to_exclude = array())
1208
+	{
1209
+		foreach ($inputs_to_exclude as $input_to_exclude_name) {
1210
+			unset($this->_subsections[ $input_to_exclude_name ]);
1211
+		}
1212
+	}
1213
+
1214
+
1215
+	/**
1216
+	 * Changes these inputs' display strategy to be EE_Hidden_Display_Strategy.
1217
+	 * @param array $inputs_to_hide
1218
+	 * @throws EE_Error
1219
+	 */
1220
+	public function hide(array $inputs_to_hide = array())
1221
+	{
1222
+		foreach ($inputs_to_hide as $input_to_hide) {
1223
+			$input = $this->get_input($input_to_hide);
1224
+			$input->set_display_strategy(new EE_Hidden_Display_Strategy());
1225
+		}
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * add_subsections
1231
+	 * Adds the listed subsections to the form section.
1232
+	 * If $subsection_name_to_target is provided,
1233
+	 * then new subsections are added before or after that subsection,
1234
+	 * otherwise to the start or end of the entire subsections array.
1235
+	 *
1236
+	 * @param EE_Form_Section_Base[] $new_subsections           array of new form subsections
1237
+	 *                                                          where keys are their names
1238
+	 * @param string                 $subsection_name_to_target an existing for section that $new_subsections
1239
+	 *                                                          should be added before or after
1240
+	 *                                                          IF $subsection_name_to_target is null,
1241
+	 *                                                          then $new_subsections will be added to
1242
+	 *                                                          the beginning or end of the entire subsections array
1243
+	 * @param boolean                $add_before                whether to add $new_subsections, before or after
1244
+	 *                                                          $subsection_name_to_target,
1245
+	 *                                                          or if $subsection_name_to_target is null,
1246
+	 *                                                          before or after entire subsections array
1247
+	 * @return void
1248
+	 * @throws EE_Error
1249
+	 */
1250
+	public function add_subsections($new_subsections, $subsection_name_to_target = null, $add_before = true)
1251
+	{
1252
+		foreach ($new_subsections as $subsection_name => $subsection) {
1253
+			if (! $subsection instanceof EE_Form_Section_Base) {
1254
+				EE_Error::add_error(
1255
+					sprintf(
1256
+						esc_html__(
1257
+							"Trying to add a %s as a subsection (it was named '%s') to the form section '%s'. It was removed.",
1258
+							'event_espresso'
1259
+						),
1260
+						get_class($subsection),
1261
+						$subsection_name,
1262
+						$this->name()
1263
+					)
1264
+				);
1265
+				unset($new_subsections[ $subsection_name ]);
1266
+			}
1267
+		}
1268
+		$this->_subsections = EEH_Array::insert_into_array(
1269
+			$this->_subsections,
1270
+			$new_subsections,
1271
+			$subsection_name_to_target,
1272
+			$add_before
1273
+		);
1274
+		if ($this->_construction_finalized) {
1275
+			foreach ($this->_subsections as $name => $subsection) {
1276
+				$subsection->_construct_finalize($this, $name);
1277
+			}
1278
+		}
1279
+	}
1280
+
1281
+
1282
+	/**
1283
+	 * @param string $subsection_name
1284
+	 * @param bool   $recursive
1285
+	 * @return bool
1286
+	 */
1287
+	public function has_subsection($subsection_name, $recursive = false)
1288
+	{
1289
+		foreach ($this->_subsections as $name => $subsection) {
1290
+			if (
1291
+				$name === $subsection_name
1292
+				|| (
1293
+					$recursive
1294
+					&& $subsection instanceof EE_Form_Section_Proper
1295
+					&& $subsection->has_subsection($subsection_name, $recursive)
1296
+				)
1297
+			) {
1298
+				return true;
1299
+			}
1300
+		}
1301
+		return false;
1302
+	}
1303
+
1304
+
1305
+
1306
+	/**
1307
+	 * Just gets all validatable subsections to clean their sensitive data
1308
+	 *
1309
+	 * @throws EE_Error
1310
+	 */
1311
+	public function clean_sensitive_data()
1312
+	{
1313
+		foreach ($this->get_validatable_subsections() as $subsection) {
1314
+			$subsection->clean_sensitive_data();
1315
+		}
1316
+	}
1317
+
1318
+
1319
+	/**
1320
+	 * Sets the submission error message (aka validation error message for this form section and all sub-sections)
1321
+	 * @param string                           $form_submission_error_message
1322
+	 * @param EE_Form_Section_Validatable $form_section unused
1323
+	 * @throws EE_Error
1324
+	 */
1325
+	public function set_submission_error_message(
1326
+		$form_submission_error_message = ''
1327
+	) {
1328
+		$this->_form_submission_error_message = ! empty($form_submission_error_message)
1329
+			? $form_submission_error_message
1330
+			: $this->getAllValidationErrorsString();
1331
+	}
1332
+
1333
+
1334
+	/**
1335
+	 * Returns the cached error message. A default value is set for this during _validate(),
1336
+	 * (called during receive_form_submission) but it can be explicitly set using
1337
+	 * set_submission_error_message
1338
+	 *
1339
+	 * @return string
1340
+	 */
1341
+	public function submission_error_message()
1342
+	{
1343
+		return $this->_form_submission_error_message;
1344
+	}
1345
+
1346
+
1347
+	/**
1348
+	 * Sets a message to display if the data submitted to the form was valid.
1349
+	 * @param string $form_submission_success_message
1350
+	 */
1351
+	public function set_submission_success_message($form_submission_success_message = '')
1352
+	{
1353
+		$this->_form_submission_success_message = ! empty($form_submission_success_message)
1354
+			? $form_submission_success_message
1355
+			: esc_html__('Form submitted successfully', 'event_espresso');
1356
+	}
1357
+
1358
+
1359
+	/**
1360
+	 * Gets a message appropriate for display when the form is correctly submitted
1361
+	 * @return string
1362
+	 */
1363
+	public function submission_success_message()
1364
+	{
1365
+		return $this->_form_submission_success_message;
1366
+	}
1367
+
1368
+
1369
+	/**
1370
+	 * Returns the prefix that should be used on child of this form section for
1371
+	 * their html names. If this form section itself has a parent, prepends ITS
1372
+	 * prefix onto this form section's prefix. Used primarily by
1373
+	 * EE_Form_Input_Base::_set_default_html_name_if_empty
1374
+	 *
1375
+	 * @return string
1376
+	 * @throws EE_Error
1377
+	 */
1378
+	public function html_name_prefix()
1379
+	{
1380
+		if ($this->parent_section() instanceof EE_Form_Section_Proper) {
1381
+			return $this->parent_section()->html_name_prefix() . '[' . $this->name() . ']';
1382
+		}
1383
+		return $this->name();
1384
+	}
1385
+
1386
+
1387
+	/**
1388
+	 * Gets the name, but first checks _construct_finalize has been called. If not,
1389
+	 * calls it (assumes there is no parent and that we want the name to be whatever
1390
+	 * was set, which is probably nothing, or the classname)
1391
+	 *
1392
+	 * @return string
1393
+	 * @throws EE_Error
1394
+	 */
1395
+	public function name()
1396
+	{
1397
+		$this->ensure_construct_finalized_called();
1398
+		return parent::name();
1399
+	}
1400
+
1401
+
1402
+	/**
1403
+	 * @return EE_Form_Section_Proper
1404
+	 * @throws EE_Error
1405
+	 */
1406
+	public function parent_section()
1407
+	{
1408
+		$this->ensure_construct_finalized_called();
1409
+		return parent::parent_section();
1410
+	}
1411
+
1412
+
1413
+	/**
1414
+	 * make sure construction finalized was called, otherwise children might not be ready
1415
+	 *
1416
+	 * @return void
1417
+	 * @throws EE_Error
1418
+	 */
1419
+	public function ensure_construct_finalized_called()
1420
+	{
1421
+		if (! $this->_construction_finalized) {
1422
+			$this->_construct_finalize($this->_parent_section, $this->_name);
1423
+		}
1424
+	}
1425
+
1426
+
1427
+	/**
1428
+	 * Checks if any of this form section's inputs, or any of its children's inputs,
1429
+	 * are in teh form data. If any are found, returns true. Else false
1430
+	 *
1431
+	 * @param array $req_data
1432
+	 * @return boolean
1433
+	 * @throws EE_Error
1434
+	 */
1435
+	public function form_data_present_in($req_data = null)
1436
+	{
1437
+		$req_data = $this->getCachedRequest($req_data);
1438
+		foreach ($this->subsections() as $subsection) {
1439
+			if ($subsection instanceof EE_Form_Input_Base) {
1440
+				if ($subsection->form_data_present_in($req_data)) {
1441
+					return true;
1442
+				}
1443
+			} elseif ($subsection instanceof EE_Form_Section_Proper) {
1444
+				if ($subsection->form_data_present_in($req_data)) {
1445
+					return true;
1446
+				}
1447
+			}
1448
+		}
1449
+		return false;
1450
+	}
1451
+
1452
+
1453
+	/**
1454
+	 * Gets validation errors for this form section and subsections
1455
+	 * Similar to EE_Form_Section_Validatable::get_validation_errors() except this
1456
+	 * gets the validation errors for ALL subsection
1457
+	 *
1458
+	 * @return EE_Validation_Error[]
1459
+	 * @throws EE_Error
1460
+	 */
1461
+	public function get_validation_errors_accumulated()
1462
+	{
1463
+		$validation_errors = $this->get_validation_errors();
1464
+		foreach ($this->get_validatable_subsections() as $subsection) {
1465
+			if ($subsection instanceof EE_Form_Section_Proper) {
1466
+				$validation_errors_on_this_subsection = $subsection->get_validation_errors_accumulated();
1467
+			} else {
1468
+				$validation_errors_on_this_subsection = $subsection->get_validation_errors();
1469
+			}
1470
+			if ($validation_errors_on_this_subsection) {
1471
+				$validation_errors = array_merge($validation_errors, $validation_errors_on_this_subsection);
1472
+			}
1473
+		}
1474
+		return $validation_errors;
1475
+	}
1476
+
1477
+	/**
1478
+	 * Fetch validation errors from children and grandchildren and puts them in a single string.
1479
+	 * This traverses the form section tree to generate this, but you probably want to instead use
1480
+	 * get_form_submission_error_message() which is usually this message cached (or a custom validation error message)
1481
+	 *
1482
+	 * @return string
1483
+	 * @since 4.9.59.p
1484
+	 */
1485
+	protected function getAllValidationErrorsString()
1486
+	{
1487
+		$submission_error_messages = array();
1488
+		// bad, bad, bad registrant
1489
+		foreach ($this->get_validation_errors_accumulated() as $validation_error) {
1490
+			if ($validation_error instanceof EE_Validation_Error) {
1491
+				$form_section = $validation_error->get_form_section();
1492
+				if ($form_section instanceof EE_Form_Input_Base) {
1493
+					$label = $validation_error->get_form_section()->html_label_text();
1494
+				} elseif ($form_section instanceof EE_Form_Section_Validatable) {
1495
+					$label = $validation_error->get_form_section()->name();
1496
+				} else {
1497
+					$label = esc_html__('Unknown', 'event_espresso');
1498
+				}
1499
+				$submission_error_messages[] = sprintf(
1500
+					esc_html__('%s : %s', 'event_espresso'),
1501
+					$label,
1502
+					$validation_error->getMessage()
1503
+				);
1504
+			}
1505
+		}
1506
+		return implode('<br>', $submission_error_messages);
1507
+	}
1508
+
1509
+
1510
+	/**
1511
+	 * This isn't just the name of an input, it's a path pointing to an input. The
1512
+	 * path is similar to a folder path: slash (/) means to descend into a subsection,
1513
+	 * dot-dot-slash (../) means to ascend into the parent section.
1514
+	 * After a series of slashes and dot-dot-slashes, there should be the name of an input,
1515
+	 * which will be returned.
1516
+	 * Eg, if you want the related input to be conditional on a sibling input name 'foobar'
1517
+	 * just use 'foobar'. If you want it to be conditional on an aunt/uncle input name
1518
+	 * 'baz', use '../baz'. If you want it to be conditional on a cousin input,
1519
+	 * the child of 'baz_section' named 'baz_child', use '../baz_section/baz_child'.
1520
+	 * Etc
1521
+	 *
1522
+	 * @param string|false $form_section_path we accept false also because substr( '../', '../' ) = false
1523
+	 * @return EE_Form_Section_Base
1524
+	 * @throws EE_Error
1525
+	 */
1526
+	public function find_section_from_path($form_section_path)
1527
+	{
1528
+		// check if we can find the input from purely going straight up the tree
1529
+		$input = parent::find_section_from_path($form_section_path);
1530
+		if ($input instanceof EE_Form_Section_Base) {
1531
+			return $input;
1532
+		}
1533
+		$next_slash_pos = strpos($form_section_path, '/');
1534
+		if ($next_slash_pos !== false) {
1535
+			$child_section_name = substr($form_section_path, 0, $next_slash_pos);
1536
+			$subpath            = substr($form_section_path, $next_slash_pos + 1);
1537
+		} else {
1538
+			$child_section_name = $form_section_path;
1539
+			$subpath            = '';
1540
+		}
1541
+		$child_section = $this->get_subsection($child_section_name);
1542
+		if ($child_section instanceof EE_Form_Section_Base) {
1543
+			return $child_section->find_section_from_path($subpath);
1544
+		}
1545
+		return null;
1546
+	}
1547 1547
 }
Please login to merge, or discard this patch.